Native menu bar (macOS): the shell describes it (menu_set, shell-only), host validates and builds it, a chosen id goes back to the shell (native-menu); App/File/Edit/View/Account/Plugins/Window/Help from the in-app menu's state, words wb.menu.*
This commit is contained in:
parent
d7903e80ce
commit
4c957df89c
12 changed files with 813 additions and 1 deletions
|
|
@ -729,6 +729,24 @@ 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())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sets the native menu bar (macOS) from the shell's description ([`crate::menu`]); other platforms keep the
|
||||||
|
/// in-app menu and answer false. Choosing an item sends its id to the shell (`native-menu`).
|
||||||
|
#[tauri::command]
|
||||||
|
async fn menu_set(webview: Webview, app: AppHandle, spec: serde_json::Value) -> Result<bool, String> {
|
||||||
|
shell_only(&webview)?;
|
||||||
|
let spec = crate::menu::parse(spec)?;
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
crate::menu::set(&app, &spec)?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
{
|
||||||
|
let _ = (app, spec);
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether safe mode is on ([`crate::safe`]): the shell shows it in the titlebar and drops its chrome theme.
|
/// Whether safe mode is on ([`crate::safe`]): the shell shows it in the titlebar and drops its chrome theme.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn safe_mode_get(webview: Webview) -> Result<crate::safe::SafeState, String> {
|
async fn safe_mode_get(webview: Webview) -> Result<crate::safe::SafeState, String> {
|
||||||
|
|
@ -1236,6 +1254,7 @@ 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,
|
||||||
|
menu_set,
|
||||||
safe_mode_get,
|
safe_mode_get,
|
||||||
safe_mode_set,
|
safe_mode_set,
|
||||||
diag_get,
|
diag_get,
|
||||||
|
|
@ -1380,6 +1399,15 @@ impl App {
|
||||||
let vault_handler = vault_handler();
|
let vault_handler = vault_handler();
|
||||||
let backup_handler = backup_handler();
|
let backup_handler = backup_handler();
|
||||||
let builder = tauri::Builder::<Wry>::default()
|
let builder = tauri::Builder::<Wry>::default()
|
||||||
|
// The native menu bar's choices go to the shell, which runs them ([`crate::menu`]).
|
||||||
|
.on_menu_event(|app, event| {
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
if let Some(id) = crate::menu::chosen(event.id().as_ref()) {
|
||||||
|
emit_shell(app, crate::menu::EVENT_NATIVE_MENU, id.to_owned());
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
let _ = (app, event);
|
||||||
|
})
|
||||||
// Must be first: a second launch focuses the running window instead of fighting over
|
// 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).
|
// the app's data and WebView profile (and hands over its link).
|
||||||
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ pub const SHELL: &[&str] = &[
|
||||||
"tab_action",
|
"tab_action",
|
||||||
"tab_zoom",
|
"tab_zoom",
|
||||||
"tab_find",
|
"tab_find",
|
||||||
|
"menu_set",
|
||||||
"safe_mode_get",
|
"safe_mode_get",
|
||||||
"safe_mode_set",
|
"safe_mode_set",
|
||||||
"diag_get",
|
"diag_get",
|
||||||
|
|
|
||||||
|
|
@ -63,6 +63,7 @@ pub mod hotfix;
|
||||||
pub mod i18n;
|
pub mod i18n;
|
||||||
pub mod layout;
|
pub mod layout;
|
||||||
pub mod media;
|
pub mod media;
|
||||||
|
pub mod menu;
|
||||||
pub mod modes;
|
pub mod modes;
|
||||||
pub mod plugins;
|
pub mod plugins;
|
||||||
pub mod popover;
|
pub mod popover;
|
||||||
|
|
|
||||||
255
crates/waybetter-host/src/menu.rs
Normal file
255
crates/waybetter-host/src/menu.rs
Normal file
|
|
@ -0,0 +1,255 @@
|
||||||
|
//! The native menu bar (macOS): the shell describes the whole bar (`menu_set`, shell-only) and
|
||||||
|
//! native code builds it; choosing an item sends its id back to the shell (`native-menu` event),
|
||||||
|
//! which runs the same actions the in-app menu does. Nothing here performs an action itself, and
|
||||||
|
//! tabs gain no command: the bar is the shell's alone.
|
||||||
|
//!
|
||||||
|
//! The description is data and is validated before anything is built: bounded depth and size,
|
||||||
|
//! one-line labels, ids of a fixed alphabet, accelerators of a fixed alphabet, and system items
|
||||||
|
//! (Services, Hide, Quit, Edit's Cut/Copy/Paste, Window's Minimize/Zoom) only by name from a fixed
|
||||||
|
//! list. Other platforms keep the in-app menu: `menu_set` does nothing there.
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
/// The shell event carrying the id of the chosen item.
|
||||||
|
pub const EVENT_NATIVE_MENU: &str = "native-menu";
|
||||||
|
|
||||||
|
const MAX_NODES: usize = 400;
|
||||||
|
const MAX_DEPTH: usize = 4;
|
||||||
|
const MAX_LABEL: usize = 120;
|
||||||
|
const MAX_ID: usize = 96;
|
||||||
|
const MAX_ACCELERATOR: usize = 32;
|
||||||
|
|
||||||
|
/// System items the shell may ask for by name.
|
||||||
|
pub const ROLES: &[&str] = &[
|
||||||
|
"services", "hide", "hide_others", "show_all", "quit", "undo", "redo", "cut", "copy", "paste", "select_all", "minimize", "maximize", "fullscreen",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// A submenu the system treats specially (macOS lists the open windows in the Window menu, adds the
|
||||||
|
/// search field to Help).
|
||||||
|
pub const SUBMENU_ROLES: &[&str] = &["window", "help"];
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
|
||||||
|
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub enum Node {
|
||||||
|
/// An item the shell handles: its id comes back when it is chosen. `checked` makes it a check item.
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
Item { id: String, label: String, #[serde(default)] accelerator: Option<String>, #[serde(default)] checked: Option<bool>, #[serde(default = "yes")] enabled: bool },
|
||||||
|
Separator,
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
Submenu { label: String, items: Vec<Node>, #[serde(default = "yes")] enabled: bool, #[serde(default)] role: Option<String> },
|
||||||
|
/// A system item by name ([`ROLES`]); `label` overrides its title.
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
Predefined { role: String, #[serde(default)] label: Option<String> },
|
||||||
|
}
|
||||||
|
|
||||||
|
fn yes() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole bar: top-level submenus only.
|
||||||
|
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct MenuSpec {
|
||||||
|
pub menus: Vec<Node>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_label(text: &str) -> bool {
|
||||||
|
let count = text.chars().count();
|
||||||
|
count > 0 && count <= MAX_LABEL && !text.chars().any(char::is_control)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ids are ASCII words (`theme:midnight`, `plugin.chat`, `file/new-tab`).
|
||||||
|
pub fn valid_id(id: &str) -> bool {
|
||||||
|
!id.is_empty() && id.len() <= MAX_ID && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-' | '/'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accelerators like `CmdOrCtrl+Shift+G`: words, `+` and one key (a letter, digit or punctuation mark).
|
||||||
|
fn valid_accelerator(text: &str) -> bool {
|
||||||
|
!text.is_empty() && text.len() <= MAX_ACCELERATOR && text.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '\\' | '[' | ']' | ',' | '.' | ';' | '\'' | '=' | '-' | '`' | '/'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates a description before anything is built.
|
||||||
|
pub fn validate(spec: &MenuSpec) -> Result<(), String> {
|
||||||
|
fn walk(nodes: &[Node], depth: usize, count: &mut usize) -> Result<(), String> {
|
||||||
|
if depth > MAX_DEPTH {
|
||||||
|
return Err("VALIDATION: menu too deep".into());
|
||||||
|
}
|
||||||
|
for node in nodes {
|
||||||
|
*count += 1;
|
||||||
|
if *count > MAX_NODES {
|
||||||
|
return Err("VALIDATION: menu too large".into());
|
||||||
|
}
|
||||||
|
match node {
|
||||||
|
Node::Item { id, label, accelerator, .. } => {
|
||||||
|
if !valid_id(id) || !valid_label(label) || accelerator.as_deref().is_some_and(|text| !valid_accelerator(text)) {
|
||||||
|
return Err("VALIDATION: invalid menu item".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Separator => {}
|
||||||
|
Node::Submenu { label, items, role, .. } => {
|
||||||
|
if !valid_label(label) || role.as_deref().is_some_and(|role| !SUBMENU_ROLES.contains(&role)) {
|
||||||
|
return Err("VALIDATION: invalid submenu".into());
|
||||||
|
}
|
||||||
|
walk(items, depth + 1, count)?;
|
||||||
|
}
|
||||||
|
Node::Predefined { role, label } => {
|
||||||
|
if !ROLES.contains(&role.as_str()) || label.as_deref().is_some_and(|text| !valid_label(text)) {
|
||||||
|
return Err("VALIDATION: invalid system item".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
if spec.menus.is_empty() || spec.menus.iter().any(|node| !matches!(node, Node::Submenu { .. })) {
|
||||||
|
return Err("VALIDATION: the bar is a list of menus".into());
|
||||||
|
}
|
||||||
|
walk(&spec.menus, 0, &mut 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses and validates the shell's JSON description.
|
||||||
|
pub fn parse(value: serde_json::Value) -> Result<MenuSpec, String> {
|
||||||
|
let spec: MenuSpec = serde_json::from_value(value).map_err(|_| "VALIDATION: invalid menu".to_string())?;
|
||||||
|
validate(&spec)?;
|
||||||
|
Ok(spec)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(feature = "tauri", target_os = "macos"))]
|
||||||
|
pub use build::set;
|
||||||
|
|
||||||
|
#[cfg(all(feature = "tauri", target_os = "macos"))]
|
||||||
|
mod build {
|
||||||
|
use super::{valid_id, Node};
|
||||||
|
use tauri::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
|
||||||
|
use tauri::{AppHandle, Runtime};
|
||||||
|
|
||||||
|
fn append<R: Runtime>(app: &AppHandle<R>, menu: &Submenu<R>, nodes: &[Node]) -> tauri::Result<()> {
|
||||||
|
for node in nodes {
|
||||||
|
let item: Box<dyn IsMenuItem<R>> = match node {
|
||||||
|
Node::Item { id, label, accelerator, checked, enabled } => {
|
||||||
|
// An accelerator the platform cannot parse leaves the item without a key, not without an item.
|
||||||
|
let key = accelerator.as_deref();
|
||||||
|
match checked {
|
||||||
|
Some(state) => Box::new(CheckMenuItem::with_id(app, id.as_str(), label, *enabled, *state, key).or_else(|_| CheckMenuItem::with_id(app, id.as_str(), label, *enabled, *state, None::<&str>))?),
|
||||||
|
None => Box::new(MenuItem::with_id(app, id.as_str(), label, *enabled, key).or_else(|_| MenuItem::with_id(app, id.as_str(), label, *enabled, None::<&str>))?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Separator => Box::new(PredefinedMenuItem::separator(app)?),
|
||||||
|
Node::Submenu { label, items, enabled, role } => {
|
||||||
|
let sub = Submenu::new(app, label, *enabled)?;
|
||||||
|
append(app, &sub, items)?;
|
||||||
|
match role.as_deref() {
|
||||||
|
Some("window") => sub.set_as_windows_menu_for_nsapp()?,
|
||||||
|
Some("help") => sub.set_as_help_menu_for_nsapp()?,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Box::new(sub)
|
||||||
|
}
|
||||||
|
Node::Predefined { role, label } => {
|
||||||
|
let text = label.as_deref();
|
||||||
|
Box::new(match role.as_str() {
|
||||||
|
"services" => PredefinedMenuItem::services(app, text)?,
|
||||||
|
"hide" => PredefinedMenuItem::hide(app, text)?,
|
||||||
|
"hide_others" => PredefinedMenuItem::hide_others(app, text)?,
|
||||||
|
"show_all" => PredefinedMenuItem::show_all(app, text)?,
|
||||||
|
"quit" => PredefinedMenuItem::quit(app, text)?,
|
||||||
|
"undo" => PredefinedMenuItem::undo(app, text)?,
|
||||||
|
"redo" => PredefinedMenuItem::redo(app, text)?,
|
||||||
|
"cut" => PredefinedMenuItem::cut(app, text)?,
|
||||||
|
"copy" => PredefinedMenuItem::copy(app, text)?,
|
||||||
|
"paste" => PredefinedMenuItem::paste(app, text)?,
|
||||||
|
"select_all" => PredefinedMenuItem::select_all(app, text)?,
|
||||||
|
"minimize" => PredefinedMenuItem::minimize(app, text)?,
|
||||||
|
"maximize" => PredefinedMenuItem::maximize(app, text)?,
|
||||||
|
_ => PredefinedMenuItem::fullscreen(app, text)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
};
|
||||||
|
menu.append(item.as_ref())?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the bar and makes it the application's menu (on the main thread).
|
||||||
|
pub fn set<R: Runtime>(app: &AppHandle<R>, spec: &super::MenuSpec) -> Result<(), String> {
|
||||||
|
let spec = spec.clone();
|
||||||
|
let handle = app.clone();
|
||||||
|
app.run_on_main_thread(move || {
|
||||||
|
let build = || -> tauri::Result<Menu<R>> {
|
||||||
|
let menu = Menu::new(&handle)?;
|
||||||
|
for node in &spec.menus {
|
||||||
|
if let Node::Submenu { label, items, enabled, role } = node {
|
||||||
|
let top = Submenu::new(&handle, label, *enabled)?;
|
||||||
|
append(&handle, &top, items)?;
|
||||||
|
match role.as_deref() {
|
||||||
|
Some("window") => top.set_as_windows_menu_for_nsapp()?,
|
||||||
|
Some("help") => top.set_as_help_menu_for_nsapp()?,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
menu.append(&top)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(menu)
|
||||||
|
};
|
||||||
|
if let Ok(menu) = build() {
|
||||||
|
let _ = handle.set_menu(menu);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map_err(|error| format!("MENU: {error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The id of a chosen item when it is one the shell described.
|
||||||
|
pub fn chosen(id: &str) -> Option<&str> {
|
||||||
|
valid_id(id).then_some(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(feature = "tauri", target_os = "macos"))]
|
||||||
|
pub use build::chosen;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn bar(items: serde_json::Value) -> serde_json::Value {
|
||||||
|
json!({ "menus": [{ "kind": "submenu", "label": "File", "items": items }] })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bar_of_items_submenus_and_system_items_is_accepted() {
|
||||||
|
let value = json!({ "menus": [
|
||||||
|
{ "kind": "submenu", "label": "App", "items": [
|
||||||
|
{ "kind": "item", "id": "settings", "label": "Settings…", "accelerator": "CmdOrCtrl+," },
|
||||||
|
{ "kind": "separator" },
|
||||||
|
{ "kind": "predefined", "role": "services" },
|
||||||
|
{ "kind": "predefined", "role": "quit" } ] },
|
||||||
|
{ "kind": "submenu", "label": "View", "items": [
|
||||||
|
{ "kind": "submenu", "label": "Theme", "items": [ { "kind": "item", "id": "theme:midnight", "label": "Midnight", "checked": true } ] } ] },
|
||||||
|
{ "kind": "submenu", "label": "Window", "role": "window", "items": [ { "kind": "predefined", "role": "minimize" } ] },
|
||||||
|
] });
|
||||||
|
let spec = parse(value).unwrap();
|
||||||
|
assert_eq!(spec.menus.len(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_description_is_bounded_and_made_of_known_things() {
|
||||||
|
assert!(parse(json!({ "menus": [] })).is_err(), "an empty bar");
|
||||||
|
assert!(parse(json!({ "menus": [{ "kind": "item", "id": "a", "label": "A" }] })).is_err(), "the bar holds menus only");
|
||||||
|
assert!(parse(bar(json!([{ "kind": "item", "id": "bad id", "label": "A" }]))).is_err(), "ids are words");
|
||||||
|
assert!(parse(bar(json!([{ "kind": "item", "id": "a", "label": "two\nlines" }]))).is_err(), "labels are one line");
|
||||||
|
assert!(parse(bar(json!([{ "kind": "item", "id": "a", "label": "" }]))).is_err());
|
||||||
|
assert!(parse(bar(json!([{ "kind": "item", "id": "a", "label": "A", "accelerator": "Cmd+<script>" }]))).is_err());
|
||||||
|
assert!(parse(bar(json!([{ "kind": "predefined", "role": "close_window" }]))).is_err(), "system items by name from the list only");
|
||||||
|
assert!(parse(bar(json!([{ "kind": "item", "id": "a", "label": "A", "extra": 1 }]))).is_err(), "no unknown fields");
|
||||||
|
assert!(parse(json!({ "menus": [{ "kind": "submenu", "label": "W", "role": "dock", "items": [] }] })).is_err());
|
||||||
|
let too_many: Vec<_> = (0..MAX_NODES + 1).map(|n| json!({ "kind": "item", "id": format!("i{n}"), "label": "x" })).collect();
|
||||||
|
assert!(parse(bar(json!(too_many))).is_err(), "size");
|
||||||
|
let mut deep = json!([{ "kind": "item", "id": "a", "label": "A" }]);
|
||||||
|
for _ in 0..MAX_DEPTH + 1 {
|
||||||
|
deep = json!([{ "kind": "submenu", "label": "S", "items": deep }]);
|
||||||
|
}
|
||||||
|
assert!(parse(bar(deep)).is_err(), "depth");
|
||||||
|
assert!(parse(bar(json!([{ "kind": "item", "id": "a".repeat(MAX_ID + 1), "label": "A" }]))).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -47,6 +47,9 @@ export type AppMenuRequest = { anchor?: AppMenuTrigger; pane?: string; submenu?:
|
||||||
/** Opens the app menu (Alt+F / F10, the palette, the account menu's last row). */
|
/** Opens the app menu (Alt+F / F10, the palette, the account menu's last row). */
|
||||||
export const openAppMenu = (request: AppMenuRequest = {}) => window.dispatchEvent(new CustomEvent('bt-app-menu', { detail: request }));
|
export const openAppMenu = (request: AppMenuRequest = {}) => window.dispatchEvent(new CustomEvent('bt-app-menu', { detail: request }));
|
||||||
|
|
||||||
|
/** Opens the "Report a problem" summary (the native menu bar's Help item). */
|
||||||
|
export const openReport = () => window.dispatchEvent(new CustomEvent('bt-report'));
|
||||||
|
|
||||||
const mac = os === 'macos';
|
const mac = os === 'macos';
|
||||||
/** The keys that open the menu, as the button's tooltip and the account menu write them. */
|
/** The keys that open the menu, as the button's tooltip and the account menu write them. */
|
||||||
export const APP_MENU_KEYS = mac ? 'F10' : 'Alt+F';
|
export const APP_MENU_KEYS = mac ? 'F10' : 'Alt+F';
|
||||||
|
|
@ -224,6 +227,12 @@ export function AppMenu({ trigger }: { trigger?: AppMenuTrigger | boolean } = {}
|
||||||
return () => window.removeEventListener('bt-app-menu', onRequest);
|
return () => window.removeEventListener('bt-app-menu', onRequest);
|
||||||
}, [version]);
|
}, [version]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const show = () => setReporting(true);
|
||||||
|
window.addEventListener('bt-report', show);
|
||||||
|
return () => window.removeEventListener('bt-report', show);
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
// Native tab webviews would cover the menu.
|
// Native tab webviews would cover the menu.
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,7 @@ 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 { initDiag } from './diag.ts';
|
import { initDiag } from './diag.ts';
|
||||||
import { installSafeMode } from './safeStore.ts';
|
import { installSafeMode } from './safeStore.ts';
|
||||||
|
import { startNativeMenu } from './nativeMenu.ts';
|
||||||
import { hasFeature, site } from './site.ts';
|
import { hasFeature, site } from './site.ts';
|
||||||
import {
|
import {
|
||||||
flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, resync, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction,
|
flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, resync, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction,
|
||||||
|
|
@ -621,6 +622,8 @@ export default function Shell() {
|
||||||
|
|
||||||
// Safe mode for this run (the host's flag): the titlebar says so and the chrome drops its theme.
|
// Safe mode for this run (the host's flag): the titlebar says so and the chrome drops its theme.
|
||||||
useEffect(() => (hasFeature('safeMode') ? installSafeMode() : undefined), []);
|
useEffect(() => (hasFeature('safeMode') ? installSafeMode() : undefined), []);
|
||||||
|
// The native menu bar (macOS only; nativeMenu.ts): described from the state the in-app menu reads.
|
||||||
|
useEffect(() => startNativeMenu(), []);
|
||||||
|
|
||||||
// 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?.(), []);
|
||||||
|
|
|
||||||
|
|
@ -50,5 +50,47 @@
|
||||||
"wb.menu.reportLede": "This is everything the report contains: versions and what is switched on. No account, no address, nothing from the pages you have open. Copy it, then paste it into your report.",
|
"wb.menu.reportLede": "This is everything the report contains: versions and what is switched on. No account, no address, nothing from the pages you have open. Copy it, then paste it into your report.",
|
||||||
"wb.menu.reportOpen": "Open the issue page",
|
"wb.menu.reportOpen": "Open the issue page",
|
||||||
"wb.menu.reportNoPage": "This app has no public issue page yet. Copy the text and send it to the developer.",
|
"wb.menu.reportNoPage": "This app has no public issue page yet. Copy the text and send it to the developer.",
|
||||||
"wb.menu.strings": "Languages"
|
"wb.menu.strings": "Languages",
|
||||||
|
"wb.menu.barFile": "File",
|
||||||
|
"wb.menu.barEdit": "Edit",
|
||||||
|
"wb.menu.barView": "View",
|
||||||
|
"wb.menu.barAccount": "Account",
|
||||||
|
"wb.menu.barPlugins": "Plugins",
|
||||||
|
"wb.menu.barWindow": "Window",
|
||||||
|
"wb.menu.barHelp": "Help",
|
||||||
|
"wb.menu.appHide": "Hide {product}",
|
||||||
|
"wb.menu.appHideOthers": "Hide Others",
|
||||||
|
"wb.menu.appShowAll": "Show All",
|
||||||
|
"wb.menu.appQuit": "Quit {product}",
|
||||||
|
"wb.menu.appServices": "Services",
|
||||||
|
"wb.menu.appUpdates": "Check for Updates…",
|
||||||
|
"wb.menu.appSettings": "Settings…",
|
||||||
|
"wb.menu.appSafe": "Safe Mode",
|
||||||
|
"wb.menu.fileClose": "Close Tab",
|
||||||
|
"wb.menu.fileInstall": "Install from File…",
|
||||||
|
"wb.menu.fileShare": "Share My Setup…",
|
||||||
|
"wb.menu.editUndo": "Undo",
|
||||||
|
"wb.menu.editRedo": "Redo",
|
||||||
|
"wb.menu.editCut": "Cut",
|
||||||
|
"wb.menu.editCopy": "Copy",
|
||||||
|
"wb.menu.editPaste": "Paste",
|
||||||
|
"wb.menu.editSelectAll": "Select All",
|
||||||
|
"wb.menu.editFind": "Find…",
|
||||||
|
"wb.menu.editFindNext": "Find Next",
|
||||||
|
"wb.menu.editFindPrevious": "Find Previous",
|
||||||
|
"wb.menu.viewZoomIn": "Zoom In",
|
||||||
|
"wb.menu.viewZoomOut": "Zoom Out",
|
||||||
|
"wb.menu.viewActual": "Actual Size",
|
||||||
|
"wb.menu.viewIconPack": "Icon Pack",
|
||||||
|
"wb.menu.viewDeck": "Deck",
|
||||||
|
"wb.menu.viewFullScreen": "Enter Full Screen",
|
||||||
|
"wb.menu.acctNone": "No accounts yet",
|
||||||
|
"wb.menu.acctAdd": "Add Account…",
|
||||||
|
"wb.menu.plugStore": "Store…",
|
||||||
|
"wb.menu.plugFolder": "Open Plugins Folder…",
|
||||||
|
"wb.menu.winMinimize": "Minimize",
|
||||||
|
"wb.menu.winZoom": "Zoom",
|
||||||
|
"wb.menu.winWorkspaces": "Workspaces",
|
||||||
|
"wb.menu.helpDocs": "Docs",
|
||||||
|
"wb.menu.helpReport": "Report a Problem…"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import type { UpdateStatus } from '../updateModel.ts';
|
||||||
import EN from './menuMessages.en.json' with { type: 'json' };
|
import EN from './menuMessages.en.json' with { type: 'json' };
|
||||||
import { tx, type Params } from './i18n.ts';
|
import { tx, type Params } from './i18n.ts';
|
||||||
import type { IconName } from './icons.tsx';
|
import type { IconName } from './icons.tsx';
|
||||||
|
import type { Choice } from './nativeMenuModel.ts';
|
||||||
|
|
||||||
/** The menu's English (`wb.menu.*`), for the catalogs. */
|
/** The menu's English (`wb.menu.*`), for the catalogs. */
|
||||||
export const MENU_MESSAGES: Readonly<Record<string, string>> = EN;
|
export const MENU_MESSAGES: Readonly<Record<string, string>> = EN;
|
||||||
|
|
@ -115,6 +116,25 @@ export function resolveTrigger(trigger: AppMenuTrigger | boolean | undefined, co
|
||||||
return trigger ?? configured ?? 'pane';
|
return trigger ?? configured ?? 'pane';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What an app adds to the native menu bar (macOS; nativeMenu.ts): lists the frame cannot know, and the
|
||||||
|
* actions only the app can run. Whatever is omitted leaves its item out of the bar.
|
||||||
|
*/
|
||||||
|
export type NativeMenuApp = {
|
||||||
|
/** The Plugins menu's checked rows (the app's plugin or area switches) and what flipping one does. */
|
||||||
|
plugins?: { list(): Choice[] | Promise<Choice[]>; set(id: string, on: boolean): Promise<void> | void; subscribe?(listener: () => void): () => void };
|
||||||
|
/** View > Icon Pack: the packs and picking one. */
|
||||||
|
iconPacks?: { list(): Choice[]; set(id: string): Promise<void> | void; subscribe?(listener: () => void): () => void };
|
||||||
|
/** File > Install from File…: asks for a file and stages it on the normal install screen. */
|
||||||
|
installFromFile?(): void;
|
||||||
|
/** File > Share My Setup…. */
|
||||||
|
shareSetup?(): void;
|
||||||
|
/** Help > Docs. */
|
||||||
|
docs?(): void;
|
||||||
|
/** Help > the project's site: the label shown (a host name) and the https address opened in the browser. */
|
||||||
|
website?: { label: string; url: string };
|
||||||
|
};
|
||||||
|
|
||||||
/** `ShellSite.menu`: the app menu's rows and what the built-in ones need from the app. */
|
/** `ShellSite.menu`: the app menu's rows and what the built-in ones need from the app. */
|
||||||
export type ShellMenu = {
|
export type ShellMenu = {
|
||||||
/**
|
/**
|
||||||
|
|
@ -140,6 +160,8 @@ export type ShellMenu = {
|
||||||
report?: { issueUrl?: string; details?(): ReportDetails | Promise<ReportDetails> };
|
report?: { issueUrl?: string; details?(): ReportDetails | Promise<ReportDetails> };
|
||||||
/** Opens the app's shortcuts sheet ("Keyboard shortcuts…"); without one the row opens the command palette. */
|
/** Opens the app's shortcuts sheet ("Keyboard shortcuts…"); without one the row opens the command palette. */
|
||||||
shortcuts?(): void;
|
shortcuts?(): void;
|
||||||
|
/** The native menu bar (macOS): the app's lists and actions. */
|
||||||
|
native?: NativeMenuApp;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The menu an app gets without saying anything: every built-in row it can serve. */
|
/** The menu an app gets without saying anything: every built-in row it can serve. */
|
||||||
|
|
|
||||||
166
packages/shell/src/frame/nativeMenu.ts
Normal file
166
packages/shell/src/frame/nativeMenu.ts
Normal file
|
|
@ -0,0 +1,166 @@
|
||||||
|
// The native menu bar (macOS): the shell describes it (`menu_set`, shell-only) from the same state the
|
||||||
|
// in-app menu reads, and runs what the system menu chooses (`native-menu`, an id). Every item goes
|
||||||
|
// through what already exists (`shell.shortcut`, `shell.run`, `shell.openPanelSection`, the theme store,
|
||||||
|
// the profile list, the safe-mode switch, the workspaces); nothing here is a new capability and tabs
|
||||||
|
// gain no command. Elsewhere (Windows, Linux) the in-app menu stays and this does nothing.
|
||||||
|
//
|
||||||
|
// The bar is described again whenever what it shows changes (a theme or mode picked, an account added,
|
||||||
|
// a pane focused, safe mode, workspaces, a plugin switched); equal descriptions are not sent twice.
|
||||||
|
|
||||||
|
import { parseUpdateStatus } from '../updateModel.ts';
|
||||||
|
import { addAccount, accountName } from './AccountSwitcher.tsx';
|
||||||
|
import { invoke, listen } from './bridge.ts';
|
||||||
|
import { subscribeText, t } from './i18n.ts';
|
||||||
|
import { menuText, type MenuWord } from './menuModel.ts';
|
||||||
|
import { planNativeMenu, runNativeMenu, type Choice, type NativeMenuActions, type NativeMenuState } from './nativeMenuModel.ts';
|
||||||
|
import { safe, setSafeMode } from './safeStore.ts';
|
||||||
|
import { hasFeature, site } from './site.ts';
|
||||||
|
import { isWeb, shell } from './state.ts';
|
||||||
|
import { openAppMenu, openReport } from './AppMenu.tsx';
|
||||||
|
import { isTauri, os } from './windowBinding.ts';
|
||||||
|
import { openWorkspaceSave } from './TitlebarExtras.tsx';
|
||||||
|
import { restoreWorkspace, workspaceList, workspaces } from './workspaces.ts';
|
||||||
|
|
||||||
|
/** Events (window) after which something the bar shows may have changed. */
|
||||||
|
const EVENTS = ['bt-zoom', 'bt-workspaces', 'bt-decks', 'bt-site', 'bt-safe', 'bt-profiles', 'bt-active-pane', 'bt-plugins-changed', 'bt-store-changed', 'wb-features-changed'];
|
||||||
|
|
||||||
|
const w = (name: string, params?: Record<string, string | number>) => menuText(name as MenuWord, params);
|
||||||
|
|
||||||
|
/** The state the bar shows now. Async parts (the mode in use, the app's plugin list) are awaited here. */
|
||||||
|
async function readState(): Promise<NativeMenuState> {
|
||||||
|
const config = site();
|
||||||
|
const menu = config.menu ?? {};
|
||||||
|
const native = menu.native ?? {};
|
||||||
|
const active = shell.api?.activePanel;
|
||||||
|
const themeState = config.themes?.current();
|
||||||
|
const themeId = config.themes && themeState ? config.themes.adapter.preset(themeState.choice) : '';
|
||||||
|
const themes: Choice[] | undefined = config.themes && themeState
|
||||||
|
? config.themes.allThemes(themeState.choice).map(theme => ({ id: theme.id, label: theme.name, checked: theme.id === themeId }))
|
||||||
|
: undefined;
|
||||||
|
let modes: Choice[] | undefined;
|
||||||
|
if (menu.modes) {
|
||||||
|
const current = await menu.modes.current().catch(() => null);
|
||||||
|
modes = menu.modes.list().map(entry => ({ id: entry.id, label: entry.label, checked: entry.id === current }));
|
||||||
|
}
|
||||||
|
const plugins = native.plugins ? await Promise.resolve(native.plugins.list()).catch(() => undefined) : undefined;
|
||||||
|
const list = workspaceList();
|
||||||
|
return {
|
||||||
|
product: config.product,
|
||||||
|
hasPanel: !!active,
|
||||||
|
canSplit: !!active && (isWeb(active) || active.group.panels.length > 1),
|
||||||
|
canFind: (shell.api?.panels ?? []).some(panel => isWeb(panel) && panel.api.isVisible),
|
||||||
|
safeActive: safe.active,
|
||||||
|
features: {
|
||||||
|
find: hasFeature('find'), zoom: hasFeature('zoom'), deck: !!config.deck, store: hasFeature('store'),
|
||||||
|
safeMode: hasFeature('safeMode'), workspaces: hasFeature('workspaces'), updates: hasFeature('updates'),
|
||||||
|
},
|
||||||
|
themes,
|
||||||
|
iconPacks: native.iconPacks?.list(),
|
||||||
|
modes,
|
||||||
|
accounts: shell.profiles.profiles.map(profile => ({ id: profile.id, label: accountName(profile), checked: profile.id === shell.profiles.active })),
|
||||||
|
plugins,
|
||||||
|
workspaces: hasFeature('workspaces') ? list.map(entry => ({ id: entry.id, label: entry.name, checked: entry.id === workspaces.active })) : undefined,
|
||||||
|
installFromFile: !!native.installFromFile,
|
||||||
|
shareSetup: !!native.shareSetup,
|
||||||
|
docs: !!native.docs,
|
||||||
|
website: native.website?.label,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function actions(): NativeMenuActions {
|
||||||
|
const menu = site().menu ?? {};
|
||||||
|
const native = menu.native ?? {};
|
||||||
|
const config = site();
|
||||||
|
return {
|
||||||
|
about: () => shell.openPanelSection('home'),
|
||||||
|
// A real check, then the panel's Updates section says what came of it.
|
||||||
|
checkUpdates: () => { void invoke('update_check').then(parseUpdateStatus).catch(() => {}); shell.openPanelSection('updates'); },
|
||||||
|
settings: () => shell.openPanelSection('settings'),
|
||||||
|
// Turning it on restarts every tab, so the in-app question (what it does, Cancel) asks first; turning it off is one step.
|
||||||
|
safeMode: () => { if (safe.active) void setSafeMode(false); else openAppMenu({ submenu: 'safe-mode', keyboard: true }); },
|
||||||
|
newTab: () => shell.shortcut('new-tab'),
|
||||||
|
splitRight: () => shell.shortcut('split-right'),
|
||||||
|
splitDown: () => shell.shortcut('split-down'),
|
||||||
|
closeTab: () => shell.shortcut('close-tab'),
|
||||||
|
installFromFile: () => native.installFromFile?.(),
|
||||||
|
shareSetup: () => native.shareSetup?.(),
|
||||||
|
find: () => shell.shortcut('find'),
|
||||||
|
findNext: () => shell.shortcut('find-next'),
|
||||||
|
findPrevious: () => shell.shortcut('find-previous'),
|
||||||
|
zoomIn: () => shell.shortcut('zoom-in'),
|
||||||
|
zoomOut: () => shell.shortcut('zoom-out'),
|
||||||
|
zoomReset: () => shell.shortcut('zoom-reset'),
|
||||||
|
deck: () => shell.shortcut('deck-toggle'),
|
||||||
|
// As Appearance does: a theme starts without the customizations made on another one.
|
||||||
|
theme: id => { const themes = config.themes; const choice = themes?.current().choice; if (themes && choice) void themes.setChoice(themes.adapter.choiceForId(choice, id)); },
|
||||||
|
iconPack: id => { void native.iconPacks?.set(id); },
|
||||||
|
// Switching asks about the owner's own changes first when there are any: that question is the in-app menu's.
|
||||||
|
mode: id => {
|
||||||
|
const modes = menu.modes;
|
||||||
|
if (!modes) return;
|
||||||
|
void modes.changes(id).then(changes => { if (changes > 0) openAppMenu({ submenu: 'mode', keyboard: true }); else return modes.apply(id, false); }).catch(() => {});
|
||||||
|
},
|
||||||
|
account: id => shell.openAccount(id),
|
||||||
|
addAccount: () => { void addAccount(shell.profiles).catch(() => {}); },
|
||||||
|
plugin: (id, on) => { void native.plugins?.set(id, on); },
|
||||||
|
store: () => shell.openPanelSection('store'),
|
||||||
|
pluginsFolder: () => { void invoke('plugins_open_folder').catch(() => {}); },
|
||||||
|
workspace: id => { void restoreWorkspace(id); },
|
||||||
|
saveWorkspace: () => openWorkspaceSave(),
|
||||||
|
docs: () => native.docs?.(),
|
||||||
|
report: () => openReport(),
|
||||||
|
website: () => { const url = native.website?.url; if (url) void invoke('open_external_url', { url }).catch(() => {}); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the bar (once, after the shell is mounted). Returns a function that stops it.
|
||||||
|
* No-op where the system menu bar is not the app's (anything but macOS).
|
||||||
|
*/
|
||||||
|
export function startNativeMenu(): () => void {
|
||||||
|
if (os !== 'macos' || !isTauri) return () => {};
|
||||||
|
let last = '';
|
||||||
|
let latest: NativeMenuState | null = null;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
let stopped = false;
|
||||||
|
|
||||||
|
const send = async () => {
|
||||||
|
try {
|
||||||
|
const state = await readState();
|
||||||
|
if (stopped) return;
|
||||||
|
latest = state;
|
||||||
|
const spec = planNativeMenu(state, w, key => t(key));
|
||||||
|
const text = JSON.stringify(spec);
|
||||||
|
if (text === last) return;
|
||||||
|
last = text;
|
||||||
|
await invoke('menu_set', { spec });
|
||||||
|
} catch (error) {
|
||||||
|
last = '';
|
||||||
|
console.error('[shell] menu_set', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const soon = () => { clearTimeout(timer); timer = setTimeout(() => void send(), 120); };
|
||||||
|
|
||||||
|
for (const event of EVENTS) window.addEventListener(event, soon);
|
||||||
|
const config = site();
|
||||||
|
const offs = [
|
||||||
|
config.themes?.subscribe(soon), config.menu?.languages?.subscribe(soon), subscribeText(soon),
|
||||||
|
config.menu?.native?.plugins?.subscribe?.(soon), config.menu?.native?.iconPacks?.subscribe?.(soon),
|
||||||
|
];
|
||||||
|
let unlisten: (() => void) | undefined;
|
||||||
|
void listen<string>('native-menu', event => {
|
||||||
|
if (typeof event.payload !== 'string' || !latest) return;
|
||||||
|
// Focus goes back to the shell first: a choice made in the system menu is the shell's action.
|
||||||
|
runNativeMenu(event.payload, latest, actions());
|
||||||
|
soon();
|
||||||
|
}).then(off => { if (stopped) off(); else unlisten = off; }).catch(() => {});
|
||||||
|
soon();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
stopped = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
for (const event of EVENTS) window.removeEventListener(event, soon);
|
||||||
|
for (const off of offs) off?.();
|
||||||
|
unlisten?.();
|
||||||
|
};
|
||||||
|
}
|
||||||
205
packages/shell/src/frame/nativeMenuModel.ts
Normal file
205
packages/shell/src/frame/nativeMenuModel.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
||||||
|
// Pure model of the native menu bar (macOS): what the shell describes to native code (`menu_set`,
|
||||||
|
// waybetter-host menu.rs) and which action each chosen id runs. No React, no Tauri: it is tested
|
||||||
|
// under node. Every item runs what the in-app menu, the palette or the keys already run; the bar
|
||||||
|
// adds no capability. Words are `wb.menu.*` (menuMessages.en.json) and the frame's own catalog keys.
|
||||||
|
|
||||||
|
/** One entry of a list the bar shows with a check (themes, modes, accounts, plugins, workspaces). */
|
||||||
|
export type Choice = { id: string; label: string; checked: boolean };
|
||||||
|
|
||||||
|
/** What the bar reflects right now. Absent lists leave their submenu out. */
|
||||||
|
export type NativeMenuState = {
|
||||||
|
product: string;
|
||||||
|
hasPanel: boolean;
|
||||||
|
canSplit: boolean;
|
||||||
|
canFind: boolean;
|
||||||
|
safeActive: boolean;
|
||||||
|
features: { find: boolean; zoom: boolean; deck: boolean; store: boolean; safeMode: boolean; workspaces: boolean; updates: boolean };
|
||||||
|
themes?: Choice[];
|
||||||
|
iconPacks?: Choice[];
|
||||||
|
modes?: Choice[];
|
||||||
|
accounts: Choice[];
|
||||||
|
plugins?: Choice[];
|
||||||
|
workspaces?: Choice[];
|
||||||
|
/** The app can install a file chosen from a dialog, share the setup, has docs and a website. */
|
||||||
|
installFromFile: boolean;
|
||||||
|
shareSetup: boolean;
|
||||||
|
docs: boolean;
|
||||||
|
website?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** What a chosen id does. The controller (nativeMenu.ts) wires these to the shell. */
|
||||||
|
export type NativeMenuActions = {
|
||||||
|
about(): void;
|
||||||
|
checkUpdates(): void;
|
||||||
|
settings(): void;
|
||||||
|
safeMode(): void;
|
||||||
|
newTab(): void;
|
||||||
|
splitRight(): void;
|
||||||
|
splitDown(): void;
|
||||||
|
closeTab(): void;
|
||||||
|
installFromFile(): void;
|
||||||
|
shareSetup(): void;
|
||||||
|
find(): void;
|
||||||
|
findNext(): void;
|
||||||
|
findPrevious(): void;
|
||||||
|
zoomIn(): void;
|
||||||
|
zoomOut(): void;
|
||||||
|
zoomReset(): void;
|
||||||
|
deck(): void;
|
||||||
|
theme(id: string): void;
|
||||||
|
iconPack(id: string): void;
|
||||||
|
mode(id: string): void;
|
||||||
|
account(id: string): void;
|
||||||
|
addAccount(): void;
|
||||||
|
plugin(id: string, on: boolean): void;
|
||||||
|
store(): void;
|
||||||
|
pluginsFolder(): void;
|
||||||
|
workspace(id: string): void;
|
||||||
|
saveWorkspace(): void;
|
||||||
|
docs(): void;
|
||||||
|
report(): void;
|
||||||
|
website(): void;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Words = (name: string, params?: Record<string, string | number>) => string;
|
||||||
|
|
||||||
|
type Node =
|
||||||
|
| { kind: 'item'; id: string; label: string; accelerator?: string; checked?: boolean; enabled?: boolean }
|
||||||
|
| { kind: 'separator' }
|
||||||
|
| { kind: 'submenu'; label: string; items: Node[]; enabled?: boolean; role?: 'window' | 'help' }
|
||||||
|
| { kind: 'predefined'; role: string; label?: string };
|
||||||
|
|
||||||
|
/** The description `menu_set` takes. */
|
||||||
|
export type NativeMenuSpec = { menus: Node[] };
|
||||||
|
|
||||||
|
/** One line, at most 120 characters (what menu.rs accepts), never empty. */
|
||||||
|
const clean = (label: string, fallback = '-') => label.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').trim().slice(0, 120) || fallback;
|
||||||
|
/** Ids carry only their alphabet (menu.rs `valid_id`); an app's ids are folded into it. */
|
||||||
|
export const safeId = (id: string) => id.replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 60);
|
||||||
|
|
||||||
|
const item = (id: string, label: string, rest: { accelerator?: string; checked?: boolean; enabled?: boolean } = {}): Node => ({ kind: 'item', id, label: clean(label), ...rest });
|
||||||
|
const system = (role: string, label?: string): Node => ({ kind: 'predefined', role, ...(label ? { label: clean(label) } : {}) });
|
||||||
|
const sep: Node = { kind: 'separator' };
|
||||||
|
const submenu = (label: string, items: Node[], rest: { enabled?: boolean; role?: 'window' | 'help' } = {}): Node => ({ kind: 'submenu', label: clean(label), items, ...rest });
|
||||||
|
const choices = (prefix: string, list: readonly Choice[]): Node[] => list.map(choice => item(`${prefix}:${safeId(choice.id)}`, choice.label, { checked: choice.checked }));
|
||||||
|
|
||||||
|
/** Separates non-empty groups with rules. */
|
||||||
|
const groups = (...parts: Node[][]): Node[] => parts.filter(part => part.length).flatMap((part, index) => (index ? [sep, ...part] : part));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The whole bar: App, File, Edit, View, Account, Plugins, Window, Help. `w` reads a `wb.menu.*` word,
|
||||||
|
* `text` a catalog key of the frame (the labels the in-app menu already uses).
|
||||||
|
*/
|
||||||
|
export function planNativeMenu(state: NativeMenuState, w: Words, text: (key: string) => string): NativeMenuSpec {
|
||||||
|
const { product, features } = state;
|
||||||
|
const app = submenu(product, groups(
|
||||||
|
[item('app.about', w('about', { product }))],
|
||||||
|
[
|
||||||
|
...(features.updates ? [item('app.updates', w('appUpdates'))] : []),
|
||||||
|
item('app.settings', w('appSettings'), { accelerator: 'CmdOrCtrl+,' }),
|
||||||
|
...(features.safeMode ? [item('app.safe', w('appSafe'), { checked: state.safeActive })] : []),
|
||||||
|
],
|
||||||
|
[system('services', w('appServices'))],
|
||||||
|
[system('hide', w('appHide', { product })), system('hide_others', w('appHideOthers')), system('show_all', w('appShowAll'))],
|
||||||
|
[system('quit', w('appQuit', { product }))],
|
||||||
|
));
|
||||||
|
const file = submenu(w('barFile'), groups(
|
||||||
|
[item('file.new-tab', text('wb.shell.tab.new'), { accelerator: 'CmdOrCtrl+T' })],
|
||||||
|
[
|
||||||
|
item('file.split-right', text('wb.shell.menu.splitRight'), { accelerator: 'CmdOrCtrl+\\', enabled: state.canSplit }),
|
||||||
|
item('file.split-down', text('wb.shell.menu.splitDown'), { accelerator: 'CmdOrCtrl+Shift+\\', enabled: state.canSplit }),
|
||||||
|
],
|
||||||
|
[item('file.close', w('fileClose'), { accelerator: 'CmdOrCtrl+W', enabled: state.hasPanel })],
|
||||||
|
[...(state.installFromFile ? [item('file.install', w('fileInstall'))] : []), ...(state.shareSetup ? [item('file.share', w('fileShare'))] : [])],
|
||||||
|
));
|
||||||
|
const edit = submenu(w('barEdit'), groups(
|
||||||
|
[system('undo', w('editUndo')), system('redo', w('editRedo'))],
|
||||||
|
[system('cut', w('editCut')), system('copy', w('editCopy')), system('paste', w('editPaste')), system('select_all', w('editSelectAll'))],
|
||||||
|
features.find ? [
|
||||||
|
item('edit.find', w('editFind'), { accelerator: 'CmdOrCtrl+F', enabled: state.canFind }),
|
||||||
|
item('edit.find-next', w('editFindNext'), { accelerator: 'CmdOrCtrl+G', enabled: state.canFind }),
|
||||||
|
item('edit.find-previous', w('editFindPrevious'), { accelerator: 'CmdOrCtrl+Shift+G', enabled: state.canFind }),
|
||||||
|
] : [],
|
||||||
|
));
|
||||||
|
const view = submenu(w('barView'), groups(
|
||||||
|
features.zoom ? [
|
||||||
|
item('view.zoom-in', w('viewZoomIn'), { accelerator: 'CmdOrCtrl+=' }),
|
||||||
|
item('view.zoom-out', w('viewZoomOut'), { accelerator: 'CmdOrCtrl+-' }),
|
||||||
|
item('view.zoom-reset', w('viewActual'), { accelerator: 'CmdOrCtrl+0' }),
|
||||||
|
] : [],
|
||||||
|
[
|
||||||
|
...(state.themes?.length ? [submenu(w('theme'), choices('theme', state.themes))] : []),
|
||||||
|
...(state.iconPacks?.length ? [submenu(w('viewIconPack'), choices('icons', state.iconPacks))] : []),
|
||||||
|
...(state.modes?.length ? [submenu(text('wb.modes.section'), choices('mode', state.modes))] : []),
|
||||||
|
],
|
||||||
|
features.deck ? [item('view.deck', w('viewDeck'), { accelerator: 'CmdOrCtrl+Shift+D' })] : [],
|
||||||
|
[system('fullscreen', w('viewFullScreen'))],
|
||||||
|
));
|
||||||
|
const account = submenu(w('barAccount'), groups(
|
||||||
|
state.accounts.length ? choices('acct', state.accounts) : [item('acct.none', w('acctNone'), { enabled: false })],
|
||||||
|
[item('acct.add', w('acctAdd'))],
|
||||||
|
));
|
||||||
|
const plugins = submenu(w('barPlugins'), groups(
|
||||||
|
state.plugins?.length ? choices('plugin', state.plugins) : [],
|
||||||
|
[...(features.store ? [item('plugins.store', w('plugStore'))] : []), item('plugins.folder', w('plugFolder'))],
|
||||||
|
));
|
||||||
|
const window = submenu(w('barWindow'), groups(
|
||||||
|
[system('minimize', w('winMinimize')), system('maximize', w('winZoom'))],
|
||||||
|
features.workspaces ? [submenu(w('winWorkspaces'), groups(
|
||||||
|
state.workspaces?.length ? choices('ws', state.workspaces) : [item('ws.none', w('noWorkspaces'), { enabled: false })],
|
||||||
|
[item('ws.save', w('saveLayout'))],
|
||||||
|
))] : [],
|
||||||
|
), { role: 'window' });
|
||||||
|
const help = submenu(w('barHelp'), groups(
|
||||||
|
state.docs ? [item('help.docs', w('helpDocs'))] : [],
|
||||||
|
[item('help.report', w('helpReport'))],
|
||||||
|
state.website ? [item('help.website', state.website)] : [],
|
||||||
|
), { role: 'help' });
|
||||||
|
return { menus: [app, file, edit, view, account, plugins, window, help] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs what `id` (an id of [`planNativeMenu`]) stands for; false for an id it does not know. */
|
||||||
|
export function runNativeMenu(id: string, state: NativeMenuState, act: NativeMenuActions): boolean {
|
||||||
|
const colon = id.indexOf(':');
|
||||||
|
if (colon > 0) {
|
||||||
|
const prefix = id.slice(0, colon);
|
||||||
|
const rest = id.slice(colon + 1);
|
||||||
|
const find = (list?: readonly Choice[]) => list?.find(choice => safeId(choice.id) === rest);
|
||||||
|
switch (prefix) {
|
||||||
|
case 'theme': { const choice = find(state.themes); if (choice) { act.theme(choice.id); return true; } return false; }
|
||||||
|
case 'icons': { const choice = find(state.iconPacks); if (choice) { act.iconPack(choice.id); return true; } return false; }
|
||||||
|
case 'mode': { const choice = find(state.modes); if (choice) { act.mode(choice.id); return true; } return false; }
|
||||||
|
case 'acct': { const choice = find(state.accounts); if (choice) { act.account(choice.id); return true; } return false; }
|
||||||
|
case 'plugin': { const choice = find(state.plugins); if (choice) { act.plugin(choice.id, !choice.checked); return true; } return false; }
|
||||||
|
case 'ws': { const choice = find(state.workspaces); if (choice) { act.workspace(choice.id); return true; } return false; }
|
||||||
|
default: return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch (id) {
|
||||||
|
case 'app.about': act.about(); return true;
|
||||||
|
case 'app.updates': act.checkUpdates(); return true;
|
||||||
|
case 'app.settings': act.settings(); return true;
|
||||||
|
case 'app.safe': act.safeMode(); return true;
|
||||||
|
case 'file.new-tab': act.newTab(); return true;
|
||||||
|
case 'file.split-right': act.splitRight(); return true;
|
||||||
|
case 'file.split-down': act.splitDown(); return true;
|
||||||
|
case 'file.close': act.closeTab(); return true;
|
||||||
|
case 'file.install': act.installFromFile(); return true;
|
||||||
|
case 'file.share': act.shareSetup(); return true;
|
||||||
|
case 'edit.find': act.find(); return true;
|
||||||
|
case 'edit.find-next': act.findNext(); return true;
|
||||||
|
case 'edit.find-previous': act.findPrevious(); return true;
|
||||||
|
case 'view.zoom-in': act.zoomIn(); return true;
|
||||||
|
case 'view.zoom-out': act.zoomOut(); return true;
|
||||||
|
case 'view.zoom-reset': act.zoomReset(); return true;
|
||||||
|
case 'view.deck': act.deck(); return true;
|
||||||
|
case 'acct.add': act.addAccount(); return true;
|
||||||
|
case 'plugins.store': act.store(); return true;
|
||||||
|
case 'plugins.folder': act.pluginsFolder(); return true;
|
||||||
|
case 'ws.save': act.saveWorkspace(); return true;
|
||||||
|
case 'help.docs': act.docs(); return true;
|
||||||
|
case 'help.report': act.report(); return true;
|
||||||
|
case 'help.website': act.website(); return true;
|
||||||
|
default: return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -232,6 +232,8 @@ test("the menu's words: English from menuMessages.en.json until a catalog has th
|
||||||
for (const file of ['AppMenu.tsx', 'TitlebarExtras.tsx', 'AccountSwitcher.tsx', 'paletteModel.ts', 'FindBar.tsx', 'menuModel.ts', 'ReportDialog.tsx']) {
|
for (const file of ['AppMenu.tsx', 'TitlebarExtras.tsx', 'AccountSwitcher.tsx', 'paletteModel.ts', 'FindBar.tsx', 'menuModel.ts', 'ReportDialog.tsx']) {
|
||||||
for (const match of readFileSync(join(here, '../src/frame', file), 'utf8').matchAll(/menuText\('([A-Za-z]+)'/g)) used.add(`wb.menu.${match[1]}`);
|
for (const match of readFileSync(join(here, '../src/frame', file), 'utf8').matchAll(/menuText\('([A-Za-z]+)'/g)) used.add(`wb.menu.${match[1]}`);
|
||||||
}
|
}
|
||||||
|
// The native menu bar reads its words through `w('name')` (nativeMenuModel.ts).
|
||||||
|
for (const match of readFileSync(join(here, '../src/frame/nativeMenuModel.ts'), 'utf8').matchAll(/w\('([A-Za-z]+)'/g)) used.add(`wb.menu.${match[1]}`);
|
||||||
for (const key of used) assert.ok(key in MENU_MESSAGES, `${key} has English`);
|
for (const key of used) assert.ok(key in MENU_MESSAGES, `${key} has English`);
|
||||||
for (const key of Object.keys(MENU_MESSAGES)) assert.ok(used.has(key), `${key} is used`);
|
for (const key of Object.keys(MENU_MESSAGES)) assert.ok(used.has(key), `${key} is used`);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
78
packages/shell/tests/nativeMenu.test.ts
Normal file
78
packages/shell/tests/nativeMenu.test.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import { planNativeMenu, runNativeMenu, safeId, type NativeMenuActions, type NativeMenuState } from '../src/frame/nativeMenuModel.ts';
|
||||||
|
import { MENU_MESSAGES } from '../src/frame/menuModel.ts';
|
||||||
|
|
||||||
|
const words = (name: string, params: Record<string, string | number> = {}) =>
|
||||||
|
(MENU_MESSAGES[`wb.menu.${name}`] ?? name).replace(/\{(\w+)\}/g, (_, key) => String(params[key] ?? ''));
|
||||||
|
const text = (key: string) => key.split('.').pop() ?? key;
|
||||||
|
|
||||||
|
const state: NativeMenuState = {
|
||||||
|
product: 'wayBetter for X', hasPanel: true, canSplit: true, canFind: true, safeActive: false,
|
||||||
|
features: { find: true, zoom: true, deck: true, store: true, safeMode: true, workspaces: true, updates: true },
|
||||||
|
themes: [{ id: 'dark', label: 'Dark', checked: true }, { id: 'my theme!', label: 'Mine', checked: false }],
|
||||||
|
iconPacks: [{ id: 'theme', label: 'Follow theme', checked: true }],
|
||||||
|
modes: [{ id: 'basic', label: 'Basic', checked: true }, { id: 'power', label: 'Power User', checked: false }],
|
||||||
|
accounts: [{ id: 'default', label: '@one', checked: true }],
|
||||||
|
plugins: [{ id: 'chat', label: 'Chat+', checked: true }, { id: 'media', label: 'Media+', checked: false }],
|
||||||
|
workspaces: [{ id: 'w1', label: 'Work', checked: false }],
|
||||||
|
installFromFile: true, shareSetup: true, docs: true, website: 'waybetter.fyi',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Every node of the description, flattened. */
|
||||||
|
type AnyNode = { kind: string; id?: string; label?: string; items?: AnyNode[]; accelerator?: string };
|
||||||
|
const walk = (nodes: AnyNode[]): AnyNode[] => nodes.flatMap(node => [node, ...walk(node.items ?? [])]);
|
||||||
|
|
||||||
|
test('the bar has the eight menus and every item in the owner\'s list', () => {
|
||||||
|
const spec = planNativeMenu(state, words, text);
|
||||||
|
assert.deepEqual(spec.menus.map(menu => (menu as AnyNode).label), ['wayBetter for X', 'File', 'Edit', 'View', 'Account', 'Plugins', 'Window', 'Help']);
|
||||||
|
const ids = walk(spec.menus as AnyNode[]).filter(node => node.kind === 'item').map(node => node.id);
|
||||||
|
for (const id of ['app.about', 'app.updates', 'app.settings', 'app.safe', 'file.new-tab', 'file.split-right', 'file.split-down', 'file.close', 'file.install', 'file.share',
|
||||||
|
'edit.find', 'edit.find-next', 'edit.find-previous', 'view.zoom-in', 'view.zoom-out', 'view.zoom-reset', 'view.deck', 'acct.add', 'plugins.store', 'plugins.folder', 'ws.save', 'help.docs', 'help.report', 'help.website']) {
|
||||||
|
assert.ok(ids.includes(id), id);
|
||||||
|
}
|
||||||
|
assert.ok(ids.includes('theme:dark') && ids.includes('mode:power') && ids.includes('icons:theme') && ids.includes('acct:default') && ids.includes('plugin:chat') && ids.includes('ws:w1'));
|
||||||
|
const roles = walk(spec.menus as AnyNode[]).filter(node => node.kind === 'predefined').map(node => (node as unknown as { role: string }).role);
|
||||||
|
for (const role of ['services', 'hide', 'quit', 'undo', 'cut', 'copy', 'paste', 'select_all', 'minimize', 'fullscreen']) assert.ok(roles.includes(role), role);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('what native code accepts: ids and labels', () => {
|
||||||
|
const spec = planNativeMenu(state, words, text);
|
||||||
|
for (const node of walk(spec.menus as AnyNode[])) {
|
||||||
|
if (node.kind === 'item') assert.match(node.id!, /^[A-Za-z0-9_.:/-]{1,96}$/, node.id);
|
||||||
|
if (node.label !== undefined) assert.ok(node.label.length > 0 && node.label.length <= 120 && !/[\u0000-\u001f]/.test(node.label), node.label);
|
||||||
|
}
|
||||||
|
assert.equal(safeId('my theme!'), 'my_theme_');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shortcuts follow the standard places', () => {
|
||||||
|
const items = new Map(walk(planNativeMenu(state, words, text).menus as AnyNode[]).filter(node => node.kind === 'item').map(node => [node.id, node.accelerator]));
|
||||||
|
assert.equal(items.get('app.settings'), 'CmdOrCtrl+,');
|
||||||
|
assert.equal(items.get('file.new-tab'), 'CmdOrCtrl+T');
|
||||||
|
assert.equal(items.get('file.close'), 'CmdOrCtrl+W');
|
||||||
|
assert.equal(items.get('edit.find'), 'CmdOrCtrl+F');
|
||||||
|
assert.equal(items.get('edit.find-next'), 'CmdOrCtrl+G');
|
||||||
|
assert.equal(items.get('edit.find-previous'), 'CmdOrCtrl+Shift+G');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('what the app does not serve leaves its items out; nothing is empty', () => {
|
||||||
|
const bare: NativeMenuState = { ...state, themes: undefined, iconPacks: undefined, modes: undefined, plugins: undefined, workspaces: undefined, accounts: [],
|
||||||
|
features: { find: false, zoom: false, deck: false, store: false, safeMode: false, workspaces: false, updates: false }, installFromFile: false, shareSetup: false, docs: false, website: undefined };
|
||||||
|
const ids = walk(planNativeMenu(bare, words, text).menus as AnyNode[]).filter(node => node.kind === 'item').map(node => node.id);
|
||||||
|
for (const gone of ['app.safe', 'app.updates', 'edit.find', 'view.zoom-in', 'view.deck', 'plugins.store', 'file.install', 'help.docs', 'help.website']) assert.ok(!ids.includes(gone), gone);
|
||||||
|
assert.ok(ids.includes('acct.none') && ids.includes('acct.add'));
|
||||||
|
assert.ok(!ids.some(id => id?.startsWith('theme:')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a chosen id runs exactly its action; unknown ids run nothing', () => {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const act = new Proxy({}, { get: (_target, name: string) => (...args: unknown[]) => { calls.push(`${name}(${args.join(',')})`); } }) as NativeMenuActions;
|
||||||
|
const run = (id: string) => runNativeMenu(id, state, act);
|
||||||
|
assert.ok(run('file.new-tab') && run('edit.find-previous') && run('theme:my_theme_') && run('mode:power') && run('acct:default') && run('plugin:media') && run('plugin:chat') && run('ws:w1') && run('icons:theme'));
|
||||||
|
assert.deepEqual(calls, ['newTab()', 'findPrevious()', 'theme(my theme!)', 'mode(power)', 'account(default)', 'plugin(media,true)', 'plugin(chat,false)', 'workspace(w1)', 'iconPack(theme)']);
|
||||||
|
calls.length = 0;
|
||||||
|
assert.equal(run('theme:nope'), false);
|
||||||
|
assert.equal(run('evil:thing'), false);
|
||||||
|
assert.equal(run('app.unknown'), false);
|
||||||
|
assert.deepEqual(calls, []);
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue