Find in page: the shell's find bar per pane (Ctrl+F, the app menu, the palette) over the engine's own find

Host: `tab_find {id, action, query}` (shell-only; start, next, previous, stop). On Windows it drives WebView2's own find (`ICoreWebView2Find` from `ICoreWebView2_28`, find options from `ICoreWebView2Environment15`; its built-in find bar suppressed, all matches highlighted) and reports the engine's match count and active match to the shell as `tab-find` events. On macOS, Linux and an older WebView2 Runtime native code evaluates the engine's `window.find` in the tab instead (next and previous work, no count); WKWebView's and WebKitGTK's native find are not wired here because this tree cannot be compiled or run for them on this machine. The query is one typed line (1..=256 characters, no control characters), goes to the engine and is kept nowhere. Tabs gain no command: a tab forwards the existing key name `find` (Ctrl+F) through tab_shortcut.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
CRTkafa 2026-09-30 22:34:48 +07:00
parent 832396801c
commit b31fa6b1d2
17 changed files with 449 additions and 19 deletions

View file

@ -559,6 +559,15 @@ async fn tab_zoom(webview: Webview, app: AppHandle, id: String, factor: Option<f
host::tab_zoom(&app, &id, factor) host::tab_zoom(&app, &id, factor)
} }
/// Find in page for tab `id` (the shell's find bar): `start` with a query, `next`, `previous`, `stop`.
/// The engine's own find where this build can drive it (counts arrive as `tab-find` events), else the
/// evaluated `window.find`. The query is one typed line (validated) and is kept nowhere.
#[tauri::command]
async fn tab_find(webview: Webview, app: AppHandle, id: String, action: String, query: Option<String>) -> Result<(), String> {
shell_only(&webview)?;
host::tab_find(&app, &id, &action, query.as_deref())
}
/// 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> {
@ -974,6 +983,7 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 's
tab_navigate, tab_navigate,
tab_action, tab_action,
tab_zoom, tab_zoom,
tab_find,
open_external_url, open_external_url,
shell_focus, shell_focus,
shell_ready, shell_ready,

View file

