M1.8: command palette, global keymap, UI commands
- Engine: ui.registerCommands (validated, replaces the previous set),
UI commands in listCommands with ui: true and labelKey, running one
through the engine emits uiCommand {id, params}.
- Frontend: ui/src/commands/ (keymap by key code, fuzzy ranking, Pinia
commands store with handlers, recents and error toasts), the command
palette (Mod+Shift+P), UI commands palette.open, settings.open (Mod+,,
disabled until M1.9b) and view.toggleProjectTree (Mod+1). The editor's
shortcuts.ts moved into the global keymap.
- Tests: engine and control-channel tests for registration and
uiCommand, Vitest for keymap, ranking, store, palette and App wiring.
- Docs: architecture, ui-parity, target-app-parity, gaps, roadmap,
ROADMAP, README.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2f8fef876b
commit
184b8a3468
33 changed files with 2282 additions and 233 deletions
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 settings;
|
||||
pub mod theme;
|
||||
pub mod ui;
|
||||
|
||||
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(theme::List))?;
|
||||
registry.register(Box::new(theme::SystemPreference))?;
|
||||
registry.register(Box::new(ui::RegisterCommands))?;
|
||||
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,
|
||||
/// Whether the command can run in the current state.
|
||||
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 {
|
||||
|
|
@ -114,6 +121,8 @@ impl CommandInfo {
|
|||
default_shortcut: spec.default_shortcut.map(str::to_string),
|
||||
params: spec.params.to_string(),
|
||||
enabled,
|
||||
label_key: None,
|
||||
ui: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ impl Engine {
|
|||
pub fn new() -> Result<Self, EngineError> {
|
||||
let mut engine = Self::empty();
|
||||
cmd::register_builtins(&mut engine.registry)?;
|
||||
engine.state.engine_commands = engine.registry.ids().collect();
|
||||
Ok(engine)
|
||||
}
|
||||
|
||||
|
|
@ -82,7 +83,10 @@ impl Engine {
|
|||
/// # Errors
|
||||
/// Returns [`EngineError::Internal`] if the id is already taken.
|
||||
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
|
||||
|
|
@ -97,11 +101,18 @@ impl Engine {
|
|||
/// [`EngineError::UnknownCommand`] for an unknown id,
|
||||
/// [`EngineError::Disabled`] if the command is disabled, the command's own
|
||||
/// 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> {
|
||||
let Self { registry, state } = self;
|
||||
let command = registry
|
||||
.get(id)
|
||||
.ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
let Some(command) = registry.get(id) else {
|
||||
let mut outcome = cmd::ui::dispatch(state, id, params)
|
||||
.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(|| {
|
||||
if !command.enabled(state) {
|
||||
return Err(EngineError::Disabled(id.to_string()));
|
||||
|
|
@ -180,16 +191,26 @@ impl Engine {
|
|||
self.state.take_events()
|
||||
}
|
||||
|
||||
/// Describes every command with its current enabled state. A command whose
|
||||
/// `enabled` check panics is listed as disabled.
|
||||
/// Describes every command with its current enabled state, the
|
||||
/// 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> {
|
||||
self.registry
|
||||
let mut list: Vec<CommandInfo> = self
|
||||
.registry
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let enabled = guard::run(|| Ok(c.enabled(&self.state))).unwrap_or(false);
|
||||
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.
|
||||
|
|
@ -359,6 +380,7 @@ mod tests {
|
|||
"test.disabled",
|
||||
"theme.list",
|
||||
"theme.systemPreference",
|
||||
"ui.registerCommands",
|
||||
]
|
||||
);
|
||||
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")]
|
||||
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`].
|
||||
|
|
@ -208,4 +216,16 @@ mod tests {
|
|||
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)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &dyn Command> {
|
||||
self.commands.values().map(Box::as_ref)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
//! Workspace state that commands read and change.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::buffers::Buffers;
|
||||
use crate::cmd::ui::UiCommand;
|
||||
use crate::journal::Journal;
|
||||
use crate::settings::Settings;
|
||||
use crate::workspace::Workspace;
|
||||
|
|
@ -28,6 +31,10 @@ pub struct State {
|
|||
/// The crash-recovery journal of the open project; `None` without a
|
||||
/// project or without persistence.
|
||||
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.
|
||||
notifications: u64,
|
||||
/// 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)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue