From 97678639bf4fbde203fbc862f2c569da2c531a4d Mon Sep 17 00:00:00 2001 From: Samit Basu Date: Wed, 18 Nov 2026 15:48:58 -0800 Subject: [PATCH 1/6] Extras: the command feature, a command palette, combobox and autosuggest (#345) The widgets of #345, in eggshell-ui-extras behind the `command` feature, on core's public API (moving to the widgets crate with #366). - `filter`: the one filter all three use. `word_prefix(query, Candidate)`: each query word must start a word of the label or of a hidden keyword, case and accents aside (Unicode decomposition, via `unicode-normalization`); the start of the label ranks before a later word, before a keyword; ties keep the app's order. An app overrides it with `.filter(|query, candidate| -> Option)`, or filters itself with `.filtering(Filtering::App(Pending::Loading | Pending::Settled))` and `.on_query(..)`. - `CommandExt::command_list(key)`: a search field (`Role::ComboBox`) over the matching items in a virtual list it drives (`keys_from`), first match highlighted, with groups from the caller (`Items::group`, `Items::commands` for a #325 table), keywords, shortcuts, checks and disabled rows, and an empty state. - `CommandExt::command_dialog(key, Open, on_close)`: the same list in a centred modal dialog; a pick runs the item, then closes it. The app opens it with a #325 command bound to Cmd/Ctrl+K, so it shows in menus and #357 keeps the browser off the chord. - `CommandExt::combobox(key, Option, options)`: a select-like trigger that opens a popover holding the list; the chosen option is checked, a pick runs `on_change` and closes it. - `CommandExt::autosuggest(key, text, suggestions)`: a text field (`Role::ComboBox`) with matching suggestions under it, none highlighted until the arrows move, so Enter is still the field's; a pick or Escape puts them away until the next edit. The look is provisional (the menu's item, heading and shortcut looks, the select's trigger), pending the user's pick in the render round. The `command_palette` example: a Ctrl+K palette over a command table and a page list, a combobox and an autosuggest; its tests drive all three. Part of #345. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PWiKKe8zfqGfVMCSC5L3up --- Cargo.lock | 16 + Cargo.toml | 2 +- crates/eggshell-ui-extras/Cargo.toml | 2 + .../eggshell-ui-extras/src/command/filter.rs | 168 +++++ crates/eggshell-ui-extras/src/command/list.rs | 597 ++++++++++++++++++ crates/eggshell-ui-extras/src/command/mod.rs | 579 +++++++++++++++++ crates/eggshell-ui-extras/src/lib.rs | 2 + examples/command_palette.rs | 164 +++++ tests/it/command_palette.rs | 267 ++++++++ tests/it/main.rs | 1 + 10 files changed, 1797 insertions(+), 1 deletion(-) create mode 100644 crates/eggshell-ui-extras/src/command/filter.rs create mode 100644 crates/eggshell-ui-extras/src/command/list.rs create mode 100644 crates/eggshell-ui-extras/src/command/mod.rs create mode 100644 examples/command_palette.rs create mode 100644 tests/it/command_palette.rs diff --git a/Cargo.lock b/Cargo.lock index f586c599..4611d2a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1174,6 +1174,7 @@ dependencies = [ "eggshell-ui", "egui", "pulldown-cmark", + "unicode-normalization", ] [[package]] @@ -4033,6 +4034,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" @@ -4201,6 +4208,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 2feae312..3db9b08b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,7 @@ eframe = "0.37" egui_kittest = "0.37" trybuild = "1" eggshell-ui-shadcn = { path = "crates/eggshell-ui-shadcn", features = ["extras"] } -eggshell-ui-extras = { path = "crates/eggshell-ui-extras", features = ["markdown"] } +eggshell-ui-extras = { path = "crates/eggshell-ui-extras", features = ["markdown", "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 737183f2..29732a72 100644 --- a/crates/eggshell-ui-extras/Cargo.toml +++ b/crates/eggshell-ui-extras/Cargo.toml @@ -10,11 +10,13 @@ repository = "https://github.com/samitbasu/eggshell" [features] # Each widget is opt-in. markdown = ["dep:pulldown-cmark"] +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..c4a4c0a5 --- /dev/null +++ b/crates/eggshell-ui-extras/src/command/list.rs @@ -0,0 +1,597 @@ +//! 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 { + 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 classes of a combobox's trigger: the select's. +pub(crate) fn trigger_classes(style: &Style) -> Tw { + let select = &style.select; + let metrics = select.sizes.get(eggshell_ui::contract::Size::DEFAULT); + let rest = select.trigger.paint.states.rest; + let hover = select.trigger.paint.states.hover; + tw().flex() + .items_center() + .justify_between() + .gap(metrics.gap / 4.0) + .px(metrics.padding_x / 4.0) + .h_px(metrics.height) + .rounded_px(f32::from(metrics.radius)) + .border(select.trigger.border_width) + .border_color(rest.border) + .bg(rest.fill) + .text(rest.text) + .role(style.role(&select.text).clone()) + .sense_click() + .hover(|p| p.bg(hover.fill)) +} + +/// The classes of a combobox trigger's chevron. +pub(crate) fn chevron_classes(style: &Style) -> Tw { + let select = &style.select; + tw().size_px(select.chevron).shrink_0().text( + select + .trigger + .paint + .states + .rest + .text + .gamma_multiply(f32::from(select.chevron_opacity)), + ) +} + +/// 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 (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 mut list = s + .virtual_list( + Part::Results, + tw().max_h_px(300.0).p(style.menu.padding / 4.0), + 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); + 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, entry); + } + }); + }); +} + +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 classes = tw() + .flex() + .items_center() + .gap(2.0) + .px(3.0) + .h_px(36.0) + .border_b(menu.popup.border_width) + .border_color(rest.border); + let ctx = s.ctx().clone(); + let mut field = Id::NULL; + s.div_id(Part::Search, classes, |s| { + field = s.id_of(Part::Query); + s.icon( + "icon", + tw().size_px(16.0).shrink_0().text(menu.shortcut), + 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(&menu.text).clone()) + .font_weight(menu.heading_weight) + .text(menu.heading); + 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, 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 hover = states.hover; + base.bg(states.rest.fill) + .text(states.rest.text) + .group_hover(|p| p.bg(hover.fill).text(hover.text)) + } + }; + let side = menu.indicator; + s.div(classes, |s| { + match entry.state { + CommandState::Plain => {} + CommandState::Checked(Mark::On) | CommandState::Chosen(Mark::On) => { + s.glyph(tw().size_px(side).shrink_0(), Icon::new(icons::CHECK)); + } + CommandState::Checked(Mark::Off) | CommandState::Chosen(Mark::Off) => { + s.div(tw().size_px(side).shrink_0(), |_| {}); + } + } + 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()); + } + }); +} 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..78f2346f --- /dev/null +++ b/crates/eggshell-ui-extras/src/command/mod.rs @@ -0,0 +1,579 @@ +//! 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; + +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::{Builder, CommandState, Icon, Key, NodeUi as _, Scope, Tw, icons, tw}; +use egui::{Id, Role}; + +pub use filter::{Candidate, Score, word_prefix}; +pub use list::{ItemChain, Items}; + +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; + +/// 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, + Trigger, + 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(), + 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(), + } + } +} + +/// Whether a combobox's popover is open: the widget's own state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Popover { + #[default] + Closed, + Open, +} + +impl Popover { + fn id(combobox: Id) -> Id { + combobox.with("eggshell-ui-extras-popover") + } + + 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)); + } +} + +/// 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>, +} + +impl<'f, A: 'static, V: Key + Copy + PartialEq> ComboboxChain<'_, '_, 'f, A, V> { + /// TODO(prose): what the trigger says with no value, and the search field's hint. + pub fn placeholder(mut self, text: impl Into) -> Self { + self.options.placeholder = Some(text.into()); + self + } + + /// TODO(prose): the accessible name of the trigger 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 trigger, such as its width. + pub fn classes(mut self, classes: Tw) -> Self { + self.options.classes = classes; + 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, + } = self; + let ctx = b.ctx().clone(); + let popover = Popover::load(&ctx, key); + let shown = value + .and_then(|value| choices.iter().find(|(v, _)| *v == value)) + .map(|(_, label)| label.clone()); + let placeholder = options.placeholder.clone().unwrap_or_default(); + let name = options.name.clone().unwrap_or_default(); + let trigger_classes = std::mem::replace(&mut options.classes, tw()); + let (open, toggle) = (ctx.clone(), popover); + let label = shown.clone().unwrap_or(placeholder); + let style = Arc::clone(b.style()); + let trigger_id = b.id_of((key, Part::Trigger)); + let trigger = b + .div_id( + (key, Part::Trigger), + list::trigger_classes(&style).merge(trigger_classes), + |s| { + s.div(tw().grow().min_w_0().truncate(), |s| s.text(tw(), label)); + s.glyph( + list::chevron_classes(&style), + Icon::new(icons::CHEVRON_DOWN), + ); + }, + ) + .role(Role::ComboBox) + .named(name) + .on_click(move |_| { + let next = match toggle { + Popover::Open => Popover::Closed, + Popover::Closed => Popover::Open, + }; + next.store(&open, key); + }); + let value_text = shown.unwrap_or_default(); + trigger.draw(move |_, ui| { + let id = ui.node_response().id; + ui.ctx().accesskit_node_builder(id, |node| { + node.set_value(value_text.as_str()); + node.set_has_popup(egui::accesskit::HasPopup::Dialog); + if popover == Popover::Closed { + node.set_expanded(false); + } + }); + }); + if popover == Popover::Closed { + 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 = ctx.clone(); + let after: Rc = Rc::new(move |_| Popover::Closed.store(&close, key)); + let dismiss = ctx.clone(); + let style = Arc::clone(b.style()); + b.overlay((key, Part::Popover)) + .anchor(Anchor::Node(trigger_id)) + .placement(Placement::below().gap(style.menu.offset)) + .match_width(MatchWidth::Anchor) + .focus(Focus::Enter) + .role(Role::Dialog) + .on_dismiss(move |_| Popover::Closed.store(&dismiss, key)) + .children(|s| { + s.div_id(Part::Box, list::popover_classes(&style), |s| { + list::show( + s, + key, + items, + options, + list::ListOptions::palette(Some(after)), + ); + }); + }); + } +} + +/// 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 (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/lib.rs b/crates/eggshell-ui-extras/src/lib.rs index 2e0b7acc..d0e37d49 100644 --- a/crates/eggshell-ui-extras/src/lib.rs +++ b/crates/eggshell-ui-extras/src/lib.rs @@ -20,5 +20,7 @@ )] //! TODO(prose) +#[cfg(feature = "command")] +pub mod command; #[cfg(feature = "markdown")] pub mod markdown; diff --git a/examples/command_palette.rs b/examples/command_palette.rs new file mode 100644 index 00000000..6615bb1a --- /dev/null +++ b/examples/command_palette.rs @@ -0,0 +1,164 @@ +//! 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 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_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..54856a02 --- /dev/null +++ b/tests/it/command_palette.rs @@ -0,0 +1,267 @@ +//! 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"); +} + +#[test] +fn the_combobox_opens_filters_and_picks() { + let mut harness = harness(); + harness + .get_by_role_and_label(Role::ComboBox, "Framework") + .click(); + harness.run_steps(20); + assert_eq!( + support::focused_path(&harness).as_deref(), + Some(""), + "the popover's search field took the focus" + ); + harness + .query_all_by_role_and_label(Role::ComboBox, "Framework") + .last() + .expect("the popover's field") + .type_text("sv"); + step(&mut harness); + assert_eq!(options(&harness), ["SvelteKit"]); + 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 popover"); + let trigger = harness.get_by_role_and_label(Role::ComboBox, "Framework"); + assert_eq!( + trigger.accesskit_node().value().as_deref(), + Some("SvelteKit") + ); +} + +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()); +} diff --git a/tests/it/main.rs b/tests/it/main.rs index 1a28b528..dec085dd 100644 --- a/tests/it/main.rs +++ b/tests/it/main.rs @@ -19,6 +19,7 @@ mod clipboard; mod clipboard_example; mod collapsible; mod combobox_parts; +mod command_palette; mod commands; mod compile_fail; mod continuity; From 965ba6fa094e3e3459d6f17fc56939adfd8fb045 Mon Sep 17 00:00:00 2001 From: Samit Basu Date: Wed, 18 Nov 2026 16:09:53 -0800 Subject: [PATCH 2/6] Autosuggest: Escape in the field puts the suggestions away (#345) A focused text field keeps Escape from the overlay's dismissal, so the autosuggest reads it from its own field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PWiKKe8zfqGfVMCSC5L3up --- crates/eggshell-ui-extras/src/command/mod.rs | 9 ++++++ tests/it/command_palette.rs | 30 ++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/crates/eggshell-ui-extras/src/command/mod.rs b/crates/eggshell-ui-extras/src/command/mod.rs index 78f2346f..feb5a309 100644 --- a/crates/eggshell-ui-extras/src/command/mod.rs +++ b/crates/eggshell-ui-extras/src/command/mod.rs @@ -526,6 +526,15 @@ impl<'f, A: 'static> AutosuggestChain<'_, '_, 'f, A> { 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); diff --git a/tests/it/command_palette.rs b/tests/it/command_palette.rs index 54856a02..cdfc0dd0 100644 --- a/tests/it/command_palette.rs +++ b/tests/it/command_palette.rs @@ -265,3 +265,33 @@ fn the_autosuggest_shows_nothing_when_nothing_matches() { 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"]); +} From e9bc2513141b9eff956c07ec373b013d6db2b9c7 Mon Sep 17 00:00:00 2001 From: Samit Basu Date: Thu, 19 Nov 2026 15:16:34 -0800 Subject: [PATCH 3/6] Command: the combobox as shadcn's input group, and the command list's current look The combobox is rebuilt to shadcn's current Combobox (registry/bases/radix/ui combobox.tsx): a field you type in, inside the select's box with the ring while it has focus, a ghost icon-xs chevron at the end (a clear button in its place while there is a value and `on_clear` is set), and the list below the box, 6 pt apart and as wide as it, with no search field of its own. Typing filters and opens it; a click, the chevron or ArrowDown opens it; Escape or a press outside closes it and puts back the chosen label. The list takes shadcn's current command look through a new CommandStyle (installed by the shadcn preset): the highlighted row is bg-muted with foreground text, the search group is h-8 rounded-lg with bg-input/30 and border-input/30 inside a p-1 pb-0 wrapper, the list stops at max-h-72, a group heading is muted text-xs, and a chosen mark sits after the label. A scroll container is as tall as it is told, so a list built with only a max height collapsed to nothing in a render; the list is now told what its rows come to, up to the style's limit. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AJYxo4YJZUXcPJ1bHdAHKy --- crates/eggshell-ui-extras/src/command/list.rs | 193 ++++++++++----- crates/eggshell-ui-extras/src/command/mod.rs | 226 +++++++++++++----- .../eggshell-ui-extras/src/command/style.rs | 45 ++++ crates/eggshell-ui-extras/src/lib.rs | 11 +- crates/eggshell-ui-shadcn/Cargo.toml | 1 + crates/eggshell-ui-shadcn/src/preset.rs | 12 + examples/command_palette.rs | 3 +- tests/it/command_palette.rs | 135 +++++++++-- 8 files changed, 482 insertions(+), 144 deletions(-) create mode 100644 crates/eggshell-ui-extras/src/command/style.rs diff --git a/crates/eggshell-ui-extras/src/command/list.rs b/crates/eggshell-ui-extras/src/command/list.rs index c4a4c0a5..4c535831 100644 --- a/crates/eggshell-ui-extras/src/command/list.rs +++ b/crates/eggshell-ui-extras/src/command/list.rs @@ -207,6 +207,7 @@ impl ListOptions { #[derive(Clone, Copy, Debug, Hash)] enum Part { + Wrapper, Search, Query, Results, @@ -312,40 +313,63 @@ pub(crate) fn popover_classes(style: &Style) -> Tw { .overflow_hidden() } -/// The classes of a combobox's trigger: the select's. -pub(crate) fn trigger_classes(style: &Style) -> Tw { +/// 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 rest = select.trigger.paint.states.rest; - let hover = select.trigger.paint.states.hover; - tw().flex() + let states = select.trigger.paint.states; + let classes = tw() + .flex() .items_center() - .justify_between() - .gap(metrics.gap / 4.0) - .px(metrics.padding_x / 4.0) + .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(rest.border) - .bg(rest.fill) - .text(rest.text) + .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() - .hover(|p| p.bg(hover.fill)) + .focusable_none() + .hover(|p| p.bg(states.hover.fill)) } -/// The classes of a combobox trigger's chevron. -pub(crate) fn chevron_classes(style: &Style) -> Tw { - let select = &style.select; - tw().size_px(select.chevron).shrink_0().text( - select - .trigger - .paint - .states - .rest - .text - .gamma_multiply(f32::from(select.chevron_opacity)), - ) +/// 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. @@ -380,6 +404,7 @@ pub(crate) fn show<'f, A: 'static>( ) { 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()), @@ -418,10 +443,11 @@ pub(crate) fn show<'f, A: 'static>( } 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().max_h_px(300.0).p(style.menu.padding / 4.0), + tw().h_px(height).p(style.menu.padding / 4.0), rows, ) .nav(ListNav::Listbox) @@ -442,6 +468,7 @@ pub(crate) fn show<'f, A: 'static>( 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 @@ -483,12 +510,31 @@ pub(crate) fn show<'f, A: 'static>( }); } if let Some(entry) = rows_of.entries.get(&row) { - item(s, &style_of, entry); + 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, @@ -500,39 +546,55 @@ fn search_field( ) -> 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) - .px(3.0) - .h_px(36.0) - .border_b(menu.popup.border_width) - .border_color(rest.border); + .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::Search, classes, |s| { - field = s.id_of(Part::Query); - s.icon( - "icon", - tw().size_px(16.0).shrink_0().text(menu.shortcut), - 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); + 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); } - Query::set(&ctx, list, query); + 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 @@ -547,9 +609,9 @@ fn heading_classes(style: &Style, at: usize) -> Tw { let classes = tw() .px(menu.item_padding.x / 4.0) .py(1.5) - .role(style.role(&menu.text).clone()) + .role(style.role(&Some(menu.shortcut_text.clone())).clone()) .font_weight(menu.heading_weight) - .text(menu.heading); + .text(menu.shortcut); if at == 0 { classes } else { @@ -557,7 +619,12 @@ fn heading_classes(style: &Style, at: usize) -> Tw { } } -fn item(s: &mut Scope<'_, '_, A>, style: &Style, entry: &Entry) { +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; @@ -572,26 +639,20 @@ fn item(s: &mut Scope<'_, '_, A>, style: &Style, entry: &Entry) { let classes = match entry.enablement { Enablement::Disabled => base.text(states.disabled.text), Enablement::Enabled => { - let hover = states.hover; + let (fill, text) = (command.selected_fill, command.selected_text); base.bg(states.rest.fill) .text(states.rest.text) - .group_hover(|p| p.bg(hover.fill).text(hover.text)) + .group_hover(|p| p.bg(fill).text(text)) } }; let side = menu.indicator; s.div(classes, |s| { - match entry.state { - CommandState::Plain => {} - CommandState::Checked(Mark::On) | CommandState::Chosen(Mark::On) => { - s.glyph(tw().size_px(side).shrink_0(), Icon::new(icons::CHECK)); - } - CommandState::Checked(Mark::Off) | CommandState::Chosen(Mark::Off) => { - s.div(tw().size_px(side).shrink_0(), |_| {}); - } - } 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 index feb5a309..ca78ccd5 100644 --- a/crates/eggshell-ui-extras/src/command/mod.rs +++ b/crates/eggshell-ui-extras/src/command/mod.rs @@ -2,17 +2,20 @@ 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::{Builder, CommandState, Icon, Key, NodeUi as _, Scope, Tw, icons, tw}; +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}; @@ -39,6 +42,7 @@ 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> { @@ -89,7 +93,9 @@ impl From for Open { enum Part { Dialog, Box, - Trigger, + Group, + Chevron, + Clear, Popover, Field, Suggestions, @@ -257,6 +263,7 @@ impl<'b, 'f, A: 'static> CommandExt<'b, 'f, A> for Builder<'b, 'f, A> { b: self, value, choices: options.into_iter().collect(), + clear: None, options: Options::default(), } } @@ -277,17 +284,27 @@ impl<'b, 'f, A: 'static> CommandExt<'b, 'f, A> for Builder<'b, 'f, A> { } } -/// Whether a combobox's popover is open: the widget's own state. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum Popover { - #[default] - Closed, - Open, +/// 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 Popover { +impl Typing { + const CLOSED: Self = Self { + open: false, + query: None, + focus: false, + }; + fn id(combobox: Id) -> Id { - combobox.with("eggshell-ui-extras-popover") + combobox.with("eggshell-ui-extras-typing") } fn load(ctx: &egui::Context, combobox: Id) -> Self { @@ -298,6 +315,21 @@ impl Popover { 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). @@ -308,16 +340,17 @@ pub struct ComboboxChain<'s, 'b, 'f, A, V> { 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): what the trigger says with no value, and the search field's hint. + /// 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 trigger and of the list. + /// 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 @@ -338,12 +371,19 @@ impl<'f, A: 'static, V: Key + Copy + PartialEq> ComboboxChain<'_, '_, 'f, A, V> self } - /// TODO(prose): classes of the trigger, such as its width. + /// 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 { @@ -352,52 +392,114 @@ impl<'f, A: 'static, V: Key + Copy + PartialEq> ComboboxChain<'_, '_, 'f, A, V> value, choices, mut options, + clear, } = self; let ctx = b.ctx().clone(); - let popover = Popover::load(&ctx, key); - let shown = value + let state = Typing::load(&ctx, key); + let chosen = value .and_then(|value| choices.iter().find(|(v, _)| *v == value)) .map(|(_, label)| label.clone()); - let placeholder = options.placeholder.clone().unwrap_or_default(); - let name = options.name.clone().unwrap_or_default(); - let trigger_classes = std::mem::replace(&mut options.classes, tw()); - let (open, toggle) = (ctx.clone(), popover); - let label = shown.clone().unwrap_or(placeholder); + let text = state + .query + .clone() + .unwrap_or_else(|| chosen.clone().unwrap_or_default()); let style = Arc::clone(b.style()); - let trigger_id = b.id_of((key, Part::Trigger)); - let trigger = b - .div_id( - (key, Part::Trigger), - list::trigger_classes(&style).merge(trigger_classes), - |s| { - s.div(tw().grow().min_w_0().truncate(), |s| s.text(tw(), label)); - s.glyph( - list::chevron_classes(&style), - Icon::new(icons::CHEVRON_DOWN), - ); - }, - ) - .role(Role::ComboBox) - .named(name) - .on_click(move |_| { - let next = match toggle { - Popover::Open => Popover::Closed, - Popover::Closed => Popover::Open, - }; - next.store(&open, key); + 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) = response.ctx.input(|input| { + ( + input.key_pressed(egui::Key::Escape), + input.key_pressed(egui::Key::ArrowDown), + ) + }); + let focused = response.has_focus(); + if escape && (focused || response.lost_focus()) { + 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 value_text = shown.unwrap_or_default(); - trigger.draw(move |_, ui| { - let id = ui.node_response().id; - ui.ctx().accesskit_node_builder(id, |node| { - node.set_value(value_text.as_str()); - node.set_has_popup(egui::accesskit::HasPopup::Dialog); - if popover == Popover::Closed { - node.set_expanded(false); + 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 popover == Popover::Closed { + if !open { return; } let on_change = Rc::new(on_change); @@ -410,17 +512,14 @@ impl<'f, A: 'static, V: Key + Copy + PartialEq> ComboboxChain<'_, '_, 'f, A, V> .state(CommandState::Checked(mark)) .on_pick(move |app| on_change(app, choice)); } - let close = ctx.clone(); - let after: Rc = Rc::new(move |_| Popover::Closed.store(&close, key)); - let dismiss = ctx.clone(); - let style = Arc::clone(b.style()); + 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(trigger_id)) - .placement(Placement::below().gap(style.menu.offset)) + .anchor(Anchor::Node(group_id)) + .placement(Placement::below().gap(list::list_offset())) .match_width(MatchWidth::Anchor) - .focus(Focus::Enter) - .role(Role::Dialog) - .on_dismiss(move |_| Popover::Closed.store(&dismiss, key)) + .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( @@ -428,7 +527,14 @@ impl<'f, A: 'static, V: Key + Copy + PartialEq> ComboboxChain<'_, '_, 'f, A, V> key, items, options, - list::ListOptions::palette(Some(after)), + ListOptions { + first: First::Highlighted, + after: Some(after), + field: list::Field::Theirs { + id: field_id, + text: state.query.unwrap_or_default(), + }, + }, ); }); }); 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 21a32c3e..02a98739 100644 --- a/crates/eggshell-ui-extras/src/lib.rs +++ b/crates/eggshell-ui-extras/src/lib.rs @@ -22,13 +22,18 @@ #[cfg(feature = "badge")] pub mod badge; -#[cfg(feature = "hover-card")] -pub mod hover_card; #[cfg(feature = "command")] pub mod command; +#[cfg(feature = "hover-card")] +pub mod hover_card; #[cfg(feature = "markdown")] pub mod markdown; #[cfg(feature = "spinner")] pub mod spinner; -#[cfg(any(feature = "badge", feature = "markdown", feature = "spinner"))] +#[cfg(any( + feature = "badge", + feature = "command", + feature = "markdown", + feature = "spinner" +))] mod styles; diff --git a/crates/eggshell-ui-shadcn/Cargo.toml b/crates/eggshell-ui-shadcn/Cargo.toml index d14c87f2..8f5a32a7 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/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 cf3dc250..766d6d2e 100644 --- a/crates/eggshell-ui-shadcn/src/preset.rs +++ b/crates/eggshell-ui-shadcn/src/preset.rs @@ -853,6 +853,7 @@ impl Shadcn { self.markdown().install_for(ctx, self.theme); self.badge(&style).install_for(ctx, self.theme); self.hover_card().install_for(ctx, self.theme); + self.command(&style).install_for(ctx, self.theme); } style.install_for(ctx, self.theme); } @@ -963,6 +964,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 hover card's look: shadcn's `HoverCardContent` /// (`w-64 rounded-lg bg-popover p-4 shadow-md duration-100`, 4 pt below, /// centred) in this preset's colours, with Radix's 700/300 ms delays. diff --git a/examples/command_palette.rs b/examples/command_palette.rs index 6615bb1a..460a084b 100644 --- a/examples/command_palette.rs +++ b/examples/command_palette.rs @@ -1,6 +1,6 @@ //! 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 picks a framework, the autosuggest a city as typed. +//! 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; @@ -125,6 +125,7 @@ pub fn layout<'f>(b: &mut Builder<'_, 'f, State>, state: &'f State) { .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") diff --git a/tests/it/command_palette.rs b/tests/it/command_palette.rs index cdfc0dd0..897b62c5 100644 --- a/tests/it/command_palette.rs +++ b/tests/it/command_palette.rs @@ -185,36 +185,107 @@ fn a_checked_command_says_so_and_a_disabled_one_is_passed_by() { 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_opens_filters_and_picks() { +fn the_combobox_is_a_field_that_opens_on_a_click_filters_as_typed_and_picks() { let mut harness = harness(); - harness - .get_by_role_and_label(Role::ComboBox, "Framework") - .click(); + combobox(&harness).click(); harness.run_steps(20); assert_eq!( support::focused_path(&harness).as_deref(), Some(""), - "the popover's search field took the focus" + "the field itself has the focus" ); - harness - .query_all_by_role_and_label(Role::ComboBox, "Framework") - .last() - .expect("the popover's field") - .type_text("sv"); + 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 popover"); - let trigger = harness.get_by_role_and_label(Role::ComboBox, "Framework"); + 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!( - trigger.accesskit_node().value().as_deref(), - Some("SvelteKit") + 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" ); } @@ -295,3 +366,39 @@ fn escape_puts_the_suggestions_away_until_the_next_edit() { 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}" + ); +} From 2e6c52dc5a309f3b2fe22d490cd4fbfd9348466d Mon Sep 17 00:00:00 2001 From: Samit Basu Date: Thu, 19 Nov 2026 15:28:08 -0800 Subject: [PATCH 4/6] Combobox: Tab out of the field closes the list Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AJYxo4YJZUXcPJ1bHdAHKy --- crates/eggshell-ui-extras/src/command/mod.rs | 6 ++++-- tests/it/command_palette.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/eggshell-ui-extras/src/command/mod.rs b/crates/eggshell-ui-extras/src/command/mod.rs index ca78ccd5..e3703684 100644 --- a/crates/eggshell-ui-extras/src/command/mod.rs +++ b/crates/eggshell-ui-extras/src/command/mod.rs @@ -434,14 +434,16 @@ impl<'f, A: 'static, V: Key + Copy + PartialEq> ComboboxChain<'_, '_, 'f, A, V> } let (handled, shown) = (ctx.clone(), text.clone()); field = field.on_response(move |_, response| { - let (escape, down) = response.ctx.input(|input| { + 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(); - if escape && (focused || response.lost_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); diff --git a/tests/it/command_palette.rs b/tests/it/command_palette.rs index 897b62c5..17630aad 100644 --- a/tests/it/command_palette.rs +++ b/tests/it/command_palette.rs @@ -402,3 +402,21 @@ fn the_list_is_as_tall_as_its_rows_up_to_the_style_limit() { "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" + ); +} From 229b2102c11078b207c87a25b2f4da94b4b7fac7 Mon Sep 17 00:00:00 2001 From: Samit Basu Date: Thu, 19 Nov 2026 15:46:20 -0800 Subject: [PATCH 5/6] Command: the lists have no scrollbar, as shadcn's cn-command-list and cn-combobox-list are no-scrollbar (style-vega.css:382, 325); the autosuggest shows the combobox's list. They use Tw::scrollbar_none, so the rows are as wide as the box and no bar sits under the search field. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AJYxo4YJZUXcPJ1bHdAHKy --- crates/eggshell-ui-extras/src/command/list.rs | 4 ++- tests/it/command_palette.rs | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/eggshell-ui-extras/src/command/list.rs b/crates/eggshell-ui-extras/src/command/list.rs index 4c535831..097d740b 100644 --- a/crates/eggshell-ui-extras/src/command/list.rs +++ b/crates/eggshell-ui-extras/src/command/list.rs @@ -447,7 +447,9 @@ pub(crate) fn show<'f, A: 'static>( let mut list = s .virtual_list( Part::Results, - tw().h_px(height).p(style.menu.padding / 4.0), + tw().h_px(height) + .p(style.menu.padding / 4.0) + .scrollbar_none(), rows, ) .nav(ListNav::Listbox) diff --git a/tests/it/command_palette.rs b/tests/it/command_palette.rs index 17630aad..2f114bdf 100644 --- a/tests/it/command_palette.rs +++ b/tests/it/command_palette.rs @@ -420,3 +420,30 @@ fn tabbing_away_from_the_field_closes_the_list() { "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() + ); +} From b5b7e24828fa2e7847a6e551680caca9a5633569 Mon Sep 17 00:00:00 2001 From: Samit Basu Date: Thu, 19 Nov 2026 16:09:07 -0800 Subject: [PATCH 6/6] Command: the lists keep 4 pt from their edges as the highlight scrolls cn-command-list and cn-combobox-list are scroll-py-1 (style-vega.css:382, 325): the lists use Tw::scroll_py(1.0), so an arrow key never leaves the highlighted row flush with the edge, under the search field. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AJYxo4YJZUXcPJ1bHdAHKy --- crates/eggshell-ui-extras/src/command/list.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/eggshell-ui-extras/src/command/list.rs b/crates/eggshell-ui-extras/src/command/list.rs index 097d740b..c7d2c24f 100644 --- a/crates/eggshell-ui-extras/src/command/list.rs +++ b/crates/eggshell-ui-extras/src/command/list.rs @@ -449,6 +449,7 @@ pub(crate) fn show<'f, A: 'static>( Part::Results, tw().h_px(height) .p(style.menu.padding / 4.0) + .scroll_py(1.0) .scrollbar_none(), rows, )