Preset picker: the caption range sizes the field as a number field does

The field measured its face over both formatted ends of the range, in the
caption's proportional figures, so a value between them could still be wider
(4888 beside 5000) and change the chip's width. caption_range now names the
numeric range and decimal places of the caption; the field measures with
NumberCodec::widest of that range, and a face's thumbnail caption shows in
tabular figures, so the widest text is the widest number whatever its digits.
BrushPresetPicker writes its caption with the same codec.

Part of storytold/photocraft#15476, for storytold/photocraft#15859.
This commit is contained in:
aiongg
2026-11-20 04:39:56 +00:00
parent e3189215d9
commit b83509532e
5 changed files with 32 additions and 27 deletions
+3 -3
View File
@@ -4,7 +4,7 @@
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, Value};
use craft_behavior::{Codec as _, EditEvent, EditEvents, IconId, Mixed, NumberCodec, Value};
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Bind, BodyCx, EditResponse, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _, TooltipSpec, Trigger, clicked,
@@ -466,8 +466,8 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
};
let mut picker = PresetPicker::new(words.picker.clone(), current.reborrowed(), rows, Bind::bound(&mut browser))
.field(PickerField::Chip)
.caption(env.units().number(values.diameter.round(), 0..=0))
.caption_range([1.0, max_diameter].map(|diameter| Label::from(env.units().number(diameter.round(), 0..=0))))
.caption(NumberCodec::new(env.units().reader(None), 0).format(&Some(values.diameter.round())))
.caption_range((1.0..=max_diameter.round(), 0))
.cell_shape(CellShape::Square)
.view(if parts.tip_only() { PresetView::Grid } else { PresetView::List })
.browser(!compact)
@@ -30,9 +30,10 @@ use crate::runtime::memory::StageAccess;
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, FocusLook, StyleCx, SurfaceLook, UiTokens};
use crate::tile_grid::TileZoom;
use craft_behavior::{EditEvent, EditEvents, HitLevel, HitPriority, Intent, Metrics, Mixed, PartKey, PressPhase, Sense, Value};
use craft_behavior::{EditEvent, EditEvents, HitLevel, HitPriority, Intent, Metrics, Mixed, NumberCodec, PartKey, PressPhase, Sense, Value};
use egui::{Pos2, Rect, Response, Ui, Vec2};
use std::hash::Hash;
use std::ops::RangeInclusive;
/// The face under the whole field.
const FACE: PartKey = PartKey::new("face");
@@ -193,11 +194,12 @@ pub struct PresetPicker<'a, K: Value + Eq + Hash + 'static> {
/// A short line under the field's thumbnail (a brush's current size).
#[prop(into)]
caption: Option<Label>,
/// The captions at the two ends of what `caption` shows (a brush's least and largest size). The field holds the
/// wider, as a number field holds the widest value of its range, so a caption that follows a dragged value moves
/// nothing beside the field.
/// The range and decimal places of the number `caption` shows (a brush's least and largest size, whole), written
/// as [`NumberCodec`] writes plain numbers. The field holds the widest number of the range as a number field does
/// ([`NumberCodec::widest`], tabular figures), so a caption that follows a dragged value moves nothing beside the
/// field.
#[prop]
caption_range: Option<[Label; 2]>,
caption_range: Option<(RangeInclusive<f64>, usize)>,
/// The field's tooltip.
#[prop(into)]
tooltip: Option<Tooltip>,
@@ -542,7 +544,7 @@ struct PickerFace<'a, K: Value + Eq + Hash + 'static> {
placeholder: Option<Label>,
display_name: Option<Label>,
caption: Option<Label>,
caption_range: Option<[Label; 2]>,
caption_range: Option<(RangeInclusive<f64>, usize)>,
face_thumb: Option<PreviewPaint>,
edit_face: bool,
open: bool,
@@ -602,12 +604,10 @@ impl<K: Value + Eq + Hash + 'static> PickerFace<'_, K> {
self.captioned(face.thumb(self.cell_shape.aspect(), |_, _| {}).name(!self.thumb_only()), caption)
}
/// The caption the field measures with: the wider end of `caption_range`, else the caption. The caption shown is
/// not measured beside the ends: its measure would change with it, and the field's with it.
fn widest_caption(&self, cx: &MeasureCx<'_, Self>) -> Option<Label> {
let Some(range) = &self.caption_range else { return self.caption.clone() };
let width = |caption: &Label| cx.face(self.empty_thumb(SelectFace::new(Label::Empty), Some(caption))).x;
range.iter().map(|caption| (width(caption), caption)).max_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, caption)| caption.clone())
/// The caption the field measures with: the widest number of `caption_range`, else the caption.
fn measured_caption(&self, env: &EnvView<'_>) -> Option<Label> {
let Some((range, decimals)) = &self.caption_range else { return self.caption.clone() };
Some(Label::from(NumberCodec::new(env.units().reader(None), *decimals).widest(range)))
}
/// The face of a field showing `text` over `caption`: with a `row`, its thumbnail and name as `field` says;
@@ -677,7 +677,7 @@ impl<K: Value + Eq + Hash + 'static> Component for PickerFace<'_, K> {
/// thumbnail face for the height, each over the widest caption.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let words = cx.words::<PresetWords>();
let caption = self.widest_caption(cx);
let caption = self.measured_caption(&cx.env);
let caption = caption.as_ref();
let empty = SelectFace::new(Label::Empty);
let empty = if self.field == PickerField::Name { empty } else { self.empty_thumb(empty, caption) };
@@ -52,8 +52,8 @@ fn preset_picker_chip(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
output.map(StoryOutput::from).unwrap_or_default()
}
/// The chip with a caption range: it holds the width of its widest caption ("5000"), so a caption that follows a
/// dragged size ("7") moves nothing beside it on the bar.
/// The chip with a caption range: it holds the width of the widest number of the range ("5000", in tabular figures),
/// so a caption that follows a dragged size ("7") moves nothing beside it on the bar.
#[story(PresetPicker<'static, u32>, covers = [], drive = Drive::Never)]
fn preset_picker_chip_caption_range(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = rows();
@@ -64,7 +64,7 @@ fn preset_picker_chip_caption_range(ui: &mut Ui, data: &mut StoryData) -> StoryO
PresetPicker::new("Swatch", Bind::bound(&mut *swatch), &rows, Bind::bound(&mut *state))
.field(PickerField::Chip)
.caption("7")
.caption_range(["1".into(), "5000".into()])
.caption_range((1.0..=5000.0, 0))
.show(ui),
);
});
@@ -93,9 +93,10 @@ fn a_picker_in_a_popover_opens_and_picks_with_the_popover_kept_open() {
assert!(parent.get(), "the pick keeps the popover open");
}
/// A chip whose caption follows a dragged value (a brush size) holds the width of its widest caption: as the caption
/// gains digits the chip and what follows it on the bar stay in place, and each frame runs one pass (a caption that
/// changed the chip's width made the bar's kept measure stale, and the frame ran again).
/// A chip whose caption follows a dragged value (a brush size) holds the width of the widest number of its range: as
/// the caption gains digits, and whatever its digits are, the chip and what follows it on the bar stay in place, and
/// each frame runs one pass (a caption that changed the chip's width made the bar's kept measure stale, and the frame
/// ran again).
#[trial]
fn a_chip_with_a_caption_range_keeps_its_width_as_the_caption_grows() {
let size = Rc::new(Cell::new(9u32));
@@ -108,7 +109,7 @@ fn a_chip_with_a_caption_range_keeps_its_width_as_the_caption_grows() {
let _ = PresetPicker::new("Brush", Bind::bound(&mut value), &rows, Bind::bound(&mut state))
.field(PickerField::Chip)
.caption(shown.get().to_string())
.caption_range(["1".into(), "5000".into()])
.caption_range((1.0..=5000.0, 0))
.show(ui);
let _ = Button::new("Mode").show(ui);
});
@@ -120,7 +121,7 @@ fn a_chip_with_a_caption_range_keeps_its_width_as_the_caption_grows() {
(chip.width(), mode.left())
};
let first = place(&fixture);
for next in [10, 100, 1000, 7] {
for next in [10, 100, 1000, 4888, 7] {
size.set(next);
fixture.frame(Vec::new());
assert_eq!(fixture.passes(), 1, "caption {next}: the frame runs one pass");
+7 -3
View File
@@ -2,7 +2,7 @@
use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, Pointer as _, PopupHandle, Props as _, Role, Styled as _};
use crate::list::{RowThumb, ThumbAspect, ThumbPaint};
use crate::primitives::{ContentPainterCx, IconSpec, TextRun};
use crate::primitives::{ContentPainterCx, IconSpec, Span, TextRun};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, IconLook, Ink, StyleCx, TextLook, TypeRole};
use crate::text::{Adornment, FieldStyle, place, reserve};
@@ -68,7 +68,8 @@ pub struct SelectFace<'a> {
/// The picked entry's icon, drawn before the text in the chevron's ink.
#[prop]
leading: Option<IconSpec<'static>>,
/// A short line centred under the thumbnail (a brush's size); it shows only with a thumbnail.
/// A short line centred under the thumbnail (a brush's size), in tabular figures, so a number's width follows its
/// digit count only; it shows only with a thumbnail.
#[prop(into)]
thumb_caption: Option<Label>,
/// Whether the text shows beside the thumbnail; `false` shows the thumbnail alone, as wide as the thumbnail and
@@ -123,7 +124,10 @@ impl<'a> SelectFace<'a> {
/// The caption's run, when there is a thumbnail to show it under.
fn caption_run<'s>(&'s self, look: &TextLook) -> Option<TextRun<'s>> {
self.thumb.as_ref().and(self.thumb_caption.as_ref()).map(|caption| TextRun::new(caption.as_str()).role(look.role))
self.thumb
.as_ref()
.and(self.thumb_caption.as_ref())
.map(|caption| TextRun::spans(vec![Span::new(caption.as_str()).tabular()]).role(look.role))
}
fn leading_glyphs(&self) -> Vec<Adornment> {