use std::{
collections::HashMap,
sync::{Arc, LazyLock, Mutex, Weak},
};
use super::{
input::{Input, InputPart},
kbd::{Kbd, KbdPart, KbdVariant, KeyPlatform},
menu::{MenuItem, MenuItemPart, MenuItemState},
names,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
separator::Separator,
shared::glyph,
spinner::Spinner,
theme::{Themed, current_theme},
};
use crate::{
app::{
events::{KeyboardEvent, MouseEvent, TextInputEvent},
theme::{BorderSize, IconSize, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle},
},
components::{Column, Modal, Root, Row, ScrollVertical},
core::{ElementRef, Signal},
layout::{
Alignment,
layout_kind::{Justify, ScrollState},
text_style::FontWeight,
},
node::{
Element, Style, border::Border, color::Color, dimension::Dimension, node_kind::TextOverflow, outline::Outline,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CommandPalettePart {
Veil,
Panel,
Search,
SearchIcon,
Input,
Key,
Results,
List,
GroupLabel,
Row,
Detail,
Empty,
Status,
Footer,
FooterHint,
}
names!(CommandPalettePart {
Veil => "veil",
Panel => "panel",
Search => "search",
SearchIcon => "search_icon",
Input => "input",
Key => "key",
Results => "results",
List => "list",
GroupLabel => "group_label",
Row => "row",
Detail => "detail",
Empty => "empty",
Status => "status",
Footer => "footer",
FooterHint => "footer_hint",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CommandPaletteState {
Loading,
Empty,
}
names!(CommandPaletteState {
Loading => "loading",
Empty => "empty",
});
pub type CommandPaletteRenderer = Arc<dyn Fn(CommandPaletteView) -> Element + Send + Sync>;
pub type CommandFilter = Arc<dyn Fn(&CommandItem, &str) -> bool + Send + Sync>;
type Handler = Arc<dyn Fn() + Send + Sync>;
type QueryHandler = Arc<dyn Fn(&str) + Send + Sync>;
#[derive(Clone)]
pub struct CommandItem {
label: Arc<str>,
icon: Option<Name>,
detail: Option<Arc<str>>,
shortcut: Option<Arc<str>>,
keywords: Vec<Arc<str>>,
disabled: bool,
on_select: Vec<Handler>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl CommandItem {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
icon: None,
detail: None,
shortcut: None,
keywords: Vec::new(),
disabled: false,
on_select: Vec::new(),
id: None,
key: None,
}
}
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.icon = Some(name.into());
self
}
pub fn detail(mut self, detail: &str) -> Self {
self.detail = Some(Arc::from(detail));
self
}
pub fn shortcut(mut self, keys: &str) -> Self {
self.shortcut = Some(Arc::from(keys));
self
}
pub fn keywords<S: AsRef<str>>(mut self, words: impl IntoIterator<Item = S>) -> Self {
self
.keywords
.extend(words.into_iter().map(|word| Arc::from(word.as_ref())));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_select(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn label(&self) -> &str {
&self.label
}
pub fn detail_text(&self) -> Option<&str> {
self.detail.as_deref()
}
pub fn keyword_list(&self) -> &[Arc<str>] {
&self.keywords
}
pub fn is_disabled(&self) -> bool {
self.disabled
}
}
pub fn matches_every_word(item: &CommandItem, query: &str) -> bool {
let text: String = std::iter::once(&*item.label)
.chain(item.detail.as_deref())
.chain(item.keywords.iter().map(|word| &**word))
.collect::<Vec<_>>()
.join(" ")
.to_lowercase();
query.split_whitespace().all(|word| text.contains(&word.to_lowercase()))
}
#[derive(Clone)]
struct CommandGroup {
label: Option<Arc<str>>,
items: Vec<CommandItem>,
}
struct Kept {
query: Signal<String>,
highlight: Signal<usize>,
scroll: ScrollState,
results: ElementRef,
rows: Vec<ElementRef>,
alive: Weak<()>,
}
static KEPT: LazyLock<Mutex<HashMap<usize, Kept>>> = LazyLock::new(Default::default);
fn kept(
open: usize,
rows: usize,
) -> (
Signal<String>,
Signal<usize>,
ScrollState,
ElementRef,
Vec<ElementRef>,
Arc<()>,
) {
let mut all = KEPT.lock().unwrap();
all.retain(|_, kept| kept.alive.strong_count() > 0);
let mut alive = None;
if let Some(kept) = all.get(&open) {
alive = kept.alive.upgrade();
}
let alive = match alive {
Some(alive) => alive,
None => {
let alive = Arc::new(());
all.insert(
open,
Kept {
query: Signal::new(String::new()),
highlight: Signal::new(0),
scroll: ScrollState::new(),
results: ElementRef::new(),
rows: Vec::new(),
alive: Arc::downgrade(&alive),
},
);
alive
}
};
let kept = all.get_mut(&open).expect("kept just now");
while kept.rows.len() < rows {
kept.rows.push(ElementRef::new());
}
(
kept.query.clone(),
kept.highlight.clone(),
kept.scroll.clone(),
kept.results.clone(),
kept.rows[..rows].to_vec(),
alive,
)
}
pub struct CommandPalette {
open: Signal<bool>,
placeholder: Arc<str>,
groups: Vec<CommandGroup>,
filter: Option<CommandFilter>,
on_query: Vec<QueryHandler>,
query: Option<Signal<String>>,
loading: bool,
empty_text: Arc<str>,
loading_text: Arc<str>,
key_hints: bool,
inline: bool,
label: Option<Arc<str>>,
on_dismiss: Vec<Handler>,
dismiss_on_escape: bool,
dismiss_on_veil: bool,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl CommandPalette {
pub fn new(open: Signal<bool>) -> Self {
Self {
open,
placeholder: super::current_locale().editing.command_placeholder.clone(),
groups: Vec::new(),
filter: None,
on_query: Vec::new(),
query: None,
loading: false,
empty_text: super::current_locale().common.no_results.clone(),
loading_text: super::current_locale().common.loading_text.clone(),
key_hints: false,
inline: false,
label: None,
on_dismiss: Vec::new(),
dismiss_on_escape: true,
dismiss_on_veil: true,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn placeholder(mut self, placeholder: &str) -> Self {
self.placeholder = Arc::from(placeholder);
self
}
pub fn item(mut self, item: CommandItem) -> Self {
match self.groups.last_mut() {
Some(group) if group.label.is_none() => group.items.push(item),
_ => self.groups.push(CommandGroup {
label: None,
items: vec![item],
}),
}
self
}
pub fn items(self, items: impl IntoIterator<Item = CommandItem>) -> Self {
items.into_iter().fold(self, Self::item)
}
pub fn group(mut self, label: &str, items: impl IntoIterator<Item = CommandItem>) -> Self {
self.groups.push(CommandGroup {
label: Some(Arc::from(label)),
items: items.into_iter().collect(),
});
self
}
pub fn filter(mut self, filter: impl Fn(&CommandItem, &str) -> bool + Send + Sync + 'static) -> Self {
self.filter = Some(Arc::new(filter));
self
}
pub fn on_query(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
self.on_query.push(Arc::new(handler));
self
}
pub fn query(mut self, query: Signal<String>) -> Self {
self.query = Some(query);
self
}
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
pub fn empty_text(mut self, text: &str) -> Self {
self.empty_text = Arc::from(text);
self
}
pub fn loading_text(mut self, text: &str) -> Self {
self.loading_text = Arc::from(text);
self
}
pub fn key_hints(mut self, key_hints: bool) -> Self {
self.key_hints = key_hints;
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn on_dismiss(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_dismiss.push(Arc::new(handler));
self
}
pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
self.dismiss_on_escape = dismiss;
self
}
pub fn dismiss_on_veil(mut self, dismiss: bool) -> Self {
self.dismiss_on_veil = dismiss;
self
}
pub fn inline(mut self, inline: bool) -> Self {
self.inline = inline;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
if !self.inline && !self.open.get() {
return Modal::new(Column::new()).open(self.open).target(Root).into();
}
let filter = self.filter.clone().unwrap_or_else(|| Arc::new(matches_every_word));
let count: usize = self.groups.iter().map(|group| group.items.len()).sum();
let (own_query, highlight, scroll, results, rows, alive) = kept(self.open.id(), count);
let query = self.query.clone().unwrap_or(own_query);
let shown = shown(&self.groups, &query.get(), &filter);
let enabled: Vec<bool> = shown.iter().map(|at| !self.command(*at).disabled).collect();
let highlighted = settle(&enabled, highlight.get());
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(CommandPaletteState::Loading, self.loading)
.state(CommandPaletteState::Empty, shown.is_empty() && !self.loading);
let view = CommandPaletteView {
placeholder: self.placeholder,
loading: self.loading,
empty_text: self.empty_text,
loading_text: self.loading_text,
key_hints: self.key_hints,
inline: self.inline,
label: self.label,
on_dismiss: self.on_dismiss,
dismiss_on_escape: self.dismiss_on_escape,
dismiss_on_veil: self.dismiss_on_veil,
highlighted,
recipe: theme
.resolve::<CommandPalette>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
groups: self.groups,
shown,
enabled,
filter,
on_query: self.on_query,
open: self.open,
query,
highlight,
scroll,
results,
rows,
alive,
id: self.id,
key: self.key,
};
match theme.renderer::<CommandPalette>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn command(&self, (group, item): (usize, usize)) -> &CommandItem {
&self.groups[group].items[item]
}
}
impl From<CommandPalette> for Element {
fn from(palette: CommandPalette) -> Self {
palette.build(¤t_theme())
}
}
fn shown(groups: &[CommandGroup], query: &str, filter: &CommandFilter) -> Vec<(usize, usize)> {
let all = query.trim().is_empty();
groups
.iter()
.enumerate()
.flat_map(|(group, commands)| {
commands
.items
.iter()
.enumerate()
.filter(move |(_, item)| all || filter(item, query))
.map(move |(item, _)| (group, item))
})
.collect()
}
fn settle(enabled: &[bool], wanted: usize) -> Option<usize> {
let wanted = wanted.min(enabled.len().saturating_sub(1));
(wanted..enabled.len()).chain(0..wanted).find(|index| enabled[*index])
}
fn step(enabled: &[bool], from: Option<usize>, forward: bool) -> Option<usize> {
let count = enabled.len();
if count == 0 {
return None;
}
let mut at = from.unwrap_or(if forward { count - 1 } else { 0 });
for _ in 0..count {
at = if forward {
(at + 1) % count
} else {
(at + count - 1) % count
};
if enabled[at] {
return Some(at);
}
}
None
}
pub struct CommandPaletteView {
pub placeholder: Arc<str>,
pub loading: bool,
pub empty_text: Arc<str>,
pub loading_text: Arc<str>,
pub key_hints: bool,
pub inline: bool,
pub label: Option<Arc<str>>,
pub highlighted: Option<usize>,
pub recipe: ResolvedRecipe,
groups: Vec<CommandGroup>,
shown: Vec<(usize, usize)>,
enabled: Vec<bool>,
filter: CommandFilter,
on_query: Vec<QueryHandler>,
on_dismiss: Vec<Handler>,
dismiss_on_escape: bool,
dismiss_on_veil: bool,
open: Signal<bool>,
query: Signal<String>,
highlight: Signal<usize>,
scroll: ScrollState,
results: ElementRef,
rows: Vec<ElementRef>,
alive: Arc<()>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl CommandPaletteView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn shown(&self) -> usize {
self.shown.len()
}
pub fn command(&self, row: usize) -> &CommandItem {
let (group, item) = self.shown[row];
&self.groups[group].items[item]
}
pub fn open(&self) -> &Signal<bool> {
&self.open
}
fn runner(&self, row: usize) -> Option<impl Fn() + Send + Sync + Clone + 'static> {
let command = self.command(row);
if command.disabled {
return None;
}
let (handlers, open) = (command.on_select.clone(), self.open.clone());
Some(move || {
open.set(false);
for handler in &handlers {
handler();
}
})
}
fn dismisser(&self) -> impl Fn() + Send + Sync + Clone + 'static {
let (open, handlers) = (self.open.clone(), self.on_dismiss.clone());
move || {
open.set(false);
for handler in &handlers {
handler();
}
}
}
fn reveal(scroll: &ScrollState, results: &ElementRef, row: &ElementRef) {
let (view, row) = (results.bounds(), row.bounds());
if view.height <= 0.0 || row.height <= 0.0 {
return;
}
let by = if row.y < view.y {
row.y - view.y
} else if row.y + row.height > view.y + view.height {
row.y + row.height - view.y - view.height
} else {
return;
};
scroll.set_scroll_pending(scroll.scroll_x(), (scroll.scroll_y() + by).max(0.0));
}
pub fn panel(&self) -> Column {
let mut panel = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(CommandPalettePart::Panel))
.max_width(Dimension::Pct(100.0))
.max_height(Dimension::Pct(100.0))
.on_click(|event: MouseEvent| event.stop_propagation())
.describe("a11y_role", "dialog")
.describe("a11y_name", self.label.clone().unwrap_or_else(|| self.placeholder.clone()));
if let Some(id) = &self.id {
panel = panel.id(id.clone());
}
panel
}
pub fn key(&self, key: &str) -> Element {
Row::new()
.flex_full(0.0, 0.0, None)
.align_items(Alignment::Center)
.child(
Kbd::new(key)
.platform(KeyPlatform::current())
.rules(&self.recipe.rules_for(CommandPalettePart::Key, KbdPart::Key))
.build(self.theme()),
)
.into()
}
pub fn input(&self) -> Element {
let rules = self.recipe.rules_for(CommandPalettePart::Input, InputPart::Control);
let mut typed = Input::new(self.query.clone())
.placeholder(&self.placeholder)
.full_width(true)
.label(&self.placeholder)
.rules(&rules);
{
let (groups, filter, highlight, handlers) = (
self.groups.clone(),
self.filter.clone(),
self.highlight.clone(),
self.on_query.clone(),
);
typed = typed.on_input(move |event: &TextInputEvent| {
let shown = shown(&groups, &event.new_value, &filter);
let enabled: Vec<bool> = shown
.iter()
.map(|(group, item)| !groups[*group].items[*item].disabled)
.collect();
let first = settle(&enabled, 0).unwrap_or(0);
if highlight.get_untracked() != first {
highlight.set(first);
}
for handler in &handlers {
handler(&event.new_value);
}
});
}
let view = typed.view(self.theme());
let keys = self.keys();
let mut control = view
.control()
.describe("a11y_role", "combobox")
.describe("a11y_expanded", "true")
.describe("a11y_autocomplete", "list")
.on_key_down(keys);
if let Some(row) = self.highlighted {
control = control.describe("a11y_activedescendant", self.command(row).label.clone());
}
view.render_with_end(control, None).into()
}
fn keys(&self) -> impl Fn(KeyboardEvent) + Send + Sync + 'static {
let runners: Vec<Option<Handler>> = (0..self.shown())
.map(|row| self.runner(row).map(|run| Arc::new(run) as Handler))
.collect();
let (enabled, highlighted) = (self.enabled.clone(), self.highlighted);
let (highlight, query, dismiss) = (self.highlight.clone(), self.query.clone(), self.dismisser());
let (dismiss_on_escape, inline) = (self.dismiss_on_escape, self.inline);
let (groups, filter) = (self.groups.clone(), self.filter.clone());
let (scroll, results, rows, alive) = (
self.scroll.clone(),
self.results.clone(),
self.rows.clone(),
self.alive.clone(),
);
move |event: KeyboardEvent| {
let _ = &alive;
if !event.focus_within || event.ctrl || event.alt || event.meta || event.composing {
return;
}
match event.key.as_str() {
"ArrowDown" | "ArrowUp" => {
event.prevent_default();
if let Some(next) = step(&enabled, highlighted, event.key == "ArrowDown") {
highlight.set(next);
if let Some(row) = rows.get(next) {
Self::reveal(&scroll, &results, row);
}
}
}
"Enter" => {
event.prevent_default();
if let Some(Some(run)) = highlighted.and_then(|row| runners.get(row)) {
run();
}
}
"Escape" => {
if query.get_untracked().is_empty() {
if !dismiss_on_escape || inline {
event.prevent_default();
}
if dismiss_on_escape && inline {
dismiss();
}
} else {
event.prevent_default();
query.set(String::new());
let all = shown(&groups, "", &filter);
let enabled: Vec<bool> = all
.iter()
.map(|(group, item)| !groups[*group].items[*item].disabled)
.collect();
highlight.set(settle(&enabled, 0).unwrap_or(0));
scroll.set_scroll_pending(0.0, 0.0);
}
}
_ => {}
}
}
}
pub fn search(&self) -> Row {
Row::new()
.align_items(Alignment::Center)
.part(&self.part(CommandPalettePart::Search))
.child(glyph(
&self.part(CommandPalettePart::SearchIcon),
Name::new(super::icons::SEARCH),
false,
))
.child(
Row::new()
.flex_full(1.0, 1.0, Some(0.0))
.align_items(Alignment::Center)
.child(self.input()),
)
.child(self.key(&super::current_locale().keys.esc))
}
pub fn group_label(&self, label: &str) -> Element {
let part = self.part(CommandPalettePart::GroupLabel);
Row::new().part(&part).child(part.text(label).nowrap()).into()
}
pub fn row(&self, row: usize) -> Element {
let command = self.command(row).clone();
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: Vec::new(),
}
.state(MenuItemState::Disabled, command.disabled);
let named = command.id.clone().or_else(|| match &command.key {
Some(key) => self
.recipe
.keyed_item(key, CommandPalettePart::Row)
.part_id(CommandPalettePart::Row),
None => self.recipe.part_id(CommandPalettePart::Row),
});
let rules = self.recipe.rules_for(CommandPalettePart::Row, MenuItemPart::Root);
let item = self
.theme()
.resolve::<MenuItem>(&case, Some(&rules))
.owned_like(&self.recipe)
.item(named.as_ref(), MenuItemPart::Root);
let on = self.highlighted == Some(row);
let forced = on.then_some(Interaction::FocusVisible);
let part = |name: MenuItemPart| item.part(name).forced(forced);
let mut root = Row::new()
.align_items(Alignment::Center)
.justify(Justify::SpaceBetween)
.part(&part(MenuItemPart::Root))
.hovered_style(Style::default())
.active_style(Style::default())
.describe("a11y_role", "option")
.describe("a11y_name", command.label.clone())
.describe("a11y_selected", if on { "true" } else { "false" });
if command.disabled {
root = root.describe("a11y_disabled", "true");
} else {
let highlight = self.highlight.clone();
root = root.on_mouse_enter(move || {
if highlight.get_untracked() != row {
highlight.set(row);
}
});
if let Some(run) = self.runner(row) {
root = root.on_click(move |_| run());
}
}
if let Some(at) = self.rows.get(row) {
root = root.ref_element(at.clone());
}
if let Some(id) = &named {
root = root.id(id.clone());
}
if let Some(key) = &command.key {
root = root.key(key.clone());
}
let gap = part(MenuItemPart::Root).rest().gap.unwrap_or_default();
let mut start = Row::new()
.flex_full(1.0, 1.0, Some(0.0))
.spacing(gap.clone())
.align_items(Alignment::Center);
if let Some(icon) = command.icon {
start = start.child(glyph(&part(MenuItemPart::Icon), icon, false));
}
let label = part(MenuItemPart::Label);
start = start.child(
Row::new()
.part(&label)
.child(label.text(&command.label).nowrap().text_overflow(TextOverflow::Elipsis)),
);
if let Some(detail) = &command.detail {
let part = self
.recipe
.item(named.as_ref(), CommandPalettePart::Row)
.part(CommandPalettePart::Detail);
start = start.child(
Row::new()
.flex_full(1.0, 1.0, Some(0.0))
.part(&part)
.child(part.text(detail).nowrap().text_overflow(TextOverflow::Elipsis)),
);
}
root = root.child(start);
if let Some(shortcut) = &command.shortcut {
root = root.child(
Row::new()
.flex_full(0.0, 0.0, None)
.align_items(Alignment::Center)
.child(
Kbd::shortcut(shortcut)
.variant(KbdVariant::Plain)
.platform(KeyPlatform::current())
.rules(&item.rules_for(MenuItemPart::Shortcut, KbdPart::Label))
.build(self.theme()),
),
);
}
root.into()
}
pub fn empty_state(&self) -> Element {
let part = self.part(CommandPalettePart::Empty);
Row::new()
.justify(Justify::Center)
.part(&part)
.child(part.text(&self.empty_text))
.into()
}
pub fn status(&self) -> Element {
let part = self.part(CommandPalettePart::Status);
Row::new()
.align_items(Alignment::Center)
.part(&part)
.describe("a11y_role", "status")
.child(
Spinner::new()
.decorative(true)
.rules(&self.recipe.lend("spinner"))
.build(self.theme()),
)
.child(part.text(&self.loading_text).nowrap())
.into()
}
pub fn results(&self) -> Element {
let mut list = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(CommandPalettePart::List))
.describe("a11y_role", "listbox");
let mut group = None;
for row in 0..self.shown() {
let at = self.shown[row].0;
if group != Some(at) {
group = Some(at);
if let Some(label) = &self.groups[at].label {
list = list.child(self.group_label(label));
}
}
list = list.child(self.row(row));
}
if self.loading {
list = list.child(self.status());
} else if self.shown.is_empty() {
list = list.child(self.empty_state());
}
ScrollVertical::new(list)
.with_scroll_state(self.scroll.clone())
.width(Dimension::Pct(100.0))
.flex_full(0.0, 1.0, None)
.part(&self.part(CommandPalettePart::Results))
.ref_element(self.results.clone())
.into()
}
pub fn footer_row(&self) -> Element {
let locale = super::current_locale();
let hint = |keys: &[&str], says: &str| {
let part = self.part(CommandPalettePart::FooterHint);
let gap = self.part(CommandPalettePart::Footer).rest().gap.unwrap_or_default();
let mut row = Row::new()
.align_items(Alignment::Center)
.spacing(gap.clone())
.part(&part);
for key in keys {
row = row.child(self.key(key));
}
row.child(part.text(says).nowrap())
};
Column::new()
.align_items(Alignment::Stretch)
.child(
Separator::horizontal()
.rules(&self.recipe.lend("separator"))
.build(self.theme()),
)
.child(
Row::new()
.align_items(Alignment::Center)
.part(&self.part(CommandPalettePart::Footer))
.child(hint(&["↑", "↓"], &locale.editing.to_move))
.child(hint(&[&locale.keys.enter], &locale.editing.to_run))
.child(hint(&[&locale.keys.esc], &locale.editing.to_close)),
)
.into()
}
pub fn veil(&self, panel: impl Into<Element>) -> Column {
let (dismiss, on_veil) = (self.dismisser(), self.dismiss_on_veil);
let mut veil = Column::new()
.size(Dimension::Pct(100.0), Dimension::Pct(100.0))
.align_items(Alignment::Center)
.justify(Justify::Start)
.part(&self.part(CommandPalettePart::Veil))
.on_click(move |_| {
if on_veil {
dismiss();
}
})
.child(panel);
if let Some(key) = &self.key {
veil = veil.key(key.clone());
}
veil
}
pub fn modal(&self, panel: impl Into<Element>) -> Element {
let mut modal = Modal::new(self.veil(panel))
.open(self.open.clone())
.target(Root)
.dismiss_on_escape(self.dismiss_on_escape)
.takes_focus(true);
for handler in &self.on_dismiss {
let handler = handler.clone();
modal = modal.on_dismiss(move || handler());
}
modal.into()
}
pub fn render(self) -> Element {
let mut panel = self.panel().child(self.search()).child(self.results());
if self.key_hints {
panel = panel.child(self.footer_row());
}
if self.inline { panel.into() } else { self.modal(panel) }
}
}
impl crate::ui::Styled for CommandPalette {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for CommandPalette {
const NAME: &'static str = "command_palette";
const ROOT: &'static str = "panel";
type Renderer = CommandPaletteRenderer;
fn parts() -> crate::ui::Declared {
CommandPalettePart::declared()
}
fn states() -> crate::ui::Declared {
CommandPaletteState::declared()
}
fn recipe() -> Recipe {
use CommandPalettePart::*;
use PaletteColor::{MutedForeground, Popover, PopoverForeground, Scrim};
let clear = Color::new(0, 0, 0, 0);
let unedged = move |s: super::PartStyle| s.background(clear).border(Border::inside(1.0, clear));
Recipe::new()
.base(Veil, |s| {
s.background(Scrim)
.padding_x(16.0)
.padding_top(72.0)
.padding_bottom(16.0)
})
.base(Panel, |s| {
s.width(420.0)
.background(Popover)
.foreground(PopoverForeground)
.border(Border::inside(BorderSize::Sm, PaletteColor::Border))
.radius(RadiusSize::Xl)
.shadow(ShadowStyle::Lg)
})
.base(Search, |s| {
s.height(44.0)
.padding_x(14.0)
.gap(10.0)
.underline(Border::inside(BorderSize::Sm, PaletteColor::Border))
})
.base(SearchIcon, |s| s.square(IconSize::Md).foreground(MutedForeground))
.base(Input, move |s| unedged(s).padding_x(0.0).typography(TypographyStyle::Body))
.hovered(Input, move |s| s.border(Border::inside(1.0, clear)))
.focus_visible(Input, move |s| s.outline(Outline::new(0.0, clear)))
.base(Results, |s| s.max_height(320.0))
.base(List, |s| s.padding_x(4.0).padding_y(4.0))
.base(GroupLabel, |s| {
s.padding_x(8.0)
.padding_y(6.0)
.typography(TypographyStyle::Label)
.font_size(12.0)
.weight(FontWeight::Medium)
.foreground(MutedForeground)
})
.base(Detail, |s| {
s.typography(TypographyStyle::Body)
.font_size(12.0)
.foreground(MutedForeground)
})
.base(Empty, |s| {
s.padding_x(8.0)
.padding_y(24.0)
.typography(TypographyStyle::Body)
.foreground(MutedForeground)
})
.base(Status, |s| {
s.height(32.0)
.padding_x(8.0)
.gap(8.0)
.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(MutedForeground)
})
.row_density(super::Selector::new(), Status, 32.0)
.base(Footer, |s| s.height(36.0).padding_x(12.0).gap(16.0))
.base(FooterHint, |s| {
s.gap(4.0)
.typography(TypographyStyle::Body)
.font_size(12.0)
.foreground(MutedForeground)
})
}
}