PM: merge M1.8 command palette, keymap, UI commands
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
bcf66f3fde
33 changed files with 2282 additions and 233 deletions
|
|
@ -62,7 +62,7 @@ claude mcp add lutra -- lutra mcp
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
**Pre-alpha (2026-10-16): M1 in progress.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs (plain text for now); unsaved text survives a crash and is offered back on the next open; syntax highlighting and PHP features come next. The MVP (M1–M3) is estimated at about 20 agent hours after calibrating on the first cycle (2.5 h done). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
|
**Pre-alpha (2026-10-16): M1 in progress.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs (plain text for now), with every command in a palette (`Mod+Shift+P`); unsaved text survives a crash and is offered back on the next open; syntax highlighting and PHP features come next. The MVP (M1–M3) is estimated at about 20 agent hours after calibrating on the first cycle (2.5 h done). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
|
||||||
[`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list.
|
[`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list.
|
||||||
|
|
||||||
**First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files,
|
**First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files,
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
# Lutra Roadmap
|
# Lutra Roadmap
|
||||||
|
|
||||||
**Stage: pre-alpha (M1 in progress)** · next: the rest of M1 (palette, settings, themes), then M2 syntax and search; alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
|
**Stage: pre-alpha (M1 in progress)** · next: the rest of M1 (settings dialog), then M2 syntax and search; alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
|
||||||
|
|
||||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-16 · **Change:** minor (M1.12: notifications) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
|
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-16 · **Change:** minor (M1.8: command palette and keymap) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
|
||||||
|
|
||||||
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
|
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
|
||||||
|
|
||||||
|
|
@ -35,7 +35,7 @@ Dimension hours overlap: language, framework and tooling hours are part of the f
|
||||||
| Stability | 8% | ~95 | [gaps.md › G11](docs/gaps.md) |
|
| Stability | 8% | ~95 | [gaps.md › G11](docs/gaps.md) |
|
||||||
| Agent automation | 10% | ~60 | AGENTS.md |
|
| Agent automation | 10% | ~60 | AGENTS.md |
|
||||||
|
|
||||||
Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a crash-recovery journal for unsaved buffers (property-tested: random edits, crash, restore) exist; the journal is not yet checked in the running app. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works; MCP and the CLI do not exist yet. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing. UI/UX fidelity 1% (estimated): light and dark themes switch live and pass a WCAG AA contrast test; the rest of the ui-parity checklist is open.
|
Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a crash-recovery journal for unsaved buffers (property-tested: random edits, crash, restore) exist; the journal is not yet checked in the running app. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works, and since M1.8 it also reaches the frontend's UI commands (opening the palette, toggling the project tree) through the `uiCommand` event; MCP and the CLI do not exist yet. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing. UI/UX fidelity 1% (estimated): light and dark themes switch live and pass a WCAG AA contrast test; the rest of the ui-parity checklist is open.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
|
|
@ -77,6 +77,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|
||||||
|
|
||||||
| Date | What landed |
|
| Date | What landed |
|
||||||
|---|---|
|
|---|---|
|
||||||
|
| 2026-10-16 | M1.8: a command palette (`Mod+Shift+P`) finds every command by fuzzy match, recent ones first, with shortcuts shown and unavailable ones dimmed; one global keymap serves engine and UI commands (`Mod+1` toggles the project tree); agents can trigger UI commands over the control channel. |
|
||||||
| 2026-10-16 | M1.12: errors and notices reach the user as toasts instead of stderr: a corrupt settings file or recovery entry, a folder that cannot be opened (also with unsaved changes when switching projects), stopped file watching and failed commands without their own UI. Info toasts go away after 5 s, warnings and errors stay. |
|
| 2026-10-16 | M1.12: errors and notices reach the user as toasts instead of stderr: a corrupt settings file or recovery entry, a folder that cannot be opened (also with unsaved changes when switching projects), stopped file watching and failed commands without their own UI. Info toasts go away after 5 s, warnings and errors stay. |
|
||||||
| 2026-10-16 | M1.7: unsaved text survives a crash. Dirty buffers are journaled about a second after the last edit; the next open offers them in a restore dialog (restore all, selected, or discard), with line endings and BOM kept. |
|
| 2026-10-16 | M1.7: unsaved text survives a crash. Dirty buffers are journaled about a second after the last edit; the next open offers them in a restore dialog (restore all, selected, or discard), with line endings and BOM kept. |
|
||||||
| 2026-10-16 | M1.10: Lutra Light next to Lutra Dark, switched live through the `appearance.theme` setting or following the OS (`system`); the window starts in the stored theme; the editor, tabs and notices get their own tokens; both themes pass a WCAG AA contrast test. |
|
| 2026-10-16 | M1.10: Lutra Light next to Lutra Dark, switched live through the `appearance.theme` setting or following the OS (`system`); the window starts in the stored theme; the editor, tabs and notices get their own tokens; both themes pass a WCAG AA contrast test. |
|
||||||
|
|
@ -90,6 +91,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| Date | Change | Summary |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| 2026-10-16 | minor | M1.8: progress log, agent automation note (scores unchanged) |
|
||||||
| 2026-10-16 | minor | M1.12: progress log (headline unchanged) |
|
| 2026-10-16 | minor | M1.12: progress log (headline unchanged) |
|
||||||
| 2026-10-16 | minor | M1.7: Stability 8%, Editor core 9%, feature depth ~1.6% (with Settings 4% from M1.10) |
|
| 2026-10-16 | minor | M1.7: Stability 8%, Editor core 9%, feature depth ~1.6% (with Settings 4% from M1.10) |
|
||||||
| 2026-10-16 | minor | M1.10: UI/UX fidelity 1%, Settings row 4% (estimates), progress log |
|
| 2026-10-16 | minor | M1.10: UI/UX fidelity 1%, Settings row 4% (estimates), progress log |
|
||||||
|
|
|
||||||
121
crates/control/tests/ui_commands.rs
Normal file
121
crates/control/tests/ui_commands.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
||||||
|
//! UI commands over a real TCP socket: after the frontend registered them,
|
||||||
|
//! `engine.listCommands` lists them with `ui: true` and running
|
||||||
|
//! `palette.open` through `engine.execute` streams `uiCommand` to
|
||||||
|
//! `events.subscribe` clients, the way the desktop window gets it and opens
|
||||||
|
//! the palette.
|
||||||
|
|
||||||
|
#![allow(
|
||||||
|
clippy::unwrap_used,
|
||||||
|
clippy::expect_used,
|
||||||
|
clippy::indexing_slicing,
|
||||||
|
clippy::panic
|
||||||
|
)]
|
||||||
|
|
||||||
|
use std::io::{BufRead, BufReader, Write};
|
||||||
|
use std::net::TcpStream;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use lutra_testkit::EngineBackend;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
/// A client that collects event lines and returns responses.
|
||||||
|
struct Client {
|
||||||
|
reader: BufReader<TcpStream>,
|
||||||
|
writer: TcpStream,
|
||||||
|
events: Vec<Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client {
|
||||||
|
fn connect(addr: std::net::SocketAddr) -> Self {
|
||||||
|
let stream = TcpStream::connect(addr).unwrap();
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||||
|
.unwrap();
|
||||||
|
Self {
|
||||||
|
writer: stream.try_clone().unwrap(),
|
||||||
|
reader: BufReader::new(stream),
|
||||||
|
events: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn line(&mut self) -> Value {
|
||||||
|
let mut line = String::new();
|
||||||
|
self.reader.read_line(&mut line).expect("line within 5 s");
|
||||||
|
serde_json::from_str(&line).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends a request and returns its response, collecting event lines that
|
||||||
|
/// arrive before it.
|
||||||
|
fn call(&mut self, request: Value) -> Value {
|
||||||
|
self.writer
|
||||||
|
.write_all(format!("{request}\n").as_bytes())
|
||||||
|
.unwrap();
|
||||||
|
loop {
|
||||||
|
let line = self.line();
|
||||||
|
if line.get("event").is_some() {
|
||||||
|
self.events.push(line["event"].clone());
|
||||||
|
} else {
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Waits for the next event of a kind (events arrive from a subscriber
|
||||||
|
/// queue, possibly after the response) and drops the events before it.
|
||||||
|
fn next(&mut self, kind: &str) -> Value {
|
||||||
|
loop {
|
||||||
|
if let Some(at) = self.events.iter().position(|e| e["kind"] == kind) {
|
||||||
|
let theme = self.events.remove(at);
|
||||||
|
self.events.drain(..at);
|
||||||
|
return theme;
|
||||||
|
}
|
||||||
|
let line = self.line();
|
||||||
|
if line.get("event").is_some() {
|
||||||
|
self.events.push(line["event"].clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(command: &str, params: Value) -> Value {
|
||||||
|
json!({"id": 2, "method": "engine.execute", "params": {"command": command, "params": params}})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn palette_open_over_control_reaches_subscribers() {
|
||||||
|
let backend = Arc::new(EngineBackend::new());
|
||||||
|
let server = lutra_control::start(0, backend.clone()).unwrap();
|
||||||
|
let mut client = Client::connect(server.local_addr());
|
||||||
|
client.call(json!({"id": 1, "method": "events.subscribe"}));
|
||||||
|
|
||||||
|
let r = client.call(execute("palette.open", Value::Null));
|
||||||
|
assert_eq!(r["error"]["code"], "unknown_command", "{r}");
|
||||||
|
|
||||||
|
let r = client.call(execute(
|
||||||
|
"ui.registerCommands",
|
||||||
|
json!({"commands": [
|
||||||
|
{"id": "palette.open", "labelKey": "command.palette.open", "defaultShortcut": "Mod+Shift+P"},
|
||||||
|
]}),
|
||||||
|
));
|
||||||
|
assert_eq!(r["result"]["registered"], 1, "{r}");
|
||||||
|
|
||||||
|
let r = client.call(json!({"id": 3, "method": "engine.listCommands"}));
|
||||||
|
let listed = r["result"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|c| c["id"] == "palette.open")
|
||||||
|
.cloned()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(listed["ui"], true);
|
||||||
|
assert_eq!(listed["defaultShortcut"], "Mod+Shift+P");
|
||||||
|
|
||||||
|
let r = client.call(execute("palette.open", json!({})));
|
||||||
|
assert_eq!(r["result"], Value::Null, "{r}");
|
||||||
|
let event = client.next("uiCommand");
|
||||||
|
assert_eq!(
|
||||||
|
event,
|
||||||
|
json!({"kind": "uiCommand", "id": "palette.open", "params": {}})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -8,6 +8,7 @@ mod project;
|
||||||
mod recovery;
|
mod recovery;
|
||||||
mod settings;
|
mod settings;
|
||||||
pub mod theme;
|
pub mod theme;
|
||||||
|
pub mod ui;
|
||||||
|
|
||||||
use crate::{EngineError, Registry};
|
use crate::{EngineError, Registry};
|
||||||
|
|
||||||
|
|
@ -37,5 +38,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
||||||
registry.register(Box::new(settings::Reset))?;
|
registry.register(Box::new(settings::Reset))?;
|
||||||
registry.register(Box::new(theme::List))?;
|
registry.register(Box::new(theme::List))?;
|
||||||
registry.register(Box::new(theme::SystemPreference))?;
|
registry.register(Box::new(theme::SystemPreference))?;
|
||||||
|
registry.register(Box::new(ui::RegisterCommands))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
202
crates/engine/src/cmd/ui.rs
Normal file
202
crates/engine/src/cmd/ui.rs
Normal file
|
|
@ -0,0 +1,202 @@
|
||||||
|
//! UI commands: commands the frontend runs itself (open the palette,
|
||||||
|
//! toggle a tool window), registered with `ui.registerCommands` so the
|
||||||
|
//! palette, the keymap and agents see them next to the engine's commands.
|
||||||
|
//!
|
||||||
|
//! The engine only lists them. Running one through [`crate::Engine::execute`]
|
||||||
|
//! (control channel, later MCP) emits [`crate::Event::UiCommand`], which the
|
||||||
|
//! frontend executes; that gives agents the same reach as the keyboard.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use crate::cmd::params::parse;
|
||||||
|
use crate::{Command, CommandInfo, CommandSpec, EngineError, Event, Outcome, State};
|
||||||
|
|
||||||
|
/// Most UI commands one registration may hold.
|
||||||
|
pub const MAX_COMMANDS: usize = 1000;
|
||||||
|
|
||||||
|
/// Longest command id, in bytes.
|
||||||
|
pub const MAX_ID_LEN: usize = 128;
|
||||||
|
|
||||||
|
/// Longest label key, menu path or shortcut, in bytes.
|
||||||
|
pub const MAX_TEXT_LEN: usize = 256;
|
||||||
|
|
||||||
|
/// Params documentation of every UI command.
|
||||||
|
const UI_PARAMS: &str = "any; passed to the frontend in uiCommand";
|
||||||
|
|
||||||
|
/// A command the frontend registered.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct UiCommand {
|
||||||
|
/// Command id, `area.action` in camelCase, e.g. `palette.open`.
|
||||||
|
pub id: String,
|
||||||
|
/// Message-catalog key of the label.
|
||||||
|
pub label_key: String,
|
||||||
|
/// Menu path with `/` separators.
|
||||||
|
#[serde(default)]
|
||||||
|
pub menu_path: Option<String>,
|
||||||
|
/// Default shortcut in Lutra notation.
|
||||||
|
#[serde(default)]
|
||||||
|
pub default_shortcut: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UiCommand {
|
||||||
|
/// Describes the command for `listCommands`; UI commands are always
|
||||||
|
/// enabled as far as the engine knows.
|
||||||
|
pub fn info(&self) -> CommandInfo {
|
||||||
|
CommandInfo {
|
||||||
|
id: self.id.clone(),
|
||||||
|
label: self.label_key.clone(),
|
||||||
|
menu_path: self.menu_path.clone(),
|
||||||
|
default_shortcut: self.default_shortcut.clone(),
|
||||||
|
params: UI_PARAMS.to_string(),
|
||||||
|
enabled: true,
|
||||||
|
label_key: Some(self.label_key.clone()),
|
||||||
|
ui: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Params of `ui.registerCommands`.
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct RegisterParams {
|
||||||
|
/// The frontend's UI commands; they replace any registered before.
|
||||||
|
commands: Vec<UiCommand>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an id has the `area.action` shape: dot-separated ASCII
|
||||||
|
/// alphanumeric parts, at least two of them.
|
||||||
|
///
|
||||||
|
/// # Parameters
|
||||||
|
/// - `id`: the id to check.
|
||||||
|
fn valid_id(id: &str) -> bool {
|
||||||
|
id.len() <= MAX_ID_LEN
|
||||||
|
&& id.split('.').count() >= 2
|
||||||
|
&& id
|
||||||
|
.split('.')
|
||||||
|
.all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks one registered command.
|
||||||
|
///
|
||||||
|
/// # Parameters
|
||||||
|
/// - `command`: the command.
|
||||||
|
/// - `state`: for the ids of the engine's own commands.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`EngineError::InvalidParams`] naming the problem.
|
||||||
|
fn validate(command: &UiCommand, state: &State) -> Result<(), EngineError> {
|
||||||
|
if !valid_id(&command.id) {
|
||||||
|
return Err(EngineError::invalid_params(
|
||||||
|
REGISTER,
|
||||||
|
format!("invalid command id {:?}", command.id),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if state.engine_commands.contains(command.id.as_str()) {
|
||||||
|
return Err(EngineError::invalid_params(
|
||||||
|
REGISTER,
|
||||||
|
format!("{} is an engine command", command.id),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if command.label_key.is_empty() || command.label_key.len() > MAX_TEXT_LEN {
|
||||||
|
return Err(EngineError::invalid_params(
|
||||||
|
REGISTER,
|
||||||
|
format!("invalid labelKey for {}", command.id),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let too_long = |text: &Option<String>| text.as_ref().is_some_and(|t| t.len() > MAX_TEXT_LEN);
|
||||||
|
if too_long(&command.menu_path) || too_long(&command.default_shortcut) {
|
||||||
|
return Err(EngineError::invalid_params(
|
||||||
|
REGISTER,
|
||||||
|
format!("menuPath or defaultShortcut of {} is too long", command.id),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Id of the registration command.
|
||||||
|
const REGISTER: &str = "ui.registerCommands";
|
||||||
|
|
||||||
|
/// `ui.registerCommands`: the frontend lists its UI commands, once after
|
||||||
|
/// `engine_ready`. A new registration replaces the previous one (a page
|
||||||
|
/// reload registers again).
|
||||||
|
pub struct RegisterCommands;
|
||||||
|
|
||||||
|
impl Command for RegisterCommands {
|
||||||
|
fn spec(&self) -> &CommandSpec {
|
||||||
|
&CommandSpec {
|
||||||
|
id: REGISTER,
|
||||||
|
label: "Register UI Commands",
|
||||||
|
menu_path: None,
|
||||||
|
default_shortcut: None,
|
||||||
|
params: "{ commands: [{ id, labelKey, menuPath?, defaultShortcut? }] }; replaces the UI commands registered before; returns { registered }",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||||
|
let p: RegisterParams = parse(REGISTER, params)?;
|
||||||
|
if p.commands.len() > MAX_COMMANDS {
|
||||||
|
return Err(EngineError::invalid_params(
|
||||||
|
REGISTER,
|
||||||
|
format!("more than {MAX_COMMANDS} commands"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut commands = BTreeMap::new();
|
||||||
|
for command in p.commands {
|
||||||
|
validate(&command, state)?;
|
||||||
|
if commands.contains_key(&command.id) {
|
||||||
|
return Err(EngineError::invalid_params(
|
||||||
|
REGISTER,
|
||||||
|
format!("{} is listed twice", command.id),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
commands.insert(command.id.clone(), command);
|
||||||
|
}
|
||||||
|
let registered = commands.len();
|
||||||
|
state.ui_commands = commands;
|
||||||
|
Ok(Outcome::value(json!({ "registered": registered })))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a registered UI command: queues [`Event::UiCommand`] for the
|
||||||
|
/// frontend.
|
||||||
|
///
|
||||||
|
/// # Parameters
|
||||||
|
/// - `state`: the state with the registered commands.
|
||||||
|
/// - `id`: the command id.
|
||||||
|
/// - `params`: passed on unchanged.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// `None` if no UI command has that id.
|
||||||
|
pub fn dispatch(state: &mut State, id: &str, params: Value) -> Option<Outcome> {
|
||||||
|
if !state.ui_commands.contains_key(id) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
state.emit(Event::UiCommand {
|
||||||
|
id: id.to_string(),
|
||||||
|
params,
|
||||||
|
});
|
||||||
|
Some(Outcome::value(Value::Null))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::valid_id;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ids_have_the_area_action_shape() {
|
||||||
|
assert!(valid_id("palette.open"));
|
||||||
|
assert!(valid_id("view.toggleProjectTree"));
|
||||||
|
assert!(valid_id("a.b.c1"));
|
||||||
|
assert!(!valid_id("palette"));
|
||||||
|
assert!(!valid_id("palette."));
|
||||||
|
assert!(!valid_id(".open"));
|
||||||
|
assert!(!valid_id("a..b"));
|
||||||
|
assert!(!valid_id("a.b c"));
|
||||||
|
assert!(!valid_id("a.ö"));
|
||||||
|
assert!(!valid_id(&format!("a.{}", "b".repeat(200))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -102,6 +102,13 @@ pub struct CommandInfo {
|
||||||
pub params: String,
|
pub params: String,
|
||||||
/// Whether the command can run in the current state.
|
/// Whether the command can run in the current state.
|
||||||
pub enabled: bool,
|
pub enabled: bool,
|
||||||
|
/// Message-catalog key of the label; set for UI commands, whose `label`
|
||||||
|
/// is the same key because the engine has no English text for them.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub label_key: Option<String>,
|
||||||
|
/// Whether the frontend registered the command (`ui.registerCommands`)
|
||||||
|
/// and runs it; running it through the engine emits `uiCommand`.
|
||||||
|
pub ui: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommandInfo {
|
impl CommandInfo {
|
||||||
|
|
@ -114,6 +121,8 @@ impl CommandInfo {
|
||||||
default_shortcut: spec.default_shortcut.map(str::to_string),
|
default_shortcut: spec.default_shortcut.map(str::to_string),
|
||||||
params: spec.params.to_string(),
|
params: spec.params.to_string(),
|
||||||
enabled,
|
enabled,
|
||||||
|
label_key: None,
|
||||||
|
ui: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -66,6 +66,7 @@ impl Engine {
|
||||||
pub fn new() -> Result<Self, EngineError> {
|
pub fn new() -> Result<Self, EngineError> {
|
||||||
let mut engine = Self::empty();
|
let mut engine = Self::empty();
|
||||||
cmd::register_builtins(&mut engine.registry)?;
|
cmd::register_builtins(&mut engine.registry)?;
|
||||||
|
engine.state.engine_commands = engine.registry.ids().collect();
|
||||||
Ok(engine)
|
Ok(engine)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -82,7 +83,10 @@ impl Engine {
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Returns [`EngineError::Internal`] if the id is already taken.
|
/// Returns [`EngineError::Internal`] if the id is already taken.
|
||||||
pub fn register(&mut self, command: Box<dyn Command>) -> Result<(), EngineError> {
|
pub fn register(&mut self, command: Box<dyn Command>) -> Result<(), EngineError> {
|
||||||
self.registry.register(command)
|
let id = command.spec().id;
|
||||||
|
self.registry.register(command)?;
|
||||||
|
self.state.engine_commands.insert(id);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs a command inside the guard. On success the outcome carries every
|
/// Runs a command inside the guard. On success the outcome carries every
|
||||||
|
|
@ -97,11 +101,18 @@ impl Engine {
|
||||||
/// [`EngineError::UnknownCommand`] for an unknown id,
|
/// [`EngineError::UnknownCommand`] for an unknown id,
|
||||||
/// [`EngineError::Disabled`] if the command is disabled, the command's own
|
/// [`EngineError::Disabled`] if the command is disabled, the command's own
|
||||||
/// error, or [`EngineError::Internal`] if it panicked.
|
/// error, or [`EngineError::Internal`] if it panicked.
|
||||||
|
///
|
||||||
|
/// A UI command registered with `ui.registerCommands` is not run here:
|
||||||
|
/// the engine queues `uiCommand` for the frontend and returns `null`.
|
||||||
pub fn execute(&mut self, id: &str, params: Value) -> Result<Outcome, EngineError> {
|
pub fn execute(&mut self, id: &str, params: Value) -> Result<Outcome, EngineError> {
|
||||||
let Self { registry, state } = self;
|
let Self { registry, state } = self;
|
||||||
let command = registry
|
let Some(command) = registry.get(id) else {
|
||||||
.get(id)
|
let mut outcome = cmd::ui::dispatch(state, id, params)
|
||||||
.ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
.ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||||
|
state.commands_run = state.commands_run.saturating_add(1);
|
||||||
|
outcome.events = state.take_events();
|
||||||
|
return Ok(outcome);
|
||||||
|
};
|
||||||
let result = guard::run(|| {
|
let result = guard::run(|| {
|
||||||
if !command.enabled(state) {
|
if !command.enabled(state) {
|
||||||
return Err(EngineError::Disabled(id.to_string()));
|
return Err(EngineError::Disabled(id.to_string()));
|
||||||
|
|
@ -180,16 +191,26 @@ impl Engine {
|
||||||
self.state.take_events()
|
self.state.take_events()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Describes every command with its current enabled state. A command whose
|
/// Describes every command with its current enabled state, the
|
||||||
/// `enabled` check panics is listed as disabled.
|
/// engine's and the registered UI commands (`ui: true`), in id order.
|
||||||
|
/// A command whose `enabled` check panics is listed as disabled.
|
||||||
pub fn list_commands(&self) -> Vec<CommandInfo> {
|
pub fn list_commands(&self) -> Vec<CommandInfo> {
|
||||||
self.registry
|
let mut list: Vec<CommandInfo> = self
|
||||||
|
.registry
|
||||||
.iter()
|
.iter()
|
||||||
.map(|c| {
|
.map(|c| {
|
||||||
let enabled = guard::run(|| Ok(c.enabled(&self.state))).unwrap_or(false);
|
let enabled = guard::run(|| Ok(c.enabled(&self.state))).unwrap_or(false);
|
||||||
CommandInfo::new(c.spec(), enabled)
|
CommandInfo::new(c.spec(), enabled)
|
||||||
})
|
})
|
||||||
.collect()
|
.chain(
|
||||||
|
self.state
|
||||||
|
.ui_commands
|
||||||
|
.values()
|
||||||
|
.map(cmd::ui::UiCommand::info),
|
||||||
|
)
|
||||||
|
.collect();
|
||||||
|
list.sort_by(|a, b| a.id.cmp(&b.id));
|
||||||
|
list
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read access to the state.
|
/// Read access to the state.
|
||||||
|
|
@ -359,6 +380,7 @@ mod tests {
|
||||||
"test.disabled",
|
"test.disabled",
|
||||||
"theme.list",
|
"theme.list",
|
||||||
"theme.systemPreference",
|
"theme.systemPreference",
|
||||||
|
"ui.registerCommands",
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
let by_id = |id: &str| list.iter().find(|c| c.id == id).unwrap();
|
let by_id = |id: &str| list.iter().find(|c| c.id == id).unwrap();
|
||||||
|
|
|
||||||
|
|
@ -129,6 +129,14 @@ pub enum Event {
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
params: Option<Map<String, Value>>,
|
params: Option<Map<String, Value>>,
|
||||||
},
|
},
|
||||||
|
/// A UI command registered with `ui.registerCommands` was run through
|
||||||
|
/// the engine (control channel, later MCP); the frontend executes it.
|
||||||
|
UiCommand {
|
||||||
|
/// Command id, e.g. `palette.open`.
|
||||||
|
id: String,
|
||||||
|
/// The params the command was run with, as given.
|
||||||
|
params: Value,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Severity of an [`Event::Notification`].
|
/// Severity of an [`Event::Notification`].
|
||||||
|
|
@ -208,4 +216,16 @@ mod tests {
|
||||||
json!({"kind": "themeChanged", "id": "lutra-light", "dark": false, "tokens": {"--lt-bg": "#f4f1ec"}})
|
json!({"kind": "themeChanged", "id": "lutra-light", "dark": false, "tokens": {"--lt-bg": "#f4f1ec"}})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ui_command_shape() {
|
||||||
|
let e = Event::UiCommand {
|
||||||
|
id: "palette.open".into(),
|
||||||
|
params: json!({}),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(e).unwrap(),
|
||||||
|
json!({"kind": "uiCommand", "id": "palette.open", "params": {}})
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,11 @@ impl Registry {
|
||||||
self.commands.get(id).map(Box::as_ref)
|
self.commands.get(id).map(Box::as_ref)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The ids of every command.
|
||||||
|
pub fn ids(&self) -> impl Iterator<Item = &'static str> + '_ {
|
||||||
|
self.commands.keys().copied()
|
||||||
|
}
|
||||||
|
|
||||||
/// Iterates over the commands in id order.
|
/// Iterates over the commands in id order.
|
||||||
pub fn iter(&self) -> impl Iterator<Item = &dyn Command> {
|
pub fn iter(&self) -> impl Iterator<Item = &dyn Command> {
|
||||||
self.commands.values().map(Box::as_ref)
|
self.commands.values().map(Box::as_ref)
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,11 @@
|
||||||
//! Workspace state that commands read and change.
|
//! Workspace state that commands read and change.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use serde_json::{Map, Value};
|
use serde_json::{Map, Value};
|
||||||
|
|
||||||
use crate::buffers::Buffers;
|
use crate::buffers::Buffers;
|
||||||
|
use crate::cmd::ui::UiCommand;
|
||||||
use crate::journal::Journal;
|
use crate::journal::Journal;
|
||||||
use crate::settings::Settings;
|
use crate::settings::Settings;
|
||||||
use crate::workspace::Workspace;
|
use crate::workspace::Workspace;
|
||||||
|
|
@ -28,6 +31,10 @@ pub struct State {
|
||||||
/// The crash-recovery journal of the open project; `None` without a
|
/// The crash-recovery journal of the open project; `None` without a
|
||||||
/// project or without persistence.
|
/// project or without persistence.
|
||||||
pub journal: Option<Journal>,
|
pub journal: Option<Journal>,
|
||||||
|
/// Ids of the engine's own commands, which UI commands may not take.
|
||||||
|
pub engine_commands: BTreeSet<&'static str>,
|
||||||
|
/// UI commands the frontend registered (`ui.registerCommands`), by id.
|
||||||
|
pub ui_commands: BTreeMap<String, UiCommand>,
|
||||||
/// Number of notifications emitted, for their ids.
|
/// Number of notifications emitted, for their ids.
|
||||||
notifications: u64,
|
notifications: u64,
|
||||||
/// Events queued for the host, oldest first.
|
/// Events queued for the host, oldest first.
|
||||||
|
|
|
||||||
172
crates/engine/tests/ui_commands.rs
Normal file
172
crates/engine/tests/ui_commands.rs
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
//! UI commands: `ui.registerCommands` validates and replaces the frontend's
|
||||||
|
//! commands, `listCommands` shows them with `ui: true`, and running one
|
||||||
|
//! through the engine emits `uiCommand` for the frontend.
|
||||||
|
|
||||||
|
#![allow(
|
||||||
|
clippy::unwrap_used,
|
||||||
|
clippy::expect_used,
|
||||||
|
clippy::panic,
|
||||||
|
clippy::indexing_slicing
|
||||||
|
)]
|
||||||
|
|
||||||
|
use lutra_engine::{Engine, Event};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
fn register(engine: &mut Engine, commands: Value) -> Result<Value, String> {
|
||||||
|
engine
|
||||||
|
.execute("ui.registerCommands", json!({ "commands": commands }))
|
||||||
|
.map(|o| o.value)
|
||||||
|
.map_err(|e| e.code().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first_commands() -> Value {
|
||||||
|
json!([
|
||||||
|
{"id": "palette.open", "labelKey": "command.palette.open", "defaultShortcut": "Mod+Shift+P"},
|
||||||
|
{"id": "settings.open", "labelKey": "command.settings.open", "defaultShortcut": "Mod+,"},
|
||||||
|
{"id": "view.toggleProjectTree", "labelKey": "command.view.toggleProjectTree", "menuPath": "View/Project", "defaultShortcut": "Mod+1"},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn registered_commands_are_listed_as_ui_commands() {
|
||||||
|
let mut e = Engine::new().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
register(&mut e, first_commands()).unwrap(),
|
||||||
|
json!({"registered": 3})
|
||||||
|
);
|
||||||
|
let list = e.list_commands();
|
||||||
|
let ids: Vec<_> = list.iter().map(|c| c.id.as_str()).collect();
|
||||||
|
let mut sorted = ids.clone();
|
||||||
|
sorted.sort_unstable();
|
||||||
|
assert_eq!(ids, sorted, "one list in id order");
|
||||||
|
let palette = list.iter().find(|c| c.id == "palette.open").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(palette).unwrap(),
|
||||||
|
json!({
|
||||||
|
"id": "palette.open",
|
||||||
|
"label": "command.palette.open",
|
||||||
|
"labelKey": "command.palette.open",
|
||||||
|
"menuPath": null,
|
||||||
|
"defaultShortcut": "Mod+Shift+P",
|
||||||
|
"params": "any; passed to the frontend in uiCommand",
|
||||||
|
"enabled": true,
|
||||||
|
"ui": true,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
let tree = list
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == "view.toggleProjectTree")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(tree.menu_path.as_deref(), Some("View/Project"));
|
||||||
|
let quit = serde_json::to_value(list.iter().find(|c| c.id == "app.quit").unwrap()).unwrap();
|
||||||
|
assert_eq!(quit["ui"], false);
|
||||||
|
assert!(quit.get("labelKey").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn running_a_ui_command_emits_ui_command() {
|
||||||
|
let mut e = Engine::new().unwrap();
|
||||||
|
register(&mut e, first_commands()).unwrap();
|
||||||
|
let outcome = e.execute("palette.open", json!({"query": "save"})).unwrap();
|
||||||
|
assert_eq!(outcome.value, Value::Null);
|
||||||
|
assert_eq!(
|
||||||
|
outcome.events,
|
||||||
|
vec![Event::UiCommand {
|
||||||
|
id: "palette.open".into(),
|
||||||
|
params: json!({"query": "save"}),
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
let outcome = e.execute("settings.open", Value::Null).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
outcome.events,
|
||||||
|
vec![Event::UiCommand {
|
||||||
|
id: "settings.open".into(),
|
||||||
|
params: Value::Null,
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_registration_replaces_the_old_one() {
|
||||||
|
let mut e = Engine::new().unwrap();
|
||||||
|
register(&mut e, first_commands()).unwrap();
|
||||||
|
register(
|
||||||
|
&mut e,
|
||||||
|
json!([{"id": "palette.open", "labelKey": "command.palette.open"}]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
e.execute("view.toggleProjectTree", Value::Null)
|
||||||
|
.unwrap_err()
|
||||||
|
.code(),
|
||||||
|
"unknown_command"
|
||||||
|
);
|
||||||
|
let ui: Vec<_> = e
|
||||||
|
.list_commands()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|c| c.ui)
|
||||||
|
.map(|c| c.id)
|
||||||
|
.collect();
|
||||||
|
assert_eq!(ui, vec!["palette.open"]);
|
||||||
|
register(&mut e, json!([])).unwrap();
|
||||||
|
assert!(e.list_commands().iter().all(|c| !c.ui));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_registrations_change_nothing() {
|
||||||
|
let mut e = Engine::new().unwrap();
|
||||||
|
register(&mut e, first_commands()).unwrap();
|
||||||
|
for bad in [
|
||||||
|
json!([{"id": "file.save", "labelKey": "x.y"}]),
|
||||||
|
json!([{"id": "nodot", "labelKey": "x.y"}]),
|
||||||
|
json!([{"id": "a.b", "labelKey": ""}]),
|
||||||
|
json!([{"id": "a.b", "labelKey": "x.y", "extra": 1}]),
|
||||||
|
json!([{"id": "a.b", "labelKey": "x.y"}, {"id": "a.b", "labelKey": "x.z"}]),
|
||||||
|
json!([{"id": "a.b", "labelKey": "x.y", "defaultShortcut": "M".repeat(300)}]),
|
||||||
|
json!({"id": "a.b"}),
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
register(&mut e, bad.clone()),
|
||||||
|
Err("invalid_params".into()),
|
||||||
|
"{bad}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let many: Vec<_> = (0..1001)
|
||||||
|
.map(|i| json!({"id": format!("a.c{i}"), "labelKey": "x.y"}))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
register(&mut e, Value::Array(many)),
|
||||||
|
Err("invalid_params".into())
|
||||||
|
);
|
||||||
|
assert_eq!(e.list_commands().iter().filter(|c| c.ui).count(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#[test]
|
||||||
|
fn arbitrary_registrations_never_panic(params in any::<String>()) {
|
||||||
|
let mut e = Engine::new().unwrap();
|
||||||
|
let value = serde_json::from_str(¶ms).unwrap_or(Value::String(params));
|
||||||
|
let _ = e.execute("ui.registerCommands", value);
|
||||||
|
let _ = e.list_commands();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn valid_ids_round_trip(area in "[a-z][a-zA-Z0-9]{0,10}", action in "[a-z][a-zA-Z0-9]{0,10}") {
|
||||||
|
let id = format!("{area}.{action}");
|
||||||
|
prop_assume!(!e_has(&id));
|
||||||
|
let mut e = Engine::new().unwrap();
|
||||||
|
register(&mut e, json!([{"id": id, "labelKey": "k.k"}])).unwrap();
|
||||||
|
let outcome = e.execute(&id, json!(1)).unwrap();
|
||||||
|
prop_assert_eq!(outcome.events, vec![Event::UiCommand { id: id.clone(), params: json!(1) }]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the engine already has a command with this id.
|
||||||
|
fn e_has(id: &str) -> bool {
|
||||||
|
Engine::new()
|
||||||
|
.unwrap()
|
||||||
|
.list_commands()
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.id == id)
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# Architecture
|
# Architecture
|
||||||
|
|
||||||
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal and notifications documented · **Last updated:** 2026-10-16
|
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands and the palette documented · **Last updated:** 2026-10-16
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
|
|
@ -47,6 +47,7 @@ As built in M0:
|
||||||
- Effects are requests the engine cannot fulfil below L6 (`Effect::Quit` so far). The host (desktop, tests) applies them after the command returns. Commands never call into Tauri.
|
- Effects are requests the engine cannot fulfil below L6 (`Effect::Quit` so far). The host (desktop, tests) applies them after the command returns. Commands never call into Tauri.
|
||||||
- `EngineError` has a stable string `code()` used by the control channel and the frontend: `unknown_command`, `disabled` (e.g. a file command without a project), `invalid_params`, `stale_version` (a `buffer.edit` based on an old version), `unsaved_changes` (closing a dirty buffer or project without `force`), `failed`, `internal`.
|
- `EngineError` has a stable string `code()` used by the control channel and the frontend: `unknown_command`, `disabled` (e.g. a file command without a project), `invalid_params`, `stale_version` (a `buffer.edit` based on an old version), `unsaved_changes` (closing a dirty buffer or project without `force`), `failed`, `internal`.
|
||||||
- Shortcut notation: `Mod` is Ctrl on Windows and Linux and Cmd on macOS (`Mod+Q`). Default shortcuts are Lutra's own.
|
- Shortcut notation: `Mod` is Ctrl on Windows and Linux and Cmd on macOS (`Mod+Q`). Default shortcuts are Lutra's own.
|
||||||
|
- UI commands (M1.8) are the frontend's own commands, listed next to the engine's; see UI commands, palette and keymap below.
|
||||||
|
|
||||||
## Guard
|
## Guard
|
||||||
|
|
||||||
|
|
@ -78,7 +79,7 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
|
||||||
|
|
||||||
### Events
|
### Events
|
||||||
|
|
||||||
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
|
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
|
||||||
|
|
||||||
Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump.
|
Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump.
|
||||||
|
|
||||||
|
|
@ -97,7 +98,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
||||||
- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it; `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them.
|
- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it; `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them.
|
||||||
- One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text.
|
- One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text.
|
||||||
- Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table.
|
- Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table.
|
||||||
- Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context. Saving and closing wait until the sync has no pending edits.
|
- Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context; since M1.8 through the global keymap (see UI commands, palette and keymap). Saving and closing wait until the sync has no pending edits.
|
||||||
- Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Lutra saves only on request for now (no autosave).
|
- Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Lutra saves only on request for now (no autosave).
|
||||||
- Theme: the editor reads colours only from `--lt-*` tokens, including the editor tokens from M1.10 (selection, active line, cursor, gutter, match, editor font size); no fallbacks remain.
|
- Theme: the editor reads colours only from `--lt-*` tokens, including the editor tokens from M1.10 (selection, active line, cursor, gutter, match, editor font size); no fallbacks remain.
|
||||||
|
|
||||||
|
|
@ -151,6 +152,36 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
||||||
- **UI:** `ui/src/components/recovery/` (store `recovery.ts`, `RecoveryDialog.vue`, mounted in `App.vue`). The list comes from `recoveryAvailable` and, because that event is not replayed after a page reload, from `recovery.list` on `projectOpened`. Restore all, Restore selected (the rest stay listed) and Discard always pass explicit paths; Escape closes and keeps the journal for the next open.
|
- **UI:** `ui/src/components/recovery/` (store `recovery.ts`, `RecoveryDialog.vue`, mounted in `App.vue`). The list comes from `recoveryAvailable` and, because that event is not replayed after a page reload, from `recovery.list` on `projectOpened`. Restore all, Restore selected (the rest stay listed) and Discard always pass explicit paths; Escape closes and keeps the journal for the next open.
|
||||||
- **Limits:** two Lutra instances on the same project share one journal directory; `diskChanged` misses a disk change that happened before the last journal write.
|
- **Limits:** two Lutra instances on the same project share one journal directory; `diskChanged` misses a disk change that happened before the last journal write.
|
||||||
|
|
||||||
|
### UI commands, palette and keymap (M1.8)
|
||||||
|
|
||||||
|
- **Registration:** the frontend calls `ui.registerCommands {commands: [{id, labelKey, menuPath?, defaultShortcut?}]}` when it starts (`ui/src/commands/store.ts`). A registration replaces the previous one, so a page reload registers again. The engine keeps them in `State::ui_commands` (`crates/engine/src/cmd/ui.rs`). It checks every entry and changes nothing on a bad one (`invalid_params`):
|
||||||
|
- ids have the `area.action` shape (ASCII alphanumeric parts), at most 128 bytes;
|
||||||
|
- an id may not be an engine command or listed twice;
|
||||||
|
- `labelKey` is not empty;
|
||||||
|
- texts are at most 256 bytes; at most 1,000 commands.
|
||||||
|
- **Listing:** `listCommands` returns one list in id order: engine commands and UI commands. `CommandInfo` has `ui: bool`; UI commands also carry `labelKey`, use it as `label` (the engine has no English for them) and are always `enabled` as far as the engine knows.
|
||||||
|
- **Running from outside:** `Engine::execute` on a UI command id queues `uiCommand {id, params}` and returns `null` (params are passed on unchanged). The desktop publishes the event to the window and to control subscribers like any other. The frontend runs the command, so `engine.execute palette.open` over the control channel opens the palette. A `uiCommand` the frontend cannot run (no handler, or disabled) becomes a warning toast.
|
||||||
|
- **Frontend:** `ui/src/commands/`:
|
||||||
|
- `uiCommands.ts` lists the UI commands: `palette.open` `Mod+Shift+P`, `settings.open` `Mod+,`, `view.toggleProjectTree` `Mod+1`.
|
||||||
|
- `keymap.ts` parses Lutra notation and matches by key code (letters, digits and US punctuation by `code`, so Alt and Shift layout effects don't matter). It also formats shortcuts for display with catalog modifier names.
|
||||||
|
- `rank.ts` ranks for the palette.
|
||||||
|
- `store.ts` (Pinia `commands`) holds the merged list, the keymap, the handlers and the recent commands.
|
||||||
|
- **Handlers:** components supply behaviour with `provide(id, {run, enabled?})`:
|
||||||
|
- the palette provides `palette.open`;
|
||||||
|
- the main layout provides `view.toggleProjectTree`;
|
||||||
|
- the editor area provides `file.save`, `file.saveAll` and `buffer.close` with the active buffer as context (they replace the editor-only keymap of M1.6).
|
||||||
|
- A UI command without a handler is disabled. `settings.open` stays disabled until the settings dialog (M1.9b) provides it.
|
||||||
|
- An engine command without a handler runs through `run(id, {})`.
|
||||||
|
- **Enabled state:** a handler's `enabled` decides, else the engine's. The list is refreshed on `projectOpened`/`projectClosed` and whenever the palette opens.
|
||||||
|
- **Keyboard:** one window `keydown` listener in the capture phase (works while CodeMirror or an input has focus). A matching shortcut is always swallowed; a disabled command does nothing. A failure raises `notification.command.failed`.
|
||||||
|
- **Palette** (`ui/src/components/palette/CommandPalette.vue`, mounted in `App.vue`):
|
||||||
|
- **Contents:** it offers UI commands and engine commands that have a menu path or a default shortcut. Protocol commands such as `buffer.edit` are left out.
|
||||||
|
- **Ranking:** labels are catalog text for UI commands and the engine's label otherwise. Tiers: prefix, word prefix, query spread over consecutive word starts, substring, in-order characters; the label or the id may match. Within a tier recent commands come first (in memory, 20, not `palette.open` itself), then shorter texts, then the label.
|
||||||
|
- **Keys:** arrow keys wrap, Enter runs an enabled row, Escape or a click outside closes.
|
||||||
|
- **Running:** the command runs after the palette closed and returned the focus.
|
||||||
|
- **Rows:** disabled rows are dimmed with `aria-disabled`.
|
||||||
|
- **Accessibility:** combobox with listbox and `aria-activedescendant`.
|
||||||
|
|
||||||
## Decisions (M0)
|
## Decisions (M0)
|
||||||
|
|
||||||
| Question | Decision | Why |
|
| Question | Decision | Why |
|
||||||
|
|
@ -168,6 +199,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| Date | Change | Summary |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| 2026-10-16 | minor | M1.8: UI commands (`ui.registerCommands`, `uiCommand`, `ui` in listCommands), global keymap, command palette |
|
||||||
| 2026-10-16 | minor | M1.12: notifications (host emission, early-event replay, toast store and stack, deferred engine_ready) |
|
| 2026-10-16 | minor | M1.12: notifications (host emission, early-event replay, toast store and stack, deferred engine_ready) |
|
||||||
| 2026-10-16 | minor | M1.13: open buffers pin their parent directory in the watcher, `bufferFocused`, truncated listing row |
|
| 2026-10-16 | minor | M1.13: open buffers pin their parent directory in the watcher, `bufferFocused`, truncated listing row |
|
||||||
| 2026-10-16 | minor | M1.7: recovery journal (storage, debounce, removal, commands, recoveryAvailable, restore dialog) |
|
| 2026-10-16 | minor | M1.7: recovery journal (storage, debounce, removal, commands, recoveryAvailable, restore dialog) |
|
||||||
|
|
|
||||||
|
|
@ -6,9 +6,10 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
|
||||||
|
|
||||||
| # | Gap | Milestone | Estimate (one agent) |
|
| # | Gap | Milestone | Estimate (one agent) |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
|
| 2026-10-16 | minor | G3: command palette, global keymap, UI commands (M1.8) |
|
||||||
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
|
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
|
||||||
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~16 h |
|
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~16 h |
|
||||||
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6); command palette, settings (backend: M1.9a; dialog: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker comes with the dialog) | M1 | ~24 h |
|
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); settings (backend: M1.9a; dialog: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker comes with the dialog) | M1 | ~24 h |
|
||||||
| G4 | Syntax and structure: tree-sitter PHP, Lezer highlighting, file structure | M2 | ~15 h |
|
| G4 | Syntax and structure: tree-sitter PHP, Lezer highlighting, file structure | M2 | ~15 h |
|
||||||
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
||||||
| G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h |
|
| G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h |
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
|
||||||
| Milestone | Goal | State | Hours |
|
| Milestone | Goal | State | Hours |
|
||||||
|---|---|---|---:|
|
|---|---|---|---:|
|
||||||
| M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) |
|
| M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) |
|
||||||
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups) | ~6 (2.5 measured for M1.1–M1.6) |
|
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap) | ~6 (2.5 measured for M1.1–M1.6) |
|
||||||
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~5 |
|
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~5 |
|
||||||
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~8 |
|
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~8 |
|
||||||
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
|
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
|
||||||
|
|
@ -31,6 +31,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| Date | Change | Summary |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| 2026-10-16 | minor | M1.8 command palette, global keymap, UI commands |
|
||||||
| 2026-10-16 | minor | M1.12 notifications |
|
| 2026-10-16 | minor | M1.12 notifications |
|
||||||
| 2026-10-16 | minor | M1.13 C1 follow-ups |
|
| 2026-10-16 | minor | M1.13 C1 follow-ups |
|
||||||
| 2026-10-16 | minor | M1.7 recovery journal |
|
| 2026-10-16 | minor | M1.7 recovery journal |
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
|
||||||
|---|---:|---:|---|---:|---|
|
|---|---:|---:|---|---:|---|
|
||||||
| Editor core | 12 | 9% (est.) | syntax highlighting (M2), code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, autosave, local history, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs; recovery journal not yet checked in the running app (gaming mode) | ~106 (est.) | M1.13: opening a file that is already open switches to its tab (`bufferFocused`; engine test, Vitest, control-channel test; live check pending (gaming mode)); files in folders the tree never expanded still reload or report changes on disk, because the parent directory of every open buffer stays watched (engine tests). M1.7: crash-recovery journal (`crates/engine/src/journal.rs`, `cmd/recovery.rs`): dirty buffers are written atomically to `<data_dir>/recovery/<project-id>/` about 1 s after the last edit (at least every 2 s while typing), never per keystroke; removed on save, close and discard; `recoveryAvailable` after `project.open`, `recovery.list/restore/discard`; restored buffers are dirty and keep line ending and BOM; corrupt entries are moved aside with a warning. Restore dialog (`ui/src/components/recovery/`: Restore all / selected / Discard, time, changed-on-disk hint). Tests: engine dropped mid-edit and a new engine restores the exact CRLF + BOM text, corrupt entries, removal paths, a property test of random edit sequences → crash → restore equals the buffer (`crates/engine/tests/recovery.rs`, 10 tests), the same flow headless over the control channel (`crates/control/tests/recovery.rs`), 10 Vitest tests for the dialog. 1 MiB entry write: 8.5 ms median (release, measured). Graded against `plan/phpstorm/04-recovery.md`. M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) |
|
| Editor core | 12 | 9% (est.) | syntax highlighting (M2), code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, autosave, local history, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs; recovery journal not yet checked in the running app (gaming mode) | ~106 (est.) | M1.13: opening a file that is already open switches to its tab (`bufferFocused`; engine test, Vitest, control-channel test; live check pending (gaming mode)); files in folders the tree never expanded still reload or report changes on disk, because the parent directory of every open buffer stays watched (engine tests). M1.7: crash-recovery journal (`crates/engine/src/journal.rs`, `cmd/recovery.rs`): dirty buffers are written atomically to `<data_dir>/recovery/<project-id>/` about 1 s after the last edit (at least every 2 s while typing), never per keystroke; removed on save, close and discard; `recoveryAvailable` after `project.open`, `recovery.list/restore/discard`; restored buffers are dirty and keep line ending and BOM; corrupt entries are moved aside with a warning. Restore dialog (`ui/src/components/recovery/`: Restore all / selected / Discard, time, changed-on-disk hint). Tests: engine dropped mid-edit and a new engine restores the exact CRLF + BOM text, corrupt entries, removal paths, a property test of random edit sequences → crash → restore equals the buffer (`crates/engine/tests/recovery.rs`, 10 tests), the same flow headless over the control channel (`crates/control/tests/recovery.rs`), 10 Vitest tests for the dialog. 1 MiB entry write: 8.5 ms median (release, measured). Graded against `plan/phpstorm/04-recovery.md`. M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) |
|
||||||
| Project view, VFS | 6 | 8% (est.) | views list (project / scopes), toolbar (Select Opened File, Expand/Collapse All), sort and display options, show/hide excluded, distinct icons for library and excluded folders, file colours, speed search, preview, file operations | ~37 (est.) | `lutra-vfs` (M1.2): lazy sorted listing, ignore rules (.gitignore, .ignore, info/exclude, global excludes, Lutra defaults), native file watching via `notify` with a polling fallback, capped UTF-8 reads, atomic writes; 34 tests on temp dirs, watcher tests run on both backends (`crates/vfs/tests`). M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine. M1.3: `project.open`, `project.close`, `project.children` (watches listed directories, capped at 256 native / 32 polling, least recently listed dropped), `treeChanged` events from disk, `events.subscribe` on the control channel with a TCP test (`crates/control/tests/events.rs`). M1.4: the tree runs against the engine in the app: folder picker (`project.openDialog`) and `lutra-desktop --control PORT PATH` open a project, the tree lists it lazily with ignored (`var/` from `.gitignore`) and excluded (`node_modules`) entries dimmed, a file created on disk appears in an expanded folder within ~100 ms; verified with `ui.screenshot` on Windows 11 and Vitest (`ui/tests/project/`, `ui/tests/ipcEvents.test.ts`). M1.13: a directory listed only partly (more than 100,000 entries) ends with a "Listing truncated" note row (Vitest). M1.12: a folder that cannot be opened from the picker or the command line (including `unsaved_changes` when switching projects) and stopped file watching show as toasts instead of stderr (`apps/lutra-desktop/src/host.rs`, `ui/src/stores/notifications.ts`, `ui/tests/notifications/`, 19 Vitest tests; live check pending, gaming mode); score unchanged. Graded against `plan/phpstorm/02-project-view.md`: tool window, folder-first tree, dimmed ignored/excluded, keyboard navigation and live refresh exist; most toolbar, view and display options do not |
|
| Project view, VFS | 6 | 8% (est.) | views list (project / scopes), toolbar (Select Opened File, Expand/Collapse All), sort and display options, show/hide excluded, distinct icons for library and excluded folders, file colours, speed search, preview, file operations | ~37 (est.) | `lutra-vfs` (M1.2): lazy sorted listing, ignore rules (.gitignore, .ignore, info/exclude, global excludes, Lutra defaults), native file watching via `notify` with a polling fallback, capped UTF-8 reads, atomic writes; 34 tests on temp dirs, watcher tests run on both backends (`crates/vfs/tests`). M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine. M1.3: `project.open`, `project.close`, `project.children` (watches listed directories, capped at 256 native / 32 polling, least recently listed dropped), `treeChanged` events from disk, `events.subscribe` on the control channel with a TCP test (`crates/control/tests/events.rs`). M1.4: the tree runs against the engine in the app: folder picker (`project.openDialog`) and `lutra-desktop --control PORT PATH` open a project, the tree lists it lazily with ignored (`var/` from `.gitignore`) and excluded (`node_modules`) entries dimmed, a file created on disk appears in an expanded folder within ~100 ms; verified with `ui.screenshot` on Windows 11 and Vitest (`ui/tests/project/`, `ui/tests/ipcEvents.test.ts`). M1.13: a directory listed only partly (more than 100,000 entries) ends with a "Listing truncated" note row (Vitest). M1.12: a folder that cannot be opened from the picker or the command line (including `unsaved_changes` when switching projects) and stopped file watching show as toasts instead of stderr (`apps/lutra-desktop/src/host.rs`, `ui/src/stores/notifications.ts`, `ui/tests/notifications/`, 19 Vitest tests; live check pending, gaming mode); score unchanged. Graded against `plan/phpstorm/02-project-view.md`: tool window, folder-first tree, dimmed ignored/excluded, keyboard navigation and live refresh exist; most toolbar, view and display options do not |
|
||||||
| Navigation | 10 | 0% | everything | ~120 (est.) | — |
|
| Navigation | 10 | 0% | everything (M1.8: a command palette over commands only, no go-to-file/class/symbol yet; score unchanged) | ~120 (est.) | M1.8: `ui/src/components/palette/`, `ui/src/commands/` (fuzzy ranking, recent commands, global keymap), Vitest `ui/tests/palette/`, `ui/tests/commands/` |
|
||||||
| Search and replace | 6 | 0% | everything | ~80 (est.) | — |
|
| Search and replace | 6 | 0% | everything | ~80 (est.) | — |
|
||||||
| Code completion | 10 | 0% | everything | ~250 (est.) | — |
|
| Code completion | 10 | 0% | everything | ~250 (est.) | — |
|
||||||
| Inspections and quick-fixes | 8 | 0% | everything | ~300 (est.) | — |
|
| Inspections and quick-fixes | 8 | 0% | everything | ~300 (est.) | — |
|
||||||
|
|
@ -31,7 +31,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
|
||||||
| HTTP client | 1 | 0% | everything | ~60 (est.) | — |
|
| HTTP client | 1 | 0% | everything | ~60 (est.) | — |
|
||||||
| Web languages | 2 | 0% | everything | ~200 (est.) | — |
|
| Web languages | 2 | 0% | everything | ~200 (est.) | — |
|
||||||
| Docker and remote | 1 | 0% | everything | ~120 (est.) | — |
|
| Docker and remote | 1 | 0% | everything | ~120 (est.) | — |
|
||||||
| Settings, keymaps, themes | 1 | 4% (est.) | settings UI, keymaps, colour scheme editor, custom and imported themes, per-language colours (M1.9a: settings backend with 3 keys, persistence, `settings.*` commands, no UI yet; M1.10: light and dark themes with live switching and a system mode, chosen through the setting only) | ~60 (est.) | — |
|
| Settings, keymaps, themes | 1 | 4% (est.) | settings UI, keymaps (M1.8: one global keymap from the commands' default shortcuts, not editable), colour scheme editor, custom and imported themes, per-language colours (M1.9a: settings backend with 3 keys, persistence, `settings.*` commands, no UI yet; M1.10: light and dark themes with live switching and a system mode, chosen through the setting only) | ~60 (est.) | — |
|
||||||
| Plug-ins | 0.5 | 0% | everything | ~120 (est.) | — |
|
| Plug-ins | 0.5 | 0% | everything | ~120 (est.) | — |
|
||||||
| AI features | 0.5 | 0% | everything | ~60 (est.) | — |
|
| AI features | 0.5 | 0% | everything | ~60 (est.) | — |
|
||||||
|
|
||||||
|
|
@ -62,6 +62,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| Date | Change | Summary |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| 2026-10-16 | minor | M1.8: Navigation and Settings/keymaps evidence (palette, global keymap), scores unchanged |
|
||||||
| 2026-10-16 | minor | M1.12: Project view evidence (picker errors as toasts), scores unchanged |
|
| 2026-10-16 | minor | M1.12: Project view evidence (picker errors as toasts), scores unchanged |
|
||||||
| 2026-10-16 | minor | M1.13: Editor core and Project view evidence (focus on re-open, watched buffer folders, truncated note), scores unchanged |
|
| 2026-10-16 | minor | M1.13: Editor core and Project view evidence (focus on re-open, watched buffer folders, truncated note), scores unchanged |
|
||||||
| 2026-10-16 | minor | M1.7: Editor core 8% → 9% (est.), crash-recovery journal and restore dialog |
|
| 2026-10-16 | minor | M1.7: Editor core 8% → 9% (est.), crash-recovery journal and restore dialog |
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# UI parity checklist
|
# UI parity checklist
|
||||||
|
|
||||||
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12) · **Last updated:** 2026-10-16
|
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8) · **Last updated:** 2026-10-16
|
||||||
|
|
||||||
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
|
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
|
||||||
- M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4).
|
- M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4).
|
||||||
|
|
@ -12,8 +12,10 @@
|
||||||
- [ ] Restore dialog for unsaved changes after a crash
|
- [ ] Restore dialog for unsaved changes after a crash
|
||||||
- M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. Behaviour notes: `plan/phpstorm/04-recovery.md`.
|
- M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. Behaviour notes: `plan/phpstorm/04-recovery.md`.
|
||||||
- [ ] Command palette / search everywhere
|
- [ ] Command palette / search everywhere
|
||||||
|
- M1.8 (2026-10-16): command palette (`Mod+Shift+P`) over every user-facing command, engine and UI (commands with a menu path or default shortcut, plus UI commands): fuzzy ranking on the label and the id (prefix, word prefix, word starts, substring, in-order characters), recently run commands first, shortcuts shown, disabled commands dimmed and not runnable, arrow keys, Enter, Escape, focus returned on close; a failing command raises an error toast. One global keymap (`ui/src/commands/`) matches every command's default shortcut by key code; UI commands `palette.open`, `settings.open` (`Mod+,`, disabled until the settings dialog, M1.9b) and `view.toggleProjectTree` (`Mod+1`). Vitest (keymap, ranking, store, palette, App); live check pending (gaming mode). Missing: files, classes, symbols and text tabs (search everywhere), settings in the results, synonyms and abbreviations, inline toggles, assigning a shortcut from the palette, recent commands across restarts. Behaviour notes: `plan/phpstorm/05-palette.md`.
|
||||||
- [ ] Settings dialog with search
|
- [ ] Settings dialog with search
|
||||||
- [ ] Keymap editor (Lutra's own default keymap; no copied keymaps)
|
- [ ] Keymap editor (Lutra's own default keymap; no copied keymaps)
|
||||||
|
- M1.8 (2026-10-16): the global keymap built from the default shortcuts of engine and UI commands; no user keymap and no editor yet.
|
||||||
- [ ] Light and dark themes from theme tokens
|
- [ ] Light and dark themes from theme tokens
|
||||||
- M1.10 (2026-10-16): Lutra Dark and Lutra Light from Rust tokens, switched live through `appearance.theme` (no reload), `system` follows the OS preference, the first frame uses the stored theme; the editor (selection, active line, cursor, gutter, matches), tabs and notices have their own tokens; WCAG AA contrast checked by Vitest for every text pair in both themes. Covered by Vitest DOM and control-channel tests; live check pending (gaming mode). Missing: a theme picker (settings dialog, M1.9b; command palette, M1.8), the native title bar following the theme, editor font size from `editor.fontSize`, colour scheme editor, high-contrast theme, design review of the values.
|
- M1.10 (2026-10-16): Lutra Dark and Lutra Light from Rust tokens, switched live through `appearance.theme` (no reload), `system` follows the OS preference, the first frame uses the stored theme; the editor (selection, active line, cursor, gutter, matches), tabs and notices have their own tokens; WCAG AA contrast checked by Vitest for every text pair in both themes. Covered by Vitest DOM and control-channel tests; live check pending (gaming mode). Missing: a theme picker (settings dialog, M1.9b; command palette, M1.8), the native title bar following the theme, editor font size from `editor.fontSize`, colour scheme editor, high-contrast theme, design review of the values.
|
||||||
- [ ] Notifications and background task indicator
|
- [ ] Notifications and background task indicator
|
||||||
|
|
@ -28,6 +30,7 @@
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| Date | Change | Summary |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| 2026-10-16 | minor | Command palette and global keymap partial (M1.8) |
|
||||||
| 2026-10-16 | minor | Notifications partial (M1.12) |
|
| 2026-10-16 | minor | Notifications partial (M1.12) |
|
||||||
| 2026-10-16 | minor | Truncated listing note, re-open switches tab (M1.13) |
|
| 2026-10-16 | minor | Truncated listing note, re-open switches tab (M1.13) |
|
||||||
| 2026-10-16 | minor | Restore dialog (M1.7) |
|
| 2026-10-16 | minor | Restore dialog (M1.7) |
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,15 @@
|
||||||
/**
|
/**
|
||||||
* Root component: mounts the main window layout with the editor area; the
|
* Root component: mounts the main window layout with the editor area; the
|
||||||
* slogan shows while no tab is open, and the restore dialog for unsaved
|
* slogan shows while no tab is open, and the restore dialog for unsaved
|
||||||
* texts from the recovery journal, and the toast stack. Loads product
|
* texts from the recovery journal, the toast stack and the command
|
||||||
* information from the engine on mount, starts showing notifications and
|
* palette. Loads product information from the engine on mount, starts
|
||||||
* following the theme (see `theme.ts`); a failed theme report raises an
|
* showing notifications, following the theme (see `theme.ts`; a failed
|
||||||
* error toast.
|
* theme report raises an error toast) and the global keymap with the UI
|
||||||
|
* commands (see `commands/store.ts`).
|
||||||
*/
|
*/
|
||||||
import { onMounted, onUnmounted } from "vue";
|
import { onMounted, onUnmounted } from "vue";
|
||||||
|
import { useCommandsStore } from "./commands/store";
|
||||||
|
import CommandPalette from "./components/palette/CommandPalette.vue";
|
||||||
import EditorArea from "./components/editor/EditorArea.vue";
|
import EditorArea from "./components/editor/EditorArea.vue";
|
||||||
import MainLayout from "./components/layout/MainLayout.vue";
|
import MainLayout from "./components/layout/MainLayout.vue";
|
||||||
import NotificationStack from "./components/notifications/NotificationStack.vue";
|
import NotificationStack from "./components/notifications/NotificationStack.vue";
|
||||||
|
|
@ -18,6 +21,7 @@ import { startTheme } from "./theme";
|
||||||
|
|
||||||
const app = useAppStore();
|
const app = useAppStore();
|
||||||
const notifications = useNotificationsStore();
|
const notifications = useNotificationsStore();
|
||||||
|
const commands = useCommandsStore();
|
||||||
|
|
||||||
/** Stops following the theme; set while mounted. */
|
/** Stops following the theme; set while mounted. */
|
||||||
let stopTheme: (() => void) | null = null;
|
let stopTheme: (() => void) | null = null;
|
||||||
|
|
@ -25,12 +29,14 @@ let stopTheme: (() => void) | null = null;
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
notifications.start();
|
notifications.start();
|
||||||
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
|
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
|
||||||
|
void commands.start();
|
||||||
void app.loadAbout();
|
void app.loadAbout();
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
stopTheme?.();
|
stopTheme?.();
|
||||||
stopTheme = null;
|
stopTheme = null;
|
||||||
|
commands.stop();
|
||||||
notifications.stop();
|
notifications.stop();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
@ -44,6 +50,7 @@ onUnmounted(() => {
|
||||||
</EditorArea>
|
</EditorArea>
|
||||||
</MainLayout>
|
</MainLayout>
|
||||||
<RecoveryDialog />
|
<RecoveryDialog />
|
||||||
|
<CommandPalette />
|
||||||
<NotificationStack />
|
<NotificationStack />
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|
|
||||||
205
ui/src/commands/keymap.ts
Normal file
205
ui/src/commands/keymap.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
||||||
|
/**
|
||||||
|
* The global keymap: default shortcuts of every command, engine and UI,
|
||||||
|
* matched against key presses by key code.
|
||||||
|
*
|
||||||
|
* Shortcuts are written in Lutra notation (`Mod+Alt+S`, `Mod` = Cmd on
|
||||||
|
* macOS, Ctrl elsewhere) and come from the command list (`listCommands`
|
||||||
|
* plus the UI commands); nothing here hard-codes a key.
|
||||||
|
*/
|
||||||
|
import { t } from "../i18n";
|
||||||
|
|
||||||
|
/** A parsed shortcut. */
|
||||||
|
export interface Shortcut {
|
||||||
|
/** Ctrl must be held. */
|
||||||
|
ctrl: boolean;
|
||||||
|
/** Meta (Cmd) must be held. */
|
||||||
|
meta: boolean;
|
||||||
|
/** Alt (Option) must be held. */
|
||||||
|
alt: boolean;
|
||||||
|
/** Shift must be held. */
|
||||||
|
shift: boolean;
|
||||||
|
/** The key, lower case (`s`, `f4`, `enter`, `,`). */
|
||||||
|
key: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One binding of the keymap. */
|
||||||
|
export interface Binding {
|
||||||
|
/** The command id. */
|
||||||
|
command: string;
|
||||||
|
/** The shortcut that runs it. */
|
||||||
|
shortcut: Shortcut;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the frontend runs on macOS, where `Mod` means Cmd. */
|
||||||
|
export function isMac(): boolean {
|
||||||
|
return typeof navigator !== "undefined" && /Mac OS X|Macintosh|iPhone|iPad/.test(navigator.userAgent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a shortcut in Lutra notation.
|
||||||
|
*
|
||||||
|
* @param text - for example `Mod+Alt+S`; a trailing `+` is the plus key
|
||||||
|
* (`Mod++`).
|
||||||
|
* @param mac - whether `Mod` means Cmd.
|
||||||
|
* @returns the shortcut, or null when the text has no key or an unknown modifier.
|
||||||
|
*/
|
||||||
|
export function parseShortcut(text: string, mac: boolean): Shortcut | null {
|
||||||
|
const plusKey = text.endsWith("++");
|
||||||
|
const parts = (plusKey ? text.slice(0, -2) : text).split("+").map((part) => part.trim().toLowerCase());
|
||||||
|
const key = plusKey ? "+" : parts.pop();
|
||||||
|
if (key === undefined || key === "") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const shortcut: Shortcut = { ctrl: false, meta: false, alt: false, shift: false, key };
|
||||||
|
for (const part of parts) {
|
||||||
|
switch (part) {
|
||||||
|
case "":
|
||||||
|
if (!plusKey) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "mod":
|
||||||
|
if (mac) {
|
||||||
|
shortcut.meta = true;
|
||||||
|
} else {
|
||||||
|
shortcut.ctrl = true;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "ctrl":
|
||||||
|
shortcut.ctrl = true;
|
||||||
|
break;
|
||||||
|
case "cmd":
|
||||||
|
case "meta":
|
||||||
|
shortcut.meta = true;
|
||||||
|
break;
|
||||||
|
case "alt":
|
||||||
|
shortcut.alt = true;
|
||||||
|
break;
|
||||||
|
case "shift":
|
||||||
|
shortcut.shift = true;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return shortcut;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Punctuation keys by `KeyboardEvent.code`, as the US layout labels them. */
|
||||||
|
const PUNCTUATION: Readonly<Record<string, string>> = {
|
||||||
|
Comma: ",",
|
||||||
|
Period: ".",
|
||||||
|
Slash: "/",
|
||||||
|
Semicolon: ";",
|
||||||
|
Quote: "'",
|
||||||
|
BracketLeft: "[",
|
||||||
|
BracketRight: "]",
|
||||||
|
Backslash: "\\",
|
||||||
|
Minus: "-",
|
||||||
|
Equal: "=",
|
||||||
|
Backquote: "`",
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The key of an event, independent of the keyboard layout effects of Alt
|
||||||
|
* and Shift for letters, digits and punctuation (`Alt+S` on macOS types
|
||||||
|
* `ß`, `Shift+1` types `!`).
|
||||||
|
*
|
||||||
|
* @param event - the key event.
|
||||||
|
*/
|
||||||
|
export function eventKey(event: KeyboardEvent): string {
|
||||||
|
const code = event.code;
|
||||||
|
if (/^Key[A-Z]$/.test(code)) {
|
||||||
|
return code.slice(3).toLowerCase();
|
||||||
|
}
|
||||||
|
if (/^(Digit|Numpad)[0-9]$/.test(code)) {
|
||||||
|
return code.slice(-1);
|
||||||
|
}
|
||||||
|
const punctuation = PUNCTUATION[code];
|
||||||
|
if (punctuation !== undefined) {
|
||||||
|
return punctuation;
|
||||||
|
}
|
||||||
|
return event.key.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a key event matches a shortcut exactly.
|
||||||
|
*
|
||||||
|
* @param event - the key event.
|
||||||
|
* @param shortcut - the shortcut.
|
||||||
|
*/
|
||||||
|
export function matches(event: KeyboardEvent, shortcut: Shortcut): boolean {
|
||||||
|
return (
|
||||||
|
event.ctrlKey === shortcut.ctrl &&
|
||||||
|
event.metaKey === shortcut.meta &&
|
||||||
|
event.altKey === shortcut.alt &&
|
||||||
|
event.shiftKey === shortcut.shift &&
|
||||||
|
eventKey(event) === shortcut.key
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the keymap from command descriptions. Commands without a shortcut
|
||||||
|
* or with one that does not parse are left out; when two commands share a
|
||||||
|
* shortcut, the first one listed wins.
|
||||||
|
*
|
||||||
|
* @param commands - id and default shortcut of each command.
|
||||||
|
* @param mac - whether `Mod` means Cmd.
|
||||||
|
*/
|
||||||
|
export function buildKeymap(
|
||||||
|
commands: readonly { id: string; defaultShortcut?: string | null | undefined }[],
|
||||||
|
mac: boolean,
|
||||||
|
): Binding[] {
|
||||||
|
const keymap: Binding[] = [];
|
||||||
|
for (const command of commands) {
|
||||||
|
const raw: unknown = command.defaultShortcut;
|
||||||
|
const shortcut = typeof raw === "string" ? parseShortcut(raw, mac) : null;
|
||||||
|
if (shortcut) {
|
||||||
|
keymap.push({ command: command.id, shortcut });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keymap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The command a key event triggers.
|
||||||
|
*
|
||||||
|
* @param keymap - the keymap.
|
||||||
|
* @param event - the key event.
|
||||||
|
* @returns the command id, or null.
|
||||||
|
*/
|
||||||
|
export function commandFor(keymap: readonly Binding[], event: KeyboardEvent): string | null {
|
||||||
|
return keymap.find((binding) => matches(event, binding.shortcut))?.command ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a shortcut for display: modifier names from the catalog, in the
|
||||||
|
* order Ctrl, Alt, Shift, Cmd, and the key in upper case
|
||||||
|
* (`Ctrl+Shift+P`, `Cmd+,`).
|
||||||
|
*
|
||||||
|
* @param text - the shortcut in Lutra notation.
|
||||||
|
* @param mac - whether `Mod` means Cmd.
|
||||||
|
* @returns the display text, or null when the shortcut does not parse.
|
||||||
|
*/
|
||||||
|
export function formatShortcut(text: string, mac: boolean): string | null {
|
||||||
|
const shortcut = parseShortcut(text, mac);
|
||||||
|
if (shortcut === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (shortcut.ctrl) {
|
||||||
|
parts.push(t("command.key.ctrl"));
|
||||||
|
}
|
||||||
|
if (shortcut.alt) {
|
||||||
|
parts.push(mac ? t("command.key.option") : t("command.key.alt"));
|
||||||
|
}
|
||||||
|
if (shortcut.shift) {
|
||||||
|
parts.push(t("command.key.shift"));
|
||||||
|
}
|
||||||
|
if (shortcut.meta) {
|
||||||
|
parts.push(t("command.key.cmd"));
|
||||||
|
}
|
||||||
|
const key = shortcut.key;
|
||||||
|
parts.push(key.length === 1 ? key.toUpperCase() : key.charAt(0).toUpperCase() + key.slice(1));
|
||||||
|
return parts.join("+");
|
||||||
|
}
|
||||||
189
ui/src/commands/rank.ts
Normal file
189
ui/src/commands/rank.ts
Normal file
|
|
@ -0,0 +1,189 @@
|
||||||
|
/**
|
||||||
|
* Fuzzy ranking of commands for the palette.
|
||||||
|
*
|
||||||
|
* A query matches a command's label (the catalog text) or its id. Matches
|
||||||
|
* fall into tiers, best first: the text starts with the query; a word of
|
||||||
|
* the text starts with it; the query is spread over the starts of
|
||||||
|
* consecutive words (`togpro` → "Toggle Project"); the text contains it;
|
||||||
|
* its characters appear in order. Within a tier, recently run commands come
|
||||||
|
* first, then shorter texts, then the label alphabetically. Without a query
|
||||||
|
* every command is listed, recent ones first.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Tier of a match; higher is better. */
|
||||||
|
export const Tier = {
|
||||||
|
/** Characters of the query appear in order. */
|
||||||
|
Fuzzy: 1,
|
||||||
|
/** The text contains the query. */
|
||||||
|
Substring: 2,
|
||||||
|
/** The query is spread over the starts of consecutive words. */
|
||||||
|
WordStarts: 3,
|
||||||
|
/** A word of the text starts with the query. */
|
||||||
|
WordPrefix: 4,
|
||||||
|
/** The text starts with the query. */
|
||||||
|
Prefix: 5,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/** Longest query considered; longer ones are cut. */
|
||||||
|
export const MAX_QUERY = 100;
|
||||||
|
|
||||||
|
/** A match: its tier and how well it fits within the tier (higher is better). */
|
||||||
|
export interface Match {
|
||||||
|
/** The tier. */
|
||||||
|
tier: number;
|
||||||
|
/** Fit within the tier; shorter texts and tighter matches fit better. */
|
||||||
|
fit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the ranking needs of a command. */
|
||||||
|
export interface Rankable {
|
||||||
|
/** Command id. */
|
||||||
|
id: string;
|
||||||
|
/** Label as shown. */
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits a text into lower-case words at spaces, punctuation and camelCase
|
||||||
|
* boundaries (`view.toggleProjectTree` → view, toggle, project, tree).
|
||||||
|
*
|
||||||
|
* @param text - the text.
|
||||||
|
*/
|
||||||
|
export function words(text: string): string[] {
|
||||||
|
return text
|
||||||
|
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||||
|
.toLowerCase()
|
||||||
|
.split(/[^\p{L}\p{N}]+/u)
|
||||||
|
.filter((word) => word !== "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the query can be split into pieces that start consecutive words,
|
||||||
|
* in order, each piece starting a later word than the one before.
|
||||||
|
*
|
||||||
|
* @param query - the query, lower case, without spaces.
|
||||||
|
* @param list - the words of the text.
|
||||||
|
*/
|
||||||
|
function spreadOverWordStarts(query: string, list: readonly string[]): boolean {
|
||||||
|
const memo = new Map<string, boolean>();
|
||||||
|
const from = (q: number, w: number): boolean => {
|
||||||
|
if (q === query.length) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const memoKey = `${String(q)}:${String(w)}`;
|
||||||
|
const known = memo.get(memoKey);
|
||||||
|
if (known !== undefined) {
|
||||||
|
return known;
|
||||||
|
}
|
||||||
|
let found = false;
|
||||||
|
for (let i = w; i < list.length && !found; i += 1) {
|
||||||
|
const word = list[i] ?? "";
|
||||||
|
let k = 0;
|
||||||
|
while (k < word.length && q + k < query.length && word[k] === query[q + k]) {
|
||||||
|
k += 1;
|
||||||
|
}
|
||||||
|
for (let take = k; take >= 1 && !found; take -= 1) {
|
||||||
|
found = from(q + take, i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
memo.set(memoKey, found);
|
||||||
|
return found;
|
||||||
|
};
|
||||||
|
return from(0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches a query against one text.
|
||||||
|
*
|
||||||
|
* @param query - the query; case and surrounding spaces are ignored.
|
||||||
|
* @param text - the label or id.
|
||||||
|
* @returns the match, or null if the query does not match.
|
||||||
|
*/
|
||||||
|
export function matchText(query: string, text: string): Match | null {
|
||||||
|
const q = query.trim().toLowerCase().slice(0, MAX_QUERY);
|
||||||
|
const lower = text.toLowerCase();
|
||||||
|
const length = -text.length;
|
||||||
|
if (q === "") {
|
||||||
|
return { tier: Tier.Prefix, fit: length };
|
||||||
|
}
|
||||||
|
if (lower.startsWith(q)) {
|
||||||
|
return { tier: Tier.Prefix, fit: length };
|
||||||
|
}
|
||||||
|
const list = words(text);
|
||||||
|
if (list.some((_, i) => list.slice(i).join(" ").startsWith(q))) {
|
||||||
|
return { tier: Tier.WordPrefix, fit: length };
|
||||||
|
}
|
||||||
|
const compact = q.replace(/\s+/g, "");
|
||||||
|
if (compact !== "" && spreadOverWordStarts(compact, list)) {
|
||||||
|
return { tier: Tier.WordStarts, fit: length };
|
||||||
|
}
|
||||||
|
const at = lower.indexOf(q);
|
||||||
|
if (at >= 0) {
|
||||||
|
return { tier: Tier.Substring, fit: length - at };
|
||||||
|
}
|
||||||
|
let gaps = 0;
|
||||||
|
let pos = -1;
|
||||||
|
for (const ch of compact) {
|
||||||
|
const next = lower.indexOf(ch, pos + 1);
|
||||||
|
if (next < 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (pos >= 0) {
|
||||||
|
gaps += next - pos - 1;
|
||||||
|
}
|
||||||
|
pos = next;
|
||||||
|
}
|
||||||
|
return compact === "" ? null : { tier: Tier.Fuzzy, fit: -gaps * 100 + length };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The better of two matches.
|
||||||
|
*
|
||||||
|
* @param a - a match or null.
|
||||||
|
* @param b - a match or null.
|
||||||
|
*/
|
||||||
|
function better(a: Match | null, b: Match | null): Match | null {
|
||||||
|
if (a === null) {
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
if (b === null) {
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
if (a.tier !== b.tier) {
|
||||||
|
return a.tier > b.tier ? a : b;
|
||||||
|
}
|
||||||
|
return a.fit >= b.fit ? a : b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ranks commands for a query.
|
||||||
|
*
|
||||||
|
* @param items - the commands.
|
||||||
|
* @param query - what the user typed.
|
||||||
|
* @param recent - ids of recently run commands, most recent first.
|
||||||
|
* @returns the matching commands, best first.
|
||||||
|
*/
|
||||||
|
export function rank<T extends Rankable>(items: readonly T[], query: string, recent: readonly string[]): T[] {
|
||||||
|
const recency = new Map(recent.map((id, i) => [id, i]));
|
||||||
|
const scored: { item: T; match: Match; recent: number }[] = [];
|
||||||
|
for (const item of items) {
|
||||||
|
const match = better(matchText(query, item.label), matchText(query, item.id));
|
||||||
|
if (match !== null) {
|
||||||
|
scored.push({ item, match, recent: recency.get(item.id) ?? Number.MAX_SAFE_INTEGER });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const empty = query.trim() === "";
|
||||||
|
scored.sort((a, b) => {
|
||||||
|
if (!empty && a.match.tier !== b.match.tier) {
|
||||||
|
return b.match.tier - a.match.tier;
|
||||||
|
}
|
||||||
|
if (a.recent !== b.recent) {
|
||||||
|
return a.recent - b.recent;
|
||||||
|
}
|
||||||
|
if (!empty && a.match.fit !== b.match.fit) {
|
||||||
|
return b.match.fit - a.match.fit;
|
||||||
|
}
|
||||||
|
return a.item.label.localeCompare(b.item.label);
|
||||||
|
});
|
||||||
|
return scored.map((entry) => entry.item);
|
||||||
|
}
|
||||||
301
ui/src/commands/store.ts
Normal file
301
ui/src/commands/store.ts
Normal file
|
|
@ -0,0 +1,301 @@
|
||||||
|
/**
|
||||||
|
* The command store: every command the user can reach, engine and UI, the
|
||||||
|
* global keymap built from their default shortcuts, and running commands
|
||||||
|
* from the keyboard, the palette and `uiCommand` events.
|
||||||
|
*
|
||||||
|
* - **List:** `listCommands` from the engine, refreshed when a project opens
|
||||||
|
* or closes and whenever the palette opens, plus the UI commands of
|
||||||
|
* {@link UI_COMMANDS} (also before the engine lists them).
|
||||||
|
* - **Keymap:** one listener on the window in the capture phase, so
|
||||||
|
* shortcuts also work while CodeMirror or an input has the focus. A
|
||||||
|
* disabled command's shortcut is swallowed and does nothing.
|
||||||
|
* - **Handlers:** components supply the behaviour of UI commands and the
|
||||||
|
* context of engine commands (the editor runs `file.save` with the active
|
||||||
|
* buffer) with {@link useCommandsStore}'s `provide`. Other engine
|
||||||
|
* commands run with empty params.
|
||||||
|
* - **Errors:** a failed command raises an error toast (M1.12).
|
||||||
|
*/
|
||||||
|
import { defineStore } from "pinia";
|
||||||
|
import { computed, ref, shallowReactive } from "vue";
|
||||||
|
import { hasMessage, t } from "../i18n";
|
||||||
|
import { listCommands, onEngineEvent, run, type CommandInfo, type EngineEventPayload, type JsonValue } from "../ipc";
|
||||||
|
import { useNotificationsStore } from "../stores/notifications";
|
||||||
|
import { buildKeymap, commandFor, formatShortcut, isMac } from "./keymap";
|
||||||
|
import { UI_COMMANDS } from "./uiCommands";
|
||||||
|
|
||||||
|
/** Behaviour a component supplies for a command. */
|
||||||
|
export interface CommandHandler {
|
||||||
|
/**
|
||||||
|
* Runs the command.
|
||||||
|
*
|
||||||
|
* @param params - the params it was run with (`{}` from the keyboard and
|
||||||
|
* the palette, as given in a `uiCommand` event).
|
||||||
|
*/
|
||||||
|
run: (params: JsonValue) => void | Promise<void>;
|
||||||
|
/** Whether it can run now; always when absent. Reactive reads update the palette. */
|
||||||
|
enabled?: () => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A command as the palette shows it. */
|
||||||
|
export interface PaletteEntry {
|
||||||
|
/** Command id. */
|
||||||
|
id: string;
|
||||||
|
/** Label: the catalog text for UI commands, the engine's label otherwise. */
|
||||||
|
label: string;
|
||||||
|
/** Default shortcut formatted for display, or null. */
|
||||||
|
shortcut: string | null;
|
||||||
|
/** Whether it can run now. */
|
||||||
|
enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Most recently run commands remembered. */
|
||||||
|
export const MAX_RECENT = 20;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the command list from the engine, keeping well-formed entries.
|
||||||
|
*
|
||||||
|
* @param raw - the `listCommands` result.
|
||||||
|
*/
|
||||||
|
function toCommandInfos(raw: unknown): CommandInfo[] | null {
|
||||||
|
if (!Array.isArray(raw)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (raw as unknown[]).filter(
|
||||||
|
(c): c is CommandInfo =>
|
||||||
|
typeof c === "object" &&
|
||||||
|
c !== null &&
|
||||||
|
"id" in c &&
|
||||||
|
typeof c.id === "string" &&
|
||||||
|
"label" in c &&
|
||||||
|
typeof c.label === "string",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The label of a command: the catalog text of its `labelKey` when the
|
||||||
|
* catalog has it, else the engine's label.
|
||||||
|
*
|
||||||
|
* @param info - the command.
|
||||||
|
*/
|
||||||
|
function labelOf(info: CommandInfo): string {
|
||||||
|
return typeof info.labelKey === "string" && hasMessage(info.labelKey) ? t(info.labelKey) : info.label;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Store of the commands, the keymap and the recently run commands. */
|
||||||
|
export const useCommandsStore = defineStore("commands", () => {
|
||||||
|
const notifications = useNotificationsStore();
|
||||||
|
/** Commands as the engine lists them; empty until loaded. */
|
||||||
|
const infos = ref<CommandInfo[]>([]);
|
||||||
|
/** Handlers supplied by components, by command id. */
|
||||||
|
const handlers = shallowReactive(new Map<string, CommandHandler>());
|
||||||
|
/** Ids of recently run commands, most recent first. */
|
||||||
|
const recent = ref<string[]>([]);
|
||||||
|
/** Whether `Mod` means Cmd. */
|
||||||
|
const mac = isMac();
|
||||||
|
/** Ends the engine event subscription; set while started. */
|
||||||
|
let unsubscribe: (() => void) | null = null;
|
||||||
|
|
||||||
|
/** Every command: the engine's list plus UI commands it does not list yet. */
|
||||||
|
const all = computed<CommandInfo[]>(() => {
|
||||||
|
const listed = new Set(infos.value.map((info) => info.id));
|
||||||
|
const local = UI_COMMANDS.filter((spec) => !listed.has(spec.id)).map(
|
||||||
|
(spec): CommandInfo => ({
|
||||||
|
id: spec.id,
|
||||||
|
label: spec.labelKey,
|
||||||
|
labelKey: spec.labelKey,
|
||||||
|
menuPath: spec.menuPath ?? null,
|
||||||
|
defaultShortcut: spec.defaultShortcut ?? null,
|
||||||
|
params: "",
|
||||||
|
enabled: true,
|
||||||
|
ui: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return [...infos.value, ...local];
|
||||||
|
});
|
||||||
|
|
||||||
|
/** The keymap of every command with a default shortcut. */
|
||||||
|
const keymap = computed(() => buildKeymap(all.value, mac));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a command can run now: its handler decides if it has one; a UI
|
||||||
|
* command without a handler cannot run; otherwise the engine's state.
|
||||||
|
*
|
||||||
|
* @param id - the command id.
|
||||||
|
*/
|
||||||
|
function isEnabled(id: string): boolean {
|
||||||
|
const handler = handlers.get(id);
|
||||||
|
if (handler) {
|
||||||
|
return handler.enabled?.() ?? true;
|
||||||
|
}
|
||||||
|
const info = all.value.find((c) => c.id === id);
|
||||||
|
return info !== undefined && info.ui !== true && info.enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The commands the palette offers: UI commands and engine commands that
|
||||||
|
* are user actions (they have a menu path or a default shortcut), not
|
||||||
|
* the protocol commands clients call with data (`buffer.edit`).
|
||||||
|
*/
|
||||||
|
const entries = computed<PaletteEntry[]>(() =>
|
||||||
|
all.value
|
||||||
|
.filter((info) => info.ui === true || info.menuPath !== null || info.defaultShortcut !== null)
|
||||||
|
.map((info) => ({
|
||||||
|
id: info.id,
|
||||||
|
label: labelOf(info),
|
||||||
|
shortcut: typeof info.defaultShortcut === "string" ? formatShortcut(info.defaultShortcut, mac) : null,
|
||||||
|
enabled: isEnabled(info.id),
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Supplies the behaviour of a command.
|
||||||
|
*
|
||||||
|
* @param id - the command id.
|
||||||
|
* @param handler - what running it does.
|
||||||
|
* @returns a function that withdraws the handler (only if it is still this one).
|
||||||
|
*/
|
||||||
|
function provide(id: string, handler: CommandHandler): () => void {
|
||||||
|
handlers.set(id, handler);
|
||||||
|
return () => {
|
||||||
|
if (handlers.get(id) === handler) {
|
||||||
|
handlers.delete(id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remembers a command as run most recently. Opening the palette itself
|
||||||
|
* is not remembered: it would always head the list it opens.
|
||||||
|
*
|
||||||
|
* @param id - the command id.
|
||||||
|
*/
|
||||||
|
function remember(id: string): void {
|
||||||
|
if (id === "palette.open") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
recent.value = [id, ...recent.value.filter((other) => other !== id)].slice(0, MAX_RECENT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs a command the user chose (keyboard or palette): through its
|
||||||
|
* handler if a component supplied one, else through the engine. A
|
||||||
|
* disabled command does nothing. A failure raises an error toast.
|
||||||
|
*
|
||||||
|
* @param id - the command id.
|
||||||
|
* @param params - the params.
|
||||||
|
*/
|
||||||
|
async function execute(id: string, params: JsonValue = {}): Promise<void> {
|
||||||
|
if (!isEnabled(id)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
remember(id);
|
||||||
|
const handler = handlers.get(id);
|
||||||
|
if (handler) {
|
||||||
|
try {
|
||||||
|
await handler.run(params);
|
||||||
|
} catch (reason: unknown) {
|
||||||
|
notifications.notifyError(id, {
|
||||||
|
code: "internal",
|
||||||
|
message: reason instanceof Error ? reason.message : String(reason),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = await run(id, params);
|
||||||
|
if (!result.ok) {
|
||||||
|
notifications.notifyError(id, result.error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs a UI command the engine dispatched (`uiCommand`). One without a
|
||||||
|
* handler, or disabled now, raises a warning toast instead, so an agent
|
||||||
|
* learns that nothing happened.
|
||||||
|
*
|
||||||
|
* @param id - the command id; unchecked, it comes from the engine.
|
||||||
|
* @param params - its params.
|
||||||
|
*/
|
||||||
|
async function dispatch(id: unknown, params: unknown): Promise<void> {
|
||||||
|
const name = typeof id === "string" ? id : String(id);
|
||||||
|
const handler = handlers.get(name);
|
||||||
|
if (!handler || !(handler.enabled?.() ?? true)) {
|
||||||
|
notifications.notify({ level: "warning", message: t("command.unavailable", { command: name }) });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await execute(name, (params ?? {}) as JsonValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Loads the command list from the engine; a failure raises an error toast. */
|
||||||
|
async function refresh(): Promise<void> {
|
||||||
|
const result = await listCommands();
|
||||||
|
const list = result.ok ? toCommandInfos(result.value) : null;
|
||||||
|
if (list) {
|
||||||
|
infos.value = list;
|
||||||
|
} else {
|
||||||
|
notifications.notifyError(
|
||||||
|
"listCommands",
|
||||||
|
result.ok
|
||||||
|
? { code: "ipc", message: t("common.error.unexpectedResult", { command: "listCommands" }) }
|
||||||
|
: result.error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles an engine event: runs `uiCommand`s and refreshes the enabled
|
||||||
|
* states when a project opens or closes.
|
||||||
|
*
|
||||||
|
* @param event - the engine event.
|
||||||
|
*/
|
||||||
|
function onEvent(event: EngineEventPayload): void {
|
||||||
|
if (event.kind === "uiCommand") {
|
||||||
|
void dispatch(event.id, event.params);
|
||||||
|
} else if (event.kind === "projectOpened" || event.kind === "projectClosed") {
|
||||||
|
void refresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the command bound to a key press.
|
||||||
|
*
|
||||||
|
* @param event - a key press anywhere in the window.
|
||||||
|
*/
|
||||||
|
function onKeydown(event: KeyboardEvent): void {
|
||||||
|
const id = commandFor(keymap.value, event);
|
||||||
|
if (id === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
void execute(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the keymap and the `uiCommand` subscription, registers the UI
|
||||||
|
* commands with the engine and loads the command list. Starting twice is
|
||||||
|
* a no-op.
|
||||||
|
*/
|
||||||
|
async function start(): Promise<void> {
|
||||||
|
if (unsubscribe) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unsubscribe = onEngineEvent(onEvent);
|
||||||
|
window.addEventListener("keydown", onKeydown, true);
|
||||||
|
const registered = await run("ui.registerCommands", {
|
||||||
|
commands: UI_COMMANDS.map((spec) => ({ ...spec })),
|
||||||
|
});
|
||||||
|
if (!registered.ok) {
|
||||||
|
notifications.notifyError("ui.registerCommands", registered.error);
|
||||||
|
}
|
||||||
|
await refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops the keymap and the subscription. */
|
||||||
|
function stop(): void {
|
||||||
|
window.removeEventListener("keydown", onKeydown, true);
|
||||||
|
unsubscribe?.();
|
||||||
|
unsubscribe = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { infos, recent, keymap, entries, isEnabled, provide, execute, dispatch, refresh, start, stop };
|
||||||
|
});
|
||||||
27
ui/src/commands/uiCommands.ts
Normal file
27
ui/src/commands/uiCommands.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
/**
|
||||||
|
* UI commands: commands the frontend runs itself. They are registered with
|
||||||
|
* the engine (`ui.registerCommands`) so `listCommands`, the palette, the
|
||||||
|
* keymap and agents see them; running one through the engine comes back as
|
||||||
|
* a `uiCommand` event. Components supply the behaviour with
|
||||||
|
* `useCommandsStore().provide(id, handler)`; a UI command nobody provides
|
||||||
|
* is disabled.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** A UI command as registered with the engine. */
|
||||||
|
export interface UiCommandSpec {
|
||||||
|
/** Command id, `area.action` in camelCase. */
|
||||||
|
id: string;
|
||||||
|
/** Catalog key of the label. */
|
||||||
|
labelKey: string;
|
||||||
|
/** Menu path with `/` separators. */
|
||||||
|
menuPath?: string;
|
||||||
|
/** Default shortcut in Lutra notation. */
|
||||||
|
defaultShortcut?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The frontend's UI commands. */
|
||||||
|
export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
||||||
|
{ id: "palette.open", labelKey: "command.palette.open", defaultShortcut: "Mod+Shift+P" },
|
||||||
|
{ id: "settings.open", labelKey: "command.settings.open", defaultShortcut: "Mod+," },
|
||||||
|
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", defaultShortcut: "Mod+1" },
|
||||||
|
];
|
||||||
|
|
@ -3,65 +3,39 @@
|
||||||
* The editor area: tab bar, a notice line for the active tab, the editor
|
* The editor area: tab bar, a notice line for the active tab, the editor
|
||||||
* and the close question. Without open tabs it shows the default slot.
|
* and the close question. Without open tabs it shows the default slot.
|
||||||
*
|
*
|
||||||
* Shortcuts come from the engine's command specs (see `shortcuts.ts`); the
|
* Save, save all and close run through the global keymap and the
|
||||||
* area listens on the window in the capture phase so they also work while
|
* palette (`commands/store.ts`): the area supplies their behaviour with the
|
||||||
* CodeMirror has the focus. A keymap that cannot be loaded raises an
|
* active buffer as context and says when they can run.
|
||||||
* error toast.
|
|
||||||
*/
|
*/
|
||||||
import { onBeforeUnmount, onMounted } from "vue";
|
import { onBeforeUnmount, onMounted } from "vue";
|
||||||
|
import { useCommandsStore } from "../../commands/store";
|
||||||
import { t } from "../../i18n";
|
import { t } from "../../i18n";
|
||||||
import { useEditorStore } from "../../stores/editor";
|
import { useEditorStore } from "../../stores/editor";
|
||||||
import { useNotificationsStore } from "../../stores/notifications";
|
|
||||||
import ClosePrompt from "./ClosePrompt.vue";
|
import ClosePrompt from "./ClosePrompt.vue";
|
||||||
import CodeEditor from "./CodeEditor.vue";
|
import CodeEditor from "./CodeEditor.vue";
|
||||||
import EditorTabs from "./EditorTabs.vue";
|
import EditorTabs from "./EditorTabs.vue";
|
||||||
import { commandFor, loadEditorKeymap, type EditorKeymap } from "./shortcuts";
|
|
||||||
|
|
||||||
const editor = useEditorStore();
|
const editor = useEditorStore();
|
||||||
const notifications = useNotificationsStore();
|
const commands = useCommandsStore();
|
||||||
|
|
||||||
/** Keymap loaded from the engine, empty until loaded. */
|
/** Withdraws the command handlers; filled while mounted. */
|
||||||
let keymap: EditorKeymap = [];
|
let withdraw: (() => void)[] = [];
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs the editor command bound to a key press.
|
|
||||||
*
|
|
||||||
* @param event - a key press anywhere in the window.
|
|
||||||
*/
|
|
||||||
function onKeydown(event: KeyboardEvent): void {
|
|
||||||
const command = commandFor(keymap, event);
|
|
||||||
if (command === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
switch (command) {
|
|
||||||
case "file.save":
|
|
||||||
void editor.save();
|
|
||||||
break;
|
|
||||||
case "file.saveAll":
|
|
||||||
void editor.saveAll();
|
|
||||||
break;
|
|
||||||
case "buffer.close":
|
|
||||||
void editor.requestClose();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
editor.start();
|
editor.start();
|
||||||
window.addEventListener("keydown", onKeydown, true);
|
const hasActive = (): boolean => editor.activeTab !== null;
|
||||||
void loadEditorKeymap().then((result) => {
|
withdraw = [
|
||||||
if (result.ok) {
|
commands.provide("file.save", { run: async () => { await editor.save(); }, enabled: hasActive }),
|
||||||
keymap = result.value;
|
commands.provide("file.saveAll", { run: () => editor.saveAll(), enabled: () => editor.tabs.length > 0 }),
|
||||||
} else {
|
commands.provide("buffer.close", { run: () => editor.requestClose(), enabled: hasActive }),
|
||||||
notifications.notifyError("listCommands", result.error);
|
];
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
window.removeEventListener("keydown", onKeydown, true);
|
for (const fn of withdraw) {
|
||||||
|
fn();
|
||||||
|
}
|
||||||
|
withdraw = [];
|
||||||
editor.stop();
|
editor.stop();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
|
|
@ -1,156 +0,0 @@
|
||||||
/**
|
|
||||||
* Editor shortcuts, taken from the engine's command specs.
|
|
||||||
*
|
|
||||||
* The engine defines default shortcuts in Lutra notation (`Mod+Alt+S`,
|
|
||||||
* `Mod` = Cmd on macOS, Ctrl elsewhere). The editor area loads them with
|
|
||||||
* `listCommands` and maps key presses to the editor commands it handles
|
|
||||||
* with context (the active buffer): saving, saving all and closing a tab.
|
|
||||||
* Nothing here hard-codes a key.
|
|
||||||
*/
|
|
||||||
import { t } from "../../i18n";
|
|
||||||
import { listCommands, type CommandInfo, type RunResult } from "../../ipc";
|
|
||||||
|
|
||||||
/** Engine commands the editor area runs with the active buffer as context. */
|
|
||||||
export const EDITOR_SHORTCUT_COMMANDS = ["file.save", "file.saveAll", "buffer.close"] as const;
|
|
||||||
|
|
||||||
/** One of {@link EDITOR_SHORTCUT_COMMANDS}. */
|
|
||||||
export type EditorShortcutCommand = (typeof EDITOR_SHORTCUT_COMMANDS)[number];
|
|
||||||
|
|
||||||
/** A parsed shortcut. */
|
|
||||||
export interface Shortcut {
|
|
||||||
/** Ctrl must be held. */
|
|
||||||
ctrl: boolean;
|
|
||||||
/** Meta (Cmd) must be held. */
|
|
||||||
meta: boolean;
|
|
||||||
/** Alt (Option) must be held. */
|
|
||||||
alt: boolean;
|
|
||||||
/** Shift must be held. */
|
|
||||||
shift: boolean;
|
|
||||||
/** The key, lower case (`s`, `f4`, `enter`). */
|
|
||||||
key: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Whether the frontend runs on macOS, where `Mod` means Cmd. */
|
|
||||||
export function isMac(): boolean {
|
|
||||||
return typeof navigator !== "undefined" && /Mac OS X|Macintosh|iPhone|iPad/.test(navigator.userAgent);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parses a shortcut in Lutra notation.
|
|
||||||
*
|
|
||||||
* @param text - for example `Mod+Alt+S`.
|
|
||||||
* @param mac - whether `Mod` means Cmd.
|
|
||||||
* @returns the shortcut, or null when the text has no key or an unknown modifier.
|
|
||||||
*/
|
|
||||||
export function parseShortcut(text: string, mac: boolean): Shortcut | null {
|
|
||||||
const parts = text.split("+").map((part) => part.trim().toLowerCase());
|
|
||||||
const key = parts.pop();
|
|
||||||
if (key === undefined || key === "") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const shortcut: Shortcut = { ctrl: false, meta: false, alt: false, shift: false, key };
|
|
||||||
for (const part of parts) {
|
|
||||||
switch (part) {
|
|
||||||
case "mod":
|
|
||||||
if (mac) {
|
|
||||||
shortcut.meta = true;
|
|
||||||
} else {
|
|
||||||
shortcut.ctrl = true;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "ctrl":
|
|
||||||
shortcut.ctrl = true;
|
|
||||||
break;
|
|
||||||
case "cmd":
|
|
||||||
case "meta":
|
|
||||||
shortcut.meta = true;
|
|
||||||
break;
|
|
||||||
case "alt":
|
|
||||||
shortcut.alt = true;
|
|
||||||
break;
|
|
||||||
case "shift":
|
|
||||||
shortcut.shift = true;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return shortcut;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The key of an event, independent of keyboard layout effects of Alt and
|
|
||||||
* Shift for letters and digits (`Alt+S` on macOS types `ß`).
|
|
||||||
*
|
|
||||||
* @param event - the key event.
|
|
||||||
*/
|
|
||||||
function eventKey(event: KeyboardEvent): string {
|
|
||||||
const code = event.code;
|
|
||||||
if (/^Key[A-Z]$/.test(code)) {
|
|
||||||
return code.slice(3).toLowerCase();
|
|
||||||
}
|
|
||||||
if (/^Digit[0-9]$/.test(code)) {
|
|
||||||
return code.slice(5);
|
|
||||||
}
|
|
||||||
return event.key.toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether a key event matches a shortcut exactly.
|
|
||||||
*
|
|
||||||
* @param event - the key event.
|
|
||||||
* @param shortcut - the shortcut.
|
|
||||||
*/
|
|
||||||
export function matches(event: KeyboardEvent, shortcut: Shortcut): boolean {
|
|
||||||
return (
|
|
||||||
event.ctrlKey === shortcut.ctrl &&
|
|
||||||
event.metaKey === shortcut.meta &&
|
|
||||||
event.altKey === shortcut.alt &&
|
|
||||||
event.shiftKey === shortcut.shift &&
|
|
||||||
eventKey(event) === shortcut.key
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Shortcuts of the editor commands, by command. */
|
|
||||||
export type EditorKeymap = { command: EditorShortcutCommand; shortcut: Shortcut }[];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Loads the default shortcuts of the editor commands from the engine.
|
|
||||||
*
|
|
||||||
* @param mac - whether `Mod` means Cmd.
|
|
||||||
* @returns the keymap, or the error of `listCommands`.
|
|
||||||
*/
|
|
||||||
export async function loadEditorKeymap(mac = isMac()): Promise<RunResult<EditorKeymap>> {
|
|
||||||
const result = await listCommands();
|
|
||||||
if (!result.ok) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
const list: unknown = result.value;
|
|
||||||
if (!Array.isArray(list)) {
|
|
||||||
return { ok: false, error: { code: "ipc", message: t("common.error.unexpectedResult", { command: "listCommands" }) } };
|
|
||||||
}
|
|
||||||
const commands = (list as unknown[]).filter(
|
|
||||||
(c): c is CommandInfo => typeof c === "object" && c !== null && "id" in c,
|
|
||||||
);
|
|
||||||
const keymap: EditorKeymap = [];
|
|
||||||
for (const command of EDITOR_SHORTCUT_COMMANDS) {
|
|
||||||
const info = commands.find((c) => c.id === command);
|
|
||||||
const raw: unknown = info?.defaultShortcut;
|
|
||||||
const shortcut = typeof raw === "string" ? parseShortcut(raw, mac) : null;
|
|
||||||
if (shortcut) {
|
|
||||||
keymap.push({ command, shortcut });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { ok: true, value: keymap };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The editor command a key event triggers.
|
|
||||||
*
|
|
||||||
* @param keymap - the loaded keymap.
|
|
||||||
* @param event - the key event.
|
|
||||||
* @returns the command, or null.
|
|
||||||
*/
|
|
||||||
export function commandFor(keymap: EditorKeymap, event: KeyboardEvent): EditorShortcutCommand | null {
|
|
||||||
return keymap.find((entry) => matches(event, entry.shortcut))?.command ?? null;
|
|
||||||
}
|
|
||||||
|
|
@ -4,9 +4,12 @@
|
||||||
* editor area in the middle and the status bar along the bottom.
|
* editor area in the middle and the status bar along the bottom.
|
||||||
*
|
*
|
||||||
* The editor area is a slot so the editor (M1.6) can replace the
|
* The editor area is a slot so the editor (M1.6) can replace the
|
||||||
* placeholder without touching the layout.
|
* placeholder without touching the layout. The layout supplies the UI
|
||||||
|
* command `view.toggleProjectTree` (`Mod+1`), which shows or hides the
|
||||||
|
* Project tool window.
|
||||||
*/
|
*/
|
||||||
import { ref } from "vue";
|
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||||
|
import { useCommandsStore } from "../../commands/store";
|
||||||
import { t } from "../../i18n";
|
import { t } from "../../i18n";
|
||||||
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
|
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
|
||||||
import StatusBar from "../StatusBar.vue";
|
import StatusBar from "../StatusBar.vue";
|
||||||
|
|
@ -16,6 +19,24 @@ import ToolWindow from "./ToolWindow.vue";
|
||||||
const leftWidth = ref(260);
|
const leftWidth = ref(260);
|
||||||
/** Whether the left tool window is shown. */
|
/** Whether the left tool window is shown. */
|
||||||
const leftOpen = ref(true);
|
const leftOpen = ref(true);
|
||||||
|
|
||||||
|
const commands = useCommandsStore();
|
||||||
|
|
||||||
|
/** Withdraws the command handler; set while mounted. */
|
||||||
|
let withdraw: (() => void) | null = null;
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
withdraw = commands.provide("view.toggleProjectTree", {
|
||||||
|
run: () => {
|
||||||
|
leftOpen.value = !leftOpen.value;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
withdraw?.();
|
||||||
|
withdraw = null;
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
|
||||||
298
ui/src/components/palette/CommandPalette.vue
Normal file
298
ui/src/components/palette/CommandPalette.vue
Normal file
|
|
@ -0,0 +1,298 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* The command palette (`palette.open`, `Mod+Shift+P`): an overlay with a
|
||||||
|
* search field over every command the user can run, engine and UI.
|
||||||
|
*
|
||||||
|
* Typing ranks the commands fuzzily by label and id (see `rank.ts`);
|
||||||
|
* recently run commands come first. Each row shows the command's
|
||||||
|
* shortcut; commands that cannot run now are dimmed and cannot be chosen.
|
||||||
|
* Arrow keys move the selection, Enter runs it, Escape or a click outside
|
||||||
|
* closes. The command runs after the palette closed and gave the focus
|
||||||
|
* back, so a command that asks something (closing a dirty tab) gets it.
|
||||||
|
*/
|
||||||
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||||
|
import { rank } from "../../commands/rank";
|
||||||
|
import { useCommandsStore, type PaletteEntry } from "../../commands/store";
|
||||||
|
import { t } from "../../i18n";
|
||||||
|
|
||||||
|
const commands = useCommandsStore();
|
||||||
|
|
||||||
|
/** Whether the palette is shown. */
|
||||||
|
const open = ref(false);
|
||||||
|
/** What the user typed. */
|
||||||
|
const query = ref("");
|
||||||
|
/** Index of the selected row. */
|
||||||
|
const selected = ref(0);
|
||||||
|
/** The search field. */
|
||||||
|
const input = ref<HTMLInputElement | null>(null);
|
||||||
|
/** The list. */
|
||||||
|
const list = ref<HTMLElement | null>(null);
|
||||||
|
/** The element that had the focus before the palette opened. */
|
||||||
|
let returnFocus: HTMLElement | null = null;
|
||||||
|
/** Withdraws the `palette.open` handler; set while mounted. */
|
||||||
|
let withdraw: (() => void) | null = null;
|
||||||
|
|
||||||
|
/** The matching commands, best first. */
|
||||||
|
const results = computed<PaletteEntry[]>(() => rank(commands.entries, query.value, commands.recent));
|
||||||
|
|
||||||
|
/** DOM id of the selected row, for `aria-activedescendant`. */
|
||||||
|
const activeId = computed(() => (results.value.length > 0 ? `lt-palette-${String(selected.value)}` : undefined));
|
||||||
|
|
||||||
|
watch(query, () => {
|
||||||
|
selected.value = 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Opens the palette with an empty query and refreshes the enabled states. */
|
||||||
|
async function show(): Promise<void> {
|
||||||
|
if (!open.value) {
|
||||||
|
const active = document.activeElement;
|
||||||
|
returnFocus = active instanceof HTMLElement ? active : null;
|
||||||
|
}
|
||||||
|
query.value = "";
|
||||||
|
selected.value = 0;
|
||||||
|
open.value = true;
|
||||||
|
await nextTick();
|
||||||
|
input.value?.focus();
|
||||||
|
await commands.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Closes the palette and gives the focus back. */
|
||||||
|
function close(): void {
|
||||||
|
if (!open.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
open.value = false;
|
||||||
|
returnFocus?.focus();
|
||||||
|
returnFocus = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs a row's command if it is enabled; the palette closes first.
|
||||||
|
*
|
||||||
|
* @param entry - the row.
|
||||||
|
*/
|
||||||
|
function choose(entry: PaletteEntry | undefined): void {
|
||||||
|
if (!entry?.enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
close();
|
||||||
|
void commands.execute(entry.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the selection, wrapping around, and keeps the row in view.
|
||||||
|
*
|
||||||
|
* @param step - rows to move, negative for up.
|
||||||
|
*/
|
||||||
|
function move(step: number): void {
|
||||||
|
const count = results.value.length;
|
||||||
|
if (count === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
selected.value = (selected.value + step + count) % count;
|
||||||
|
void nextTick(() => {
|
||||||
|
const row = list.value?.querySelector<HTMLElement>(`#lt-palette-${String(selected.value)}`);
|
||||||
|
row?.scrollIntoView({ block: "nearest" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keyboard handling of the search field.
|
||||||
|
*
|
||||||
|
* @param event - the key press.
|
||||||
|
*/
|
||||||
|
function onKeydown(event: KeyboardEvent): void {
|
||||||
|
switch (event.key) {
|
||||||
|
case "ArrowDown":
|
||||||
|
move(1);
|
||||||
|
break;
|
||||||
|
case "ArrowUp":
|
||||||
|
move(-1);
|
||||||
|
break;
|
||||||
|
case "Enter":
|
||||||
|
choose(results.value[selected.value]);
|
||||||
|
break;
|
||||||
|
case "Escape":
|
||||||
|
close();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
withdraw = commands.provide("palette.open", { run: show });
|
||||||
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
withdraw?.();
|
||||||
|
withdraw = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
defineExpose({ show, close });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
v-if="open"
|
||||||
|
class="palette"
|
||||||
|
data-test="palette"
|
||||||
|
@mousedown.self.prevent="close()"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="palette__dialog"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
:aria-label="t('palette.label')"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref="input"
|
||||||
|
v-model="query"
|
||||||
|
class="palette__input"
|
||||||
|
type="text"
|
||||||
|
role="combobox"
|
||||||
|
aria-autocomplete="list"
|
||||||
|
aria-expanded="true"
|
||||||
|
aria-controls="lt-palette-list"
|
||||||
|
:aria-activedescendant="activeId"
|
||||||
|
:aria-label="t('palette.label')"
|
||||||
|
:placeholder="t('palette.placeholder')"
|
||||||
|
spellcheck="false"
|
||||||
|
autocomplete="off"
|
||||||
|
data-test="palette-input"
|
||||||
|
@keydown="onKeydown"
|
||||||
|
>
|
||||||
|
<ul
|
||||||
|
id="lt-palette-list"
|
||||||
|
ref="list"
|
||||||
|
class="palette__list"
|
||||||
|
role="listbox"
|
||||||
|
:aria-label="t('palette.label')"
|
||||||
|
>
|
||||||
|
<li
|
||||||
|
v-for="(entry, index) in results"
|
||||||
|
:id="`lt-palette-${String(index)}`"
|
||||||
|
:key="entry.id"
|
||||||
|
class="palette__row"
|
||||||
|
:class="{
|
||||||
|
'palette__row--selected': index === selected,
|
||||||
|
'palette__row--disabled': !entry.enabled,
|
||||||
|
}"
|
||||||
|
role="option"
|
||||||
|
:aria-selected="index === selected"
|
||||||
|
:aria-disabled="!entry.enabled"
|
||||||
|
:data-command="entry.id"
|
||||||
|
data-test="palette-row"
|
||||||
|
@mousemove="selected = index"
|
||||||
|
@mousedown.prevent
|
||||||
|
@click="choose(entry)"
|
||||||
|
>
|
||||||
|
<span class="palette__label">{{ entry.label }}</span>
|
||||||
|
<span class="palette__id">{{ entry.id }}</span>
|
||||||
|
<kbd
|
||||||
|
v-if="entry.shortcut"
|
||||||
|
class="palette__shortcut"
|
||||||
|
data-test="palette-shortcut"
|
||||||
|
>{{ entry.shortcut }}</kbd>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p
|
||||||
|
v-if="results.length === 0"
|
||||||
|
class="palette__empty"
|
||||||
|
role="status"
|
||||||
|
data-test="palette-empty"
|
||||||
|
>
|
||||||
|
{{ t("palette.noMatches") }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.palette {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: center;
|
||||||
|
padding-top: 12vh;
|
||||||
|
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
|
||||||
|
z-index: 30;
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__dialog {
|
||||||
|
width: min(600px, 90vw);
|
||||||
|
max-height: 60vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: var(--lt-bg);
|
||||||
|
color: var(--lt-fg);
|
||||||
|
border: 1px solid var(--lt-border);
|
||||||
|
border-radius: 6px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__input {
|
||||||
|
padding: 8px 12px;
|
||||||
|
font: inherit;
|
||||||
|
color: var(--lt-fg);
|
||||||
|
background: var(--lt-editor-bg);
|
||||||
|
border: none;
|
||||||
|
border-bottom: 1px solid var(--lt-border);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__list {
|
||||||
|
margin: 0;
|
||||||
|
padding: 4px 0;
|
||||||
|
list-style: none;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__row {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 4px 12px;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__row--selected {
|
||||||
|
background: var(--lt-editor-selection-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__row--disabled {
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__label {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__id {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__shortcut {
|
||||||
|
font: inherit;
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__row--selected .palette__id,
|
||||||
|
.palette__row--selected .palette__shortcut {
|
||||||
|
color: var(--lt-fg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.palette__empty {
|
||||||
|
margin: 0;
|
||||||
|
padding: 8px 12px;
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
@ -1,5 +1,14 @@
|
||||||
{
|
{
|
||||||
"app.statusBar.version": "{name} {version}",
|
"app.statusBar.version": "{name} {version}",
|
||||||
|
"command.key.alt": "Alt",
|
||||||
|
"command.key.cmd": "Cmd",
|
||||||
|
"command.key.ctrl": "Ctrl",
|
||||||
|
"command.key.option": "Option",
|
||||||
|
"command.key.shift": "Shift",
|
||||||
|
"command.palette.open": "Command Palette",
|
||||||
|
"command.settings.open": "Settings…",
|
||||||
|
"command.unavailable": "{command} cannot run right now",
|
||||||
|
"command.view.toggleProjectTree": "Show or Hide Project",
|
||||||
"common.cancel": "Cancel",
|
"common.cancel": "Cancel",
|
||||||
"common.close": "Close",
|
"common.close": "Close",
|
||||||
"common.dismiss": "Dismiss",
|
"common.dismiss": "Dismiss",
|
||||||
|
|
@ -31,6 +40,9 @@
|
||||||
"notification.stack.more": "+{count} more",
|
"notification.stack.more": "+{count} more",
|
||||||
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
|
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
|
||||||
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
|
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
|
||||||
|
"palette.label": "Command palette",
|
||||||
|
"palette.noMatches": "No matching commands",
|
||||||
|
"palette.placeholder": "Type a command name",
|
||||||
"project.empty.noFolder": "No folder is open.",
|
"project.empty.noFolder": "No folder is open.",
|
||||||
"project.openFolder": "Open Folder…",
|
"project.openFolder": "Open Folder…",
|
||||||
"project.toolWindow.title": "Project",
|
"project.toolWindow.title": "Project",
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,13 @@ export type EngineEventPayload =
|
||||||
message?: unknown;
|
message?: unknown;
|
||||||
/** Placeholder values; unchecked. */
|
/** Placeholder values; unchecked. */
|
||||||
params?: unknown;
|
params?: unknown;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
kind: "uiCommand";
|
||||||
|
/** Id of the UI command to run; unchecked, it comes from the engine. */
|
||||||
|
id: unknown;
|
||||||
|
/** The params it was run with, as given; unchecked. */
|
||||||
|
params?: unknown;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Callback receiving engine events. */
|
/** Callback receiving engine events. */
|
||||||
|
|
@ -140,8 +147,10 @@ export type RunResult<T> = { ok: true; value: T } | { ok: false; error: EngineEr
|
||||||
export interface CommandInfo {
|
export interface CommandInfo {
|
||||||
/** Command id, e.g. `app.about`. */
|
/** Command id, e.g. `app.about`. */
|
||||||
id: string;
|
id: string;
|
||||||
/** Label shown in menus and the command palette. */
|
/** Label shown in menus and the command palette; for UI commands the catalog key. */
|
||||||
label: string;
|
label: string;
|
||||||
|
/** Catalog key of the label; set for UI commands. */
|
||||||
|
labelKey?: string;
|
||||||
/** Menu path such as `Help/About Lutra`, or null if not in a menu. */
|
/** Menu path such as `Help/About Lutra`, or null if not in a menu. */
|
||||||
menuPath: string | null;
|
menuPath: string | null;
|
||||||
/** Default shortcut in Lutra notation (`Mod+Q`), or null. */
|
/** Default shortcut in Lutra notation (`Mod+Q`), or null. */
|
||||||
|
|
@ -150,6 +159,8 @@ export interface CommandInfo {
|
||||||
params: string;
|
params: string;
|
||||||
/** Whether the command can run in the current state. */
|
/** Whether the command can run in the current state. */
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
|
/** Whether the frontend registered the command (`ui.registerCommands`) and runs it. */
|
||||||
|
ui?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
/**
|
/**
|
||||||
* Tests for the root component: it loads product information on mount and
|
* Tests for the root component: it loads product information on mount and
|
||||||
* shows it, or the error, in the status bar.
|
* shows it, or the error, in the status bar, and it wires the UI commands:
|
||||||
|
* `Mod+1` hides and shows the Project tool window, `Mod+Shift+P` opens the
|
||||||
|
* palette.
|
||||||
*/
|
*/
|
||||||
import { flushPromises, mount } from "@vue/test-utils";
|
import { flushPromises, mount } from "@vue/test-utils";
|
||||||
import { createPinia, setActivePinia } from "pinia";
|
import { createPinia, setActivePinia } from "pinia";
|
||||||
|
|
@ -39,4 +41,25 @@ describe("App", () => {
|
||||||
expect(bar.text()).toBe("engine unavailable");
|
expect(bar.text()).toBe("engine unavailable");
|
||||||
expect(bar.classes()).toContain("status-bar--error");
|
expect(bar.classes()).toContain("status-bar--error");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("toggles the project tree and opens the palette from the keyboard", async () => {
|
||||||
|
invoke.mockImplementation((command: string) =>
|
||||||
|
Promise.resolve(command === "engine_list_commands" ? [] : null),
|
||||||
|
);
|
||||||
|
const wrapper = mount(App, { attachTo: document.body });
|
||||||
|
await flushPromises();
|
||||||
|
const press = async (init: KeyboardEventInit): Promise<void> => {
|
||||||
|
window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
|
||||||
|
await flushPromises();
|
||||||
|
};
|
||||||
|
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(true);
|
||||||
|
await press({ key: "1", code: "Digit1", ctrlKey: true });
|
||||||
|
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(false);
|
||||||
|
expect(wrapper.find("[data-test=tool-window-stripe]").exists()).toBe(true);
|
||||||
|
await press({ key: "1", code: "Digit1", ctrlKey: true });
|
||||||
|
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(true);
|
||||||
|
await press({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true });
|
||||||
|
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||||
|
wrapper.unmount();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
86
ui/tests/commands/keymap.test.ts
Normal file
86
ui/tests/commands/keymap.test.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
/**
|
||||||
|
* Tests of the global keymap: parsing Lutra notation (`Mod` per platform),
|
||||||
|
* matching by key code independent of what Alt and Shift type, building
|
||||||
|
* the keymap from command descriptions and formatting shortcuts for
|
||||||
|
* display.
|
||||||
|
*/
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { buildKeymap, commandFor, eventKey, formatShortcut, matches, parseShortcut } from "../../src/commands/keymap";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A key event.
|
||||||
|
*
|
||||||
|
* @param init - its properties.
|
||||||
|
*/
|
||||||
|
function key(init: KeyboardEventInit): KeyboardEvent {
|
||||||
|
return new KeyboardEvent("keydown", init);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("parseShortcut", () => {
|
||||||
|
it("maps Mod to Ctrl or Cmd", () => {
|
||||||
|
expect(parseShortcut("Mod+Shift+P", false)).toEqual({ ctrl: true, meta: false, alt: false, shift: true, key: "p" });
|
||||||
|
expect(parseShortcut("Mod+Shift+P", true)).toEqual({ ctrl: false, meta: true, alt: false, shift: true, key: "p" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads punctuation, digits and the plus key", () => {
|
||||||
|
expect(parseShortcut("Mod+,", false)?.key).toBe(",");
|
||||||
|
expect(parseShortcut("Mod+1", false)?.key).toBe("1");
|
||||||
|
expect(parseShortcut("Mod++", false)).toEqual({ ctrl: true, meta: false, alt: false, shift: false, key: "+" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects unknown modifiers and missing keys", () => {
|
||||||
|
expect(parseShortcut("Hyper+S", false)).toBeNull();
|
||||||
|
expect(parseShortcut("Mod+", false)).toBeNull();
|
||||||
|
expect(parseShortcut("", false)).toBeNull();
|
||||||
|
expect(parseShortcut("Mod++S", false)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("matching", () => {
|
||||||
|
it("uses the key code for letters, digits and punctuation", () => {
|
||||||
|
expect(eventKey(key({ key: "ß", code: "KeyS" }))).toBe("s");
|
||||||
|
expect(eventKey(key({ key: "!", code: "Digit1" }))).toBe("1");
|
||||||
|
expect(eventKey(key({ key: ";", code: "Comma" }))).toBe(",");
|
||||||
|
expect(eventKey(key({ key: "F4", code: "F4" }))).toBe("f4");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requires the exact modifiers", () => {
|
||||||
|
const shortcut = parseShortcut("Mod+Shift+P", false);
|
||||||
|
expect(shortcut).not.toBeNull();
|
||||||
|
if (!shortcut) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
expect(matches(key({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true }), shortcut)).toBe(true);
|
||||||
|
expect(matches(key({ key: "p", code: "KeyP", ctrlKey: true }), shortcut)).toBe(false);
|
||||||
|
expect(matches(key({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true, altKey: true }), shortcut)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("finds the command of a key press, the first listed winning", () => {
|
||||||
|
const keymap = buildKeymap(
|
||||||
|
[
|
||||||
|
{ id: "palette.open", defaultShortcut: "Mod+Shift+P" },
|
||||||
|
{ id: "settings.open", defaultShortcut: "Mod+," },
|
||||||
|
{ id: "view.toggleProjectTree", defaultShortcut: "Mod+1" },
|
||||||
|
{ id: "other.palette", defaultShortcut: "Mod+Shift+P" },
|
||||||
|
{ id: "no.shortcut", defaultShortcut: null },
|
||||||
|
{ id: "bad.shortcut", defaultShortcut: "Hyper+X" },
|
||||||
|
],
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(keymap.map((b) => b.command)).toEqual(["palette.open", "settings.open", "view.toggleProjectTree", "other.palette"]);
|
||||||
|
expect(commandFor(keymap, key({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true }))).toBe("palette.open");
|
||||||
|
expect(commandFor(keymap, key({ key: ",", code: "Comma", ctrlKey: true }))).toBe("settings.open");
|
||||||
|
expect(commandFor(keymap, key({ key: "1", code: "Digit1", ctrlKey: true }))).toBe("view.toggleProjectTree");
|
||||||
|
expect(commandFor(keymap, key({ key: "1", code: "Digit1", metaKey: true }))).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("formatShortcut", () => {
|
||||||
|
it("names the modifiers of the platform", () => {
|
||||||
|
expect(formatShortcut("Mod+Shift+P", false)).toBe("Ctrl+Shift+P");
|
||||||
|
expect(formatShortcut("Mod+Alt+S", true)).toBe("Option+Cmd+S");
|
||||||
|
expect(formatShortcut("Mod+,", false)).toBe("Ctrl+,");
|
||||||
|
expect(formatShortcut("Shift+F4", false)).toBe("Shift+F4");
|
||||||
|
expect(formatShortcut("Nope+X", false)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
94
ui/tests/commands/rank.test.ts
Normal file
94
ui/tests/commands/rank.test.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
/**
|
||||||
|
* Tests of the palette ranking: the match tiers (prefix, word prefix,
|
||||||
|
* word starts, substring, in-order characters), matching on the id as
|
||||||
|
* well as the label, recently run commands first, and the order without a
|
||||||
|
* query.
|
||||||
|
*/
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { Tier, matchText, rank, words } from "../../src/commands/rank";
|
||||||
|
|
||||||
|
/** Commands as the palette ranks them. */
|
||||||
|
const COMMANDS = [
|
||||||
|
{ id: "file.save", label: "Save" },
|
||||||
|
{ id: "file.saveAll", label: "Save All" },
|
||||||
|
{ id: "project.openDialog", label: "Open Folder…" },
|
||||||
|
{ id: "project.close", label: "Close Project" },
|
||||||
|
{ id: "buffer.close", label: "Close Tab" },
|
||||||
|
{ id: "view.toggleProjectTree", label: "Show or Hide Project" },
|
||||||
|
{ id: "palette.open", label: "Command Palette" },
|
||||||
|
{ id: "app.quit", label: "Quit" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ids of the ranking.
|
||||||
|
*
|
||||||
|
* @param query - the query.
|
||||||
|
* @param recent - recently run ids.
|
||||||
|
*/
|
||||||
|
function ids(query: string, recent: string[] = []): string[] {
|
||||||
|
return rank(COMMANDS, query, recent).map((c) => c.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("words", () => {
|
||||||
|
it("splits at punctuation, spaces and camelCase", () => {
|
||||||
|
expect(words("view.toggleProjectTree")).toEqual(["view", "toggle", "project", "tree"]);
|
||||||
|
expect(words("Open Folder…")).toEqual(["open", "folder"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("matchText", () => {
|
||||||
|
it("sorts matches into tiers", () => {
|
||||||
|
expect(matchText("sav", "Save All")?.tier).toBe(Tier.Prefix);
|
||||||
|
expect(matchText("all", "Save All")?.tier).toBe(Tier.WordPrefix);
|
||||||
|
expect(matchText("hide proj", "Show or Hide Project")?.tier).toBe(Tier.WordPrefix);
|
||||||
|
expect(matchText("shp", "Show or Hide Project")?.tier).toBe(Tier.WordStarts);
|
||||||
|
expect(matchText("togpro", "view.toggleProjectTree")?.tier).toBe(Tier.WordStarts);
|
||||||
|
expect(matchText("ave", "Save All")?.tier).toBe(Tier.Substring);
|
||||||
|
expect(matchText("sel", "Save All")?.tier).toBe(Tier.Fuzzy);
|
||||||
|
expect(matchText("xyz", "Save All")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores case and surrounding spaces", () => {
|
||||||
|
expect(matchText(" SAVE ", "save all")?.tier).toBe(Tier.Prefix);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rank", () => {
|
||||||
|
it("puts prefix and word-start matches before in-order characters", () => {
|
||||||
|
expect(ids("clo")).toEqual(["buffer.close", "project.close", "project.openDialog"]);
|
||||||
|
expect(ids("pro").slice(0, 3)).toEqual(["project.close", "project.openDialog", "view.toggleProjectTree"]);
|
||||||
|
expect(ids("sa")[0]).toBe("file.save");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches the id too", () => {
|
||||||
|
expect(ids("togglepro")).toEqual(["view.toggleProjectTree"]);
|
||||||
|
expect(ids("app.quit")).toEqual(["app.quit"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("puts recent commands first within a tier", () => {
|
||||||
|
expect(ids("clo", ["project.close"]).slice(0, 2)).toEqual(["project.close", "buffer.close"]);
|
||||||
|
expect(ids("sav", ["file.saveAll"])).toEqual(["file.saveAll", "file.save"]);
|
||||||
|
expect(ids("sav", ["project.close"])).toEqual(["file.save", "file.saveAll"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not let recency beat a better tier", () => {
|
||||||
|
expect(ids("sa", ["view.toggleProjectTree"])[0]).toBe("file.save");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lists everything without a query, recent first, then by label", () => {
|
||||||
|
expect(ids("", ["app.quit", "file.save"])).toEqual([
|
||||||
|
"app.quit",
|
||||||
|
"file.save",
|
||||||
|
"project.close",
|
||||||
|
"buffer.close",
|
||||||
|
"palette.open",
|
||||||
|
"project.openDialog",
|
||||||
|
"file.saveAll",
|
||||||
|
"view.toggleProjectTree",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns nothing for a query that matches nothing", () => {
|
||||||
|
expect(ids("zzz")).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -2,8 +2,9 @@
|
||||||
* Tests for the editor area and the editor store: opening tabs (from the
|
* Tests for the editor area and the editor store: opening tabs (from the
|
||||||
* tree and from engine events), editing through CodeMirror into
|
* tree and from engine events), editing through CodeMirror into
|
||||||
* `buffer.edit`, the dirty marker, closing (middle click, shortcut, the
|
* `buffer.edit`, the dirty marker, closing (middle click, shortcut, the
|
||||||
* Save / Don't Save / Cancel question), saving through shortcuts loaded
|
* Save / Don't Save / Cancel question), saving through the global keymap
|
||||||
* from the engine's command list, and the notice for files changed on disk.
|
* (`commands/store.ts`) with shortcuts loaded from the engine's command
|
||||||
|
* list, and the notice for files changed on disk.
|
||||||
* The engine is a fake behind the mocked Tauri `invoke`.
|
* The engine is a fake behind the mocked Tauri `invoke`.
|
||||||
*/
|
*/
|
||||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||||
|
|
@ -14,6 +15,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
const invoke = vi.hoisted(() => vi.fn());
|
const invoke = vi.hoisted(() => vi.fn());
|
||||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||||
|
|
||||||
|
import { useCommandsStore } from "../../src/commands/store";
|
||||||
import EditorArea from "../../src/components/editor/EditorArea.vue";
|
import EditorArea from "../../src/components/editor/EditorArea.vue";
|
||||||
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
|
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
|
||||||
import { emitEngineEvent } from "../../src/components/project/engineEvents";
|
import { emitEngineEvent } from "../../src/components/project/engineEvents";
|
||||||
|
|
@ -159,8 +161,9 @@ let pinia: Pinia;
|
||||||
/** Mounted components to unmount after each test. */
|
/** Mounted components to unmount after each test. */
|
||||||
let mounted: VueWrapper[] = [];
|
let mounted: VueWrapper[] = [];
|
||||||
|
|
||||||
/** Mounts the editor area. */
|
/** Mounts the editor area and starts the global keymap. */
|
||||||
async function mountArea(): Promise<VueWrapper> {
|
async function mountArea(): Promise<VueWrapper> {
|
||||||
|
await useCommandsStore(pinia).start();
|
||||||
const wrapper = mount(EditorArea, {
|
const wrapper = mount(EditorArea, {
|
||||||
attachTo: document.body,
|
attachTo: document.body,
|
||||||
slots: { default: "empty" },
|
slots: { default: "empty" },
|
||||||
|
|
@ -236,6 +239,7 @@ beforeEach(() => {
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
await flushPromises();
|
await flushPromises();
|
||||||
|
useCommandsStore(pinia).stop();
|
||||||
for (const wrapper of mounted) {
|
for (const wrapper of mounted) {
|
||||||
wrapper.unmount();
|
wrapper.unmount();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -27,9 +27,12 @@ function sourceFiles(dir: string): string[] {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Every call of `t` with a literal first argument, by file. */
|
/**
|
||||||
|
* Every call of `t` with a literal first argument, and every literal
|
||||||
|
* `labelKey` (UI commands, whose labels the palette looks up), by file.
|
||||||
|
*/
|
||||||
const usedKeys = sourceFiles(SRC).flatMap((file) =>
|
const usedKeys = sourceFiles(SRC).flatMap((file) =>
|
||||||
[...readFileSync(file, "utf8").matchAll(/\bt\(\s*(["'`])([^"'`]*)\1/g)].map((m) => ({
|
[...readFileSync(file, "utf8").matchAll(/(?:\bt\(|\blabelKey:)\s*(["'`])([^"'`]*)\1/g)].map((m) => ({
|
||||||
file,
|
file,
|
||||||
key: m[2] ?? "",
|
key: m[2] ?? "",
|
||||||
})),
|
})),
|
||||||
|
|
@ -105,7 +108,7 @@ describe("en.json", () => {
|
||||||
it("uses flat dotted keys of known areas with string values", () => {
|
it("uses flat dotted keys of known areas with string values", () => {
|
||||||
for (const [key, value] of Object.entries(en)) {
|
for (const [key, value] of Object.entries(en)) {
|
||||||
expect(key).toMatch(
|
expect(key).toMatch(
|
||||||
/^(app|project|editor|common|theme|recovery|notification)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
/^(app|command|project|editor|common|palette|theme|recovery|notification)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||||
);
|
);
|
||||||
expect(typeof value).toBe("string");
|
expect(typeof value).toBe("string");
|
||||||
expect(value.trim()).not.toBe("");
|
expect(value.trim()).not.toBe("");
|
||||||
|
|
|
||||||
350
ui/tests/palette/CommandPalette.test.ts
Normal file
350
ui/tests/palette/CommandPalette.test.ts
Normal file
|
|
@ -0,0 +1,350 @@
|
||||||
|
/**
|
||||||
|
* Tests of the command store and the palette: registering the UI commands
|
||||||
|
* with the engine, the global keymap, running engine and UI commands
|
||||||
|
* (error toasts for failures, disabled commands doing nothing), `uiCommand`
|
||||||
|
* events from the engine, and the palette's keyboard handling, ranking,
|
||||||
|
* shortcuts, dimmed disabled rows and recent commands. The engine is a
|
||||||
|
* fake behind the mocked Tauri `invoke` and `listen`.
|
||||||
|
*/
|
||||||
|
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||||
|
import { createPinia, setActivePinia, type Pinia } from "pinia";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { defineComponent, h } from "vue";
|
||||||
|
|
||||||
|
const invoke = vi.hoisted(() => vi.fn());
|
||||||
|
const listen = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||||
|
vi.mock("@tauri-apps/api/event", () => ({ listen }));
|
||||||
|
|
||||||
|
import { useCommandsStore } from "../../src/commands/store";
|
||||||
|
import { UI_COMMANDS } from "../../src/commands/uiCommands";
|
||||||
|
import CommandPalette from "../../src/components/palette/CommandPalette.vue";
|
||||||
|
import { useNotificationsStore } from "../../src/stores/notifications";
|
||||||
|
|
||||||
|
/** Engine commands the fake lists. */
|
||||||
|
const ENGINE_COMMANDS = [
|
||||||
|
{ id: "app.quit", label: "Quit", menuPath: "File/Quit", defaultShortcut: "Mod+Q", params: "", enabled: true, ui: false },
|
||||||
|
{ id: "project.close", label: "Close Project", menuPath: "File/Close Project", defaultShortcut: null, params: "", enabled: false, ui: false },
|
||||||
|
{ id: "project.openDialog", label: "Open Folder…", menuPath: "File/Open Folder…", defaultShortcut: "Mod+O", params: "", enabled: true, ui: false },
|
||||||
|
{ id: "buffer.edit", label: "Edit Buffer", menuPath: null, defaultShortcut: null, params: "", enabled: true, ui: false },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Every `engine_execute` call, in order. */
|
||||||
|
let calls: { command: string; params: unknown }[];
|
||||||
|
/** Engine commands that fail, with their error code. */
|
||||||
|
let failing: Map<string, string>;
|
||||||
|
/** The engine event callback the store subscribed with. */
|
||||||
|
let deliver: ((payload: unknown) => void) | null;
|
||||||
|
/** Pinia of the current test. */
|
||||||
|
let pinia: Pinia;
|
||||||
|
/** Mounted components, unmounted after each test. */
|
||||||
|
let mounted: VueWrapper[];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The fake engine's listing: its commands plus the registered UI commands.
|
||||||
|
*/
|
||||||
|
function listing(): unknown[] {
|
||||||
|
const registered = calls.find((c) => c.command === "ui.registerCommands")?.params as
|
||||||
|
| { commands: { id: string; labelKey: string; defaultShortcut?: string }[] }
|
||||||
|
| undefined;
|
||||||
|
const ui = (registered?.commands ?? []).map((c) => ({
|
||||||
|
id: c.id,
|
||||||
|
label: c.labelKey,
|
||||||
|
labelKey: c.labelKey,
|
||||||
|
menuPath: null,
|
||||||
|
defaultShortcut: c.defaultShortcut ?? null,
|
||||||
|
params: "",
|
||||||
|
enabled: true,
|
||||||
|
ui: true,
|
||||||
|
}));
|
||||||
|
return [...ENGINE_COMMANDS, ...ui];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends an engine event to the store.
|
||||||
|
*
|
||||||
|
* @param payload - the event.
|
||||||
|
*/
|
||||||
|
async function emit(payload: unknown): Promise<void> {
|
||||||
|
deliver?.(payload);
|
||||||
|
await flushPromises();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Presses a key on the focused element (or the body).
|
||||||
|
*
|
||||||
|
* @param init - key event properties.
|
||||||
|
*/
|
||||||
|
async function press(init: KeyboardEventInit): Promise<void> {
|
||||||
|
const target = document.activeElement ?? document.body;
|
||||||
|
target.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
|
||||||
|
await flushPromises();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ctrl+Shift+P, the palette's shortcut off macOS. */
|
||||||
|
const PALETTE_KEY = { key: "P", code: "KeyP", ctrlKey: true, shiftKey: true };
|
||||||
|
|
||||||
|
/** A focusable button standing in for the editor. */
|
||||||
|
const Host = defineComponent({
|
||||||
|
setup: () => () => h("button", { id: "host-button" }, "host"),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Mounts the palette next to a focusable button and starts the store. */
|
||||||
|
async function mountPalette(): Promise<VueWrapper> {
|
||||||
|
const host = mount(Host, { attachTo: document.body });
|
||||||
|
const wrapper = mount(CommandPalette, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||||
|
mounted.push(host, wrapper);
|
||||||
|
await useCommandsStore(pinia).start();
|
||||||
|
await flushPromises();
|
||||||
|
return wrapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ids of the palette's rows, in order.
|
||||||
|
*
|
||||||
|
* @param wrapper - the palette.
|
||||||
|
*/
|
||||||
|
function rows(wrapper: VueWrapper): string[] {
|
||||||
|
return wrapper.findAll("[data-test=palette-row]").map((row) => row.attributes("data-command") ?? "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Types into the palette's search field.
|
||||||
|
*
|
||||||
|
* @param wrapper - the palette.
|
||||||
|
* @param text - the query.
|
||||||
|
*/
|
||||||
|
async function type(wrapper: VueWrapper, text: string): Promise<void> {
|
||||||
|
await wrapper.find("[data-test=palette-input]").setValue(text);
|
||||||
|
await flushPromises();
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
pinia = createPinia();
|
||||||
|
setActivePinia(pinia);
|
||||||
|
calls = [];
|
||||||
|
failing = new Map();
|
||||||
|
deliver = null;
|
||||||
|
mounted = [];
|
||||||
|
Element.prototype.scrollIntoView = () => undefined;
|
||||||
|
invoke.mockReset();
|
||||||
|
listen.mockReset();
|
||||||
|
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
|
||||||
|
deliver = (payload) => {
|
||||||
|
callback({ payload });
|
||||||
|
};
|
||||||
|
return Promise.resolve(() => undefined);
|
||||||
|
});
|
||||||
|
invoke.mockImplementation((cmd: string, args?: { command: string; params: unknown }) => {
|
||||||
|
if (cmd === "engine_list_commands") {
|
||||||
|
return Promise.resolve(listing());
|
||||||
|
}
|
||||||
|
if (cmd === "engine_execute" && args) {
|
||||||
|
calls.push({ command: args.command, params: args.params });
|
||||||
|
const code = failing.get(args.command);
|
||||||
|
if (code !== undefined) {
|
||||||
|
return Promise.reject(Object.assign(new Error(code), { code, message: `${args.command} broke` }));
|
||||||
|
}
|
||||||
|
return Promise.resolve(null);
|
||||||
|
}
|
||||||
|
return Promise.resolve(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
useCommandsStore(pinia).stop();
|
||||||
|
for (const wrapper of mounted) {
|
||||||
|
wrapper.unmount();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("command store", () => {
|
||||||
|
it("registers the UI commands and lists them from the engine", async () => {
|
||||||
|
await mountPalette();
|
||||||
|
const store = useCommandsStore(pinia);
|
||||||
|
expect(calls[0]).toEqual({ command: "ui.registerCommands", params: { commands: UI_COMMANDS.map((c) => ({ ...c })) } });
|
||||||
|
expect(store.infos.filter((c) => c.ui === true).map((c) => c.id)).toEqual(UI_COMMANDS.map((c) => c.id));
|
||||||
|
expect(store.entries.map((e) => e.id)).not.toContain("buffer.edit");
|
||||||
|
const toggle = store.entries.find((e) => e.id === "view.toggleProjectTree");
|
||||||
|
expect(toggle).toEqual({ id: "view.toggleProjectTree", label: "Show or Hide Project", shortcut: "Ctrl+1", enabled: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the UI commands when the engine refuses them, with an error toast", async () => {
|
||||||
|
failing.set("ui.registerCommands", "invalid_params");
|
||||||
|
await mountPalette();
|
||||||
|
const store = useCommandsStore(pinia);
|
||||||
|
expect(store.entries.map((e) => e.id)).toContain("palette.open");
|
||||||
|
expect(useNotificationsStore(pinia).toasts.map((t) => t.text)).toEqual([
|
||||||
|
"ui.registerCommands failed: ui.registerCommands broke",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("runs engine commands from their shortcut and reports failures", async () => {
|
||||||
|
await mountPalette();
|
||||||
|
failing.set("project.openDialog", "failed");
|
||||||
|
await press({ key: "o", code: "KeyO", ctrlKey: true });
|
||||||
|
expect(calls.at(-1)).toEqual({ command: "project.openDialog", params: {} });
|
||||||
|
expect(useNotificationsStore(pinia).toasts.map((t) => t.text)).toEqual([
|
||||||
|
"project.openDialog failed: project.openDialog broke",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("runs provided handlers and skips disabled commands", async () => {
|
||||||
|
await mountPalette();
|
||||||
|
const store = useCommandsStore(pinia);
|
||||||
|
let toggled = 0;
|
||||||
|
let allowed = false;
|
||||||
|
const withdraw = store.provide("view.toggleProjectTree", {
|
||||||
|
run: () => {
|
||||||
|
toggled += 1;
|
||||||
|
},
|
||||||
|
enabled: () => allowed,
|
||||||
|
});
|
||||||
|
const event = new KeyboardEvent("keydown", { key: "1", code: "Digit1", ctrlKey: true, bubbles: true, cancelable: true });
|
||||||
|
window.dispatchEvent(event);
|
||||||
|
await flushPromises();
|
||||||
|
expect(toggled).toBe(0);
|
||||||
|
expect(event.defaultPrevented).toBe(true);
|
||||||
|
allowed = true;
|
||||||
|
await press({ key: "1", code: "Digit1", ctrlKey: true });
|
||||||
|
expect(toggled).toBe(1);
|
||||||
|
withdraw();
|
||||||
|
await press({ key: "1", code: "Digit1", ctrlKey: true });
|
||||||
|
expect(toggled).toBe(1);
|
||||||
|
expect(calls.map((c) => c.command)).toEqual(["ui.registerCommands"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("runs a uiCommand from the engine and warns about one nobody handles", async () => {
|
||||||
|
await mountPalette();
|
||||||
|
const store = useCommandsStore(pinia);
|
||||||
|
const seen: unknown[] = [];
|
||||||
|
store.provide("view.toggleProjectTree", {
|
||||||
|
run: (params) => {
|
||||||
|
seen.push(params);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await emit({ kind: "uiCommand", id: "view.toggleProjectTree", params: { from: "agent" } });
|
||||||
|
expect(seen).toEqual([{ from: "agent" }]);
|
||||||
|
await emit({ kind: "uiCommand", id: "settings.open", params: {} });
|
||||||
|
expect(useNotificationsStore(pinia).toasts.map((t) => t.text)).toEqual(["settings.open cannot run right now"]);
|
||||||
|
expect(store.recent).toEqual(["view.toggleProjectTree"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports a handler that throws", async () => {
|
||||||
|
await mountPalette();
|
||||||
|
const store = useCommandsStore(pinia);
|
||||||
|
store.provide("view.toggleProjectTree", {
|
||||||
|
run: () => {
|
||||||
|
throw new Error("boom");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await store.execute("view.toggleProjectTree");
|
||||||
|
expect(useNotificationsStore(pinia).toasts.map((t) => t.text)).toEqual(["view.toggleProjectTree failed: boom"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reloads the enabled states when a project opens", async () => {
|
||||||
|
await mountPalette();
|
||||||
|
const before = invoke.mock.calls.filter(([cmd]) => cmd === "engine_list_commands").length;
|
||||||
|
await emit({ kind: "projectOpened", root: "/p", name: "p" });
|
||||||
|
expect(invoke.mock.calls.filter(([cmd]) => cmd === "engine_list_commands").length).toBe(before + 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("CommandPalette", () => {
|
||||||
|
it("opens with Mod+Shift+P and lists commands with shortcuts", async () => {
|
||||||
|
const wrapper = await mountPalette();
|
||||||
|
expect(wrapper.find("[data-test=palette]").exists()).toBe(false);
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||||
|
expect(document.activeElement).toBe(wrapper.find("[data-test=palette-input]").element);
|
||||||
|
expect(rows(wrapper)).toEqual([
|
||||||
|
"project.close",
|
||||||
|
"palette.open",
|
||||||
|
"project.openDialog",
|
||||||
|
"app.quit",
|
||||||
|
"settings.open",
|
||||||
|
"view.toggleProjectTree",
|
||||||
|
]);
|
||||||
|
const quit = wrapper.find("[data-command='app.quit']");
|
||||||
|
expect(quit.find("[data-test=palette-shortcut]").text()).toBe("Ctrl+Q");
|
||||||
|
expect(quit.text()).toContain("Quit");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opens from a uiCommand the engine sends (control channel)", async () => {
|
||||||
|
const wrapper = await mountPalette();
|
||||||
|
await emit({ kind: "uiCommand", id: "palette.open", params: {} });
|
||||||
|
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("filters and moves with the arrow keys, runs with Enter", async () => {
|
||||||
|
const wrapper = await mountPalette();
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
await type(wrapper, "o");
|
||||||
|
expect(rows(wrapper).slice(0, 2)).toEqual(["project.openDialog", "palette.open"]);
|
||||||
|
await type(wrapper, "open f");
|
||||||
|
expect(rows(wrapper)[0]).toBe("project.openDialog");
|
||||||
|
await press({ key: "ArrowDown" });
|
||||||
|
await press({ key: "ArrowUp" });
|
||||||
|
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("project.openDialog");
|
||||||
|
await press({ key: "Enter" });
|
||||||
|
expect(wrapper.find("[data-test=palette]").exists()).toBe(false);
|
||||||
|
expect(calls.at(-1)).toEqual({ command: "project.openDialog", params: {} });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("wraps around with the arrow keys", async () => {
|
||||||
|
const wrapper = await mountPalette();
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
await press({ key: "ArrowUp" });
|
||||||
|
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("view.toggleProjectTree");
|
||||||
|
await press({ key: "ArrowDown" });
|
||||||
|
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("project.close");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("dims disabled commands, which Enter and clicks do not run", async () => {
|
||||||
|
const wrapper = await mountPalette();
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
await type(wrapper, "close proj");
|
||||||
|
const row = wrapper.find("[data-command='project.close']");
|
||||||
|
expect(row.attributes("aria-disabled")).toBe("true");
|
||||||
|
expect(row.classes()).toContain("palette__row--disabled");
|
||||||
|
await press({ key: "Enter" });
|
||||||
|
await row.trigger("click");
|
||||||
|
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||||
|
expect(calls.map((c) => c.command)).not.toContain("project.close");
|
||||||
|
await type(wrapper, "settings");
|
||||||
|
expect(wrapper.find("[data-command='settings.open']").attributes("aria-disabled")).toBe("true");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("closes with Escape and gives the focus back", async () => {
|
||||||
|
const wrapper = await mountPalette();
|
||||||
|
const button = document.getElementById("host-button");
|
||||||
|
button?.focus();
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
expect(document.activeElement).not.toBe(button);
|
||||||
|
await press({ key: "Escape" });
|
||||||
|
expect(wrapper.find("[data-test=palette]").exists()).toBe(false);
|
||||||
|
expect(document.activeElement).toBe(button);
|
||||||
|
expect(calls.map((c) => c.command)).toEqual(["ui.registerCommands"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows recently run commands first", async () => {
|
||||||
|
const wrapper = await mountPalette();
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
await type(wrapper, "quit");
|
||||||
|
await press({ key: "Enter" });
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
expect(rows(wrapper)[0]).toBe("app.quit");
|
||||||
|
await wrapper.find("[data-command='project.openDialog']").trigger("click");
|
||||||
|
await flushPromises();
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
expect(rows(wrapper).slice(0, 2)).toEqual(["project.openDialog", "app.quit"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("says when nothing matches", async () => {
|
||||||
|
const wrapper = await mountPalette();
|
||||||
|
await press(PALETTE_KEY);
|
||||||
|
await type(wrapper, "zzzz");
|
||||||
|
expect(rows(wrapper)).toEqual([]);
|
||||||
|
expect(wrapper.find("[data-test=palette-empty]").text()).toBe("No matching commands");
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue