Select closed face: Entry::closed_label is the face's text while the list, type-ahead and accessible value keep the label; Select::picture draws an entry's thumbnail in its row and on the face, alone with picture_only; ConnectorBar and the stroke editor use it, TabStopsDialog shows the leader fill alone in the box and the Leader cell

This commit is contained in:
aiongg
2026-11-12 14:32:46 +00:00
parent d33c7b23f9
commit d1afe97dc8
9 changed files with 158 additions and 41 deletions
+18 -13
View File
@@ -5,10 +5,10 @@ use craft_ui::choice::Segmented;
use craft_ui::contract::{Bind, Entry, Outcome, Show as _, ShowContainer as _};
use craft_ui::display::Divider;
use craft_ui::layout_components::Row;
use craft_ui::list::ThumbSize;
use craft_ui::pickers::Select;
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::Env;
use egui::{Response, Ui};
use egui::{Rect, Response, Ui};
use super::words::ConnectorBarWords;
use crate::geometry::connector::Routing;
@@ -136,10 +136,13 @@ impl<'a> ConnectorBar<'a> {
let mut select = Select::new(name.clone(), Bind::given(current), &entries);
if let Some(paint) = &row.paint {
let choices = row.choices;
select = select.decorate(move |id: &String, list_row| match choices.iter().find(|c| &c.id == id) {
Some(choice) => list_row.thumb(ThumbSize::Small, move |cx, rect| paint.paint(cx, rect, choice)),
None => list_row,
});
select = select
.picture(move |id: &String, cx: &ContentPainterCx, rect: Rect| {
if let Some(choice) = choices.iter().find(|c| &c.id == id) {
paint.paint(cx, rect, choice);
}
})
.picture_only();
}
if let Some(id) = select.show(ui).value().cloned() {
*slot = Some(id);
@@ -164,13 +167,15 @@ impl<'a> ConnectorBar<'a> {
Mixed::Same(held) => held,
Mixed::Mixed => ConnectorLine::default(),
};
let select = Select::new(words.line_style.clone(), Bind::given(current), &entries).decorate(move |pick: &LinePick, list_row| {
let (dashed, weight) = match *pick {
LinePick::Style(dashed) => (dashed, held.weight),
LinePick::Weight(index) => (held.dashed, ConnectorLine::WEIGHTS[index]),
};
list_row.thumb(ThumbSize::Small, move |cx, rect| StrokePreview::new(&sample(weight, dashed), weight as f32).paint(cx, rect))
});
let select = Select::new(words.line_style.clone(), Bind::given(current), &entries)
.picture(move |pick: &LinePick, cx: &ContentPainterCx, rect: Rect| {
let (dashed, weight) = match *pick {
LinePick::Style(dashed) => (dashed, held.weight),
LinePick::Weight(index) => (held.dashed, ConnectorLine::WEIGHTS[index]),
};
StrokePreview::new(&sample(weight, dashed), weight as f32).paint(cx, rect);
})
.picture_only();
if let Some(pick) = select.show(ui).value().copied() {
line_pick = Some(match pick {
LinePick::Style(dashed) => ConnectorLine { dashed, ..held },
+6 -5
View File
@@ -16,11 +16,11 @@ use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::{List, ListRow, ThumbAspect, ThumbSize};
use craft_ui::pickers::Select;
use craft_ui::primitives::IconSpec;
use craft_ui::primitives::{ContentPainterCx, IconSpec};
use craft_ui::runtime::env::{Env, Label, UnitKind};
use craft_ui::style::{ComponentStyle, StyleCx, SurfaceLook, TypeRole};
use craft_ui::text::NumberField;
use egui::{Response, Ui, Vec2};
use egui::{Rect, Response, Ui, Vec2};
use std::sync::Arc;
use super::{
@@ -383,9 +383,10 @@ impl Body<'_> {
Field::new(row.label.clone()).id_salt(("row", row.id.as_str())).show(ui, |ui, _| {
let mut select = Select::new(row.label.clone(), Bind::given(current.clone()), &entries);
if let Some(painter) = &row.paint {
select = select.decorate(move |id: &String, entry| match row.choices.iter().find(|choice| &choice.id == id) {
Some(choice) => entry.thumb(ThumbSize::Small, move |cx, rect| painter.paint(cx, rect, choice)),
None => entry,
select = select.picture(move |id: &String, cx: &ContentPainterCx, rect: Rect| {
if let Some(choice) = row.choices.iter().find(|choice| &choice.id == id) {
painter.paint(cx, rect, choice);
}
});
}
picked = select.show(ui).value().cloned();
+10 -1
View File
@@ -316,7 +316,11 @@ impl TabStopsDialog {
let stops = self.stops.clone();
let unit = self.unit;
let aligns: Vec<Entry<TabAlign>> = TabAlign::ALL.into_iter().map(|align| Entry::new(align, align_text(words, align))).collect();
let leaders: Vec<Entry<TabLeader>> = TabLeader::ALL.into_iter().map(|leader| Entry::new(leader, leader_text(words, leader))).collect();
// The closed box shows the fill alone, as Word's does; the list reads "1 ……".
let leaders: Vec<Entry<TabLeader>> = TabLeader::ALL
.into_iter()
.map(|leader| Entry::new(leader, leader_text(words, leader)).closed_label(leader_face(words, leader)))
.collect();
let range = -f64::from(MAX_POSITION)..=f64::from(MAX_POSITION);
let edits: RefCell<Vec<(usize, CellEdit)>> = RefCell::new(Vec::new());
let position_ids: RefCell<Vec<(usize, egui::Id)>> = RefCell::new(Vec::new());
@@ -423,6 +427,11 @@ fn align_text(words: &TabStopsWords, align: TabAlign) -> String {
.to_owned()
}
/// A leader's text in its closed box: "None", or the fill alone.
pub fn leader_face(words: &TabStopsWords, kind: TabLeader) -> String {
if kind == TabLeader::None { words.leader_none.as_str().to_owned() } else { kind.sample().to_owned() }
}
/// A leader option's text as Word's list reads: "None", or the fill after its number.
pub fn leader_text(words: &TabStopsWords, kind: TabLeader) -> String {
match TabLeader::ALL.iter().position(|other| *other == kind) {
+22 -1
View File
@@ -26,6 +26,7 @@ enum Row<T> {
struct Item<T> {
value: T,
label: Label,
closed: Option<Label>,
icon: Option<IconSpec<'static>>,
enabled: bool,
reason: Option<Label>,
@@ -36,7 +37,9 @@ struct Item<T> {
impl<T> Entry<T> {
/// An entry reporting `value` when picked, shown as `label`: enabled and unchecked, without an icon.
pub fn new(value: T, label: impl Into<Label>) -> Self {
Entry { row: Row::Item(Item { value, label: label.into(), icon: None, enabled: true, reason: None, checked: false, stepped: true }) }
Entry {
row: Row::Item(Item { value, label: label.into(), closed: None, icon: None, enabled: true, reason: None, checked: false, stepped: true }),
}
}
/// A rule between groups of entries. It is not a row: it takes no pick and no lead.
@@ -72,6 +75,16 @@ impl<T> Entry<T> {
self.icon(IconSpec::empty_swatch())
}
/// The text a closed control shows for the entry in place of its label (a tab leader's fill without its number).
/// The list, type-ahead and the accessible value keep the label. A heading or separator has none.
#[must_use]
pub fn closed_label(mut self, text: impl Into<Label>) -> Self {
if let Row::Item(item) = &mut self.row {
item.closed = Some(text.into());
}
self
}
/// Whether the entry can be picked; a disabled entry shows dimmed and never takes the lead.
#[must_use]
pub fn enabled(mut self, on: bool) -> Self {
@@ -129,6 +142,14 @@ impl<T> Entry<T> {
}
}
/// The text a closed control shows for the entry: its closed label, else its label.
pub fn face_label(&self) -> &Label {
match &self.row {
Row::Item(Item { closed: Some(closed), .. }) => closed,
_ => self.label(),
}
}
/// The icon before the label.
pub fn icon_spec(&self) -> Option<&IconSpec<'static>> {
match &self.row {
+1 -1
View File
@@ -208,7 +208,7 @@ impl Component for ComboBox<'_> {
.selection(Bind::given(selection))
.filter(&query, |key| labels[*key].clone())
.ranked(true)
.show_items(ui, &rows, &mut |key, _| rows.row(*key, current, decorate))
.show_items(ui, &rows, &mut |key, _| rows.row(*key, current, decorate, None))
.events
});
let (mut picked, mut keyed_to) = (None, None);
+21 -1
View File
@@ -1,6 +1,8 @@
//! `RowDress`: what a picker adds to an option's row.
//! `RowDress` and `SelectPicture`: what a picker adds to an option's row and face.
use crate::list::ListRow;
use crate::primitives::ContentPainterCx;
use egui::Rect;
/// What a picker adds to an option's row: the host's content for an option (a detail line, a trailing shortcut text, a
/// thumbnail painter). `Select::decorate` and `ComboBox::decorate` take the closure.
@@ -19,3 +21,21 @@ impl<'a, T> RowDress<'a, T> {
(self.0)(value, row)
}
}
/// The picture of an option (an arrowhead, a line style): one painter draws it in the option's list row and on the
/// closed face. `Select::picture` takes the closure.
pub struct SelectPicture<'a, T>(Box<PictureFn<'a, T>>);
type PictureFn<'a, T> = dyn Fn(&T, &ContentPainterCx, Rect) + 'a;
impl<'a, T> SelectPicture<'a, T> {
/// The picture `paint` draws for an option, given its value, into the rect the row or face gives it.
pub fn new(paint: impl Fn(&T, &ContentPainterCx, Rect) + 'a) -> Self {
SelectPicture(Box::new(paint))
}
/// Paints the picture of `value` into `rect`.
pub(super) fn paint(&self, value: &T, cx: &ContentPainterCx, rect: Rect) {
(self.0)(value, cx, rect)
}
}
+19 -5
View File
@@ -1,8 +1,8 @@
//! `EntryRows`: the entries of a picker as the rows of its option list.
use super::dress::RowDress;
use super::dress::{RowDress, SelectPicture};
use crate::contract::{Entry, Props as _, TooltipSpec};
use crate::list::ListRow;
use crate::list::{ListRow, ThumbSize};
use crate::runtime::env::Label;
use craft_behavior::{DisplayOrder, ItemSource};
use std::borrow::Cow;
@@ -20,9 +20,19 @@ impl<'a, T> EntryRows<'a, T> {
}
/// The row of the entry at `at`: its label and icon as an option, checked when it is the `chosen` entry, a caption
/// for a heading, a spacer for a separator, the host's dress over the rest.
pub(super) fn row<'r>(&self, at: usize, chosen: Option<usize>, dress: Option<&RowDress<'r, T>>) -> ListRow<'r> {
let entry = &self.entries[at];
/// for a heading, a spacer for a separator, the host's picture as the thumbnail and its dress over the rest.
pub(super) fn row<'r>(
&self,
at: usize,
chosen: Option<usize>,
dress: Option<&RowDress<'r, T>>,
picture: Option<&'r SelectPicture<'r, T>>,
) -> ListRow<'r>
where
'a: 'r,
{
let entries: &'a [Entry<T>] = self.entries;
let entry = &entries[at];
let Some(value) = entry.value() else {
return if entry.is_heading() { ListRow::heading(self.labels[at].clone()) } else { ListRow::spacer() };
};
@@ -31,6 +41,10 @@ impl<'a, T> EntryRows<'a, T> {
Some(icon) => row.icon(icon.clone()),
None => row,
};
let row = match picture {
Some(picture) => row.thumb(ThumbSize::Small, move |cx, rect| picture.paint(value, cx, rect)),
None => row,
};
let row = match entry.why_disabled() {
Some(reason) => row.description(reason.as_str()).tooltip(TooltipSpec::new(reason.clone()).disabled_text(reason.clone())),
None => row,
+47 -14
View File
@@ -4,7 +4,7 @@
//! hook on the dropdown preset. Focus stays on the field: the host hands the list keys to the listbox while it is
//! open, and Escape closes it without a change.
use super::dress::RowDress;
use super::dress::{RowDress, SelectPicture};
use super::face::{SelectFace, toggle_on_key};
use super::rows::EntryRows;
use super::search;
@@ -16,8 +16,9 @@ use crate::contract::{
MeasureCx, Numeric, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Role, Show as _,
ShowCollection as _, ShowContainer as _, WordSetCx as _, step_stop, step_stops,
};
use crate::list::{List, ListRow};
use crate::list::{List, ListRow, ThumbAspect};
use crate::menu::Menu;
use crate::primitives::ContentPainterCx;
use crate::runtime::env::Label;
use crate::runtime::focus::FocusMove;
use crate::runtime::overlay::CloseReason;
@@ -27,7 +28,7 @@ use craft_behavior::{
CancelReason, GesturePhase, HitLevel, HitPriority, IconId, Metrics, NavMove, PartKey, Selection, Sense, TypeAhead, Value, wheel_step,
};
use craft_theme::{Stateful, States};
use egui::{Ui, Vec2};
use egui::{Rect, Ui, Vec2};
use std::borrow::Cow;
#[cfg(feature = "testing")]
@@ -75,6 +76,10 @@ impl<'a> HeaderMenu<'a> {
/// arrow keys, Home, End and the wheel (while the field is focused or armed) step the pick through the stepped entries
/// ([`Entry::stepped`]); from a value that is none of them, forward lands on the first and back on the last. The field is as wide as its widest entry, placeholder or mixed word, so it keeps its
/// width whichever is shown.
///
/// The face shows the picked entry's [closed label](Entry::closed_label) where it has one; the list, type-ahead and
/// the accessible value keep the full label. A [`picture`](Select::picture) draws each entry's thumbnail in its row
/// and before the face's text, or alone on the face with [`picture_only`](Select::picture_only).
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(overlay, probe(Select<'static, u8>))]
pub struct Select<'a, T: Value + 'static> {
@@ -91,6 +96,12 @@ pub struct Select<'a, T: Value + 'static> {
/// Adds the host's content to each entry's row.
#[prop(func = "Fn(&T, ListRow<'a>) -> ListRow<'a>")]
decorate: Option<RowDress<'a, T>>,
/// Paints an entry's picture, given its value: the thumbnail of its row and of the face while it is picked.
#[prop(func = "Fn(&T, &ContentPainterCx, Rect)")]
picture: Option<SelectPicture<'a, T>>,
/// The face shows the picked entry's picture alone; its label stays the accessible value.
#[prop(flag)]
picture_only: bool,
/// The row under the pointer is proposed as the value while the list is open, as the rows the keys reach are;
/// closing the list without a pick restores the value.
#[prop(flag)]
@@ -103,14 +114,31 @@ pub struct Select<'a, T: Value + 'static> {
impl<'a, T: Value + 'static> Select<'a, T> {
/// A select named `label` over `value`, choosing among `entries`.
pub fn new(label: impl Into<Label>, value: Bind<'a, T>, entries: &'a [Entry<T>]) -> Self {
Select { common: Common::new(), value, entries, searchable: false, placeholder: None, decorate: None, preview: false, header_menu: None }
.label(label)
Select {
common: Common::new(),
value,
entries,
searchable: false,
placeholder: None,
decorate: None,
picture: None,
picture_only: false,
preview: false,
header_menu: None,
}
.label(label)
}
fn position(&self, value: Option<&T>) -> Option<usize> {
value.and_then(|value| self.entries.iter().position(|entry| entry.value() == Some(value)))
}
/// The face of `text`, with the picture's room before it, or the picture alone, when the select has a picture.
fn sized_face(&self, text: Label, picture: bool) -> SelectFace<'static> {
let face = SelectFace::new(text);
if self.picture.is_some() && picture { face.thumb(ThumbAspect::SQUARE, |_, _| {}).name(!self.picture_only) } else { face }
}
/// Sets the value to the entry at `at` unless it is the value already.
fn pick(&self, cx: &mut Cx<'_, Self>, at: usize) {
if let Some(value) = self.entries[at].value()
@@ -150,12 +178,13 @@ impl<T: Value + 'static> Component for Select<'_, T> {
}
}
/// The widest face of an entry, the placeholder and the mixed word, so the field keeps its size whichever is shown.
/// The widest face of an entry (its closed label, or its picture), the placeholder and the mixed word, so the field
/// keeps its size whichever is shown.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let mixed = cx.words::<PickerWords>().mixed.clone();
let entries = self.entries.iter().filter(|entry| entry.is_item()).map(Entry::label);
let texts = entries.chain(self.placeholder.as_ref()).chain(std::iter::once(&mixed));
texts.map(|text| cx.face(SelectFace::new(cx.env.resolve(text)))).fold(Vec2::ZERO, Vec2::max)
let entries = self.entries.iter().filter(|entry| entry.is_item()).map(|entry| (entry.face_label(), true));
let texts = entries.chain(self.placeholder.iter().map(|text| (text, false))).chain(std::iter::once((&mixed, false)));
texts.map(|(text, picture)| cx.face(self.sized_face(cx.env.resolve(text), picture))).fold(Vec2::ZERO, Vec2::max)
}
fn bind(&mut self) -> Option<BindMut<'_, T>> {
@@ -238,7 +267,7 @@ impl<T: Value + 'static> Component for Select<'_, T> {
let name = cx.label();
let words = cx.words::<PickerWords>();
let held = self.position(cx.value());
let (searchable, dress) = (self.searchable, self.decorate.as_ref());
let (searchable, dress, picture) = (self.searchable, self.decorate.as_ref(), self.picture.as_ref());
let mut header_menu = self.header_menu.as_mut();
let events = ui.show(popup, Overlay::dropdown(), |ui, body| {
let list = ui.scope_id().with("options");
@@ -268,7 +297,7 @@ impl<T: Value + 'static> Component for Select<'_, T> {
.selection(Bind::given(selection))
.lead_on_open(lead)
.filter(&query, |at| labels[*at].clone())
.show_items(ui, &rows, &mut |at, _| rows.row(*at, held, dress))
.show_items(ui, &rows, &mut |at, _| rows.row(*at, held, dress, picture))
.events
});
let mut picked = None;
@@ -301,15 +330,19 @@ impl<T: Value + 'static> Component for Select<'_, T> {
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let (text, muted) = match self.position(cx.value()) {
Some(at) => (cx.env.resolve(self.entries[at].label()), false),
let held = self.position(cx.value());
let (text, muted) = match held {
Some(at) => (cx.env.resolve(self.entries[at].face_label()), false),
None if cx.value().is_none() => (cx.env.resolve(&cx.words::<PickerWords>().mixed.clone()), true),
None => (self.placeholder.as_ref().map_or(Label::Empty, |text| cx.env.resolve(text)), true),
};
let mut face = SelectFace::new(text);
if let Some(icon) = self.position(cx.value()).and_then(|at| self.entries[at].icon_spec()) {
if let Some(icon) = held.and_then(|at| self.entries[at].icon_spec()) {
face = face.leading(icon.clone());
}
if let (Some(picture), Some(value)) = (self.picture.as_ref(), held.and_then(|at| self.entries[at].value())) {
face = face.thumb(ThumbAspect::SQUARE, move |cx, rect| picture.paint(value, cx, rect)).name(!self.picture_only);
}
ui.face(FACE, if muted { face.placeholder() } else { face });
}
@@ -35,3 +35,17 @@ fn a_select_steps_over_its_stepped_entries_and_from_an_unstepped_one_to_an_end()
assert_eq!(step(4, Key::ArrowDown), (1, (true, true)), "from an unstepped entry, forward lands on the first stop");
assert_eq!(step(4, Key::ArrowUp), (3, (true, true)), "from an unstepped entry, back lands on the last stop");
}
#[trial]
fn the_closed_face_shows_an_entrys_closed_label_and_the_accessible_value_keeps_its_label() {
let mut fixture = Fixture::new(|ui| {
let entries = [Entry::new(1u8, "1 Dots").closed_label("Dots"), Entry::new(2u8, "2 Lines").closed_label("Lines")];
Select::new("Leader", Bind::given(1u8), &entries).show(ui);
});
fixture.settle();
let texts: Vec<String> = fixture.texts().iter().map(|run| run.text.clone()).collect();
assert!(texts.iter().any(|text| text == "Dots"), "the face shows the closed label: {texts:?}");
assert!(!texts.iter().any(|text| text == "1 Dots"), "and not the list text");
let node = fixture.by_role(Role::COMBO_BOX).first().expect("the field").node;
assert_eq!(fixture.tree().value_of(node), Some("1 Dots"), "the accessible value is the full label");
}