//! Lists commands reachable from the active keymap. use crate::dialog::{DialogCx, DialogKeymap, DialogOptions, Dialogs}; use crate::keymap::COMMAND_PALETTE_COMMAND; use crate::select::{SelectOption, SelectProps, select}; use opentui::prelude::*; use std::rc::Rc; /// Runs a picked command by its id, in place of dispatching it at once. pub type Run = Rc; /// The palette's rows for the commands `keymap` can reach now; a pick goes to `run` when given. pub fn command_options(keymap: &Rc, run: Option<&Run>) -> Vec<(SelectOption, bool)> { keymap .commands() .into_iter() .filter(|command| command.palette && command.id != COMMAND_PALETTE_COMMAND) .map(|command| { let footer = keymap.shortcut_all(&command.id); let search_text = [Some(command.id.clone()), command.description.clone()] .into_iter() .flatten() .filter(|part| !part.is_empty()) .collect::>() .join(" "); let search_footer = [command.group.clone(), footer.clone()] .into_iter() .flatten() .filter(|part| !part.is_empty()) .collect::>() .join(" ยท "); let id = command.id.clone(); let run_keymap = Rc::downgrade(keymap); let run = run.cloned(); let mut option = SelectOption::new(command.title.clone().unwrap_or_else(|| command.id.clone()), command.id.clone()) .search_text(search_text) .on_select(move |dialogs: &Dialogs| { dialogs.clear(); match &run { Some(run) => run(&id), None => { if let Some(keymap) = run_keymap.upgrade() { keymap.dispatch(&id, None); } } } }); option.description = command.description.clone(); option.category = command.group.clone(); option.footer = footer; option.search_footer = Some(search_footer); (option, command.suggested) }) .collect() } /// Settings rows appear only while filtering. pub fn palette(cx: &Rc, settings: Vec>, run: Option<&Run>) -> View { let commands = command_options(&cx.keymap, run); let options = Rc::new(move |filter: &str| { if !filter.is_empty() { return commands.iter().map(|(option, _)| option.clone()).chain(settings.iter().cloned()).collect(); } let suggested = commands.iter().filter(|(_, suggested)| *suggested).map(|(option, _)| { let mut option = option.clone(); option.value = format!("suggested:{}", option.value); option.category = Some("Suggested".to_owned()); option }); suggested.chain(commands.iter().map(|(option, _)| option.clone())).collect() }); let mut props = SelectProps::dynamic("Commands", options); props.search_in_title = true; props.title_placeholder = Some("Search commands".into()); props.flat = true; props.filter_threshold = 0.7; select(cx, props).0 } /// Opens the palette in place of any open dialog. pub fn show(dialogs: &Dialogs, settings: Vec>, run: Option) { dialogs.replace(move |cx| palette(cx, settings.clone(), run.as_ref()), None, DialogOptions::default()); }