@ -58,7 +58,7 @@ mod tests {
fn forwarded_shortcuts_are_ones_the_host_accepts() { fn forwarded_shortcuts_are_ones_the_host_accepts() {
for name in ["deck-toggle", "deck-compose", "column-page-prev", "column-page-next", "column-prev", "column-next", "reopen-tab", "new-tab", for name in ["deck-toggle", "deck-compose", "column-page-prev", "column-page-next", "column-prev", "column-next", "reopen-tab", "new-tab",
"open-panel", "close-tab", "focus-address", "command-palette", "prev-tab", "next-tab", "hard-reload", "reload", "split-down", "open-panel", "close-tab", "focus-address", "command-palette", "prev-tab", "next-tab", "hard-reload", "reload", "split-down",
"split-right", "back", "forward", "app-menu", "zoom-in", "zoom-out", "zoom-reset"] { "split-right", "back", "forward", "app-menu", "zoom-in", "zoom-out", "zoom-reset", "find"] {
assert!(SOURCE.contains(&format!("'{name}'")), "{name} is not in the bridge"); assert!(SOURCE.contains(&format!("'{name}'")), "{name} is not in the bridge");
assert!(crate::tabs::valid_shortcut(name), "{name} would be refused"); assert!(crate::tabs::valid_shortcut(name), "{name} would be refused");
} }

View file

@ -12,6 +12,7 @@ pub const SHELL: &[&str] = &[
"tab_navigate", "tab_navigate",
"tab_action", "tab_action",
"tab_zoom", "tab_zoom",
"tab_find",
"open_external_url", "open_external_url",
"shell_focus", "shell_focus",
"shell_ready", "shell_ready",

View file

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

View file

@ -145,6 +145,115 @@ pub fn forget_tab_zoom<R: Runtime>(app: &AppHandle<R>, id: &str) {
} }
} }
/// `tab_find`: searches tab `id`'s page ([`crate::find`]). The engine's own find where this build
/// can drive it (WebView2's `ICoreWebView2Find`, which reports counts through `tab-find` events);
/// otherwise the evaluated `window.find` fallback. The query is kept nowhere.
pub fn tab_find<R: Runtime>(app: &AppHandle<R>, id: &str, action: &str, query: Option<&str>) -> Result<(), String> {
if !policy::valid_tab_id(id) {
return Err("VALIDATION: invalid tab id".into());
}
let request = crate::find::request(action, query)?;
let tab = tab_webview(app, id).ok_or("TAB: not found")?;
#[cfg(windows)]
{
let fallback = tab.clone();
let (app, id) = (app.clone(), id.to_owned());
tab.with_webview(move |platform| {
// The engine has no find interface (an older WebView2 Runtime): the evaluated fallback.
if !find_windows::run(&app, &platform, &id, &request) {
let _ = fallback.eval(crate::find::fallback_script(&request));
}
})
.map_err(|error| format!("TAB: {error}"))
}
#[cfg(not(windows))]
{
tab.eval(crate::find::fallback_script(&request)).map_err(|error| format!("TAB: {error}"))
}
}
/// WebView2's own find (`ICoreWebView2Find`, WebView2 Runtime with `ICoreWebView2_28`): the find
/// session, its highlights and its counts are the engine's; its own find bar stays hidden.
#[cfg(windows)]
mod find_windows {
use super::{emit_shell, AppHandle, Runtime};
use crate::find::{FindAction, FindRequest, FindState, EVENT_TAB_FIND};
use std::collections::HashSet;
use std::sync::{Mutex, OnceLock};
use webview2_com::Microsoft::Web::WebView2::Win32::{ICoreWebView2Environment15, ICoreWebView2Find, ICoreWebView2_28};
use webview2_com::{FindActiveMatchIndexChangedEventHandler, FindMatchCountChangedEventHandler, FindStartCompletedHandler};
use windows::core::{Interface, HSTRING};
/// Tab webviews whose find object already reports its counts (one pair of handlers each).
fn watched() -> std::sync::MutexGuard<'static, HashSet<String>> {
static WATCHED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
WATCHED.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// The tab's webview is gone: a new one under the same id registers its own handlers.
pub(super) fn forget(id: &str) {
watched().remove(id);
}
fn report<R: Runtime>(app: &AppHandle<R>, id: &str, find: &ICoreWebView2Find) {
let (mut count, mut index) = (0i32, -1i32);
// SAFETY: COM property reads on the live find object, on the main thread.
unsafe {
let _ = find.MatchCount(&mut count);
let _ = find.ActiveMatchIndex(&mut index);
}
emit_shell(app, EVENT_TAB_FIND, FindState { id: id.to_owned(), count, index });
}
/// Runs `request` with the engine's find on the main thread; false when this runtime has none.
pub(super) fn run<R: Runtime>(app: &AppHandle<R>, platform: &tauri::webview::PlatformWebview, id: &str, request: &FindRequest) -> bool {
// SAFETY: COM calls on this webview's live controller and environment, on the main thread
// (with_webview runs the closure there; the handlers run there too).
unsafe {
let Ok(core) = platform.controller().CoreWebView2() else { return false };
let (Ok(core), Ok(environment)) = (core.cast::<ICoreWebView2_28>(), platform.environment().cast::<ICoreWebView2Environment15>()) else { return false };
let Ok(find) = core.Find() else { return false };
if watched().insert(id.to_owned()) {
let mut token = 0i64;
let (count_app, count_id) = (app.clone(), id.to_owned());
let counted = FindMatchCountChangedEventHandler::create(Box::new(move |sender, _| {
if let Some(find) = sender { report(&count_app, &count_id, &find); }
Ok(())
}));
let _ = find.add_MatchCountChanged(&counted, &mut token);
let (index_app, index_id) = (app.clone(), id.to_owned());
let moved = FindActiveMatchIndexChangedEventHandler::create(Box::new(move |sender, _| {
if let Some(find) = sender { report(&index_app, &index_id, &find); }
Ok(())
}));
let _ = find.add_ActiveMatchIndexChanged(&moved, &mut token);
}
match (request.action, request.query.as_deref()) {
(FindAction::Start, Some(query)) => {
let Ok(options) = environment.CreateFindOptions() else { return false };
let _ = options.SetFindTerm(&HSTRING::from(query));
let _ = options.SetSuppressDefaultFindDialog(true);
let _ = options.SetShouldHighlightAllMatches(true);
let _ = options.SetIsCaseSensitive(false);
let _ = options.SetShouldMatchWord(false);
// A new query is a new session, from the first match.
let _ = find.Stop();
let (done_app, done_id, done_find) = (app.clone(), id.to_owned(), find.clone());
let started = FindStartCompletedHandler::create(Box::new(move |_| {
report(&done_app, &done_id, &done_find);
Ok(())
}));
let _ = find.Start(&options, &started);
}
(FindAction::Next, _) => { let _ = find.FindNext(); }
(FindAction::Previous, _) => { let _ = find.FindPrevious(); }
(FindAction::Stop, _) | (FindAction::Start, None) => { let _ = find.Stop(); }
}
}
true
}
}
/// A browser shortcut pressed inside tab `id`, forwarded to the shell (`tab-shortcut`). /// A browser shortcut pressed inside tab `id`, forwarded to the shell (`tab-shortcut`).
pub fn forward_shortcut<R: Runtime>(app: &AppHandle<R>, id: String, shortcut: String) -> Result<(), String> { pub fn forward_shortcut<R: Runtime>(app: &AppHandle<R>, id: String, shortcut: String) -> Result<(), String> {
if !tabs::valid_shortcut(&shortcut) { if !tabs::valid_shortcut(&shortcut) {
@ -803,6 +912,11 @@ pub fn forget_tab<R: Runtime>(app: &AppHandle<R>, label: &str) {
} }
#[cfg(not(windows))] #[cfg(not(windows))]
let _ = app; let _ = app;
// Its find session went with the webview: a new one under the same id registers its own handlers.
#[cfg(windows)]
if let Some(id) = policy::tab_id(label) {
find_windows::forget(id);
}
placements().forget(label); placements().forget(label);
} }

View file

@ -85,6 +85,8 @@
if (key === 'w') return 'close-tab'; if (key === 'w') return 'close-tab';
if (key === 'l') return 'focus-address'; if (key === 'l') return 'focus-address';
if (key === 'k' && !event.shiftKey) return 'command-palette'; if (key === 'k' && !event.shiftKey) return 'command-palette';
// Find in page is the shell's bar (`tab_find`): this tab only says the keys were pressed.
if (key === 'f' && !event.shiftKey) return 'find';
if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab'; if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab';
if (key === 'r') return event.shiftKey ? 'hard-reload' : 'reload'; if (key === 'r') return event.shiftKey ? 'hard-reload' : 'reload';
// Physical key: layouts like Turkish-Q produce other characters on this key. // Physical key: layouts like Turkish-Q produce other characters on this key.

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', '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', '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

@ -265,6 +265,7 @@ export function AppMenu() {
case 'plugins': return item(id, section(t('wb.panel.section.plugins')), 'plug', { run: () => shell.openPanelSection('plugins') }); case 'plugins': return item(id, section(t('wb.panel.section.plugins')), 'plug', { run: () => shell.openPanelSection('plugins') });
case 'store': return item(id, section(t('wb.panel.section.store')), 'bag', { run: () => shell.openPanelSection('store') }); case 'store': return item(id, section(t('wb.panel.section.store')), 'bag', { run: () => shell.openPanelSection('store') });
case 'workspaces': return item(id, t('wb.ws.title'), 'layout', { submenu: true, hint: workspaces.store.items.find(entry => entry.id === workspaces.active)?.name }); case 'workspaces': return item(id, t('wb.ws.title'), 'layout', { submenu: true, hint: workspaces.store.items.find(entry => entry.id === workspaces.active)?.name });
case 'find': return item(id, menuText('find'), 'search', { shortcut: 'Ctrl+F', disabled: !active || !isWeb(active), run: () => shell.shortcut('find') });
case 'shortcuts': return item(id, menuText('shortcuts'), 'keyboard', { run: () => (menu.shortcuts ? menu.shortcuts() : shell.shortcut('command-palette')) }); case 'shortcuts': return item(id, menuText('shortcuts'), 'keyboard', { run: () => (menu.shortcuts ? menu.shortcuts() : shell.shortcut('command-palette')) });
case 'palette': return item(id, menuText('palette'), 'command', { shortcut: 'Ctrl+K', run: () => shell.shortcut('command-palette') }); case 'palette': return item(id, menuText('palette'), 'command', { shortcut: 'Ctrl+K', run: () => shell.shortcut('command-palette') });
case 'developer': return item(id, menuText('developer'), 'code', { submenu: true }); case 'developer': return item(id, menuText('developer'), 'code', { submenu: true });
@ -342,7 +343,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'), store: hasFeature('store'), workspaces: hasFeature('workspaces'), developer: hasFeature('developer'), updates: hasFeature('updates'), zoom: hasFeature('zoom'), find: hasFeature('find'), 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

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

View file

@ -20,6 +20,7 @@ import { openAppMenu } from './AppMenu.tsx';
import { invoke, listen } from './bridge.ts'; import { invoke, listen } from './bridge.ts';
import { CommandPalette } from './CommandPalette.tsx'; import { CommandPalette } from './CommandPalette.tsx';
import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx'; import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx';
import { openFind, stepFind } from './FindBar.tsx';
import { columnSourceUrl, createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts'; import { columnSourceUrl, createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts';
import { installDevHost } from './devHost.ts'; import { installDevHost } from './devHost.ts';
import { useProfiles, useT } from './hooks.ts'; import { useProfiles, useT } from './hooks.ts';
@ -264,6 +265,7 @@ function runPalette(action: PaletteAction) {
case 'plugin-command': runPluginCommand(action.tab, action.command); break; case 'plugin-command': runPluginCommand(action.tab, action.command); break;
case 'workspace': void restoreWorkspace(action.id); break; case 'workspace': void restoreWorkspace(action.id); break;
case 'workspace-save': openWorkspaceSave(); break; case 'workspace-save': openWorkspaceSave(); break;
case 'find': runShortcut('find'); break;
case 'menu': openAppMenu({ keyboard: true }); break; case 'menu': openAppMenu({ keyboard: true }); break;
} }
} }
@ -290,6 +292,9 @@ function runShortcut(shortcut: string, id?: string) {
const panel = id === undefined ? api.activePanel : api.getPanel(id); const panel = id === undefined ? api.activePanel : api.getPanel(id);
switch (shortcut) { switch (shortcut) {
case 'new-tab': addStart(); break; case 'new-tab': addStart(); break;
// Find in page: the find bar of that tab (the one the keys were pressed in, else the one in front).
case 'find': if (panel && isWeb(panel) && hasFeature('find')) { panel.api.setActive(); openFind(panel.id); } break;
case 'find-next': case 'find-previous': if (panel && isWeb(panel)) stepFind(panel.id, shortcut === 'find-next' ? 1 : -1); break;
case 'close-tab': if (panel) closeTab(panel); break; case 'close-tab': if (panel) closeTab(panel); break;
case 'reopen-tab': { const tab = shell.closed.pop(); if (tab) addWeb(tab.url, undefined, true, tab.profile); break; } case 'reopen-tab': { const tab = shell.closed.pop(); if (tab) addWeb(tab.url, undefined, true, tab.profile); break; }
case 'focus-address': if (panel && (isWeb(panel) || (panel.params as TabParams).kind === 'start')) focusAddress(panel.id); break; case 'focus-address': if (panel && (isWeb(panel) || (panel.params as TabParams).kind === 'start')) focusAddress(panel.id); break;
@ -340,6 +345,7 @@ function shortcutFor(event: KeyboardEvent): string | null {
if (key === 'l') return 'focus-address'; if (key === 'l') return 'focus-address';
if (key === 'g' && event.shiftKey) return 'media-panel'; if (key === 'g' && event.shiftKey) return 'media-panel';
if (key === 'k' && !event.shiftKey) return 'command-palette'; if (key === 'k' && !event.shiftKey) return 'command-palette';
if (key === 'f' && !event.shiftKey && hasFeature('find')) return 'find';
if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab'; if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab';
if (key === 'r') return 'reload'; if (key === 'r') return 'reload';
if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right'; if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right';
@ -349,6 +355,7 @@ function shortcutFor(event: KeyboardEvent): string | null {
if (key === '0' || event.code === 'Numpad0') return 'zoom-reset'; if (key === '0' || event.code === 'Numpad0') return 'zoom-reset';
} }
} }
if (event.key === 'F3' && !mod && !event.altKey) return event.shiftKey ? 'find-previous' : 'find-next';
// The app menu, like a browser's: F10, and Alt+F where Alt is not a typing key (not on macOS). // The app menu, like a browser's: F10, and Alt+F where Alt is not a typing key (not on macOS).
if (event.key === 'F10' && !mod && !event.altKey && !event.shiftKey) return 'app-menu'; if (event.key === 'F10' && !mod && !event.altKey && !event.shiftKey) return 'app-menu';
if (event.altKey && !mod && !event.shiftKey && event.code === 'KeyF' && os !== 'macos') return 'app-menu'; if (event.altKey && !mod && !event.shiftKey && event.code === 'KeyF' && os !== 'macos') return 'app-menu';

View file

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

View file

@ -0,0 +1,10 @@
/* Find in page (FindBar.tsx): the find field takes the address field's place in its pane's toolbar,
so it borrows that field's shape (.bt-omni, shell.css) and only adds what is its own. */
.bt-omni.bt-find input { font: 400 13px/1 var(--bt-ui); }
.bt-omni.bt-find input::placeholder { color: var(--bt-faint); }
.bt-find-count { flex: none; padding-inline: 6px 4px; color: var(--bt-muted); font: 500 11.5px/1 var(--bt-mono); font-variant-numeric: tabular-nums; white-space: nowrap; }
.bt-find.is-none .bt-find-count { color: var(--bt-danger); }
.bt-find .bt-omni-action { color: var(--bt-muted); }
.bt-find .bt-omni-action:disabled { color: var(--bt-faint); opacity: .6; cursor: default; background: transparent; }
.bt-shell .bt-find .bt-omni-action svg { width: 15px; height: 15px; }
.bt-shell .bt-find .bt-find-up { transform: rotate(180deg); }

View file

@ -18,5 +18,14 @@
"wb.menu.developer": "Developer", "wb.menu.developer": "Developer",
"wb.menu.pluginsFolder": "Open plugins folder", "wb.menu.pluginsFolder": "Open plugins folder",
"wb.menu.about": "About {product}", "wb.menu.about": "About {product}",
"wb.menu.section": "{section}…" "wb.menu.section": "{section}…",
"wb.menu.find": "Find in page…",
"wb.menu.findField": "Find in page",
"wb.menu.findHint": "Finds what this page has loaded so far",
"wb.menu.findCount": "{index}/{count}",
"wb.menu.findTotal": "{count, plural, one {# match} other {# matches}}",
"wb.menu.findNone": "No matches",
"wb.menu.findNext": "Next match",
"wb.menu.findPrevious": "Previous match",
"wb.menu.findClose": "Close find bar"
} }

