Safe mode: one run with only the shell working (the app menu, --safe-mode, Shift at launch on Windows)

Host: `safe.rs` is a flag in this process's memory, never written to disk, so the next normal start is back to the owner's setup. While it is on a site tab gets the tab bridge and nothing of the app's page layers: its document-start scripts are `SiteHooks::safe_init_scripts` (default: the bridge alone) instead of `init_scripts`; `site_page_loaded`, `tab_placed` and `tab_background` are not called; `page_scripts` is empty; `eval_in_site_tabs` does nothing. So no page runtime, plugins, theme, custom CSS, feature flags, fixes, hotfix data or words reach a page: the site runs as in a browser, and only the shell is the app's. It starts from the launch argument `--safe-mode` (for when the interface itself is broken), from Shift held while the app starts (Windows), or from the shell: `safe_mode_get` / `safe_mode_set {on}` (shell-only), where a switch rebuilds every tab webview (profiles marked stale, `tabs-rebuild` asks the shell for its layout) so document-start scripts change too. Tests: the argument, the flag, and that app.rs and host.rs gate every layer.

Frame: the app menu's "Restart in safe mode…" says what it does before anything reloads; while on, the titlebar shows an amber "Safe mode | Leave" chip (one click leaves) and the row reads "Leave safe mode"; the chrome drops its theme (and pane themes) and takes it back on leaving, without touching the first-frame cache. `features.safeMode` (on by default).
This commit is contained in:
CRTkafa 2026-09-30 23:13:03 +07:00
parent 08e2ca3998
commit 30cc85f3ff
19 changed files with 342 additions and 20 deletions

View file

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

View file

