1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
//! Command model and registry backing the palette, keymap, and menus.
//!
//! A [`Command`] is a leaf action or a submenu of nested commands; the
//! [`CommandRegistry`] stores them in reactive context, tracks recently run
//! ids, and dispatches by id.
use leptos::prelude::*;
/// A single palette action or a submenu of nested commands.
///
/// Build leaves with [`Command::new`] and groupings with [`Command::submenu`],
/// then chain the `with_*` builders to attach a group label, keybinding, or an
/// `enabled` signal that gates whether the command can run.
#[derive(Clone)]
pub struct Command {
pub id: String,
pub title: String,
pub group: String,
pub keybinding: Option<String>,
pub run: Option<Callback<()>>,
pub children: Vec<Command>,
enabled: Signal<bool>,
}
impl Command {
/// Creates a runnable leaf command with the given id, title, and callback.
pub fn new(id: impl Into<String>, title: impl Into<String>, run: Callback<()>) -> Self {
Self {
id: id.into(),
title: title.into(),
group: String::new(),
keybinding: None,
run: Some(run),
children: Vec::new(),
enabled: Signal::derive(|| true),
}
}
/// Creates a non-runnable submenu command whose `children` open as a nested level.
pub fn submenu(
id: impl Into<String>,
title: impl Into<String>,
children: Vec<Command>,
) -> Self {
Self {
id: id.into(),
title: title.into(),
group: String::new(),
keybinding: None,
run: None,
children,
enabled: Signal::derive(|| true),
}
}
/// Sets the group label shown alongside the command in the palette.
pub fn with_group(mut self, group: impl Into<String>) -> Self {
self.group = group.into();
self
}
/// Attaches a keybinding string (for example `"mod+k"`) used by the keymap and shown as a hint.
pub fn with_keybinding(mut self, keybinding: impl Into<String>) -> Self {
self.keybinding = Some(keybinding.into());
self
}
/// Alias for [`Command::with_group`], reading better when the group is used as a trailing hint.
pub fn with_hint(mut self, group: impl Into<String>) -> Self {
self.group = group.into();
self
}
/// Gates the command behind a reactive `enabled` signal; disabled commands are hidden and never run.
pub fn with_enabled(mut self, enabled: impl Into<Signal<bool>>) -> Self {
self.enabled = enabled.into();
self
}
/// Returns `true` when this command has children and opens as a submenu rather than running.
pub fn is_submenu(&self) -> bool {
!self.children.is_empty()
}
/// Reactively reads whether the command is currently enabled.
pub fn enabled(&self) -> bool {
self.enabled.get()
}
fn enabled_untracked(&self) -> bool {
self.enabled.get_untracked()
}
}
const RECENT_LIMIT: usize = 8;
/// Reactive store of registered commands plus a bounded most-recently-run list.
///
/// It is `Copy` and lives in Leptos context; obtain it with [`use_commands`]
/// after calling [`provide_command_registry`] near the app root.
#[derive(Clone, Copy)]
pub struct CommandRegistry {
commands: RwSignal<Vec<Command>>,
recent: RwSignal<Vec<String>>,
}
impl Default for CommandRegistry {
fn default() -> Self {
Self {
commands: RwSignal::new(Vec::new()),
recent: RwSignal::new(Vec::new()),
}
}
}
impl CommandRegistry {
/// Adds a command, replacing any existing one with the same id.
pub fn register(&self, command: Command) {
self.commands.update(|list| {
if let Some(slot) = list.iter_mut().find(|existing| existing.id == command.id) {
*slot = command;
} else {
list.push(command);
}
});
}
/// Registers each command in the iterator in order.
pub fn register_all(&self, commands: impl IntoIterator<Item = Command>) {
for command in commands {
self.register(command);
}
}
/// Removes the top-level command with the given id, if present.
pub fn unregister(&self, id: &str) {
self.commands
.update(|list| list.retain(|command| command.id != id));
}
/// Removes every registered command.
pub fn clear(&self) {
self.commands.update(Vec::clear);
}
/// Reactively reads the registered top-level commands.
pub fn commands(&self) -> Vec<Command> {
self.commands.get()
}
/// Reads the registered top-level commands without tracking reactivity.
pub fn commands_untracked(&self) -> Vec<Command> {
self.commands.get_untracked()
}
/// Searches the command tree, descending into submenus, for a command with the given id.
pub fn find(&self, id: &str) -> Option<Command> {
find_command(&self.commands.get_untracked(), id)
}
/// Reactively reads the most-recently-run command ids, newest first.
pub fn recent(&self) -> Vec<String> {
self.recent.get()
}
/// Runs the command with the given id, recording it as recent; returns `false` if it is missing, has no callback, or is disabled.
pub fn run(&self, id: &str) -> bool {
let Some(command) = self.find(id) else {
return false;
};
let Some(callback) = command.run else {
return false;
};
if !command.enabled_untracked() {
return false;
}
self.record(id);
callback.run(());
true
}
fn record(&self, id: &str) {
self.recent.update(|list| {
list.retain(|existing| existing != id);
list.insert(0, id.to_string());
list.truncate(RECENT_LIMIT);
});
}
}
fn find_command(commands: &[Command], id: &str) -> Option<Command> {
for command in commands {
if command.id == id {
return Some(command.clone());
}
if let Some(found) = find_command(&command.children, id) {
return Some(found);
}
}
None
}
/// Creates a [`CommandRegistry`], provides it as context, and returns it.
pub fn provide_command_registry() -> CommandRegistry {
let registry = CommandRegistry::default();
provide_context(registry);
registry
}
/// Retrieves the [`CommandRegistry`] from context, or a fresh empty default if none was provided.
pub fn use_commands() -> CommandRegistry {
use_context::<CommandRegistry>().unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::Command;
use super::find_command;
use leptos::prelude::Callback;
fn leaf(id: &str) -> Command {
Command::new(id, id, Callback::new(|_| {}))
}
#[test]
fn find_command_descends_into_submenus() {
let tree = vec![
leaf("a"),
Command::submenu("group", "Group", vec![leaf("b"), leaf("c")]),
];
assert!(find_command(&tree, "a").is_some());
assert!(find_command(&tree, "c").is_some());
assert!(find_command(&tree, "missing").is_none());
}
}