refactor: utility macro to declare multiple handlers with ease

pull/12902/head
Nikita Revenco 2025-02-17 21:41:23 +00:00
parent 9a28d4fa42
commit 5d29a175f3
2 changed files with 28 additions and 20 deletions

View File

@ -37,6 +37,8 @@ use std::collections::HashMap;
use std::path::Path;
use std::{error::Error, path::PathBuf};
use self::picker::PickerKeyHandler;
struct Utf8PathBuf {
path: String,
is_dir: bool,
@ -299,18 +301,16 @@ pub fn file_explorer(root: PathBuf, editor: &Editor) -> Result<FileExplorer, std
},
)];
let delete: Box<dyn Fn(&mut Context) + 'static> = Box::new(|cx: &mut Context| {
log::error!("delete file");
});
let create: Box<dyn Fn(&mut Context) + 'static> = Box::new(|cx: &mut Context| {
log::error!("create file");
});
let rename: Box<dyn Fn(&mut Context) + 'static> = Box::new(|cx: &mut Context| {
log::error!("rename file");
});
let copy: Box<dyn Fn(&mut Context) + 'static> = Box::new(|cx: &mut Context| {
log::error!("copy file");
});
macro_rules! declare_key_handlers {
($($op:literal $key:expr => $handler:expr),*) => {
hashmap!(
$(
$key => Box::new($handler)
as Box<dyn Fn(&mut Context) + 'static>
),*
)
};
}
let picker = Picker::new(
columns,
@ -341,12 +341,20 @@ pub fn file_explorer(root: PathBuf, editor: &Editor) -> Result<FileExplorer, std
},
)
.with_preview(|_editor, (path, _is_dir)| Some((path.as_path().into(), None)))
.with_key_handler(HashMap::from([
(alt!('c'), create),
(alt!('d'), delete),
(alt!('y'), copy),
(alt!('r'), rename),
]));
.with_key_handlers(declare_key_handlers! {
"Create" alt!('c') => |cx: &mut Context| {
log::error!("create file");
},
"Delete" alt!('d') => |cx: &mut Context| {
log::error!("delete file");
},
"Copy" alt!('y') => |cx: &mut Context| {
log::error!("copy file");
},
"Rename" alt!('r') => |cx: &mut Context| {
log::error!("rename file");
}
});
Ok(picker)
}

View File

@ -395,7 +395,7 @@ impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
}
}
pub fn with_key_handler(mut self, handlers: PickerKeyHandler) -> Self {
pub fn with_key_handlers(mut self, handlers: PickerKeyHandler) -> Self {
self.custom_key_handlers = handlers;
self
}
@ -1179,4 +1179,4 @@ impl<T: 'static + Send + Sync, D> Drop for Picker<T, D> {
}
type PickerCallback<T> = Box<dyn Fn(&mut Context, &T, Action)>;
type PickerKeyHandler = HashMap<KeyEvent, Box<dyn Fn(&mut Context)>>;
pub type PickerKeyHandler = HashMap<KeyEvent, Box<dyn Fn(&mut Context) + 'static>>;