@ -137,6 +137,13 @@ pub trait SiteHooks: Send + Sync + 'static {
/// (`waybetter_host::bridge`), then the app's page runtime. /// (`waybetter_host::bridge`), then the app's page runtime.
fn init_scripts(&self, app: &AppHandle, tab: &NewTab) -> Vec<String>; fn init_scripts(&self, app: &AppHandle, tab: &NewTab) -> Vec<String>;
/// The document-start scripts of a tab in safe mode ([`crate::safe`]) instead of
/// [`Self::init_scripts`]: by default the host's tab bridge alone, so nothing of the app's page
/// layers runs. An app returns more here only for a layer it wants to survive safe mode.
fn safe_init_scripts(&self, _app: &AppHandle, _tab: &NewTab) -> Vec<String> {
vec![crate::bridge::SOURCE.to_owned()]
}
/// The new tab webview's background until the page paints. /// The new tab webview's background until the page paints.
fn tab_background(&self, _app: &AppHandle, _label: &str) -> Option<tauri::window::Color> { fn tab_background(&self, _app: &AppHandle, _label: &str) -> Option<tauri::window::Color> {
None None
@ -272,6 +279,10 @@ impl PageScripts {
/// The page state as scripts for a site document that just loaded (evaluate them natively, so the /// The page state as scripts for a site document that just loaded (evaluate them natively, so the
/// page's CSP cannot block them). An app with scripts of its own places them between these. /// page's CSP cannot block them). An app with scripts of its own places them between these.
pub fn page_scripts(app: &AppHandle) -> Result<PageScripts, String> { pub fn page_scripts(app: &AppHandle) -> Result<PageScripts, String> {
// Safe mode: a site page gets none of them.
if crate::safe::active() {
return Ok(PageScripts { features: String::new(), links: String::new(), css: None, plugins: Vec::new() });
}
let site = config(app).site; let site = config(app).site;
let page = page(app)?; let page = page(app)?;
let css = page.plugins.css(); let css = page.plugins.css();
@ -484,7 +495,7 @@ pub(crate) async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLa
let new_tab = NewTab { id: &item.id, label: &label, profile: &item.profile, item: &item }; 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); let builder = tab_builder(&app, &hooks, &new_tab, url, data_dir);
// The site's page color until it paints (never the WebView's white). // The site's page color until it paints (never the WebView's white).
let builder = match hooks.tab_background(&app, &label) { let builder = match crate::safe::layer(crate::safe::active(), || hooks.tab_background(&app, &label), || None) {
Some(color) => builder.background_color(color), Some(color) => builder.background_color(color),
None => builder, None => builder,
}; };
@ -506,7 +517,9 @@ pub(crate) async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLa
} }
} }
}; };
hooks.tab_placed(&app, &tab, &item); if !crate::safe::active() {
hooks.tab_placed(&app, &tab, &item);
}
host::place_tab(&tab, (x, y, width, height), visible, item.parked || rect.is_none()); host::place_tab(&tab, (x, y, width, height), visible, item.parked || rect.is_none());
placed.push((item.id.clone(), (x, y, width, height), visible)); placed.push((item.id.clone(), (x, y, width, height), visible));
} }
@ -568,6 +581,38 @@ async fn tab_find(webview: Webview, app: AppHandle, id: String, action: String,
host::tab_find(&app, &id, &action, query.as_deref()) host::tab_find(&app, &id, &action, query.as_deref())
} }
/// Whether safe mode is on ([`crate::safe`]): the shell shows it in the titlebar and drops its chrome theme.
#[tauri::command]
async fn safe_mode_get(webview: Webview) -> Result<crate::safe::SafeState, String> {
shell_only(&webview)?;
Ok(crate::safe::state())
}
/// Switches safe mode for this run (memory only, never saved) and rebuilds every tab webview, so
/// each page starts again with or without the app's page layers. The app menu's "Restart in safe
/// mode" and the titlebar's "Leave".
#[tauri::command]
async fn safe_mode_set(webview: Webview, app: AppHandle, on: bool) -> Result<crate::safe::SafeState, String> {
shell_only(&webview)?;
if crate::safe::set(on) {
emit_shell(&app, crate::safe::EVENT, crate::safe::state());
rebuild_tabs(&app);
}
Ok(crate::safe::state())
}
/// Every tab webview is built again on the shell's next layout: their recorded profiles are marked
/// stale (`tabs_sync` then closes and recreates each one with the document-start scripts of the
/// moment) and the shell is asked to send its layout.
pub fn rebuild_tabs(app: &AppHandle) {
if let Ok(mut data) = profiles(app) {
for profile in data.tab_profiles.values_mut() {
*profile = crate::safe::STALE_PROFILE.to_owned();
}
}
emit_shell(app, crate::safe::EVENT_REBUILD, ());
}
/// Gives keyboard focus back to the shell (e.g. Ctrl+L pressed inside a tab). /// Gives keyboard focus back to the shell (e.g. Ctrl+L pressed inside a tab).
#[tauri::command] #[tauri::command]
async fn shell_focus(webview: Webview) -> Result<(), String> { async fn shell_focus(webview: Webview) -> Result<(), String> {
@ -848,7 +893,8 @@ fn tab_builder(app: &AppHandle, hooks: &Arc<dyn SiteHooks>, tab: &NewTab, url: U
builder = builder.data_store_identifier(profiles::store_identifier(tab.profile)); builder = builder.data_store_identifier(profiles::store_identifier(tab.profile));
} }
} }
for script in hooks.init_scripts(app, tab) { // Safe mode: the safe set (the tab bridge) instead of the app's page layers.
for script in crate::safe::layer(crate::safe::active(), || hooks.init_scripts(app, tab), || hooks.safe_init_scripts(app, tab)) {
builder = builder.initialization_script(script); builder = builder.initialization_script(script);
} }
builder builder
@ -927,7 +973,7 @@ fn tab_builder(app: &AppHandle, hooks: &Arc<dyn SiteHooks>, tab: &NewTab, url: U
host::restore_tab_zoom(app, &tab); host::restore_tab_zoom(app, &tab);
} }
emit_tab_state(app, TabState { id: load_id.clone(), url: Some(payload.url().to_string()), loading: Some(!finished), ..Default::default() }); emit_tab_state(app, TabState { id: load_id.clone(), url: Some(payload.url().to_string()), loading: Some(!finished), ..Default::default() });
if finished && site.is_origin(payload.url()) { if finished && site.is_origin(payload.url()) && !crate::safe::active() {
load_hooks.site_page_loaded(app, &tab, payload.url()); load_hooks.site_page_loaded(app, &tab, payload.url());
} }
}) })
@ -984,6 +1030,8 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 's
tab_action, tab_action,
tab_zoom, tab_zoom,
tab_find, tab_find,
safe_mode_get,
safe_mode_set,
open_external_url, open_external_url,
shell_focus, shell_focus,
shell_ready, shell_ready,
@ -1118,6 +1166,8 @@ impl App {
}); });
tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings, modes }))); tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings, modes })));
tauri_app.manage(Host { config, hooks }); tauri_app.manage(Host { config, hooks });
// Safe mode for this run: the launch argument, or Shift held while starting (Windows).
crate::safe::set(crate::safe::at_launch(std::env::args(), host::shift_held()));
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
crate::devloop::start(&handle); crate::devloop::start(&handle);
if let Some(setup) = setup { if let Some(setup) = setup {

View file

@ -13,6 +13,8 @@ pub const SHELL: &[&str] = &[
"tab_action", "tab_action",
"tab_zoom", "tab_zoom",
"tab_find", "tab_find",
"safe_mode_get",
"safe_mode_set",
"open_external_url", "open_external_url",
"shell_focus", "shell_focus",
"shell_ready", "shell_ready",

View file

@ -48,6 +48,10 @@ pub fn tab_webview<R: Runtime>(app: &AppHandle<R>, id: &str) -> Option<Webview<R
/// Evaluates `script` in every tab that is on the site right now. /// Evaluates `script` in every tab that is on the site right now.
pub fn eval_in_site_tabs<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, script: &str) { pub fn eval_in_site_tabs<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, script: &str) {
// Safe mode: site pages run none of the app's layers, so nothing is pushed into them either.
if crate::safe::active() {
return;
}
for (label, webview) in app.webviews() { for (label, webview) in app.webviews() {
if policy::tab_id(&label).is_some() && webview.url().is_ok_and(|url| site.is_origin(&url)) { if policy::tab_id(&label).is_some() && webview.url().is_ok_and(|url| site.is_origin(&url)) {
let _ = webview.eval(script); let _ = webview.eval(script);
@ -89,6 +93,21 @@ pub fn tab_action<R: Runtime>(app: &AppHandle<R>, id: &str, action: &str) -> Res
result.map_err(|error| format!("TAB: {error}")) result.map_err(|error| format!("TAB: {error}"))
} }
/// Whether Shift is held right now (asked once while the app starts: safe mode). Windows only;
/// elsewhere the launch argument is the way in.
pub fn shift_held() -> bool {
#[cfg(windows)]
{
use windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_SHIFT};
// SAFETY: a plain Win32 key-state read. The high bit means the key is down.
unsafe { GetAsyncKeyState(i32::from(VK_SHIFT.0)) < 0 }
}
#[cfg(not(windows))]
{
false
}
}
/// The remembered page zoom per tab ([`crate::zoom`], app data `zoom.json`), read once. /// The remembered page zoom per tab ([`crate::zoom`], app data `zoom.json`), read once.
fn zooms<R: Runtime>(app: &AppHandle<R>) -> std::sync::MutexGuard<'static, crate::zoom::ZoomMap> { fn zooms<R: Runtime>(app: &AppHandle<R>) -> std::sync::MutexGuard<'static, crate::zoom::ZoomMap> {
use std::sync::{Mutex, OnceLock}; use std::sync::{Mutex, OnceLock};

View file

@ -30,6 +30,7 @@
//! feature flags, as validated data and the scripts that hand them to site tabs. //! feature flags, as validated data and the scripts that hand them to site tabs.
//! - [`modes`]: the onboarding mode the owner started from (the presets are the app's feature table). //! - [`modes`]: the onboarding mode the owner started from (the presets are the app's feature table).
//! - [`zoom`]: page zoom per tab (a clamped factor the shell sets, remembered in `zoom.json`). //! - [`zoom`]: page zoom per tab (a clamped factor the shell sets, remembered in `zoom.json`).
//! - [`safe`]: safe mode for one run (a flag in memory: site tabs get the tab bridge and nothing else).
//! - [`find`]: find in page (the request the shell sends, the fallback script; the query is kept nowhere). //! - [`find`]: find in page (the request the shell sends, the fallback script; the query is kept nowhere).
//! - [`alerts`]: local keyword alerts (keywords, snippets, per-item/per-keyword rate limits). //! - [`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). //! - [`media`]: gallery folders (path containment) and the opt-in clipboard history (private copies skipped).
@ -65,6 +66,7 @@ pub mod modes;
pub mod plugins; pub mod plugins;
pub mod policy; pub mod policy;
pub mod profiles; pub mod profiles;
pub mod safe;
pub mod settings; pub mod settings;
pub mod site; pub mod site;
pub mod store; pub mod store;

View file

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

View file

@ -151,7 +151,7 @@ const COMMANDS = {
*/ */
export const HOST_COMMANDS = { export const HOST_COMMANDS = {
shell: [ shell: [
'tabs_sync', 'tab_navigate', 'tab_action', 'tab_zoom', 'tab_find', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu', 'tabs_sync', 'tab_navigate', 'tab_action', 'tab_zoom', 'tab_find', 'safe_mode_get', 'safe_mode_set', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu',
'profiles_get', 'profiles_set', 'i18n_get', 'i18n_set', 'profiles_get', 'profiles_set', 'i18n_get', 'i18n_set',
'plugins_list', 'plugin_set_enabled', 'plugins_open_folder', 'custom_css_get', 'custom_css_set', 'features_get', 'features_set', 'mode_get', 'mode_set', 'settings_get', 'settings_set', 'plugins_list', 'plugin_set_enabled', 'plugins_open_folder', 'custom_css_get', 'custom_css_set', 'features_get', 'features_set', 'mode_get', 'mode_set', 'settings_get', 'settings_set',
], ],

View file

@ -24,6 +24,7 @@ import {
DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow, DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow,
type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuRow, type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuRow,
} from './menuModel.ts'; } from './menuModel.ts';
import { safe, setSafeMode } from './safeStore.ts';
import { hasFeature, site } from './site.ts'; import { hasFeature, site } from './site.ts';
import { isWeb, setOverlay, shell, type TabParams } from './state.ts'; import { isWeb, setOverlay, shell, type TabParams } from './state.ts';
import { openWorkspaceSave } from './TitlebarExtras.tsx'; import { openWorkspaceSave } from './TitlebarExtras.tsx';
@ -93,7 +94,7 @@ export function AppMenu() {
// Whatever a row shows may change while the menu is open (a language or theme picked in it). // Whatever a row shows may change while the menu is open (a language or theme picked in it).
useEffect(() => { useEffect(() => {
const events = ['bt-zoom', 'bt-workspaces', 'bt-decks', 'bt-site']; const events = ['bt-zoom', 'bt-workspaces', 'bt-decks', 'bt-site', 'bt-safe'];
for (const event of events) window.addEventListener(event, tick); for (const event of events) window.addEventListener(event, tick);
const off = [config.themes?.subscribe(tick), menu.languages?.subscribe(tick)]; const off = [config.themes?.subscribe(tick), menu.languages?.subscribe(tick)];
return () => { return () => {
@ -301,6 +302,10 @@ export function AppMenu() {
}, },
}); });
} }
// Off: a submenu that says what it does before anything reloads. On: one row that leaves it.
case 'safe-mode': return safe.active
? item(id, menuText('safeLeave'), 'shield', { run: () => setSafeMode(false) })
: item(id, menuText('safeRestart'), 'shield', { submenu: true });
case 'about': return item(id, menuText('about', { product: config.product }), 'info', { run: () => shell.openPanelSection('home') }); case 'about': return item(id, menuText('about', { product: config.product }), 'info', { run: () => shell.openPanelSection('home') });
case 'settings': return item(id, section(t('wb.panel.section.settings')), 'settings', { run: () => shell.openPanelSection('settings') }); case 'settings': return item(id, section(t('wb.panel.section.settings')), 'settings', { run: () => shell.openPanelSection('settings') });
} }
@ -363,6 +368,11 @@ export function AppMenu() {
: [{ kind: 'note', id: 'ws:none', title: '', text: menuText('noWorkspaces') }]; : [{ kind: 'note', id: 'ws:none', title: '', text: menuText('noWorkspaces') }];
return joinGroups([rows, [item('ws:save', menuText('saveLayout'), 'plus', { run: openWorkspaceSave })]]); return joinGroups([rows, [item('ws:save', menuText('saveLayout'), 'plus', { run: openWorkspaceSave })]]);
} }
case 'safe-mode': return [
{ kind: 'note', id: 'safe:question', title: menuText('safeQuestion'), text: menuText('safeExplain') },
item('safe:confirm', menuText('safeConfirm'), 'shield', { run: () => setSafeMode(true) }),
item('safe:cancel', t('wb.common.cancel'), 'close', { keepOpen: true, run: () => closeSub(path.indexOf('safe-mode') + 1) }),
];
case 'developer': return [ case 'developer': return [
item('dev:mode', t('wb.dev.mode'), undefined, { check: 'checkbox', checked: dev.enabled, keepOpen: true, run: async () => { await invoke('dev_set', { enabled: !dev.enabled }); await refreshDev(); } }), item('dev:mode', t('wb.dev.mode'), undefined, { check: 'checkbox', checked: dev.enabled, keepOpen: true, run: async () => { await invoke('dev_set', { enabled: !dev.enabled }); await refreshDev(); } }),
item('dev:folder', menuText('pluginsFolder'), 'folder', { run: () => invoke('plugins_open_folder') }), item('dev:folder', menuText('pluginsFolder'), 'folder', { run: () => invoke('plugins_open_folder') }),
@ -374,7 +384,7 @@ export function AppMenu() {
const groups = menu.groups ?? DEFAULT_MENU; const groups = menu.groups ?? DEFAULT_MENU;
const env: MenuEnv = { const env: MenuEnv = {
decks: !!config.deck, languages: !!menu.languages, themes: !!config.themes, modes: modeList.length > 0, decks: !!config.deck, languages: !!menu.languages, themes: !!config.themes, modes: modeList.length > 0,
zoom: hasFeature('zoom'), find: hasFeature('find'), store: hasFeature('store'), workspaces: hasFeature('workspaces'), developer: hasFeature('developer'), updates: hasFeature('updates'), zoom: hasFeature('zoom'), find: hasFeature('find'), safeMode: hasFeature('safeMode'), store: hasFeature('store'), workspaces: hasFeature('workspaces'), developer: hasFeature('developer'), updates: hasFeature('updates'),
}; };
const rootRows = () => joinGroups(planMenu(groups, env).map(group => group.flatMap(entry => (typeof entry === 'string' ? [builtin(entry)] : specRows([entry]))))); const rootRows = () => joinGroups(planMenu(groups, env).map(group => group.flatMap(entry => (typeof entry === 'string' ? [builtin(entry)] : specRows([entry])))));
const labelOf = (id: string, rows: MenuRow[]) => rows.find((row): row is MenuItemRow => row.kind === 'item' && row.id === id)?.label ?? ''; const labelOf = (id: string, rows: MenuRow[]) => rows.find((row): row is MenuItemRow => row.kind === 'item' && row.id === id)?.label ?? '';

View file

@ -31,9 +31,10 @@ import { NewTabPage } from './NewTabPage.tsx';
import type { PaletteAction, PaletteContext } from './paletteModel.ts'; import type { PaletteAction, PaletteContext } from './paletteModel.ts';
import { PaneThemeHost, openPaneTheme } from './PaneTheme.tsx'; import { PaneThemeHost, openPaneTheme } from './PaneTheme.tsx';
import { focusedCommands, installPluginCommands, notePanelActive, refreshPluginNames, runPluginCommand } from './pluginCommandStore.ts'; import { focusedCommands, installPluginCommands, notePanelActive, refreshPluginNames, runPluginCommand } from './pluginCommandStore.ts';
import { installSafeMode } from './safeStore.ts';
import { hasFeature, site } from './site.ts'; import { hasFeature, site } from './site.ts';
import { import {
flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction, flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, resync, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction,
type DeckParams, type PanelParams, type StartParams, type TabParams, type WebParams, type DeckParams, type PanelParams, type StartParams, type TabParams, type WebParams,
} from './state.ts'; } from './state.ts';
import { installSyncHost } from './syncHost.ts'; import { installSyncHost } from './syncHost.ts';
@ -590,6 +591,9 @@ export default function Shell() {
return () => off.forEach(dispose => dispose()); return () => off.forEach(dispose => dispose());
}, []); }, []);
// Safe mode for this run (the host's flag): the titlebar says so and the chrome drops its theme.
useEffect(() => (hasFeature('safeMode') ? installSafeMode() : undefined), []);
// The site's own settings and events (e.g. X's Twitter/X wording). // The site's own settings and events (e.g. X's Twitter/X wording).
useEffect(() => site().start?.(), []); useEffect(() => site().start?.(), []);
@ -636,6 +640,8 @@ export default function Shell() {
if (payload.beside && source) { openBeside(payload.url, source, !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); addWeb(payload.url, payload.from ? { referencePanel: payload.from, direction: 'within' } : undefined, !payload.background, profile);
}), }),
// Native code builds every tab webview anew (safe mode switched): it needs the layout again.
listen('tabs-rebuild', () => resync()),
listen<{ id: string; shortcut: string }>('tab-shortcut', ({ payload }) => runShortcut(payload.shortcut, payload.id)), listen<{ 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)), 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. // A tab's link drag: `start` carries the natively validated link, `enter` is an external drag.

View file

@ -10,6 +10,7 @@ import { useDev, usePaneTick, useSync, useT } from './hooks.ts';
import { formatNumber, t } from './i18n.ts'; import { formatNumber, t } from './i18n.ts';
import { Icon } from './icons.tsx'; import { Icon } from './icons.tsx';
import { menuText } from './menuModel.ts'; import { menuText } from './menuModel.ts';
import { safe, setSafeMode } from './safeStore.ts';
import { hasFeature } from './site.ts'; import { hasFeature } from './site.ts';
import { setOverlay, shell } from './state.ts'; import { setOverlay, shell } from './state.ts';
import { WORKSPACE_LIMITS } from './workspaceModel.ts'; import { WORKSPACE_LIMITS } from './workspaceModel.ts';
@ -45,6 +46,7 @@ export function TitlebarExtras() {
return () => { observer.disconnect(); document.documentElement.style.removeProperty('--bt-tb-extra'); }; return () => { observer.disconnect(); document.documentElement.style.removeProperty('--bt-tb-extra'); };
}, []); }, []);
return <div className="bt-tb-extras" ref={root}> return <div className="bt-tb-extras" ref={root}>
{hasFeature('safeMode') && <SafeChip/>}
{hasFeature('zoom') && <ZoomChip/>} {hasFeature('zoom') && <ZoomChip/>}
{hasFeature('sync') && <SyncChip/>} {hasFeature('sync') && <SyncChip/>}
{hasFeature('developer') && <DevChip/>} {hasFeature('developer') && <DevChip/>}
@ -52,6 +54,23 @@ export function TitlebarExtras() {
</div>; </div>;
} }
/** Safe mode: said in the titlebar for as long as it is on; one click leaves it (the tabs load again with the owner's setup). */
function SafeChip() {
useT();
const [, tick] = useState(0);
const [busy, setBusy] = useState(false);
useEffect(() => {
const update = () => tick(value => value + 1);
window.addEventListener('bt-safe', update);
return () => window.removeEventListener('bt-safe', update);
}, []);
if (!safe.active) return null;
return <button className="bt-tb-chip bt-safe-chip" title={menuText('safeChip')} aria-label={`${menuText('safe')}. ${menuText('safeLeave')}`} disabled={busy}
onClick={() => { setBusy(true); void setSafeMode(false).catch(() => {}).finally(() => setBusy(false)); }}>
<Icon name="shield"/><span className="bt-tb-chip-text">{menuText('safe')}</span><span className="bt-safe-leave">{menuText('safeLeaveShort')}</span>
</button>;
}
/** The page zoom of the pane in front, only while it is not 100% (Ctrl with + and - say nothing else); a click resets it. */ /** The page zoom of the pane in front, only while it is not 100% (Ctrl with + and - say nothing else); a click resets it. */
function ZoomChip() { function ZoomChip() {
useT(); useT();

View file

@ -90,3 +90,12 @@
/* The titlebar's zoom chip: only while the pane in front is not at 100% (TitlebarExtras.tsx). */ /* The titlebar's zoom chip: only while the pane in front is not at 100% (TitlebarExtras.tsx). */
.bt-zoom-chip { font-family: var(--bt-mono); font-size: 11.5px; font-variant-numeric: tabular-nums; } .bt-zoom-chip { font-family: var(--bt-mono); font-size: 11.5px; font-variant-numeric: tabular-nums; }
.bt-zoom-chip .bt-glyph { color: var(--bt-muted); } .bt-zoom-chip .bt-glyph { color: var(--bt-muted); }
/* Safe mode, said in the titlebar for as long as it is on (TitlebarExtras.tsx): amber, and one click leaves it. */
.bt-safe-chip { border-color: rgba(245, 158, 11, .38); background: rgba(245, 158, 11, .1); color: var(--bt-text); font-weight: 600; }
.bt-safe-chip:hover { border-color: rgba(245, 158, 11, .6); background: rgba(245, 158, 11, .16); }
.bt-safe-chip .bt-glyph { color: #f59e0b; }
.bt-safe-leave { margin-inline-start: 2px; padding-inline-start: 9px; border-inline-start: 1px solid rgba(245, 158, 11, .35); color: var(--bt-text-2); font-weight: 500; }
.bt-safe-chip:hover .bt-safe-leave { color: var(--bt-text); }
.bt-safe-chip:disabled { opacity: .6; cursor: default; }
.bt-app-sub .bt-app-note { max-width: 300px; }

View file

@ -51,6 +51,7 @@ export const ICONS = {
code: 'M9 8l-4 4 4 4M15 8l4 4-4 4', code: 'M9 8l-4 4 4 4M15 8l4 4-4 4',
folder: 'M4 7h6l2 2h8v10H4z', folder: 'M4 7h6l2 2h8v10H4z',
info: 'M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM12 11v5M12 8h.01', info: 'M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM12 11v5M12 8h.01',
shield: 'M12 3l7 3v5.5c0 4.2-2.9 7.9-7 9.5-4.1-1.6-7-5.3-7-9.5V6z',
} as const; } as const;
export type IconName = keyof typeof ICONS; export type IconName = keyof typeof ICONS;

View file

@ -36,5 +36,13 @@
"wb.menu.updateInstalling": "Installing {version}…", "wb.menu.updateInstalling": "Installing {version}…",
"wb.menu.updateRestart": "Restart to update", "wb.menu.updateRestart": "Restart to update",
"wb.menu.updateFailed": "Could not check", "wb.menu.updateFailed": "Could not check",
"wb.menu.updateFailedHint": "The update server did not answer. Nothing is wrong with the app; it checks again later on its own." "wb.menu.updateFailedHint": "The update server did not answer. Nothing is wrong with the app; it checks again later on its own.",
"wb.menu.safe": "Safe mode",
"wb.menu.safeRestart": "Restart in safe mode…",
"wb.menu.safeQuestion": "Restart the tabs in safe mode?",
"wb.menu.safeExplain": "Every tab loads again with plugins, themes, custom CSS and page features off, for this run only. Your setup is back the next time you start the app.",
"wb.menu.safeConfirm": "Restart tabs in safe mode",
"wb.menu.safeLeave": "Leave safe mode",
"wb.menu.safeLeaveShort": "Leave",
"wb.menu.safeChip": "Safe mode is on: plugins, themes, custom CSS and page features are off for this run. Click to leave; the tabs load again with your setup."
} }

View file

@ -36,7 +36,7 @@ export const MENU_BUILTINS = [
'zoom', 'zoom',
'plugins', 'store', 'workspaces', 'plugins', 'store', 'workspaces',
'find', 'shortcuts', 'palette', 'find', 'shortcuts', 'palette',
'developer', 'updates', 'about', 'settings', 'developer', 'updates', 'safe-mode', 'about', 'settings',
] as const; ] as const;
export type BuiltinMenuItem = typeof MENU_BUILTINS[number]; export type BuiltinMenuItem = typeof MENU_BUILTINS[number];
@ -110,7 +110,7 @@ export const DEFAULT_MENU: MenuGroups = [
['zoom'], ['zoom'],
['plugins', 'store', 'workspaces'], ['plugins', 'store', 'workspaces'],
['find', 'shortcuts', 'palette'], ['find', 'shortcuts', 'palette'],
['developer', 'updates', 'about', 'settings'], ['developer', 'updates', 'safe-mode', 'about', 'settings'],
]; ];
const entryId = (entry: MenuEntry) => (typeof entry === 'string' ? entry : entry.id); const entryId = (entry: MenuEntry) => (typeof entry === 'string' ? entry : entry.id);
@ -146,6 +146,8 @@ export type MenuEnv = {
/** `features`: native page zoom (`tab_zoom`), find in page (`tab_find`), the Store, workspaces, developer mode, the updater. */ /** `features`: native page zoom (`tab_zoom`), find in page (`tab_find`), the Store, workspaces, developer mode, the updater. */
zoom: boolean; zoom: boolean;
find: boolean; find: boolean;
/** `features.safeMode`: safe mode for one run (`safe_mode_get/set`, the host's own). */
safeMode: boolean;
store: boolean; store: boolean;
workspaces: boolean; workspaces: boolean;
developer: boolean; developer: boolean;
@ -161,6 +163,7 @@ export function builtinAvailable(id: BuiltinMenuItem, env: MenuEnv): boolean {
case 'mode': return env.modes; case 'mode': return env.modes;
case 'zoom': return env.zoom; case 'zoom': return env.zoom;
case 'find': return env.find; case 'find': return env.find;
case 'safe-mode': return env.safeMode;
case 'store': return env.store; case 'store': return env.store;
case 'workspaces': return env.workspaces; case 'workspaces': return env.workspaces;
case 'developer': return env.developer; case 'developer': return env.developer;

View file

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

View file

@ -147,11 +147,11 @@ export type ShellSite = {
/** /**
* Native features the app serves (waybetter-host modules it wires up): workspaces (`workspaces_*`), * Native features the app serves (waybetter-host modules it wires up): workspaces (`workspaces_*`),
* encrypted folder sync (`sync_*`), developer mode (`dev_*`), plugin palette commands * encrypted folder sync (`sync_*`), developer mode (`dev_*`), plugin palette commands
* (`tab_run_command`), page zoom and find in page (`tab_zoom`, `tab_find`: the host's own); and what its panel has that the * (`tab_run_command`), page zoom, find in page and safe mode (`tab_zoom`, `tab_find`, `safe_mode_*`: the host's own); and what its panel has that the
* app menu links to: the Store (`PanelSite.store`) and the updater (`PanelSite.updates`). Each is * app menu links to: the Store (`PanelSite.store`) and the updater (`PanelSite.updates`). Each is
* on unless set to false; off, the frame shows nothing of it. * on unless set to false; off, the frame shows nothing of it.
*/ */
features?: { workspaces?: boolean; sync?: boolean; developer?: boolean; pluginCommands?: boolean; zoom?: boolean; find?: boolean; store?: boolean; updates?: boolean }; features?: { workspaces?: boolean; sync?: boolean; developer?: boolean; pluginCommands?: boolean; zoom?: boolean; find?: boolean; safeMode?: boolean; store?: boolean; updates?: boolean };
/** /**
* The app menu (the titlebar's "Settings and more", Alt+F / F10): its rows in order (built-in * The app menu (the titlebar's "Settings and more", Alt+F / F10): its rows in order (built-in
* ones by name, the app's own as objects) and what the Language and Mode submenus need. Omit for * ones by name, the app's own as objects) and what the Language and Mode submenus need. Omit for

View file

@ -102,6 +102,12 @@ export function scheduleSync() {
frame = requestAnimationFrame(() => { frame = 0; void syncTabs(); }); frame = requestAnimationFrame(() => { frame = 0; void syncTabs(); });
} }
/** Sends the layout again even though nothing moved: native code asked to build every tab webview anew (`tabs-rebuild`). */
export function resync() {
lastPayload = '';
scheduleSync();
}
/** Sends the tab rectangles now (e.g. so native code knows closed tabs are gone before a profile removal). */ /** Sends the tab rectangles now (e.g. so native code knows closed tabs are gone before a profile removal). */
export function flushSync(): Promise<void> { export function flushSync(): Promise<void> {
if (frame) { cancelAnimationFrame(frame); frame = 0; } if (frame) { cancelAnimationFrame(frame); frame = 0; }

View file

@ -10,6 +10,7 @@ import { BOOT_CACHE_KEY } from './boot.ts';
import { invoke } from './bridge.ts'; import { invoke } from './bridge.ts';
import { CHROME_VAR_NAMES, chromeVars, type ChromeTheme } from './chromeTheme.ts'; import { CHROME_VAR_NAMES, chromeVars, type ChromeTheme } from './chromeTheme.ts';
import { SCOPES_DEFAULT, normalizeScopes, prunePanes, themeIdFor, type ScopeSource, type ThemeScopes } from './themeScopes.ts'; import { SCOPES_DEFAULT, normalizeScopes, prunePanes, themeIdFor, type ScopeSource, type ThemeScopes } from './themeScopes.ts';
import { safe } from './safeStore.ts';
import { shell, type TabParams } from './state.ts'; import { shell, type TabParams } from './state.ts';
export type Weights = { kind: 'range'; min: number; max: number } | { kind: 'list'; values: number[] }; export type Weights = { kind: 'range'; min: number; max: number } | { kind: 'list'; values: number[] };
@ -193,7 +194,11 @@ export function createThemeStore<Choice, Spec extends ThemeDoc>(adapter: ThemeAd
/** The chrome follows the global theme (or the editor's draft); panes with their own theme follow theirs. */ /** The chrome follows the global theme (or the editor's draft); panes with their own theme follow theirs. */
function applyChrome() { function applyChrome() {
if (typeof document === 'undefined' || !state.ready) return; if (typeof document === 'undefined') return;
// Safe mode: the frame's own look, whatever the theme (a theme may be what broke the chrome). The
// first-frame cache is left alone, so the next normal start paints the owner's theme again.
if (safe.active) { setVars(document.documentElement, {}); syncGroups(); return; }
if (!state.ready) return;
const own = state.scopes.chrome === 'own'; const own = state.scopes.chrome === 'own';
const global = state.preview ?? adapter.resolve(state.choice); const global = state.preview ?? adapter.resolve(state.choice);
chromeFontsFor(global); chromeFontsFor(global);
@ -213,7 +218,7 @@ export function createThemeStore<Choice, Spec extends ThemeDoc>(adapter: ThemeAd
for (const group of api.groups) { for (const group of api.groups) {
const params = group.activePanel?.params as TabParams | undefined; const params = group.activePanel?.params as TabParams | undefined;
const tab = params && (params.kind === 'web' || params.kind === 'start') ? { id: params.kind === 'web' ? group.activePanel!.id : undefined, profile: params.profile ?? 'default' } : null; const tab = params && (params.kind === 'web' || params.kind === 'start') ? { id: params.kind === 'web' ? group.activePanel!.id : undefined, profile: params.profile ?? 'default' } : null;
const scoped = !own && !state.preview && tab ? tabTheme(tab) : null; const scoped = !own && !safe.active && !state.preview && tab ? tabTheme(tab) : null;
const element = group.element; const element = group.element;
if (scoped && scoped.source !== 'global') { if (scoped && scoped.source !== 'global') {
chromeFontsFor(scoped.theme); chromeFontsFor(scoped.theme);
@ -228,6 +233,9 @@ export function createThemeStore<Choice, Spec extends ThemeDoc>(adapter: ThemeAd
} }
} }
// Safe mode switched: the chrome drops (or takes back) the theme at once.
if (typeof window !== 'undefined') window.addEventListener('bt-safe', applyChrome);
/** Shell.tsx hands over the dock once it exists: pane chrome follows focus and layout changes. */ /** Shell.tsx hands over the dock once it exists: pane chrome follows focus and layout changes. */
function attachDock(api: DockviewApi) { function attachDock(api: DockviewApi) {
dock = api; dock = api;

View file

@ -15,8 +15,8 @@ import {
import { buildItems } from '../src/frame/paletteModel.ts'; import { buildItems } from '../src/frame/paletteModel.ts';
const here = dirname(fileURLToPath(import.meta.url)); const here = dirname(fileURLToPath(import.meta.url));
const ALL: MenuEnv = { decks: true, languages: true, themes: true, modes: true, zoom: true, find: true, store: true, workspaces: true, developer: true, updates: true }; const ALL: MenuEnv = { decks: true, languages: true, themes: true, modes: true, zoom: true, find: true, safeMode: true, store: true, workspaces: true, developer: true, updates: true };
const NONE: MenuEnv = { decks: false, languages: false, themes: false, modes: false, zoom: false, find: false, store: false, workspaces: false, developer: false, updates: false }; const NONE: MenuEnv = { decks: false, languages: false, themes: false, modes: false, zoom: false, find: false, safeMode: false, store: false, workspaces: false, developer: false, updates: false };
const ids = (groups: ReturnType<typeof planMenu>) => groups.map(group => group.map(entry => (typeof entry === 'string' ? entry : entry.id))); const ids = (groups: ReturnType<typeof planMenu>) => groups.map(group => group.map(entry => (typeof entry === 'string' ? entry : entry.id)));
const items = (rows: MenuRow[]) => rows.filter((row): row is MenuItemRow => row.kind === 'item'); const items = (rows: MenuRow[]) => rows.filter((row): row is MenuItemRow => row.kind === 'item');
@ -35,7 +35,7 @@ test('a row the app cannot serve is left out, and a group left empty takes its r
]); ]);
// Each gate is its own. // Each gate is its own.
const gates: Array<[keyof MenuEnv, string]> = [ const gates: Array<[keyof MenuEnv, string]> = [
['decks', 'new-column'], ['languages', 'language'], ['themes', 'theme'], ['modes', 'mode'], ['zoom', 'zoom'], ['find', 'find'], ['decks', 'new-column'], ['languages', 'language'], ['themes', 'theme'], ['modes', 'mode'], ['zoom', 'zoom'], ['find', 'find'], ['safeMode', 'safe-mode'],
['store', 'store'], ['workspaces', 'workspaces'], ['developer', 'developer'], ['updates', 'updates'], ['store', 'store'], ['workspaces', 'workspaces'], ['developer', 'developer'], ['updates', 'updates'],
]; ];
for (const [feature, row] of gates) { for (const [feature, row] of gates) {
@ -63,7 +63,7 @@ test('an app orders, removes and adds rows; its own rows follow their `when`', (
assert.equal(ids(planMenu(groups, ALL)).flat().includes('drafts'), false); assert.equal(ids(planMenu(groups, ALL)).flat().includes('drafts'), false);
drafts = true; drafts = true;
assert.deepEqual(ids(planMenu(menuWithout(groups, 'store', 'zoom', 'drafts'), ALL)), [ assert.deepEqual(ids(planMenu(menuWithout(groups, 'store', 'zoom', 'drafts'), ALL)), [
['new-tab', 'split-right', 'split-down', 'new-column'], ['language', 'theme', 'mode'], ['plugins', 'workspaces'], ['find', 'shortcuts', 'palette'], ['developer', 'updates', 'about', 'settings'], ['new-tab', 'split-right', 'split-down', 'new-column'], ['language', 'theme', 'mode'], ['plugins', 'workspaces'], ['find', 'shortcuts', 'palette'], ['developer', 'updates', 'safe-mode', 'about', 'settings'],
]); ]);
// Explicit order; a row listed twice shows once; an unknown name and an own row named like a built-in are ignored. // Explicit order; a row listed twice shows once; an unknown name and an own row named like a built-in are ignored.
const custom: MenuGroups = [['settings', 'new-tab', 'settings', 'nope' as never], [{ id: 'zoom', label: () => 'Fake zoom' }, own]]; const custom: MenuGroups = [['settings', 'new-tab', 'settings', 'nope' as never], [{ id: 'zoom', label: () => 'Fake zoom' }, own]];