diff --git a/Cargo.lock b/Cargo.lock index 28b98c73..d2f56809 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1177,6 +1177,7 @@ dependencies = [ "eggshell-ui", "egui", "pulldown-cmark", + "unicode-normalization", ] [[package]] @@ -4036,6 +4037,12 @@ dependencies = [ "serde_json", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.54.1" @@ -4204,6 +4211,15 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-properties" version = "0.1.5" diff --git a/Cargo.toml b/Cargo.toml index 0d4b6580..d1154b2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ trybuild = "1" # eggshell's own tests drive views through `testing::Driver`. eggshell-ui = { path = ".", features = ["driver"] } eggshell-ui-shadcn = { path = "crates/eggshell-ui-shadcn", features = ["extras"] } -eggshell-ui-extras = { path = "crates/eggshell-ui-extras", features = ["form", "hover-card", "markdown", "badge", "spinner", "skeleton"] } +eggshell-ui-extras = { path = "crates/eggshell-ui-extras", features = ["form", "hover-card", "markdown", "badge", "spinner", "skeleton", "command"] } # proptest's rng wants a getrandom backend that the browser build does not # select, and the fuzzers only run natively. diff --git a/crates/eggshell-ui-extras/Cargo.toml b/crates/eggshell-ui-extras/Cargo.toml index f08ff79d..e704ece9 100644 --- a/crates/eggshell-ui-extras/Cargo.toml +++ b/crates/eggshell-ui-extras/Cargo.toml @@ -15,11 +15,13 @@ badge = [] form = [] spinner = [] skeleton = [] +command = ["dep:unicode-normalization"] [dependencies] eggshell-ui = { path = "../..", version = "0.1.0" } egui = "0.37" pulldown-cmark = { version = "0.13.6", default-features = false, optional = true } +unicode-normalization = { version = "0.1.25", optional = true } [package.metadata.docs.rs] all-features = true diff --git a/crates/eggshell-ui-extras/src/command/filter.rs b/crates/eggshell-ui-extras/src/command/filter.rs new file mode 100644 index 00000000..89e60813 --- /dev/null +++ b/crates/eggshell-ui-extras/src/command/filter.rs @@ -0,0 +1,168 @@ +//! TODO(prose): the one filter Combobox, Command and Autosuggest share: a query's words each the start of a word of an item's label or keywords. + +use unicode_normalization::UnicodeNormalization as _; +use unicode_normalization::char::is_combining_mark; + +/// TODO(prose): how well an item matches a query; the lower ranks first, and items of equal score keep the app's order. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Score(u32); + +impl Score { + /// TODO(prose): the best score: what an empty query gives every item. + pub const BEST: Self = Self(0); + + /// TODO(prose): a score of `rank`, for a filter of the app's own; lower ranks first. + pub fn new(rank: u32) -> Self { + Self(rank) + } +} + +impl From for u32 { + fn from(score: Score) -> Self { + score.0 + } +} + +/// TODO(prose): what a filter sees of an item: its label and its hidden keywords. +#[derive(Clone, Copy, Debug)] +pub struct Candidate<'a> { + /// TODO(prose): the text the row shows. + pub label: &'a str, + /// TODO(prose): more words the item is found by, not shown. + pub keywords: &'a [String], +} + +/// The rank of a match: the label's first word, a later word of the label, +/// or a keyword. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Place { + LabelStart, + LabelWord, + Keyword, +} + +/// TODO(prose): the library's matcher: each word of `query` must start a word of the label or of a keyword, case and accents aside; a match at the start of the label ranks first, then one at a later word of it, then one in a keyword. An empty query matches everything at [`Score::BEST`]. +pub fn word_prefix(query: &str, candidate: Candidate<'_>) -> Option { + let wanted = words(query); + let label = words(candidate.label); + let keywords: Vec = candidate.keywords.iter().flat_map(|k| words(k)).collect(); + let mut worst = Place::LabelStart; + for word in &wanted { + let place = label + .iter() + .position(|have| have.starts_with(word.as_str())) + .map(|at| { + if at == 0 { + Place::LabelStart + } else { + Place::LabelWord + } + }) + .or_else(|| { + keywords + .iter() + .any(|have| have.starts_with(word.as_str())) + .then_some(Place::Keyword) + })?; + worst = worst.max(place); + } + Some(Score(worst as u32)) +} + +/// The words of `text`, lower-cased and without accents: split at anything +/// that is not a letter or a digit. +fn words(text: &str) -> Vec { + let folded: String = text + .nfd() + .filter(|c| !is_combining_mark(*c)) + .flat_map(char::to_lowercase) + .collect(); + folded + .split(|c: char| !c.is_alphanumeric()) + .filter(|word| !word.is_empty()) + .map(str::to_owned) + .collect() +} + +/// The items of `scores` that matched, best first, ties in the given order. +pub(crate) fn ranked(scored: impl IntoIterator, T)>) -> Vec { + let mut kept: Vec<(Score, usize, T)> = scored + .into_iter() + .enumerate() + .filter_map(|(at, (score, item))| Some((score?, at, item))) + .collect(); + kept.sort_by_key(|&(score, at, _)| (score, at)); + kept.into_iter().map(|(_, _, item)| item).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn score(query: &str, label: &str) -> Option { + word_prefix( + query, + Candidate { + label, + keywords: &[], + }, + ) + } + + #[test] + fn every_word_of_the_query_must_start_a_word() { + assert!(score("com pal", "Command palette").is_some()); + assert!(score("pal com", "Command palette").is_some()); + assert_eq!( + score("cmdpl", "Command palette"), + None, + "no fuzzy subsequences" + ); + assert_eq!(score("mand", "Command palette"), None, "not inside a word"); + assert_eq!(score("com xyz", "Command palette"), None); + } + + #[test] + fn case_and_accents_are_ignored() { + assert!(score("ZUR", "zürich").is_some()); + assert!(score("zür", "Zurich").is_some()); + assert!(score("ecole", "École normale").is_some()); + } + + #[test] + fn the_start_of_the_label_ranks_before_a_later_word_before_a_keyword() { + let keywords = ["remove".to_owned()]; + let keyword = word_prefix( + "rem", + Candidate { + label: "Delete", + keywords: &keywords, + }, + ); + let start = score("rem", "Remove line"); + let later = score("rem", "Line remove"); + assert!( + start < later && later < keyword, + "{start:?} {later:?} {keyword:?}" + ); + assert!(keyword.is_some(), "a hidden keyword finds the item"); + } + + #[test] + fn an_empty_query_matches_everything_at_the_best_score() { + assert_eq!(score("", "Anything"), Some(Score::BEST)); + assert_eq!(score(" ", "Anything"), Some(Score::BEST)); + } + + #[test] + fn ties_keep_the_given_order() { + let ranked = ranked([ + (Some(Score::new(1)), "b"), + (Some(Score::new(0)), "a"), + (None, "gone"), + (Some(Score::new(1)), "c"), + (Some(Score::new(0)), "d"), + ]); + assert_eq!(ranked, ["a", "d", "b", "c"]); + } +} diff --git a/crates/eggshell-ui-extras/src/command/list.rs b/crates/eggshell-ui-extras/src/command/list.rs new file mode 100644 index 00000000..c7d2c24f --- /dev/null +++ b/crates/eggshell-ui-extras/src/command/list.rs @@ -0,0 +1,661 @@ +//! The one list a command list, a combobox and an autosuggest show: a search +//! field, and the items that match its query in a virtual list it drives. + +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::Arc; + +use eggshell_ui::owned::{Enablement, Mark}; +use eggshell_ui::vlist::ListNav; +use eggshell_ui::{ + Builder, Command, CommandState, Commands, Icon, Key, Scope, Shell, Style, Tw, child_id, icons, + tw, +}; +use egui::{Context, Id, Role}; + +use super::{Filter, Filtering, Options, Pending, filter}; + +type Pick = Rc; + +/// The key of a row: the item's group and its own key, the same from frame +/// to frame while the query narrows the rows. +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +pub(crate) struct Row(Id); + +struct Entry { + row: Row, + group: usize, + label: String, + keywords: Vec, + shortcut: Option, + state: CommandState, + enablement: Enablement, + pick: Option>, +} + +/// TODO(prose): the items of a list, in groups, as [`CommandList::items`](super::CommandList::items) is given them. +pub struct Items { + entries: Vec>, + /// Each group's heading; the first is the items outside every group. + groups: Vec>, + group: usize, + shell: Shell, +} + +impl Items { + pub(crate) fn new(b: &Builder<'_, '_, A>) -> Self { + Self { + entries: Vec::new(), + groups: vec![None], + group: 0, + shell: b.shell(), + } + } + + /// TODO(prose): the items `body` adds, under the heading `heading`. + pub fn group(&mut self, heading: impl Into, body: impl FnOnce(&mut Self)) { + self.groups.push(Some(heading.into())); + let outer = std::mem::replace(&mut self.group, self.groups.len() - 1); + body(self); + self.group = outer; + } + + /// TODO(prose): an item labelled `label`, under its own key `key` in its group. + pub fn item(&mut self, key: K, label: impl Into) -> ItemChain<'_, A> { + let row = Row(child_id(Id::NULL.with(self.group), &key)); + self.entries.push(Entry { + row, + group: self.group, + label: label.into(), + keywords: Vec::new(), + shortcut: None, + state: CommandState::Plain, + enablement: Enablement::Enabled, + pick: None, + }); + let at = self.entries.len() - 1; + ItemChain { items: self, at } + } + + /// TODO(prose): each command of `table` under the heading `heading`: its title, its shortcut, whether it is enabled and its check or dot; a pick runs it. + pub fn commands(&mut self, heading: impl Into, table: &Commands, app: &A) { + let shell = self.shell.clone(); + self.group(heading, |items| { + for (at, command) in table.iter().enumerate() { + let command: Command = *command; + let shell = shell.clone(); + let shortcut = command.shortcut_text(shell.ctx()); + let mut item = items + .item(at, command.title()) + .state(command.state(app)) + .enablement(command.is_enabled(app).into()); + if let Some(shortcut) = shortcut { + item = item.shortcut(shortcut); + } + item.on_pick(move |app| command.run(app, &shell)); + } + }); + } +} + +/// TODO(prose): an item being added; its options. +pub struct ItemChain<'i, A> { + items: &'i mut Items, + at: usize, +} + +impl ItemChain<'_, A> { + fn entry(&mut self) -> Option<&mut Entry> { + self.items.entries.get_mut(self.at) + } + + /// TODO(prose): more words the item is found by, not shown: "remove" finds Delete. + pub fn keywords(mut self, words: impl IntoIterator>) -> Self { + if let Some(entry) = self.entry() { + entry.keywords = words.into_iter().map(Into::into).collect(); + } + self + } + + /// TODO(prose): the shortcut the row shows at its end, as a menu item does. + pub fn shortcut(mut self, text: impl Into) -> Self { + if let Some(entry) = self.entry() { + entry.shortcut = Some(text.into()); + } + self + } + + /// TODO(prose): a check or a dot before the label, as a command's menu item shows. + pub fn state(mut self, state: CommandState) -> Self { + if let Some(entry) = self.entry() { + entry.state = state; + } + self + } + + /// TODO(prose): a disabled item is shown greyed, and the arrows and picks pass it by. + pub fn enablement(mut self, enablement: Enablement) -> Self { + if let Some(entry) = self.entry() { + entry.enablement = enablement; + } + self + } + + /// TODO(prose): runs `then` when the item is picked: clicked, or Enter on its highlight. + pub fn on_pick(mut self, then: impl Fn(&mut A) + 'static) { + if let Some(entry) = self.entry() { + entry.pick = Some(Rc::new(then)); + } + } +} + +/// The query of a list: the widget's own state, kept from frame to frame. +pub(crate) struct Query; + +impl Query { + fn id(list: Id) -> Id { + list.with("eggshell-ui-extras-query") + } + + pub(crate) fn get(ctx: &Context, list: Id) -> String { + ctx.data(|data| data.get_temp::(Self::id(list))) + .unwrap_or_default() + } + + pub(crate) fn set(ctx: &Context, list: Id, query: String) { + ctx.data_mut(|data| data.insert_temp(Self::id(list), query)); + } + + pub(crate) fn clear(ctx: &Context, list: Id) { + ctx.data_mut(|data| data.remove::(Self::id(list))); + } +} + +/// Whether the first row is highlighted as the rows change. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum First { + Highlighted, + Left, +} + +/// How the list shows for its shape. +pub(crate) struct ListOptions { + pub(crate) first: First, + /// What runs after an item's own pick: closing what holds the list. + pub(crate) after: Option>, + /// The search field, or the app's own field, and what typing in it does. + pub(crate) field: Field, +} + +/// Where the query comes from. +pub(crate) enum Field { + /// The list's own search field. + Own, + /// A field of the caller's, `id`, whose text is `text`. + Theirs { id: Id, text: String }, +} + +impl ListOptions { + pub(crate) fn palette(after: Option>) -> Self { + Self { + first: First::Highlighted, + after, + field: Field::Own, + } + } +} + +#[derive(Clone, Copy, Debug, Hash)] +enum Part { + Wrapper, + Search, + Query, + Results, + Empty, + Loading, +} + +/// How well `entry` matches `query`, by `filter` or the library's own, or +/// as the app gave it when the app filters. +fn score( + entry: &Entry, + query: &str, + filter: Option<&Filter>, + filtering: Filtering, +) -> Option { + let candidate = filter::Candidate { + label: &entry.label, + keywords: &entry.keywords, + }; + match (filtering, filter) { + (Filtering::App(_), _) => Some(filter::Score::BEST), + (Filtering::Ours, Some(filter)) => filter(query, candidate), + (Filtering::Ours, None) => filter::word_prefix(query, candidate), + } +} + +impl Items { + /// Whether any item matches `query`. + pub(crate) fn any_match( + &self, + query: &str, + filter: Option<&Filter>, + filtering: Filtering, + ) -> bool { + self.entries + .iter() + .any(|entry| score(entry, query, filter, filtering).is_some()) + } +} + +/// The items that match `query`, ranked, as rows; the entries by their row. +pub(crate) struct Listing { + rows: Vec, + entries: HashMap>, + groups: Vec>, +} + +impl Listing { + /// The items of `items` that `query` matches, best first within each + /// group, the groups in the order given, empty groups left out. + fn filtered( + items: Items, + query: &str, + filter: Option<&Filter>, + filtering: Filtering, + ) -> Self { + let Items { + entries, groups, .. + } = items; + let mut by_group: Vec, Entry)>> = + groups.iter().map(|_| Vec::new()).collect(); + for entry in entries { + let scored = (score(&entry, query, filter, filtering), entry); + if let Some(group) = by_group.get_mut(scored.1.group) { + group.push(scored); + } + } + let mut rows = Vec::new(); + let mut kept = HashMap::new(); + for group in by_group { + for entry in filter::ranked(group) { + rows.push(entry.row); + kept.insert(entry.row, entry); + } + } + Self { + rows, + entries: kept, + groups, + } + } + + /// Whether `row` is the first of its group, which shows the heading. + fn heading(&self, at: usize) -> Option<&str> { + let row = self.rows.get(at)?; + let group = self.entries.get(row)?.group; + let first = at == 0 + || self + .rows + .get(at - 1) + .and_then(|before| self.entries.get(before)) + .is_some_and(|before| before.group != group); + first.then(|| self.groups.get(group)?.as_deref()).flatten() + } +} + +/// The classes of the box a combobox's or an autosuggest's list sits in. +pub(crate) fn popover_classes(style: &Style) -> Tw { + style + .menu + .box_classes(style.role(&style.menu.text)) + .p(0.0) + .overflow_hidden() +} + +/// The gap between a combobox's field and its list: shadcn's `sideOffset 6`. +pub(crate) fn list_offset() -> eggshell_ui::overlay::Distance { + eggshell_ui::overlay::Distance::new(6.0) +} + +/// The classes of a combobox's box, shadcn's input group: the select's box +/// with the ring while the field inside has focus. The field's own padding +/// is the box's left, and the end button sits close to its right. +pub(crate) fn group_classes(style: &Style) -> Tw { + let select = &style.select; + let metrics = select.sizes.get(eggshell_ui::contract::Size::DEFAULT); + let states = select.trigger.paint.states; + let classes = tw() + .flex() + .items_center() + .pl(metrics.padding_x / 4.0) + .pr(1.0) + .h_px(metrics.height) + .rounded_px(f32::from(metrics.radius)) + .border(select.trigger.border_width) + .border_color(states.rest.border) + .bg(states.rest.fill) + .text(states.rest.text) + .role(style.role(&select.text).clone()) + .focus_within(|p| { + p.border_color(states.focused.border) + .ring(style.focus.width, style.focus.color) + }); + match select.trigger.paint.shadow { + Some(shadow) => classes.shadow(shadow), + None => classes, + } +} + +/// The classes of the button at the end of a combobox's box, shadcn's ghost +/// `icon-xs`: the stepper's button. +pub(crate) fn end_button_classes(style: &Style) -> Tw { + let stepper = &style.stepper; + let metrics = stepper.sizes.get(eggshell_ui::contract::Size::DEFAULT); + let states = stepper.button.paint.states; + tw().flex() + .items_center() + .justify_center() + .size_px(metrics.button_width) + .shrink_0() + .rounded_px(f32::from(style.menu.item_radius)) + .bg(states.rest.fill) + .sense_click() + .focusable_none() + .hover(|p| p.bg(states.hover.fill)) +} + +/// The classes of the glyph in the end button: muted, `size-4`. +pub(crate) fn end_glyph_classes(style: &Style) -> Tw { + tw().size_px(style.select.chevron) + .shrink_0() + .text(style.input.icon) +} + +/// The classes of a command dialog's box. +pub(crate) fn dialog_classes(style: &Style) -> Tw { + let menu = &style.menu; + let rest = menu.popup.paint.states.rest; + let classes = tw() + .flex() + .flex_col() + .w_px(512.0) + .max_w_full() + .border(menu.popup.border_width) + .border_color(rest.border) + .bg(rest.fill) + .text(rest.text) + .rounded_px(f32::from(menu.radius) + 2.0) + .overflow_hidden(); + match menu.popup.paint.shadow { + Some(shadow) => classes.shadow(shadow), + None => classes, + } +} + +/// Adds the list with its field: the items of `items` that match the query, +/// in a virtual list the field's keys move through. +pub(crate) fn show<'f, A: 'static>( + b: &mut Builder<'_, 'f, A>, + key: Id, + items: Items, + options: Options<'f, A>, + shape: ListOptions, +) { + let style = Arc::clone(b.style()); + let ctx = b.ctx().clone(); + let command = super::CommandStyle::of(&ctx); + let (field, query) = match &shape.field { + Field::Own => (None, Query::get(&ctx, key)), + Field::Theirs { id, text } => (Some(*id), text.clone()), + }; + let Options { + placeholder, + name, + filter, + filtering, + on_query, + empty, + classes, + } = options; + let listing = Rc::new(Listing::filtered(items, &query, filter.as_ref(), filtering)); + b.div_id(key, tw().flex().flex_col().min_h_0().merge(classes), |s| { + let field = match field { + Some(field) => field, + None => search_field(s, &style, key, &query, placeholder, name.clone(), on_query), + }; + let rows = listing.rows.clone(); + if rows.is_empty() { + match filtering { + Filtering::App(Pending::Loading) => { + s.div_id(Part::Loading, note_classes(&style), |s| { + s.text(tw(), "Loading…") + }); + } + Filtering::App(Pending::Settled) | Filtering::Ours => { + s.div_id(Part::Empty, note_classes(&style), |s| match empty { + Some(empty) => empty(s), + None => s.text(tw(), "No results found."), + }); + } + } + return; + } + let text = style.role(&style.menu.text).clone(); + let row_height = style.menu.row_height(&text); + let height = list_height(&style, &command, &listing, row_height); + let mut list = s + .virtual_list( + Part::Results, + tw().h_px(height) + .p(style.menu.padding / 4.0) + .scroll_py(1.0) + .scrollbar_none(), + rows, + ) + .nav(ListNav::Listbox) + .keys_from(field) + .estimate_px(row_height); + if shape.first == First::Highlighted { + list = list.highlight_first(); + } + if let Some(name) = name { + list = list.named(name); + } + let (labels, enabled, picks) = ( + Rc::clone(&listing), + Rc::clone(&listing), + Rc::clone(&listing), + ); + let marks = Rc::clone(&listing); + let after = shape.after.clone(); + let rows_of = Rc::clone(&listing); + let style_of = Arc::clone(&style); + let command_of = Arc::clone(&command); + list.row_name(move |row| { + labels + .entries + .get(&row) + .map(|entry| entry.label.clone()) + .unwrap_or_default() + }) + .row_mark(move |row| { + marks.entries.get(&row).and_then(|entry| match entry.state { + CommandState::Plain => None, + CommandState::Checked(mark) | CommandState::Chosen(mark) => Some(mark), + }) + }) + .row_enablement(move |row| { + enabled + .entries + .get(&row) + .map_or(Enablement::Disabled, |entry| entry.enablement) + }) + .on_activate(move |app, row| { + let Some(entry) = picks.entries.get(&row) else { + return; + }; + if entry.enablement == Enablement::Disabled { + return; + } + if let Some(pick) = &entry.pick { + pick(app); + } + if let Some(after) = &after { + after(app); + } + }) + .items(move |s, row| { + let at = rows_of.rows.iter().position(|&r| r == row).unwrap_or(0); + if let Some(heading) = rows_of.heading(at) { + s.div(heading_classes(&style_of, at), |s| { + s.text(tw(), heading.to_owned()) + }); + } + if let Some(entry) = rows_of.entries.get(&row) { + item(s, &style_of, &command_of, entry); + } + }); + }); +} + +/// How tall the rows are, up to the style's limit: a scroll container is as +/// tall as it is told, so the list is told what its rows come to. +fn list_height( + style: &Style, + command: &super::CommandStyle, + listing: &Listing, + row_height: f32, +) -> f32 { + let heading = style + .role(&Some(style.menu.shortcut_text.clone())) + .line_height; + let headings: f32 = (0..listing.rows.len()) + .filter(|&at| listing.heading(at).is_some()) + .map(|at| heading + 12.0 + if at == 0 { 0.0 } else { 5.0 }) + .sum(); + let rows = listing.rows.len() as f32 * row_height; + (rows + headings + 2.0 * style.menu.padding).min(command.list_height) +} + +fn search_field( + s: &mut Scope<'_, '_, A>, + style: &Style, + list: Id, + query: &str, + placeholder: Option, + name: Option, + on_query: Option>, +) -> Id { + let menu = &style.menu; + let rest = menu.popup.paint.states.rest; + let tint = style + .input + .look + .paint + .states + .rest + .border + .gamma_multiply(0.3); + let wrapper = tw().p(1.0).pb(0.0); + let classes = tw() + .flex() + .items_center() + .gap(2.0) + .pl(2.0) + .pr(2.5) + .h_px(32.0) + .rounded_px(f32::from(menu.radius) + 2.0) + .border(1.0) + .border_color(tint) + .bg(tint); + let ctx = s.ctx().clone(); + let mut field = Id::NULL; + s.div_id(Part::Wrapper, wrapper, |s| { + s.div_id(Part::Search, classes, |s| { + field = s.id_of(Part::Query); + s.icon( + "icon", + tw().size_px(16.0) + .shrink_0() + .text(rest.text.gamma_multiply(0.5)), + Icon::new(icons::SEARCH), + ); + let mut chain = s + .text_field(Part::Query, query) + .bare() + .role(Role::ComboBox) + .classes(tw().grow().min_w_0()); + if let Some(placeholder) = placeholder { + chain = chain.hint(placeholder); + } + if let Some(name) = name { + chain = chain.named(name); + } + chain.on_change(move |app, query| { + if let Some(on_query) = &on_query { + on_query(app, &query); + } + Query::set(&ctx, list, query); + }); + }); + }); + field +} + +fn note_classes(style: &Style) -> Tw { + tw().py(6.0).text_center().text(style.menu.shortcut) +} + +fn heading_classes(style: &Style, at: usize) -> Tw { + let menu = &style.menu; + let classes = tw() + .px(menu.item_padding.x / 4.0) + .py(1.5) + .role(style.role(&Some(menu.shortcut_text.clone())).clone()) + .font_weight(menu.heading_weight) + .text(menu.shortcut); + if at == 0 { + classes + } else { + classes.mt(1.0).border_t(1.0).border_color(menu.separator) + } +} + +fn item( + s: &mut Scope<'_, '_, A>, + style: &Style, + command: &super::CommandStyle, + entry: &Entry, +) { + let menu = &style.menu; + let text = style.role(&menu.text); + let states = menu.item.paint.states; + let base = tw() + .flex() + .items_center() + .gap(menu.item_gap / 4.0) + .px(menu.item_padding.x / 4.0) + .h_px(menu.row_height(text)) + .rounded_px(f32::from(menu.item_radius)) + .whitespace_nowrap(); + let classes = match entry.enablement { + Enablement::Disabled => base.text(states.disabled.text), + Enablement::Enabled => { + let (fill, text) = (command.selected_fill, command.selected_text); + base.bg(states.rest.fill) + .text(states.rest.text) + .group_hover(|p| p.bg(fill).text(text)) + } + }; + let side = menu.indicator; + s.div(classes, |s| { + s.div(tw().grow().min_w_0(), |s| s.text(tw(), entry.label.clone())); + if let Some(shortcut) = &entry.shortcut { + s.text(tw().text(menu.shortcut).ml_auto(), shortcut.clone()); + } + if let CommandState::Checked(Mark::On) | CommandState::Chosen(Mark::On) = entry.state { + s.glyph(tw().size_px(side).shrink_0(), Icon::new(icons::CHECK)); + } + }); +} diff --git a/crates/eggshell-ui-extras/src/command/mod.rs b/crates/eggshell-ui-extras/src/command/mod.rs new file mode 100644 index 00000000..e3703684 --- /dev/null +++ b/crates/eggshell-ui-extras/src/command/mod.rs @@ -0,0 +1,696 @@ +//! TODO(prose): searchable lists: a command list (a search field over a filtered, virtual list of results, inline or as a Cmd/Ctrl+K dialog), a combobox and an autosuggest, sharing one list and one filter. + +mod filter; +mod list; +mod style; + +use std::rc::Rc; +use std::sync::Arc; + +use eggshell_ui::overlay::{Anchor, Focus, MatchWidth, Modal, Placement}; +use eggshell_ui::owned::Mark; +use eggshell_ui::prim::text_field::Select; +use eggshell_ui::{Builder, CommandState, Icon, Key, Scope, Tw, icons, tw}; +use egui::{Id, Role}; + +pub use filter::{Candidate, Score, word_prefix}; +pub use list::{ItemChain, Items}; +pub use style::CommandStyle; + +use list::{First, ListOptions, Query}; + +/// TODO(prose): who filters the items: the list, by its filter, or the app, which hears the query and gives back the items to show as they are. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Filtering { + /// TODO(prose): the list filters and ranks the items it is given. + #[default] + Ours, + /// TODO(prose): the app does, as it is `pending`. + App(Pending), +} + +/// TODO(prose): whether the app's results for the query are in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Pending { + /// TODO(prose): the items given are the results. + Settled, + /// TODO(prose): results are on their way: a loading row shows. + Loading, +} + +type Filter = Rc) -> Option>; +type Heard = Rc; +type Empty<'f, A> = Box) + 'f>; +type Typed = Rc; +type Cleared = Rc; + +/// TODO(prose): the builder methods of this module. +pub trait CommandExt<'b, 'f, A> { + /// TODO(prose): an inline command list: a search field over the results. + fn command_list(&mut self, key: K) -> CommandList<'_, 'b, 'f, A>; + + /// TODO(prose): a command list in a centred modal dialog, shown while `open`; a pick or a dismissal runs `on_close`. + fn command_dialog( + &mut self, + key: K, + open: Open, + on_close: impl Fn(&mut A) + 'static, + ) -> CommandList<'_, 'b, 'f, A>; + + /// TODO(prose): a combobox: a trigger showing `value`'s label that opens a searchable list of `options`; a pick runs `on_change`. + fn combobox( + &mut self, + key: K, + value: Option, + options: impl IntoIterator, + ) -> ComboboxChain<'_, 'b, 'f, A, V>; + + /// TODO(prose): a text field that suggests `suggestions` matching what is typed; the text is the value. + fn autosuggest( + &mut self, + key: K, + text: &str, + suggestions: impl IntoIterator, + ) -> AutosuggestChain<'_, 'b, 'f, A>; +} + +/// TODO(prose): whether a dialog is open. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Open { + /// TODO(prose): shown. + Yes, + /// TODO(prose): not shown. + No, +} + +impl From for Open { + fn from(open: bool) -> Self { + if open { Self::Yes } else { Self::No } + } +} + +#[derive(Clone, Copy, Debug, Hash)] +enum Part { + Dialog, + Box, + Group, + Chevron, + Clear, + Popover, + Field, + Suggestions, +} + +/// How a command list sits, and what a pick does to it. +enum Shape { + Inline, + Dialog { + open: Open, + close: Rc, + }, +} + +/// TODO(prose): a command list, started with [`CommandExt::command_list`] or [`CommandExt::command_dialog`] and finished with [`items`](Self::items). +#[must_use = "a command list is not added until you call `.items(..)`"] +pub struct CommandList<'s, 'b, 'f, A> { + b: &'s mut Builder<'b, 'f, A>, + key: Id, + shape: Shape, + options: Options<'f, A>, +} + +/// What a command list, a combobox and an autosuggest all take. +struct Options<'f, A> { + placeholder: Option, + name: Option, + filter: Option, + filtering: Filtering, + on_query: Option>, + empty: Option>, + classes: Tw, +} + +impl Default for Options<'_, A> { + fn default() -> Self { + Self { + placeholder: None, + name: None, + filter: None, + filtering: Filtering::Ours, + on_query: None, + empty: None, + classes: tw(), + } + } +} + +impl<'f, A: 'static> CommandList<'_, '_, 'f, A> { + /// TODO(prose): greyed text in the empty search field. + pub fn placeholder(mut self, text: impl Into) -> Self { + self.options.placeholder = Some(text.into()); + self + } + + /// TODO(prose): the accessible name of the list, and of the dialog. + pub fn named(mut self, name: impl Into) -> Self { + self.options.name = Some(name.into()); + self + } + + /// TODO(prose): ranks the items by `filter` instead of [`word_prefix`]; `None` leaves an item out. + pub fn filter( + mut self, + filter: impl Fn(&str, Candidate<'_>) -> Option + 'static, + ) -> Self { + self.options.filter = Some(Rc::new(filter)); + self + } + + /// TODO(prose): who filters: [`Filtering::App`] shows the items as given, for an app that fetches its own results; hear the query with [`on_query`](Self::on_query). + pub fn filtering(mut self, filtering: Filtering) -> Self { + self.options.filtering = filtering; + self + } + + /// TODO(prose): runs `then` with the query each time it is edited. + pub fn on_query(mut self, then: impl Fn(&mut A, &str) + 'static) -> Self { + self.options.on_query = Some(Rc::new(then)); + self + } + + /// TODO(prose): what shows when nothing matches. + pub fn empty(mut self, body: impl FnOnce(&mut Scope<'_, 'f, A>) + 'f) -> Self { + self.options.empty = Some(Box::new(body)); + self + } + + /// TODO(prose): classes of the list's box, such as its width. + pub fn classes(mut self, classes: Tw) -> Self { + self.options.classes = classes; + self + } + + /// TODO(prose): adds the list, whose items `items` gives, in groups. + pub fn items(self, items: impl FnOnce(&mut Items)) { + let Self { + b, + key, + shape, + options, + } = self; + let mut given = Items::new(b); + items(&mut given); + match shape { + Shape::Inline => list::show(b, key, given, options, ListOptions::palette(None)), + Shape::Dialog { open: Open::No, .. } => Query::clear(b.ctx(), key), + Shape::Dialog { + open: Open::Yes, + close, + } => { + let name = options.name.clone().unwrap_or_default(); + let dismiss = Rc::clone(&close); + b.overlay((key, Part::Dialog)) + .modal(Modal::Center) + .role(Role::Dialog) + .named(name) + .on_dismiss(move |app| dismiss(app)) + .children(|s| { + let classes = list::dialog_classes(s.style()); + s.div_id(Part::Box, classes, |s| { + list::show(s, key, given, options, ListOptions::palette(Some(close))); + }); + }); + } + } + } +} + +impl<'b, 'f, A: 'static> CommandExt<'b, 'f, A> for Builder<'b, 'f, A> { + fn command_list(&mut self, key: K) -> CommandList<'_, 'b, 'f, A> { + CommandList { + key: self.id_of(key), + b: self, + shape: Shape::Inline, + options: Options::default(), + } + } + + fn command_dialog( + &mut self, + key: K, + open: Open, + on_close: impl Fn(&mut A) + 'static, + ) -> CommandList<'_, 'b, 'f, A> { + CommandList { + key: self.id_of(key), + b: self, + shape: Shape::Dialog { + open, + close: Rc::new(on_close), + }, + options: Options::default(), + } + } + + fn combobox( + &mut self, + key: K, + value: Option, + options: impl IntoIterator, + ) -> ComboboxChain<'_, 'b, 'f, A, V> { + ComboboxChain { + key: self.id_of(key), + b: self, + value, + choices: options.into_iter().collect(), + clear: None, + options: Options::default(), + } + } + + fn autosuggest( + &mut self, + key: K, + text: &str, + suggestions: impl IntoIterator, + ) -> AutosuggestChain<'_, 'b, 'f, A> { + AutosuggestChain { + key: self.id_of(key), + b: self, + text: text.to_owned(), + suggestions: suggestions.into_iter().collect(), + options: Options::default(), + } + } +} + +/// A combobox's own state: whether its list is open, and what was typed since +/// it opened. Until something is typed the field shows the chosen label and +/// the list shows every option. +#[derive(Clone, Debug, Default, PartialEq)] +struct Typing { + open: bool, + query: Option, + /// The field takes the focus on the next frame: a press on a button beside + /// it asked for it. + focus: bool, +} + +impl Typing { + const CLOSED: Self = Self { + open: false, + query: None, + focus: false, + }; + + fn id(combobox: Id) -> Id { + combobox.with("eggshell-ui-extras-typing") + } + + fn load(ctx: &egui::Context, combobox: Id) -> Self { + ctx.data(|data| data.get_temp::(Self::id(combobox))) + .unwrap_or_default() + } + + fn store(self, ctx: &egui::Context, combobox: Id) { + ctx.data_mut(|data| data.insert_temp(Self::id(combobox), self)); + } + + fn opened() -> Self { + Self { + open: true, + query: None, + focus: false, + } + } + + fn focusing(self) -> Self { + Self { + focus: true, + ..self + } + } +} + +/// TODO(prose): a combobox, started with [`CommandExt::combobox`] and finished with [`on_change`](Self::on_change). +#[must_use = "a combobox is not added until you call `.on_change(..)`"] +pub struct ComboboxChain<'s, 'b, 'f, A, V> { + b: &'s mut Builder<'b, 'f, A>, + key: Id, + value: Option, + choices: Vec<(V, String)>, + options: Options<'f, A>, + clear: Option>, +} + +impl<'f, A: 'static, V: Key + Copy + PartialEq> ComboboxChain<'_, '_, 'f, A, V> { + /// TODO(prose): greyed text in the empty field. + pub fn placeholder(mut self, text: impl Into) -> Self { + self.options.placeholder = Some(text.into()); + self + } + + /// TODO(prose): the accessible name of the field and of the list. + pub fn named(mut self, name: impl Into) -> Self { + self.options.name = Some(name.into()); + self + } + + /// TODO(prose): ranks the options by `filter` instead of [`word_prefix`]. + pub fn filter( + mut self, + filter: impl Fn(&str, Candidate<'_>) -> Option + 'static, + ) -> Self { + self.options.filter = Some(Rc::new(filter)); + self + } + + /// TODO(prose): what shows when nothing matches. + pub fn empty(mut self, body: impl FnOnce(&mut Scope<'_, 'f, A>) + 'f) -> Self { + self.options.empty = Some(Box::new(body)); + self + } + + /// TODO(prose): classes of the field's box, such as its width. + pub fn classes(mut self, classes: Tw) -> Self { + self.options.classes = classes; + self + } + + /// TODO(prose): a clear button in place of the chevron while there is a + /// value; it runs `on_clear`. + pub fn on_clear(mut self, on_clear: impl Fn(&mut A) + 'static) -> Self { + self.clear = Some(Rc::new(on_clear)); + self + } + + /// TODO(prose): adds the combobox; `on_change` runs with the option picked. + pub fn on_change(self, on_change: impl Fn(&mut A, V) + 'static) { + let Self { + b, + key, + value, + choices, + mut options, + clear, + } = self; + let ctx = b.ctx().clone(); + let state = Typing::load(&ctx, key); + let chosen = value + .and_then(|value| choices.iter().find(|(v, _)| *v == value)) + .map(|(_, label)| label.clone()); + let text = state + .query + .clone() + .unwrap_or_else(|| chosen.clone().unwrap_or_default()); + let style = Arc::clone(b.style()); + let group_id = b.id_of((key, Part::Group)); + let mut field_id = Id::NULL; + let group_classes = + list::group_classes(&style).merge(std::mem::replace(&mut options.classes, tw())); + let (placeholder, name) = (options.placeholder.clone(), options.name.clone()); + let open = state.open; + let clearing = clear.filter(|_| value.is_some()); + b.div_id((key, Part::Group), group_classes, |s| { + field_id = s.id_of((key, Part::Field)); + let mut field = s + .text_field((key, Part::Field), text.clone()) + .bare() + .role(Role::ComboBox) + .classes(tw().grow().min_w_0()); + if let Some(placeholder) = placeholder { + field = field.hint(placeholder); + } + if let Some(name) = name { + field = field.named(name); + } + if state.focus { + Typing { + focus: false, + ..state.clone() + } + .store(&ctx, key); + field = field.focus_now(Select::None); + } + let (handled, shown) = (ctx.clone(), text.clone()); + field = field.on_response(move |_, response| { + let (escape, down, tab) = response.ctx.input(|input| { + ( + input.key_pressed(egui::Key::Escape), + input.key_pressed(egui::Key::ArrowDown), + input.key_pressed(egui::Key::Tab), + ) + }); + let focused = response.has_focus(); + let tabbed_away = tab && response.lost_focus(); + if (escape && (focused || response.lost_focus())) || tabbed_away { + Typing::CLOSED.store(&handled, key); + } else if (down && focused && !open) || response.clicked() { + Typing::opened().store(&handled, key); + } + response.ctx.accesskit_node_builder(response.id, |node| { + node.set_has_popup(egui::accesskit::HasPopup::Listbox); + node.set_expanded(open); + node.set_value(shown.as_str()); + }); + }); + let typed = ctx.clone(); + field.on_change(move |_, text| { + Typing { + open: true, + query: Some(text), + focus: false, + } + .store(&typed, key); + }); + let toggled = ctx.clone(); + match clearing { + Some(clear) => { + let cleared = ctx.clone(); + s.div_id((key, Part::Clear), list::end_button_classes(&style), |s| { + s.glyph(list::end_glyph_classes(&style), Icon::new(icons::CLOSE)); + }) + .role(Role::Button) + .named("Clear") + .on_click(move |app| { + clear(app); + Typing::CLOSED.focusing().store(&cleared, key); + }); + } + None => { + s.div_id( + (key, Part::Chevron), + list::end_button_classes(&style), + |s| { + s.glyph( + list::end_glyph_classes(&style), + Icon::new(icons::CHEVRON_DOWN), + ); + }, + ) + .role(Role::Button) + .named("Show options") + .on_click(move |_| { + let next = if open { + Typing::CLOSED + } else { + Typing::opened() + }; + next.focusing().store(&toggled, key); + }); + } + } + }); + if !open { + return; + } + let on_change = Rc::new(on_change); + let mut items = Items::new(b); + for (choice, label) in choices { + let on_change = Rc::clone(&on_change); + let mark = Mark::from(Some(choice) == value); + items + .item(choice, label) + .state(CommandState::Checked(mark)) + .on_pick(move |app| on_change(app, choice)); + } + let (close, dismiss) = (ctx.clone(), ctx.clone()); + let after: Rc = Rc::new(move |_| Typing::CLOSED.store(&close, key)); + b.overlay((key, Part::Popover)) + .anchor(Anchor::Node(group_id)) + .placement(Placement::below().gap(list::list_offset())) + .match_width(MatchWidth::Anchor) + .focus(Focus::Stay) + .on_dismiss(move |_| Typing::CLOSED.store(&dismiss, key)) + .children(|s| { + s.div_id(Part::Box, list::popover_classes(&style), |s| { + list::show( + s, + key, + items, + options, + ListOptions { + first: First::Highlighted, + after: Some(after), + field: list::Field::Theirs { + id: field_id, + text: state.query.unwrap_or_default(), + }, + }, + ); + }); + }); + } +} + +/// TODO(prose): an autosuggest, started with [`CommandExt::autosuggest`] and finished with [`on_change`](Self::on_change). +#[must_use = "an autosuggest is not added until you call `.on_change(..)`"] +pub struct AutosuggestChain<'s, 'b, 'f, A> { + b: &'s mut Builder<'b, 'f, A>, + key: Id, + text: String, + suggestions: Vec, + options: Options<'f, A>, +} + +/// Whether Escape or a pick put an autosuggest's suggestions away until the +/// next edit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Suggesting { + #[default] + Yes, + Dismissed, +} + +impl Suggesting { + fn id(field: Id) -> Id { + field.with("eggshell-ui-extras-suggesting") + } + + fn load(ctx: &egui::Context, field: Id) -> Self { + ctx.data(|data| data.get_temp::(Self::id(field))) + .unwrap_or_default() + } + + fn store(self, ctx: &egui::Context, field: Id) { + ctx.data_mut(|data| data.insert_temp(Self::id(field), self)); + } +} + +impl<'f, A: 'static> AutosuggestChain<'_, '_, 'f, A> { + /// TODO(prose): greyed text in the empty field. + pub fn placeholder(mut self, text: impl Into) -> Self { + self.options.placeholder = Some(text.into()); + self + } + + /// TODO(prose): the accessible name of the field and of the suggestions. + pub fn named(mut self, name: impl Into) -> Self { + self.options.name = Some(name.into()); + self + } + + /// TODO(prose): ranks the suggestions by `filter` instead of [`word_prefix`]. + pub fn filter( + mut self, + filter: impl Fn(&str, Candidate<'_>) -> Option + 'static, + ) -> Self { + self.options.filter = Some(Rc::new(filter)); + self + } + + /// TODO(prose): who filters; see [`CommandList::filtering`]. + pub fn filtering(mut self, filtering: Filtering) -> Self { + self.options.filtering = filtering; + self + } + + /// TODO(prose): classes of the field, such as its width. + pub fn classes(mut self, classes: Tw) -> Self { + self.options.classes = classes; + self + } + + /// TODO(prose): adds the field; `on_change` runs with the text as typed, or with a suggestion picked. + pub fn on_change(self, on_change: impl Fn(&mut A, String) + 'static) { + let Self { + b, + key, + text, + suggestions, + mut options, + } = self; + let ctx = b.ctx().clone(); + let on_change: Typed = Rc::new(on_change); + let classes = std::mem::replace(&mut options.classes, tw()); + let field_id = b.id_of((key, Part::Field)); + let mut field = b + .text_field((key, Part::Field), text.clone()) + .role(Role::ComboBox) + .classes(classes); + if let Some(placeholder) = options.placeholder.take() { + field = field.hint(placeholder); + } + if let Some(name) = options.name.clone() { + field = field.named(name); + } + let escaped = ctx.clone(); + field = field.on_response(move |_, response| { + let escape = response + .ctx + .input(|input| input.key_pressed(egui::Key::Escape)); + if escape && (response.has_focus() || response.lost_focus()) { + Suggesting::Dismissed.store(&escaped, field_id); + } + }); + let (typed, reset) = (Rc::clone(&on_change), ctx.clone()); + field.on_change(move |app, text| { + Suggesting::Yes.store(&reset, field_id); + typed(app, text); + }); + let suggesting = Suggesting::load(&ctx, field_id); + let focused = b.has_focus_within((key, Part::Field)); + if !focused || suggesting == Suggesting::Dismissed || text.trim().is_empty() { + return; + } + let mut items = Items::new(b); + for suggestion in suggestions { + let picked = Rc::clone(&on_change); + let label = suggestion.clone(); + items + .item(suggestion.clone(), suggestion) + .on_pick(move |app| picked(app, label.clone())); + } + if !items.any_match(&text, options.filter.as_ref(), options.filtering) + && options.filtering == Filtering::Ours + { + return; + } + let (close, dismiss) = (ctx.clone(), ctx.clone()); + let after: Rc = + Rc::new(move |_| Suggesting::Dismissed.store(&close, field_id)); + let style = Arc::clone(b.style()); + options.empty = Some(Box::new(|_| {})); + b.overlay((key, Part::Suggestions)) + .anchor(Anchor::Node(field_id)) + .placement(Placement::below().gap(style.menu.offset)) + .match_width(MatchWidth::Anchor) + .focus(Focus::Stay) + .on_dismiss(move |_| Suggesting::Dismissed.store(&dismiss, field_id)) + .children(|s| { + s.div_id(Part::Box, list::popover_classes(&style), |s| { + list::show( + s, + key, + items, + options, + list::ListOptions { + first: First::Left, + after: Some(after), + field: list::Field::Theirs { id: field_id, text }, + }, + ); + }); + }); + } +} diff --git a/crates/eggshell-ui-extras/src/command/style.rs b/crates/eggshell-ui-extras/src/command/style.rs new file mode 100644 index 00000000..da7b23e2 --- /dev/null +++ b/crates/eggshell-ui-extras/src/command/style.rs @@ -0,0 +1,45 @@ +//! How a command list, a combobox's list and an autosuggest's look beyond the +//! menu they are built from. + +use std::sync::Arc; + +use eggshell_ui::Style; +use egui::{Color32, Context, Theme}; + +/// TODO(prose): the look of the rows and the box of a command list, and of +/// the lists of a combobox and an autosuggest. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct CommandStyle { + /// TODO(prose): the fill of the highlighted row, which the pointer and + /// the arrow keys move. + pub selected_fill: Color32, + /// TODO(prose): the text of the highlighted row. + pub selected_text: Color32, + /// TODO(prose): how tall the list of rows grows before it scrolls. + pub list_height: f32, +} + +impl CommandStyle { + /// TODO(prose): the menu item's highlight, and a list `max-h-72` tall. + pub fn from_style(style: &Style) -> Self { + let hover = style.menu.item.paint.states.hover; + Self { + selected_fill: hover.fill, + selected_text: hover.text, + list_height: 288.0, + } + } + + /// TODO(prose): the command style installed for the context's theme, else + /// [`from_style`](Self::from_style) of its [`Style`]. + pub fn of(ctx: &Context) -> Arc { + crate::styles::of(ctx, Self::from_style) + } + + /// TODO(prose): makes `self` the command style of `ctx` while its theme + /// is `theme`. + pub fn install_for(self, ctx: &Context, theme: Theme) { + crate::styles::install_for(self, ctx, theme); + } +} diff --git a/crates/eggshell-ui-extras/src/lib.rs b/crates/eggshell-ui-extras/src/lib.rs index a66fd8bf..b4d24d37 100644 --- a/crates/eggshell-ui-extras/src/lib.rs +++ b/crates/eggshell-ui-extras/src/lib.rs @@ -22,6 +22,8 @@ #[cfg(feature = "badge")] pub mod badge; +#[cfg(feature = "command")] +pub mod command; #[cfg(feature = "form")] pub mod form; #[cfg(feature = "hover-card")] @@ -34,6 +36,7 @@ pub mod skeleton; pub mod spinner; #[cfg(any( feature = "badge", + feature = "command", feature = "form", feature = "markdown", feature = "skeleton", diff --git a/crates/eggshell-ui-shadcn/Cargo.toml b/crates/eggshell-ui-shadcn/Cargo.toml index 26b7ca7c..aebec4c2 100644 --- a/crates/eggshell-ui-shadcn/Cargo.toml +++ b/crates/eggshell-ui-shadcn/Cargo.toml @@ -15,6 +15,7 @@ fonts = [] extras = [ "dep:eggshell-ui-extras", "eggshell-ui-extras/badge", + "eggshell-ui-extras/command", "eggshell-ui-extras/form", "eggshell-ui-extras/hover-card", "eggshell-ui-extras/markdown", diff --git a/crates/eggshell-ui-shadcn/src/preset.rs b/crates/eggshell-ui-shadcn/src/preset.rs index 3e830902..05b4236c 100644 --- a/crates/eggshell-ui-shadcn/src/preset.rs +++ b/crates/eggshell-ui-shadcn/src/preset.rs @@ -854,6 +854,7 @@ impl Shadcn { self.badge(&style).install_for(ctx, self.theme); self.form(&style).install_for(ctx, self.theme); self.hover_card().install_for(ctx, self.theme); + self.command(&style).install_for(ctx, self.theme); self.skeleton(&style).install_for(ctx, self.theme); } style.install_for(ctx, self.theme); @@ -976,6 +977,17 @@ impl Shadcn { badge } + /// TODO(prose): the look of a command list's rows: shadcn's + /// `CommandItem`, `data-selected:bg-muted data-selected:text-foreground`, + /// and its list `max-h-72`. + #[cfg(feature = "extras")] + pub fn command(&self, style: &contract::Style) -> eggshell_ui_extras::command::CommandStyle { + let mut command = eggshell_ui_extras::command::CommandStyle::from_style(style); + command.selected_fill = self.tokens.muted; + command.selected_text = self.tokens.foreground; + command + } + /// TODO(prose): the form section and labelled row look. shadcn has no /// grouped-form box, so the section is `FieldSet`'s semantics in `Card`'s /// frame, with the looks the user chose on #370. From `ref/shadcn` diff --git a/examples/command_palette.rs b/examples/command_palette.rs new file mode 100644 index 00000000..460a084b --- /dev/null +++ b/examples/command_palette.rs @@ -0,0 +1,165 @@ +//! The command palette, a combobox and an autosuggest (#345): Ctrl+K (Cmd+K +//! on macOS) opens a palette over the app's command table and a page list; +//! the combobox (an input group: type in it, or press its chevron) picks a framework, the autosuggest a city as typed. + +#[path = "common/mod.rs"] +mod common; + +use eggshell_ui::owned::Mark; +use eggshell_ui::{Builder, Chord, Command, Commands, tw}; +use eggshell_ui_extras::command::{CommandExt, Open}; +use egui::{Key, Modifiers}; + +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +enum Part { + Page, + Palette, + Opener, + Framework, + City, + Said, + Action(Action), +} + +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +enum Action { + Search, + NewFile, + Save, + Grid, + Delete, +} + +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +pub enum Framework { + Next, + SvelteKit, + Nuxt, + Remix, + Astro, +} + +pub const FRAMEWORKS: [(Framework, &str); 5] = [ + (Framework::Next, "Next.js"), + (Framework::SvelteKit, "SvelteKit"), + (Framework::Nuxt, "Nuxt.js"), + (Framework::Remix, "Remix"), + (Framework::Astro, "Astro"), +]; + +const CITIES: [&str; 8] = [ + "Amsterdam", + "Athens", + "Berlin", + "Bern", + "Lisbon", + "London", + "Paris", + "Zürich", +]; + +const PAGES: [(&str, &[&str]); 6] = [ + ("Getting started", &["install", "intro"]), + ("Layout", &["flex", "grid"]), + ("Overlays", &["popover", "menu", "dialog"]), + ("Commands", &["shortcut", "keyboard"]), + ("Virtual lists", &["scroll", "long"]), + ("Theming", &["shadcn", "colours"]), +]; + +#[derive(Default)] +pub struct State { + pub palette: bool, + pub grid: bool, + pub framework: Option, + pub city: String, + pub said: String, +} + +fn search() -> Chord { + const { Chord::new(Modifiers::COMMAND, Key::K).expect("not reserved") } +} + +fn commands() -> Commands { + Commands::new() + .add( + Part::Action(Action::Search), + Command::new("Search…", |state: &mut State| state.palette = true).shortcut(search()), + ) + .add( + Part::Action(Action::NewFile), + Command::new("New file", |state: &mut State| { + state.said = "New file".into() + }), + ) + .add( + Part::Action(Action::Save), + Command::new("Save", |state: &mut State| state.said = "Saved".into()) + .shortcut(const { Chord::new(Modifiers::COMMAND, Key::S).expect("not reserved") }), + ) + .add( + Part::Action(Action::Grid), + Command::new("Show grid", |state: &mut State| state.grid = !state.grid) + .checked(|state| Mark::from(state.grid)), + ) + .add( + Part::Action(Action::Delete), + Command::new("Delete", |_| {}).enabled(|_| false), + ) +} + +pub fn layout<'f>(b: &mut Builder<'_, 'f, State>, state: &'f State) { + let table = commands(); + b.commands(&table, state); + b.div_id( + Part::Page, + tw().flex().flex_col().gap(4.0).p(6.0).w_px(360.0), + |s| { + s.button(Part::Opener, "Search… (Ctrl+K)") + .on_click(|state: &mut State| state.palette = true); + s.combobox( + Part::Framework, + state.framework, + FRAMEWORKS.map(|(value, label)| (value, label.to_owned())), + ) + .placeholder("Select framework…") + .named("Framework") + .classes(tw().w_px(200.0)) + .on_clear(|state: &mut State| state.framework = None) + .on_change(|state: &mut State, value| state.framework = Some(value)); + s.autosuggest(Part::City, &state.city, CITIES.map(str::to_owned)) + .placeholder("City") + .named("City") + .classes(tw().w_px(200.0)) + .on_change(|state: &mut State, city| state.city = city); + s.div_id(Part::Said, tw(), |s| { + s.text(tw(), format!("Last: {}", state.said)); + }); + }, + ); + b.command_dialog( + Part::Palette, + Open::from(state.palette), + |state: &mut State| { + state.palette = false; + }, + ) + .placeholder("Type a command or search…") + .named("Command palette") + .items(|items| { + items.group("Pages", |items| { + for (title, tags) in PAGES { + items + .item(title, title) + .keywords(tags.iter().copied()) + .on_pick(move |state: &mut State| state.said = format!("Opened {title}")); + } + }); + items.commands("Actions", &table, state); + }); +} + +#[allow(dead_code, reason = "the tests include this file for `layout`")] +fn main() -> eframe::Result { + common::run_app("command_palette", State::default(), layout) +} diff --git a/tests/it/command_palette.rs b/tests/it/command_palette.rs new file mode 100644 index 00000000..aff97c63 --- /dev/null +++ b/tests/it/command_palette.rs @@ -0,0 +1,491 @@ +//! The extras `command` feature through the real path: the example's +//! palette, combobox and autosuggest, driven by kittest's keys and pointer, +//! read back through the accessibility tree. + +#[path = "../../examples/command_palette.rs"] +#[allow(dead_code)] +mod example; + +use eggshell_ui::{TextSpec, TextStyle, Weight}; +use egui::accesskit::{Role, Toggled}; +use egui::{Color32, FontFamily, Key, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; + +use crate::support::{self, Rig}; +use example::State; + +fn base_text() -> TextStyle { + TextStyle::new( + TextSpec { + size: 14.0, + line_height: 20.0, + family: FontFamily::Proportional, + weight: Weight::Normal, + }, + Color32::BLACK, + ) +} + +fn harness() -> Harness<'static, Rig> { + let mut harness = support::harness( + vec2(800.0, 700.0), + base_text(), + State::default(), + example::layout, + ); + harness.run_steps(4); + harness +} + +fn step(harness: &mut Harness<'_, Rig>) { + harness.run_steps(6); +} + +fn press(harness: &mut Harness<'_, Rig>, key: Key) { + harness.key_press(key); + step(harness); +} + +fn open_palette(harness: &mut Harness<'_, Rig>) { + harness.key_press_modifiers(Modifiers::COMMAND, Key::K); + harness.run_steps(20); + assert!( + harness.state().app.palette, + "precondition: Ctrl+K opened it" + ); + assert!( + harness + .query_by_role_and_label(Role::Dialog, "Command palette") + .is_some(), + "precondition: the palette is showing" + ); +} + +/// The label of the item the field of the combobox named `name` announces +/// as its active descendant. +fn active(harness: &Harness<'_, Rig>, name: &str) -> Option { + harness + .get_by_role_and_label(Role::ComboBox, name) + .accesskit_node() + .active_descendant() + .and_then(|node| node.label()) +} + +fn options(harness: &Harness<'_, Rig>) -> Vec { + harness + .query_all_by_role(Role::ListBoxOption) + .filter_map(|node| node.accesskit_node().label()) + .collect() +} + +#[test] +fn ctrl_k_opens_the_palette_with_its_field_focused_and_the_first_item_highlighted() { + let mut harness = harness(); + open_palette(&mut harness); + assert_eq!( + support::focused_path(&harness).as_deref(), + Some(""), + "the search field's text edit has the focus" + ); + assert_eq!( + active(&harness, "Command palette").as_deref(), + Some("Getting started") + ); +} + +#[test] +fn typing_filters_by_word_prefix_and_keywords() { + let mut harness = harness(); + open_palette(&mut harness); + harness + .get_by_role_and_label(Role::ComboBox, "Command palette") + .type_text("lay"); + step(&mut harness); + assert_eq!(options(&harness), ["Layout"]); + harness + .get_by_role_and_label(Role::ComboBox, "Command palette") + .type_text("x"); + step(&mut harness); + harness.key_press(Key::Backspace); + harness.key_press(Key::Backspace); + harness.key_press(Key::Backspace); + harness.key_press(Key::Backspace); + step(&mut harness); + harness + .get_by_role_and_label(Role::ComboBox, "Command palette") + .type_text("dialog"); + step(&mut harness); + assert_eq!(options(&harness), ["Overlays"], "a keyword finds its item"); +} + +#[test] +fn nothing_matching_shows_the_empty_state() { + let mut harness = harness(); + open_palette(&mut harness); + harness + .get_by_role_and_label(Role::ComboBox, "Command palette") + .type_text("zzz"); + step(&mut harness); + assert!(options(&harness).is_empty()); + assert!(harness.query_by_label("No results found.").is_some()); +} + +#[test] +fn enter_picks_the_highlighted_item_and_closes_the_palette() { + let mut harness = harness(); + open_palette(&mut harness); + press(&mut harness, Key::ArrowDown); + assert_eq!( + active(&harness, "Command palette").as_deref(), + Some("Layout") + ); + press(&mut harness, Key::Enter); + harness.run_steps(20); + assert_eq!(harness.state().app.said, "Opened Layout"); + assert!(!harness.state().app.palette, "a pick closes the palette"); +} + +#[test] +fn a_picked_command_runs() { + let mut harness = harness(); + open_palette(&mut harness); + harness + .get_by_role_and_label(Role::ComboBox, "Command palette") + .type_text("show"); + step(&mut harness); + assert_eq!( + active(&harness, "Command palette").as_deref(), + Some("Show grid") + ); + press(&mut harness, Key::Enter); + assert!(harness.state().app.grid); + assert!(!harness.state().app.palette); +} + +#[test] +fn a_checked_command_says_so_and_a_disabled_one_is_passed_by() { + let mut harness = harness(); + harness.state_mut().app.grid = true; + open_palette(&mut harness); + let grid = harness.get_by_role_and_label(Role::ListBoxOption, "Show grid"); + assert_eq!(grid.accesskit_node().toggled(), Some(Toggled::True)); + let delete = harness.get_by_role_and_label(Role::ListBoxOption, "Delete"); + assert!(delete.accesskit_node().is_disabled()); + harness + .get_by_role_and_label(Role::ComboBox, "Command palette") + .type_text("show"); + step(&mut harness); + assert_eq!( + active(&harness, "Command palette").as_deref(), + Some("Show grid") + ); + harness.key_press(Key::Escape); + harness.run_steps(20); + assert!(!harness.state().app.palette, "Escape closes the palette"); +} + +fn combobox<'a>(harness: &'a Harness<'_, Rig>) -> egui_kittest::Node<'a> { + harness.get_by_role_and_label(Role::ComboBox, "Framework") +} + +#[test] +fn the_combobox_is_a_field_that_opens_on_a_click_filters_as_typed_and_picks() { + let mut harness = harness(); + combobox(&harness).click(); + harness.run_steps(20); + assert_eq!( + support::focused_path(&harness).as_deref(), + Some(""), + "the field itself has the focus" + ); + assert_eq!( + options(&harness).len(), + example::FRAMEWORKS.len(), + "every option shows before anything is typed" + ); + combobox(&harness).type_text("sv"); + step(&mut harness); + assert_eq!(options(&harness), ["SvelteKit"]); + assert_eq!( + active(&harness, "Framework").as_deref(), + Some("SvelteKit"), + "the first match is highlighted" + ); + press(&mut harness, Key::Enter); + harness.run_steps(20); + assert_eq!( + harness.state().app.framework, + Some(example_framework("SvelteKit")) + ); + assert!(options(&harness).is_empty(), "a pick closes the list"); + assert_eq!( + combobox(&harness).accesskit_node().value().as_deref(), + Some("SvelteKit"), + "the field shows the chosen label" + ); +} + +#[test] +fn the_chevron_opens_the_list_and_gives_the_field_the_focus() { + let mut harness = harness(); + harness + .get_by_role_and_label(Role::Button, "Show options") + .click(); + harness.run_steps(20); + assert_eq!(options(&harness).len(), example::FRAMEWORKS.len()); + assert_eq!(support::focused_path(&harness).as_deref(), Some("")); +} + +#[test] +fn escape_closes_the_list_and_puts_back_the_chosen_label() { + let mut harness = harness(); + harness.state_mut().app.framework = Some(example_framework("SvelteKit")); + harness.run_steps(4); + combobox(&harness).click(); + harness.run_steps(20); + combobox(&harness).type_text("x"); + step(&mut harness); + harness.key_press(Key::Escape); + harness.run_steps(20); + assert!(options(&harness).is_empty(), "Escape closes the list"); + assert_eq!( + combobox(&harness).accesskit_node().value().as_deref(), + Some("SvelteKit"), + "what was typed is dropped" + ); +} + +#[test] +fn the_down_arrow_opens_a_closed_list() { + let mut harness = harness(); + combobox(&harness).focus(); + step(&mut harness); + assert!(options(&harness).is_empty(), "precondition: closed"); + press(&mut harness, Key::ArrowDown); + harness.run_steps(10); + assert_eq!(options(&harness).len(), example::FRAMEWORKS.len()); +} + +#[test] +fn a_chosen_value_can_be_cleared_with_the_clear_button() { + let mut harness = harness(); + harness.state_mut().app.framework = Some(example_framework("SvelteKit")); + harness.run_steps(4); + assert!( + harness + .query_by_role_and_label(Role::Button, "Show options") + .is_none(), + "the clear button takes the chevron's place" + ); + harness.get_by_role_and_label(Role::Button, "Clear").click(); + harness.run_steps(20); + assert_eq!(harness.state().app.framework, None); + assert!( + harness + .query_by_role_and_label(Role::Button, "Show options") + .is_some(), + "the chevron is back" + ); +} + +fn example_framework(label: &str) -> example::Framework { + example::FRAMEWORKS + .iter() + .find(|(_, name)| *name == label) + .map(|(value, _)| *value) + .expect("a framework of that name") +} + +#[test] +fn the_autosuggest_suggests_without_a_highlight_and_takes_a_pick() { + let mut harness = harness(); + harness + .get_by_role_and_label(Role::ComboBox, "City") + .click(); + step(&mut harness); + harness + .get_by_role_and_label(Role::ComboBox, "City") + .type_text("b"); + step(&mut harness); + assert_eq!(options(&harness), ["Berlin", "Bern"]); + assert_eq!(active(&harness, "City"), None, "nothing is highlighted"); + press(&mut harness, Key::ArrowDown); + press(&mut harness, Key::ArrowDown); + assert_eq!(active(&harness, "City").as_deref(), Some("Bern")); + press(&mut harness, Key::Enter); + assert_eq!(harness.state().app.city, "Bern"); + assert!( + options(&harness).is_empty(), + "a pick puts the suggestions away" + ); +} + +#[test] +fn the_autosuggest_shows_nothing_when_nothing_matches() { + let mut harness = harness(); + harness + .get_by_role_and_label(Role::ComboBox, "City") + .click(); + step(&mut harness); + harness + .get_by_role_and_label(Role::ComboBox, "City") + .type_text("q"); + step(&mut harness); + assert_eq!(harness.state().app.city, "q", "precondition: it typed"); + assert!(options(&harness).is_empty()); + assert!(harness.query_by_label("No results found.").is_none()); +} + +#[test] +fn escape_puts_the_suggestions_away_until_the_next_edit() { + let mut harness = harness(); + harness + .get_by_role_and_label(Role::ComboBox, "City") + .click(); + step(&mut harness); + harness + .get_by_role_and_label(Role::ComboBox, "City") + .type_text("b"); + step(&mut harness); + assert!(!options(&harness).is_empty(), "precondition: suggesting"); + harness.key_press(Key::Escape); + harness.run_steps(20); + assert!( + options(&harness).is_empty(), + "focus after Escape: {:?}", + support::focused_path(&harness) + ); + harness + .get_by_role_and_label(Role::ComboBox, "City") + .click(); + step(&mut harness); + harness + .get_by_role_and_label(Role::ComboBox, "City") + .type_text("e"); + step(&mut harness); + assert_eq!(options(&harness), ["Berlin", "Bern"]); +} + +fn results_height(harness: &Harness<'_, Rig>) -> f32 { + harness + .state() + .nodes + .iter() + .find(|(path, _)| path.ends_with("/Results")) + .map_or(0.0, |(_, rect)| rect.height()) +} + +#[test] +fn the_list_is_as_tall_as_its_rows_up_to_the_style_limit() { + let mut harness = harness(); + combobox(&harness).click(); + harness.run_steps(20); + let few = results_height(&harness); + let rows = example::FRAMEWORKS.len() as f32; + assert!( + (few - (rows * 32.0 + 8.0)).abs() < 1.0, + "{rows} rows of 32 and the list's padding: {few}" + ); + combobox(&harness).type_text("sv"); + step(&mut harness); + assert!( + results_height(&harness) < few, + "a narrower query shortens the list" + ); + harness.key_press(Key::Escape); + harness.run_steps(10); + open_palette(&mut harness); + let height = results_height(&harness); + assert!( + (height - 288.0).abs() < 1.0, + "a long list stops at max-h-72: {height}" + ); +} + +#[test] +fn tabbing_away_from_the_field_closes_the_list() { + let mut harness = harness(); + combobox(&harness).click(); + harness.run_steps(20); + assert!( + !options(&harness).is_empty(), + "precondition: the list is open" + ); + press(&mut harness, Key::Tab); + harness.run_steps(10); + assert!(options(&harness).is_empty(), "Tab closes the list"); + assert!( + !combobox(&harness).accesskit_node().is_focused(), + "precondition: the focus left the field" + ); +} + +#[test] +fn the_lists_have_no_scrollbar_so_their_rows_are_as_wide_as_the_box() { + let mut harness = harness(); + open_palette(&mut harness); + let results = harness + .state() + .nodes + .iter() + .find(|(path, _)| path.ends_with("/Results")) + .map(|(_, rect)| *rect) + .expect("the palette's list"); + let rows = harness + .state() + .nodes + .iter() + .find(|(path, _)| path.ends_with("/Results/")) + .map(|(_, rect)| *rect) + .expect("the rows"); + let padding = 8.0; + assert!( + (rows.width() - (results.width() - padding)).abs() < 1.0, + "the rows span the list less its padding, with no gutter: {} of {}", + rows.width(), + results.width() + ); +} + +#[test] +fn the_highlight_keeps_four_points_from_the_lists_edges_as_the_arrows_scroll_it() { + let mut harness = harness(); + open_palette(&mut harness); + let results = |harness: &Harness<'_, Rig>| { + harness + .state() + .nodes + .iter() + .find(|(path, _)| path.ends_with("/Results")) + .map(|(_, rect)| *rect) + .expect("the palette's list") + }; + let highlighted = |harness: &Harness<'_, Rig>| { + let label = active(harness, "Command palette").expect("a highlight"); + harness + .get_by_role_and_label(Role::ListBoxOption, &label) + .rect() + }; + let rows = options(&harness).len(); + let mut nearest_below = f32::MAX; + let mut nearest_above = f32::MAX; + for _ in 0..rows + 3 { + press(&mut harness, Key::ArrowDown); + let (list, row) = (results(&harness), highlighted(&harness)); + nearest_below = nearest_below.min(list.max.y - row.max.y); + } + for _ in 0..rows + 3 { + press(&mut harness, Key::ArrowUp); + let (list, row) = (results(&harness), highlighted(&harness)); + nearest_above = nearest_above.min(row.min.y - list.min.y); + } + assert!( + nearest_below >= 3.5, + "going down, no highlighted row comes nearer the bottom than 4 pt: {nearest_below}" + ); + assert!( + nearest_above >= 3.5, + "going up, no highlighted row comes nearer the top than 4 pt: {nearest_above}" + ); +} diff --git a/tests/it/main.rs b/tests/it/main.rs index 7978240b..6beb138d 100644 --- a/tests/it/main.rs +++ b/tests/it/main.rs @@ -28,6 +28,7 @@ mod clipboard; mod clipboard_example; mod collapsible; mod combobox_parts; +mod command_palette; mod commands; mod compile_fail; mod continuity;