chrome-w3: net change of 2 commits

- chrome-w3: written from its sheet
- chrome-w3: review fixes (review-1)
This commit is contained in:
Martin Ball
2026-11-18 16:01:11 +00:00
parent 8edb3735ab
commit e7613f6a30
4 changed files with 484 additions and 94 deletions
@@ -1,4 +1,5 @@
//! Panel and overlay patterns: `Panel`, `Inspector`, `HistoryPanel`, `ModifierKeysPanel`, `CommandPalette` and `Tour`.
//! Panel and overlay patterns: `Panel`, `Inspector`, `HistoryPanel`, `ModifierKeysPanel`, `CommandPalette` (a centred
//! box, or in place under a search box through `PaletteFace::InPlace`) and `Tour`.
mod words;
+292 -84
View File
@@ -1,24 +1,27 @@
//! `CommandPalette` (24.4): a search over the app's commands in one centred modal box.
//! `CommandPalette` (24.4): a search over the app's commands, in one centred modal box or in place under a search box.
use super::words::PanelWords;
use crate::contract::overlay::{OverlayFit, ViewportShare};
use crate::contract::{
Bind, CollectionEvent, Overlay, Pattern, Politeness, Props, Show as _, ShowCollection as _, ShowContainer as _, Sizing, announce,
Bind, BodyCx, CollectionEvent, Overlay, Pattern, Politeness, Props, Show as _, ShowCollection as _, ShowContainer as _, Sizing, announce, clicked,
};
use crate::display::{Shade, Text};
use crate::layout_components::Stack;
use crate::layout_components::{Row, Stack};
use crate::list::{List, ListRow};
use crate::menu::search::{HelpEntry, search_order};
use crate::popover::Popover;
use crate::popover::{Popover, PopupList};
use crate::runtime::commands::{self, CommandRef, FireSource};
use crate::runtime::env::{Env, Label, WordTemplate};
use crate::runtime::focus::{self, FocusTarget};
use crate::runtime::memory::Remember as _;
use crate::runtime::overlay::CloseReason;
use crate::runtime::words::common::CommonWords;
use crate::style::TypeRole;
use crate::text::TextField;
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed, Selection};
use egui::{Response, Ui};
use egui::{Id, Response, Ui};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
@@ -32,15 +35,25 @@ pub const RECENT: usize = 8;
/// The box's widest share of the window; its height is capped at the same share of the window's height.
const SHARE: ViewportShare = ViewportShare::new(0.6, 0.7);
/// What the palette keeps in its stack's memory while it is open: the query, the active row and the number of
/// What the palette keeps in its container's memory while it is open: the query, the active row and the number of
/// results last announced.
#[derive(Clone, Default)]
struct Session {
query: String,
selection: Selection<usize>,
selection: Selection<Line>,
announced: Option<usize>,
}
/// The key of a row of the list: the suggested heading, a command by its position in the app's entries, or the
/// fallback row.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum Line {
#[default]
Heading,
Entry(usize),
Fallback,
}
/// Where a [`CommandPalette`] shows its search.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
@@ -74,19 +87,26 @@ impl crate::contract::Outcome for PaletteOutput {
}
}
/// A search over the app's commands in a centred modal box: a search field over the matching commands.
/// A search over the app's commands: a search field over the matching commands, in a centred modal box or in place.
///
/// - Entries: [`HelpEntry`]s, found by label, English label or menu path and ranked by [`search_order`]. A row is one
/// line: the label, the menu path (dropped when the label would get too narrow) and the command's chord at the end.
/// A command is enabled as the window under the palette has it: the palette closes before the command runs, so
/// its own modal layer blocks none. A disabled command is listed and does not run.
/// - Empty query: the commands last run, newest first (the `recents` binding), else the first entries.
/// - Entries: [`HelpEntry`]s, found by label, English label, menu path or command id and ranked by [`search_order`].
/// A row is one line: the label, the menu path (dropped when the label would get too narrow) and the command's chord
/// at the end. A command is enabled as the window under the palette has it: the palette closes before the command
/// runs, so its own modal layer blocks none. A disabled command is listed and does not run.
/// - Faces: [`PaletteFace::Dialog`] is a centred modal box. [`PaletteFace::InPlace`] is a search box where it is laid
/// out, showing the `placeholder`; it opens to the field with the key focus in the pass that opens it and lists the
/// results in a popup under the field.
/// - Empty query: with `suggested`, its heading and those commands; else the commands last run, newest first (the
/// `recents` binding), else the first entries.
/// - Fallback: with `fallback`, a last row follows the matches of a query, or stands alone when nothing matches. Picking
/// it closes the palette and reports the query in the output's `fallback`; no command runs.
/// - Keys: the field keeps the focus; Up, Down, Page Up, Page Down move the active row (Up and Down wrap at the ends),
/// Enter picks it, Escape clears
/// the query and, on an empty query, closes the box; a press outside closes it. A caption under the list names the keys. The number of results is announced politely.
/// - Picking: the box closes, focus returns to where it was before the palette opened, the command fires as
/// `FireSource::Palette` (the app receives it as it receives a menu's) and goes first in `recents`;
/// [`CommandPalette::remember`] is the rule. The output's `picked` names it. Without a binding the palette keeps `recents` for the session.
/// Enter picks it, Escape clears the query and, on an empty query, closes the box; a press outside closes it. The dialog
/// face shows a caption under the list that names the keys. The number of results is announced politely.
/// - Picking: the box closes, the command fires as `FireSource::Palette` (the app receives it as it receives a menu's)
/// and goes first in `recents`; [`CommandPalette::remember`] is the rule. The output's `picked` names it. Without a
/// binding the palette keeps `recents` for the session. The dialog face returns the focus to where it was before the
/// palette opened; the in-place face leaves it where the host puts it after the popup closes.
#[derive(Pattern, Props)]
pub struct CommandPalette<'a> {
label: Label,
@@ -133,13 +153,20 @@ impl<'a> CommandPalette<'a> {
/// Shows the palette while it is open.
pub fn show(self, ui: &mut Ui) -> PaletteOutput {
let CommandPalette { label, entries, open, mut recents, face, placeholder, suggested, fallback } = self;
let _ = (face, placeholder, suggested, fallback); // P3(chrome-w3): ch.C9, dg.F27
match self.face {
PaletteFace::Dialog => self.show_dialog(ui),
PaletteFace::InPlace => self.show_in_place(ui),
}
}
fn show_dialog(self, ui: &mut Ui) -> PaletteOutput {
let CommandPalette { label, entries, open, mut recents, placeholder, suggested, fallback, .. } = self;
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let words = env.words::<PanelWords>();
let list_id = ui.scope_id().with("palette-rows");
let mut picked: Option<CommandRef> = None;
let hint: Label = placeholder.unwrap_or_else(|| Label::from(words.palette_placeholder.clone()));
let mut chosen = Chosen::default();
let shown = Popover::new(label.clone(), open)
.collection_body()
.overlay(|_| {
@@ -148,16 +175,14 @@ impl<'a> CommandPalette<'a> {
overlay
})
.show(ui, |ui, cx| {
let recent: Vec<CommandRef> = recents.reborrow().read(cx).and_then(|held| held.same().cloned()).unwrap_or_default();
let texts = texts_of(entries, &cx.env);
let folder = cx.env.folder();
let recent = recent_of(&mut recents, cx);
// The field is the stack's header and the key hint its footer, so the list takes the room left in
// the capped box and scrolls inside it. The three regions share the stack's memory.
Stack::new()
.header(|ui, stack| {
let state = stack.memory::<Session>();
TextField::search(words.palette_search.clone(), Bind::bound(&mut state.query))
.placeholder(words.palette_placeholder.clone())
.placeholder(hint.clone())
.drives(list_id)
.show(ui);
})
@@ -166,63 +191,194 @@ impl<'a> CommandPalette<'a> {
})
.show(ui, |ui, stack| {
let state = stack.memory::<Session>();
let listed = listing(entries, &state.query, &folder, &texts, &recent);
let rows = row_data(&ctx, entries, &texts, &listed, &cx.env);
let source = Listed { keys: &listed, rows: &rows };
let stamp = stamp_of(&state.query);
let events = List::options(words.palette_list.clone())
.id(list_id)
.arrows_wrap(true)
.empty(words.palette_empty.clone())
.selection(Bind::bound(&mut state.selection))
.rows_stamp(stamp)
.sizing(Sizing::Fill)
.show_items(ui, &source, &mut |key, _| rows[position(&listed, *key)].row())
.events;
for event in events {
if let CollectionEvent::Activate(key) = event {
picked = Some(entries[key].command().clone());
}
}
if state.announced != Some(listed.len()) && !state.query.trim().is_empty() {
let n = listed.len() as u64;
announce(&ctx, words.palette_results.text(n, &cx.env.format().integer(n)), Politeness::Polite);
}
state.announced = Some(listed.len());
let input = RowsInput {
ctx: &ctx,
entries,
words: &words,
list_id,
suggested: suggested.as_ref(),
fallback: fallback.as_ref(),
recent: &recent,
fill: true,
};
chosen = show_rows(ui, &input, state, &cx.env);
});
if let Some(command) = &picked {
cx.request_close();
commands::fire_beneath(&ctx, command.clone(), FireSource::Palette);
let before = recent.clone();
let mut after = recent;
Self::remember(&mut after, command.clone());
let name: Arc<str> = Arc::from(label.as_str());
let _ = recents.reborrow().write(cx, &EditEvent::set(Mixed::Same(before), after, name, None));
}
conclude(cx, &ctx, &chosen, &label, recent, &mut recents);
});
let closed = shown.output.closed;
PaletteOutput { response: shown.output.response, picked, closed, fallback: None }
PaletteOutput { response: shown.output.response, picked: chosen.picked, closed, fallback: chosen.fallback }
}
fn show_in_place(self, ui: &mut Ui) -> PaletteOutput {
let CommandPalette { label, entries, mut open, mut recents, placeholder, suggested, fallback, .. } = self;
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let words = env.words::<PanelWords>();
let scope = ui.scope_id();
let list_id = scope.with("palette-rows");
let field_id = scope.with("palette-field");
let face_hint: Label = placeholder.unwrap_or_else(|| Label::from(words.palette_placeholder.clone()));
let mut chosen = Chosen::default();
let mut closed = None;
let shown = Row::new().show(ui, |ui, cx| {
let mut is_open = open.reborrow().read(cx).and_then(|held| held.same().cloned()).unwrap_or(false);
// A click on the face and an app that sets `open` take the same path: the open branch below runs in this
// pass, and the field takes the key focus in it.
// The closed face is the search field's own look at its own size, so what sits beside it does not shift on open.
let closed_face = !is_open
&& clicked(
&TextField::search(words.palette_search.clone(), Bind::given(String::new()))
.placeholder(face_hint.clone())
.id(field_id)
.show(ui)
.response,
);
if closed_face {
let name: Arc<str> = Arc::from(label.as_str());
let _ = open.reborrow().write(cx, &EditEvent::set(Mixed::Same(false), true, name, None));
is_open = true;
}
if !is_open {
return;
}
// The container exists only while the palette is open, so its memory starts empty at each opening.
Row::new().show(ui, |ui, inner| {
if inner.appeared() {
focus::request(&ctx, FocusTarget::Id(field_id));
}
let session = inner.memory::<Session>();
let field = TextField::search(words.palette_search.clone(), Bind::bound(&mut session.query))
.placeholder(face_hint.clone())
.id(field_id)
.show(ui)
.response;
let popup = PopupList::new(label.clone(), open.reborrowed()).opened_by(&field).show(ui, |ui, popup| {
let recent = recent_of(&mut recents, popup);
let input = RowsInput {
ctx: &ctx,
entries,
words: &words,
list_id,
suggested: suggested.as_ref(),
fallback: fallback.as_ref(),
recent: &recent,
fill: false,
};
chosen = show_rows(ui, &input, session, &popup.env);
conclude(popup, &ctx, &chosen, &label, recent, &mut recents);
});
closed = popup.output.closed;
});
});
PaletteOutput { response: shown.output, picked: chosen.picked, closed, fallback: chosen.fallback }
}
}
/// The `[label, English label, menu path]` texts of `entries` for the matcher.
fn texts_of(entries: &[HelpEntry], env: &crate::runtime::env::EnvView<'_>) -> Vec<[String; 3]> {
/// What a pass of the list chose.
#[derive(Default)]
struct Chosen {
picked: Option<CommandRef>,
fallback: Option<String>,
}
/// What the list body reads, the same for both faces.
struct RowsInput<'a> {
ctx: &'a egui::Context,
entries: &'a [HelpEntry],
words: &'a PanelWords,
list_id: Id,
suggested: Option<&'a (Label, Vec<CommandRef>)>,
fallback: Option<&'a WordTemplate>,
recent: &'a [CommandRef],
/// The list fills the room its box leaves (the capped dialog) instead of the width alone (a popup that sizes to it).
fill: bool,
}
/// The commands last run, read through the `recents` binding.
fn recent_of(recents: &mut Bind<'_, Vec<CommandRef>>, cx: &mut BodyCx<'_>) -> Vec<CommandRef> {
recents.reborrow().read(cx).and_then(|held| held.same().cloned()).unwrap_or_default()
}
/// Shows the list of `state`'s query and reports what the user picked in it.
fn show_rows(ui: &mut Ui, input: &RowsInput<'_>, state: &mut Session, env: &crate::runtime::env::EnvView<'_>) -> Chosen {
let texts = texts_of(input.entries, env);
let folder = env.folder();
let found = state.query.trim().to_owned();
let suggested = input.suggested.map(|(_, commands)| commands.as_slice());
let keys = layout(input.entries, &state.query, &folder, &texts, input.recent, suggested, input.fallback.is_some());
let heading = input.suggested.map(|(label, _)| env.resolve(label).as_str().to_owned()).unwrap_or_default();
let fallback_text = input.fallback.map(|template| template.fill(&[("text", found.as_str())])).unwrap_or_default();
let rows = row_data(input.ctx, input.entries, &texts, &keys, &heading, &fallback_text, env);
let source = Listed { keys: &keys, rows: &rows };
let stamp = stamp_of(&state.query);
let events = List::options(input.words.palette_list.clone())
.id(input.list_id)
.arrows_wrap(true)
.empty(input.words.palette_empty.clone())
.selection(Bind::bound(&mut state.selection))
.rows_stamp(stamp)
.sizing(if input.fill { Sizing::Fill } else { Sizing::FillWidth })
.show_items(ui, &source, &mut |key, _| rows[position(&keys, *key)].row())
.events;
let mut chosen = Chosen::default();
for event in events {
if let CollectionEvent::Activate(key) = event {
match key {
Line::Entry(at) => chosen.picked = input.entries.get(at).map(|entry| entry.command().clone()),
Line::Fallback => chosen.fallback = Some(found.clone()),
Line::Heading => {}
}
}
}
let results = keys.iter().filter(|key| matches!(key, Line::Entry(_))).count();
if state.announced != Some(results) && !found.is_empty() {
let n = results as u64;
announce(input.ctx, input.words.palette_results.text(n, &env.format().integer(n)), Politeness::Polite);
}
state.announced = Some(results);
chosen
}
/// Closes the palette for a pick or the fallback, fires the picked command and puts it first in `recents`.
fn conclude(
cx: &mut BodyCx<'_>,
ctx: &egui::Context,
chosen: &Chosen,
label: &Label,
recent: Vec<CommandRef>,
recents: &mut Bind<'_, Vec<CommandRef>>,
) {
if chosen.fallback.is_some() {
cx.request_close();
}
let Some(command) = &chosen.picked else { return };
cx.request_close();
commands::fire_beneath(ctx, command.clone(), FireSource::Palette);
let before = recent.clone();
let mut after = recent;
CommandPalette::remember(&mut after, command.clone());
let name: Arc<str> = Arc::from(label.as_str());
let _ = recents.reborrow().write(cx, &EditEvent::set(Mixed::Same(before), after, name, None));
}
/// The `[label, English label, menu path, command id]` texts of `entries` for the matcher.
fn texts_of(entries: &[HelpEntry], env: &crate::runtime::env::EnvView<'_>) -> Vec<[String; 4]> {
let separator = env.words::<CommonWords>().path_separator.as_str().to_owned();
entries
.iter()
.map(|entry| {
let path: Vec<String> = entry.path().iter().map(|label| env.resolve(label).as_str().to_owned()).collect();
let english = entry.english().map(|label| env.resolve(label).as_str().to_owned()).unwrap_or_default();
[env.resolve(entry.label()).as_str().to_owned(), english, path.join(&separator)]
[env.resolve(entry.label()).as_str().to_owned(), english, path.join(&separator), entry.command().id.clone()]
})
.collect()
}
/// The entries the list shows, by position in `entries`: the matches for a query, best first, else the commands
/// last run, newest first, else the first entries. A command appears once.
fn listing(entries: &[HelpEntry], query: &str, folder: &craft_i18n::Folder, texts: &[[String; 3]], recent: &[CommandRef]) -> Vec<usize> {
// P3(chrome-w3): dg.F26 (the fourth text is the command id; empty until chrome-w3 passes it)
let refs: Vec<[&str; 4]> = texts.iter().map(|[label, english, path]| [label.as_str(), english.as_str(), path.as_str(), ""]).collect();
fn listing(entries: &[HelpEntry], query: &str, folder: &craft_i18n::Folder, texts: &[[String; 4]], recent: &[CommandRef]) -> Vec<usize> {
let refs: Vec<[&str; 4]> =
texts.iter().map(|[label, english, path, id]| [label.as_str(), english.as_str(), path.as_str(), id.as_str()]).collect();
let candidates: Vec<usize> = if query.trim().is_empty() {
let last: Vec<usize> = recent.iter().filter_map(|command| entries.iter().position(|entry| entry.command() == command)).collect();
if last.is_empty() { (0..entries.len()).collect() } else { last }
@@ -243,8 +399,41 @@ fn listing(entries: &[HelpEntry], query: &str, folder: &craft_i18n::Folder, text
.collect()
}
/// The position of the entry `key` in the listing.
fn position(listed: &[usize], key: usize) -> usize {
/// The rows of the list in display order. An empty query with `suggested` lists the heading and the suggested commands
/// that are entries, and nothing else; a query lists its matches and, with a fallback, the fallback row last.
fn layout(
entries: &[HelpEntry],
query: &str,
folder: &craft_i18n::Folder,
texts: &[[String; 4]],
recent: &[CommandRef],
suggested: Option<&[CommandRef]>,
with_fallback: bool,
) -> Vec<Line> {
if query.trim().is_empty() {
let mut at: Vec<usize> = Vec::new();
for command in suggested.unwrap_or_default() {
if let Some(found) = entries.iter().position(|entry| entry.command() == command)
&& !at.contains(&found)
{
at.push(found);
}
}
// Suggestions that name no entry leave the empty query its usual list rather than "no results".
if at.is_empty() {
return listing(entries, query, folder, texts, recent).into_iter().map(Line::Entry).collect();
}
return std::iter::once(Line::Heading).chain(at.into_iter().map(Line::Entry)).collect();
}
let mut rows: Vec<Line> = listing(entries, query, folder, texts, recent).into_iter().map(Line::Entry).collect();
if with_fallback {
rows.push(Line::Fallback);
}
rows
}
/// The position of the row `key` in the listing.
fn position(listed: &[Line], key: Line) -> usize {
listed.iter().position(|at| *at == key).unwrap_or(0)
}
@@ -260,13 +449,20 @@ struct RowData {
path: Option<String>,
chord: Option<String>,
enabled: bool,
/// The row heads the rows after it.
heading: bool,
/// A rule under the row sets it off from the fallback row that follows.
rule: bool,
}
impl RowData {
/// One line: the label, then the menu path, which drops out when the label would get too narrow, and the chord
/// at the end.
fn row(&self) -> ListRow<'static> {
let row = ListRow::new(self.label.clone()).option().command_row().enabled(self.enabled);
if self.heading {
return ListRow::new(self.label.clone()).heading();
}
let row = ListRow::new(self.label.clone()).option().command_row().enabled(self.enabled).rule(self.rule);
// The first trailing item is the outermost: the chord ends the row and the path sits before it.
let row = match &self.chord {
Some(chord) => row.trailing(chord.clone()),
@@ -282,47 +478,59 @@ impl RowData {
fn row_data(
ctx: &egui::Context,
entries: &[HelpEntry],
texts: &[[String; 3]],
listed: &[usize],
texts: &[[String; 4]],
keys: &[Line],
heading: &str,
fallback: &str,
env: &crate::runtime::env::EnvView<'_>,
) -> Vec<RowData> {
let (os, layout) = (env.shell().os, env.keyboard_layout());
listed
.iter()
.map(|at| {
let resolved = commands::resolve_beneath(ctx, entries[*at].command().clone());
RowData {
label: texts[*at][0].clone(),
path: Some(texts[*at][2].clone()).filter(|path| !path.is_empty()),
chord: resolved.chord.as_ref().map(|chord| chord.display_for(os, layout)),
enabled: resolved.enabled,
keys.iter()
.enumerate()
.map(|(index, key)| match key {
Line::Heading => RowData { label: heading.to_owned(), path: None, chord: None, enabled: true, heading: true, rule: false },
Line::Fallback => RowData { label: fallback.to_owned(), path: None, chord: None, enabled: true, heading: false, rule: false },
Line::Entry(at) => {
let resolved = commands::resolve_beneath(ctx, entries[*at].command().clone());
RowData {
label: texts[*at][0].clone(),
path: Some(texts[*at][2].clone()).filter(|path| !path.is_empty()),
chord: resolved.chord.as_ref().map(|chord| chord.display_for(os, layout)),
enabled: resolved.enabled,
heading: false,
rule: keys.get(index + 1) == Some(&Line::Fallback),
}
}
})
.collect()
}
/// The listed entries as the options of the list, keyed by their position in the app's entries.
/// The listed rows as the options of the list.
struct Listed<'a> {
keys: &'a [usize],
keys: &'a [Line],
rows: &'a [RowData],
}
impl DisplayOrder<usize> for Listed<'_> {
impl DisplayOrder<Line> for Listed<'_> {
fn len(&self) -> usize {
self.keys.len()
}
fn key(&self, at: usize) -> usize {
fn key(&self, at: usize) -> Line {
self.keys[at]
}
fn is_section(&self, at: usize) -> bool {
self.rows[at].heading
}
fn enabled(&self, at: usize) -> bool {
self.rows[at].enabled
}
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
Some(std::borrow::Cow::Borrowed(self.rows[at].label.as_str()))
(!self.rows[at].heading).then(|| std::borrow::Cow::Borrowed(self.rows[at].label.as_str()))
}
}
impl ItemSource<usize> for Listed<'_> {}
impl ItemSource<Line> for Listed<'_> {}
@@ -1,9 +1,10 @@
//! Stories of `CommandPalette`: PhotoCraft's menu commands and tools, with no command run yet and with three run.
use super::CommandPalette;
use super::{CommandPalette, PaletteFace};
use crate::contract::Bind;
use crate::menu::search::HelpEntry;
use crate::runtime::commands::{CommandInput, CommandRef, CommandState, EditCommands};
use crate::runtime::env::{Label, WordTemplate};
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use std::sync::LazyLock;
@@ -52,22 +53,51 @@ static ENTRIES: LazyLock<Vec<HelpEntry>> = LazyLock::new(|| {
/// The open palette over [`ENTRIES`], starting with `recents` as the commands last run, and the last command picked
/// as the readout.
fn palette(ui: &mut Ui, data: &mut StoryData, recents: Vec<CommandRef>) -> StoryOutput {
configured(ui, data, recents, true, |palette| palette)
}
/// The palette over [`ENTRIES`] as `configure` sets it, open from the start when `open_at_start`; the last command
/// picked and the last query the fallback row handed back are the readout.
fn configured(
ui: &mut Ui,
data: &mut StoryData,
recents: Vec<CommandRef>,
open_at_start: bool,
configure: fn(CommandPalette<'_>) -> CommandPalette<'_>,
) -> StoryOutput {
// The palette binds two story values; it edits a copy of `open`, which goes back after the pass.
let mut open = *data.value("open", true);
let out = CommandPalette::new("Command palette", ENTRIES.as_slice(), Bind::bound(&mut open))
.recents(Bind::bound(data.value("recents", recents)))
.show(ui);
*data.value("open", true) = open;
let mut open = *data.value("open", open_at_start);
let palette = CommandPalette::new("Command palette", ENTRIES.as_slice(), Bind::bound(&mut open)).recents(Bind::bound(data.value("recents", recents)));
let out = configure(palette).show(ui);
*data.value("open", open_at_start) = open;
let last = data.value("last", None::<String>);
if let Some(picked) = &out.picked
&& let Some(entry) = ENTRIES.iter().find(|entry| entry.command() == picked)
{
*last = Some(entry.label().as_str().to_owned());
}
let readout = format!("Last run: {}", last.as_deref().unwrap_or("none"));
let mut readout = format!("Last run: {}", last.as_deref().unwrap_or("none"));
let searched = data.value("searched", None::<String>);
if let Some(query) = &out.fallback {
*searched = Some(query.clone());
}
if let Some(query) = searched.as_deref() {
readout.push_str(&format!(". Searched the document for: {query}"));
}
StoryOutput::from(out).readout(readout)
}
/// The in-place face with its hint.
fn in_place_face(palette: CommandPalette<'_>) -> CommandPalette<'_> {
palette.face(PaletteFace::InPlace).placeholder(Label::from("Search commands"))
}
/// Suggested commands for the empty query and the fallback row.
fn with_suggested_and_fallback(palette: CommandPalette<'_>) -> CommandPalette<'_> {
let suggested = [PhotoCraftCommand::Levels, PhotoCraftCommand::Brush].map(CommandRef::from).to_vec();
palette.suggested((Label::from("Suggested"), suggested)).fallback(WordTemplate::new("Find “{text}” in the document"))
}
/// The command states the stories run under: Redo is disabled, as the entries list it.
fn commands(input: CommandInput) -> CommandInput {
input.state(EditCommands::Redo, CommandState::new().enabled(false))
@@ -83,3 +113,13 @@ fn command_palette_recents(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let recents = [PhotoCraftCommand::Levels, PhotoCraftCommand::Brush, PhotoCraftCommand::Search].map(CommandRef::from).to_vec();
palette(ui, data, recents)
}
#[story(CommandPalette<'static>, covers = [], drive = Drive::Never, title = "In place", commands = commands)]
fn command_palette_in_place(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
configured(ui, data, Vec::new(), false, in_place_face)
}
#[story(CommandPalette<'static>, covers = [], drive = Drive::Never, title = "Suggested and fallback", commands = commands)]
fn suggested_and_fallback(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
configured(ui, data, Vec::new(), true, with_suggested_and_fallback)
}
+143 -2
View File
@@ -4,12 +4,13 @@
use craft_ui::contract::{Bind, CommandSet, Overlay, Role, ShowContainer as _};
use craft_ui::menu::search::HelpEntry;
use craft_ui::patterns::panels::CommandPalette;
use craft_ui::patterns::panels::{CommandPalette, PaletteFace};
use craft_ui::popover::Popover;
use craft_ui::runtime::commands::{CommandRef, CommandState, EditCommands, FireSource};
use craft_ui::runtime::env::{Label, WordTemplate};
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::{Fixture, stories, trial};
use egui::{Key, Modifiers, Ui};
use egui::{Key, Modifiers, Pos2, Ui};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -125,6 +126,146 @@ fn a_command_the_app_disables_lists_disabled_and_does_not_run_even_after_typing_
assert!(take_output(fixture.ctx()).fired.is_empty(), "nothing ran");
}
/// A palette of `face` over `entries`, open from the start or not; `picked` and `handed` hold the last pick and the
/// last query the fallback row handed back.
type FacedRig = (Fixture, Rc<Cell<bool>>, Rc<RefCell<Option<CommandRef>>>, Rc<RefCell<Option<String>>>);
fn faced(
face: PaletteFace,
entries: Vec<HelpEntry>,
suggested: Option<(Label, Vec<CommandRef>)>,
fallback: Option<WordTemplate>,
start_open: bool,
) -> FacedRig {
let open = Rc::new(Cell::new(start_open));
let picked = Rc::new(RefCell::new(None::<CommandRef>));
let handed = Rc::new(RefCell::new(None::<String>));
let (shown_open, shown_picked, shown_handed) = (open.clone(), picked.clone(), handed.clone());
let fixture = Fixture::new(move |ui| {
let mut is_open = shown_open.get();
let mut palette = CommandPalette::new("Commands", &entries, Bind::bound(&mut is_open)).face(face).placeholder(Label::from("Search"));
if let Some(suggested) = suggested.clone() {
palette = palette.suggested(suggested);
}
if let Some(fallback) = fallback.clone() {
palette = palette.fallback(fallback);
}
let output = palette.show(ui);
shown_open.set(is_open);
if let Some(command) = output.picked {
*shown_picked.borrow_mut() = Some(command);
}
if let Some(query) = output.fallback {
*shown_handed.borrow_mut() = Some(query);
}
});
(fixture, open, picked, handed)
}
fn trial_entries() -> Vec<HelpEntry> {
vec![
HelpEntry::new(TrialCommand::Rotate, "Rotate").with_path(["Image"]),
HelpEntry::new(TrialCommand::Flip, "Flip").with_path(["Image"]),
HelpEntry::new(TrialCommand::Crop, "Crop").with_path(["Image"]),
]
}
fn find_template() -> WordTemplate {
WordTemplate::new("Find “{text}” in the document")
}
#[trial]
fn keys_of_the_opening_pass_go_into_the_field_and_enter_is_used_up() {
let (mut fixture, open, picked, handed) = faced(PaletteFace::InPlace, trial_entries(), None, None, false);
fixture.settle();
assert!(rows(&fixture).is_empty(), "the closed face lists nothing");
// The first typed letter arrives in the pass that opens the face: a letter lost would leave every row listed.
open.set(true);
fixture.type_text("f").settle();
let listed = rows(&fixture);
assert_eq!(listed.len(), 1, "the letter typed in the opening pass reached the field: {listed:?}");
assert!(listed[0].0.starts_with("Flip"), "{listed:?}");
let _ = take_output(fixture.ctx());
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(*picked.borrow(), Some(CommandRef::from(TrialCommand::Flip)), "Enter picked the first row");
assert_eq!(*handed.borrow(), None, "no fallback was configured");
assert!(!open.get(), "picking closed the face");
let fired = take_output(fixture.ctx()).fired;
assert_eq!(fired.len(), 1, "Enter was used up by the list and ran nothing else: {fired:?}");
assert_eq!(fired[0].command, CommandRef::from(TrialCommand::Flip));
}
#[trial]
fn escape_and_a_press_outside_close_the_in_place_face_and_the_fallback_row_carries_the_query() {
let (mut fixture, open, picked, handed) = faced(PaletteFace::InPlace, trial_entries(), None, Some(find_template()), false);
fixture.settle();
open.set(true);
fixture.settle();
assert!(open.get(), "the face is open");
// Escape clears a typed query first and closes only on an empty field.
fixture.type_text("ro").settle();
fixture.key(Key::Escape, Modifiers::NONE).settle();
assert!(open.get(), "Escape on a typed query only clears it");
assert_eq!(rows(&fixture).len(), 3, "the cleared field lists every entry again: {:?}", rows(&fixture));
fixture.key(Key::Escape, Modifiers::NONE).settle();
assert!(!open.get(), "Escape on an empty field closes it");
open.set(true);
fixture.settle();
let below = fixture.by_role(Role::LIST_BOX_OPTION).pop().expect("a listed row").rect;
fixture.click_at(Pos2::new(below.center().x, below.bottom() + 40.0)).settle();
assert!(!open.get(), "a press outside closes it");
// With nothing matching, the fallback row stands alone and Enter takes it.
open.set(true);
fixture.type_text("zzz").settle();
let listed = rows(&fixture);
assert_eq!(listed.len(), 1, "only the fallback row: {listed:?}");
assert!(listed[0].0.contains("zzz"), "the fallback row carries the query: {listed:?}");
let _ = take_output(fixture.ctx());
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(*handed.borrow(), Some("zzz".to_owned()), "Enter handed the query back");
assert_eq!(*picked.borrow(), None, "the fallback picks no command");
assert!(!open.get(), "the fallback closed the face");
assert!(take_output(fixture.ctx()).fired.is_empty(), "no command ran");
// With a match, the fallback row is the last one and a click on it hands the query back.
*handed.borrow_mut() = None;
open.set(true);
fixture.type_text("flip").settle();
let listed = rows(&fixture);
assert_eq!(listed.len(), 2, "the match and the fallback row: {listed:?}");
assert!(listed[0].0.starts_with("Flip"), "{listed:?}");
assert!(listed[1].0.contains("Find “flip” in the document"), "{listed:?}");
let last = fixture.by_role(Role::LIST_BOX_OPTION).pop().expect("the fallback row");
fixture.click(&last).settle();
assert_eq!(*handed.borrow(), Some("flip".to_owned()), "the click handed the query back");
assert_eq!(*picked.borrow(), None, "the fallback picks no command");
assert!(!open.get());
}
#[trial]
fn an_empty_query_lists_the_suggested_commands_and_a_query_lists_matches() {
for face in [PaletteFace::Dialog, PaletteFace::InPlace] {
let suggested = (Label::from("Suggested"), vec![CommandRef::from(TrialCommand::Crop), CommandRef::from(TrialCommand::Flip)]);
let (mut fixture, open, ..) = faced(face, trial_entries(), Some(suggested), None, face == PaletteFace::Dialog);
fixture.settle();
open.set(true);
fixture.settle();
let names: Vec<String> = rows(&fixture).into_iter().map(|(name, _)| name).collect();
assert_eq!(names.len(), 2, "{face:?}: only the suggested commands list: {names:?}");
assert!(names[0].starts_with("Crop") && names[1].starts_with("Flip"), "{face:?}: in the suggested order: {names:?}");
fixture.type_text("rot").settle();
let names: Vec<String> = rows(&fixture).into_iter().map(|(name, _)| name).collect();
assert_eq!(names.len(), 1, "{face:?}: a query lists its matches only: {names:?}");
assert!(names[0].starts_with("Rotate"), "{face:?}: {names:?}");
}
}
#[trial]
fn a_palette_opened_in_a_modal_dialog_lists_what_the_dialog_blocks_as_disabled() {
let entries = vec![HelpEntry::new(TrialCommand::Rotate, "Rotate"), HelpEntry::new(TrialCommand::Zoom, "Zoom")];