use gpui::{Action, App, SharedString, Window};
type CommandHandler = dyn Fn(&mut Window, &mut App);
pub struct Command {
pub(crate) name: SharedString,
pub(crate) action: Box<dyn Action>,
pub(crate) category: SharedString,
pub(crate) keybinding: Option<SharedString>,
pub(crate) handler: Option<Box<CommandHandler>>,
}
impl Command {
pub fn new(name: impl Into<SharedString>, action: impl Action) -> Self {
Self {
name: name.into(),
action: Box::new(action),
category: SharedString::new_static("General"),
keybinding: None,
handler: None,
}
}
pub fn category(mut self, category: impl Into<SharedString>) -> Self {
self.category = category.into();
self
}
pub fn keybinding(mut self, binding: impl Into<SharedString>) -> Self {
self.keybinding = Some(binding.into());
self
}
pub fn handler(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.handler = Some(Box::new(f));
self
}
pub fn name(&self) -> &SharedString {
&self.name
}
pub fn category_name(&self) -> &SharedString {
&self.category
}
pub fn binding(&self) -> Option<&SharedString> {
self.keybinding.as_ref()
}
pub fn action(&self) -> &dyn Action {
self.action.as_ref()
}
pub fn run(&self, window: &mut Window, cx: &mut App) {
if let Some(handler) = &self.handler {
handler(window, cx);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use gpui::actions;
actions!([SaveFile, ToggleSidebar]);
#[test]
fn builder_defaults() {
let command = Command::new("Save File", SaveFile);
assert_eq!(command.name(), "Save File");
assert_eq!(command.category_name(), "General");
assert!(command.binding().is_none());
assert_eq!(command.action().name(), "SaveFile");
}
#[test]
fn builder_chaining() {
let command = Command::new("Toggle Sidebar", ToggleSidebar)
.category("View")
.keybinding("cmd-b")
.handler(|_, _| {});
assert_eq!(command.category_name(), "View");
assert_eq!(command.binding().unwrap(), "cmd-b");
assert!(command.handler.is_some());
}
}