View file

@ -34,7 +34,7 @@ export const MENU_BUILTINS = [
'language', 'theme', 'mode', 'language', 'theme', 'mode',
'zoom', 'zoom',
'plugins', 'store', 'workspaces', 'plugins', 'store', 'workspaces',
'shortcuts', 'palette', 'find', 'shortcuts', 'palette',
'developer', 'updates', 'about', 'settings', 'developer', 'updates', 'about', 'settings',
] as const; ] as const;
export type BuiltinMenuItem = typeof MENU_BUILTINS[number]; export type BuiltinMenuItem = typeof MENU_BUILTINS[number];
@ -108,7 +108,7 @@ export const DEFAULT_MENU: MenuGroups = [
['language', 'theme', 'mode'], ['language', 'theme', 'mode'],
['zoom'], ['zoom'],
['plugins', 'store', 'workspaces'], ['plugins', 'store', 'workspaces'],
['shortcuts', 'palette'], ['find', 'shortcuts', 'palette'],
['developer', 'updates', 'about', 'settings'], ['developer', 'updates', 'about', 'settings'],
]; ];
@ -142,8 +142,9 @@ export type MenuEnv = {
themes: boolean; themes: boolean;
/** `menu.modes` with at least one mode. */ /** `menu.modes` with at least one mode. */
modes: boolean; modes: boolean;
/** `features`: native page zoom (`tab_zoom`), 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;
store: boolean; store: boolean;
workspaces: boolean; workspaces: boolean;
developer: boolean; developer: boolean;
@ -158,6 +159,7 @@ export function builtinAvailable(id: BuiltinMenuItem, env: MenuEnv): boolean {
case 'theme': return env.themes; case 'theme': return env.themes;
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 '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;
@ -383,5 +385,18 @@ export function zoomStep(factor: number, direction: 1 | -1 | 0): number {
return [...ZOOM_STEPS].reverse().find(step => step < factor - near) ?? ZOOM_MIN; return [...ZOOM_STEPS].reverse().find(step => step < factor - near) ?? ZOOM_MIN;
} }
// ---------------------------------------------------------------------------------------------
// Find in page
/**
* What the find bar says about a search: "3/17" (the active match of the total), the total alone
* while no match is active, "No matches" for none. `number` writes a number in the active language.
*/
export function findLabel(counts: { count: number; index: number }, number: (value: number) => string = String): string {
if (counts.count <= 0) return menuText('findNone');
if (counts.index < 0 || counts.index >= counts.count) return menuText('findTotal', { count: counts.count });
return menuText('findCount', { index: number(counts.index + 1), count: number(counts.count) });
}
/** Whole percent of a factor (1.1 → 110). */ /** Whole percent of a factor (1.1 → 110). */
export const zoomPercent = (factor: number) => Math.round(factor * 100); export const zoomPercent = (factor: number) => Math.round(factor * 100);

View file

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

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`) and page zoom (`tab_zoom`, the host's own); and what its panel has that the * (`tab_run_command`), page zoom and find in page (`tab_zoom`, `tab_find`: 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; store?: boolean; updates?: boolean }; features?: { workspaces?: boolean; sync?: boolean; developer?: boolean; pluginCommands?: boolean; zoom?: boolean; find?: 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

@ -8,15 +8,15 @@ import test from 'node:test';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { setShellI18n, type ShellI18n } from '../src/frame/i18n.ts'; import { setShellI18n, type ShellI18n } from '../src/frame/i18n.ts';
import { import {
DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, ZOOM_MAX, ZOOM_MIN, ZOOM_STEPS, builtinAvailable, findSpec, joinGroups, languageChoice, languageRows, menuText, menuWith, DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, ZOOM_MAX, ZOOM_MIN, ZOOM_STEPS, builtinAvailable, findLabel, findSpec, joinGroups, languageChoice, languageRows, menuText, menuWith,
menuWithout, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, zoomPercent, zoomStep, menuWithout, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, zoomPercent, zoomStep,
type MenuEnv, type MenuGroups, type MenuItemRow, type MenuItemSpec, type MenuLanguage, type MenuRow, type MenuEnv, type MenuGroups, type MenuItemRow, type MenuItemSpec, type MenuLanguage, type MenuRow,
} from '../src/frame/menuModel.ts'; } from '../src/frame/menuModel.ts';
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, store: true, workspaces: true, developer: true, updates: true }; const ALL: MenuEnv = { decks: true, languages: true, themes: true, modes: true, zoom: true, find: true, store: true, workspaces: true, developer: true, updates: true };
const NONE: MenuEnv = { decks: false, languages: false, themes: false, modes: false, zoom: false, store: false, workspaces: false, developer: false, updates: false }; const NONE: MenuEnv = { decks: false, languages: false, themes: false, modes: false, zoom: false, find: 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');
@ -26,7 +26,7 @@ test('the default menu lists every built-in row once, and an app that serves eve
}); });
test('a row the app cannot serve is left out, and a group left empty takes its rule with it', () => { test('a row the app cannot serve is left out, and a group left empty takes its rule with it', () => {
// A new app (create-waybetter): no decks, languages, themes, zoom, Store, workspaces, developer mode or updater. // An app that serves none of the optional parts: no decks, languages, themes, zoom, find, Store, workspaces, developer mode or updater.
assert.deepEqual(ids(planMenu(DEFAULT_MENU, NONE)), [ assert.deepEqual(ids(planMenu(DEFAULT_MENU, NONE)), [
['new-tab', 'split-right', 'split-down'], ['new-tab', 'split-right', 'split-down'],
['plugins'], ['plugins'],
@ -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'], ['decks', 'new-column'], ['languages', 'language'], ['themes', 'theme'], ['modes', 'mode'], ['zoom', 'zoom'], ['find', 'find'],
['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'], ['shortcuts', 'palette'], ['developer', 'updates', 'about', 'settings'], ['new-tab', 'split-right', 'split-down', 'new-column'], ['language', 'theme', 'mode'], ['plugins', 'workspaces'], ['find', 'shortcuts', 'palette'], ['developer', 'updates', '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]];
@ -229,15 +229,28 @@ test("the menu's words: English from menuMessages.en.json until a catalog has th
assert.equal(menuText('zoom'), 'Zoom', 'a key the catalog lacks still reads in English'); assert.equal(menuText('zoom'), 'Zoom', 'a key the catalog lacks still reads in English');
// The component and the palette name their words through menuText, never as raw keys. // The component and the palette name their words through menuText, never as raw keys.
const used = new Set<string>(); const used = new Set<string>();
for (const file of ['AppMenu.tsx', 'TitlebarExtras.tsx', 'AccountSwitcher.tsx', 'paletteModel.ts']) { for (const file of ['AppMenu.tsx', 'TitlebarExtras.tsx', 'AccountSwitcher.tsx', 'paletteModel.ts', 'FindBar.tsx', 'menuModel.ts']) {
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]}`);
} }
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`);
}); });
test("the find bar says which match of how many, in the reader's numbers", () => {
assert.equal(findLabel({ count: 17, index: 2 }), '3/17');
assert.equal(findLabel({ count: 1, index: 0 }), '1/1');
assert.equal(findLabel({ count: 0, index: -1 }), 'No matches');
assert.equal(findLabel({ count: 5, index: -1 }), '5 matches', 'a count without an active match');
assert.equal(findLabel({ count: 1, index: -1 }), '1 match');
assert.equal(findLabel({ count: 12, index: 3 }, value => `<${value}>`), '<4>/<12>');
});
test('the palette opens the menu', () => { test('the palette opens the menu', () => {
const all = buildItems({ tabs: [], profiles: [], activeProfile: 'default' }, '', { site: { placeholder: () => '', sections: [] }, product: 'App', decks: false, media: false }); const all = buildItems({ tabs: [], profiles: [], activeProfile: 'default' }, '', { site: { placeholder: () => '', sections: [] }, product: 'App', decks: false, media: false });
const entry = all.find(item => item.id === 'app-menu'); const entry = all.find(item => item.id === 'app-menu');
assert.deepEqual([entry?.action, entry?.group], [{ type: 'menu' }, 'App']); assert.deepEqual([entry?.action, entry?.group], [{ type: 'menu' }, 'App']);
// Find in page is there unless the app has no find.
assert.deepEqual(all.find(item => item.id === 'find')?.action, { type: 'find' });
const without = buildItems({ tabs: [], profiles: [], activeProfile: 'default' }, '', { site: { placeholder: () => '', sections: [] }, product: 'App', decks: false, media: false, find: false });
assert.equal(without.some(item => item.id === 'find'), false);
}); });