From 3dd1f117716a8280412499d1434ccb58eeb2d2d5 Mon Sep 17 00:00:00 2001 From: skylar Date: Tue, 17 Nov 2026 22:43:12 +0100 Subject: [PATCH] Adapt number presentation to next and measure proportional ranges --- crates/ui-widgets/src/text/number.rs | 10 +-- crates/ui-widgets/src/text/number/rule.rs | 26 +++++--- .../tests/it/text/number_presentation.rs | 61 +++++++++++++++++-- docs/contract-api.md | 4 +- 4 files changed, 76 insertions(+), 25 deletions(-) diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index bd33b15ce..ae9119529 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -412,13 +412,6 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { decimals: self.shown_decimals(), } } - - /// Measure the value with the same type role and monospace setting as the text adapter. A mono span selects the - /// monospace role's font and size; otherwise the configured role is used. - fn value_run<'s>(&self, text: &'s str) -> TextRun<'s> { - let span = if self.options.mono { Span::new(text).mono() } else { Span::new(text) }; - TextRun::spans(vec![span]).role(self.options.role) - } } impl Component for NumberField<'_, V> { const ROLE: Role = Role::SPIN_BUTTON; @@ -462,8 +455,7 @@ impl Component for NumberField<'_, V> { let content = content_sized(cx); // A mixed field is sized as it is with a value, so it keeps its width when the selection changes. let blank = V::blank().unwrap_or_else(|| V::of_number(self.rule().blank())); - let sample = codec.sample(cx.value().unwrap_or(&blank)); - let mut text = cx.field_text(&self.value_run(sample.as_ref())); + let mut text = codec.samples(cx.value().unwrap_or(&blank)).map(|sample| cx.field_text(&self.value_run(&sample))).fold(Vec2::ZERO, Vec2::max); if content { text.x = crate::layout::ambient_width(cx.ui.ctx(), &VALUES, text.x).map_or(text.x, |width| width.max(text.x)); } diff --git a/crates/ui-widgets/src/text/number/rule.rs b/crates/ui-widgets/src/text/number/rule.rs index f468fe7d6..f1e533422 100644 --- a/crates/ui-widgets/src/text/number/rule.rs +++ b/crates/ui-widgets/src/text/number/rule.rs @@ -131,6 +131,22 @@ impl Clone for Ruled { } impl Ruled { + /// The existing range representatives, kept separate so proportional text is compared by shaped width rather + /// than character count. At most four strings are formatted, regardless of the range or precision. + pub(super) fn samples(&self, current: &V) -> impl Iterator { + let samples = if current.named().is_none() && self.rule.low.is_finite() && self.rule.high.is_finite() { + // Match NumberCodec::widest, including the last decimal just inside each bound and commit precision. + let codec = self.decimals.map_or_else(|| self.inner.clone(), |places| self.inner.clone().at_most(places)); + let (low, high) = (self.rule.low, self.rule.high); + let place = 10f64.powi(-i32::try_from(codec.decimals()).unwrap_or(i32::MAX)); + let inside = |end: f64, other: f64| (codec.decimals() > 0 && (other - end).abs() >= place).then(|| end + place.copysign(other - end)); + [Some(low), Some(high), inside(low, high), inside(high, low)].map(|number| number.map(|number| codec.format(&Some(number)))) + } else { + [Some(self.format(current)), None, None, None] + }; + samples.into_iter().flatten() + } + fn held(&self, number: f64) -> f64 { let snapped = if self.snap { self.rule.snap(number) } else { number }; self.rule.settle(self.decimals.map_or(snapped, |decimals| round_to(snapped, decimals))) @@ -205,14 +221,6 @@ impl Codec for Ruled { } fn sample(&self, current: &V) -> Cow<'_, str> { - match current.named() { - Some(_) => Cow::Owned(self.format(current)), - // A field that rounds what it commits shows no more places than that. - None if self.rule.low.is_finite() && self.rule.high.is_finite() => { - let codec = self.decimals.map_or_else(|| self.inner.clone(), |places| self.inner.clone().at_most(places)); - Cow::Owned(codec.widest(&(self.rule.low..=self.rule.high))) - } - None => Cow::Owned(self.format(current)), - } + Cow::Owned(self.samples(current).max_by_key(|text| text.chars().count()).unwrap_or_default()) } } diff --git a/crates/ui-widgets/tests/it/text/number_presentation.rs b/crates/ui-widgets/tests/it/text/number_presentation.rs index ce5c50ae7..1bdc94e42 100644 --- a/crates/ui-widgets/tests/it/text/number_presentation.rs +++ b/crates/ui-widgets/tests/it/text/number_presentation.rs @@ -1,6 +1,6 @@ //! Number-field alignment and type roles agree across measurement, resting paint and editing. -use craft_behavior::Mixed; +use craft_behavior::{Codec, Mixed, NumberCodec, Reader}; use craft_i18n::Direction; use craft_ui::contract::{Bind, Props as _, Show as _, Sizing}; use craft_ui::display::Text; @@ -8,7 +8,7 @@ use craft_ui::primitives::HAlign; use craft_ui::runtime::env::UnitKind; use craft_ui::style::TypeRole; use craft_ui::testing::{Fixture, trial}; -use craft_ui::text::NumberField; +use craft_ui::text::{NumberField, UnitPlacement}; use egui::{FontId, Key, Modifiers, Rect, Shape}; use std::cell::RefCell; use std::rc::Rc; @@ -55,7 +55,8 @@ fn edge(run: Rect, field: Rect, align: HAlign, rtl: bool) -> f32 { fn alignment_places_values_at_the_reading_edges_and_keeps_units_separate() { for direction in [Direction::Ltr, Direction::Rtl] { let rtl = direction == Direction::Rtl; - for with_unit in [false, true] { + for placement in [None, Some(UnitPlacement::Inside), Some(UnitPlacement::After)] { + let with_unit = placement == Some(UnitPlacement::Inside); let boxes: Rc>> = Rc::default(); let b = boxes.clone(); let mut fixture = Fixture::new(move |ui| { @@ -68,8 +69,8 @@ fn alignment_places_values_at_the_reading_edges_and_keeps_units_separate() { if align != HAlign::Center { field = field.align(align); } - if with_unit { - field = field.unit_kind(UnitKind::Percent); + if let Some(placement) = placement { + field = field.unit_kind(UnitKind::Percent).unit_placement(placement); } boxes.push(field.id_salt((at, which)).show(ui).response.rect); } @@ -97,6 +98,12 @@ fn alignment_places_values_at_the_reading_edges_and_keeps_units_separate() { } } } + if placement == Some(UnitPlacement::After) { + assert!( + runs.iter().all(|run| run.text != "%" || boxes.iter().all(|field| !field.contains_rect(run.rect))), + "outside units stay outside for every alignment" + ); + } // Different edge choices must actually move the short value, not all silently centre it. let offsets: Vec<_> = [0, 2, 4].into_iter().map(|at| shown(&runs, boxes[at], "5").rect.left() - boxes[at].left()).collect(); assert!( @@ -191,6 +198,50 @@ fn a_number_field_measures_and_paints_its_chosen_type_role() { rooms.iter().all(|room| (room - rooms[0]).abs() <= 1.0), "measurement uses the painted role, leaving the same padding and caret room: {rooms:?}" ); + assert_range_samples_fit(); +} + +fn assert_range_samples_fit() { + for (range, places, fixed, values) in [ + (100.0..=111.0, 0, true, vec![100.0, 111.0]), + (100.0..=111.0, 1, true, vec![100.0, 111.0, 100.1, 110.9]), + (0.0..=100.0, 1, false, vec![0.0, 100.0, 0.1, 99.9]), + ] { + let codec = NumberCodec::new(Reader::default(), places); + let codec = if fixed { codec.fixed() } else { codec }; + let expected: Vec<_> = values.iter().map(|value| codec.format(&Some(*value))).collect(); + let boxes: Rc>> = Rc::default(); + let b = boxes.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut boxes = b.borrow_mut(); + boxes.clear(); + for (at, value) in values.iter().copied().enumerate() { + for ranged in [false, true] { + let mut field = NumberField::new("N", Bind::given(Some(value))).role(TypeRole::Body).sizing(Sizing::Content); + field = if fixed { field.fixed_decimals(places) } else { field.codec(codec.clone()) }; + if ranged { + field = field.range(range.clone()); + } + boxes.push(field.id_salt((at, ranged)).show(ui).response.rect); + } + } + }); + fixture.settle(); + let boxes = boxes.borrow().clone(); + let runs = painted_runs(&mut fixture); + let required = boxes.iter().step_by(2).map(|rect| rect.width()).fold(0.0, f32::max); + for (at, text) in expected.iter().enumerate() { + shown(&runs, boxes[at * 2], text); + shown(&runs, boxes[at * 2 + 1], text); + assert!( + boxes[at * 2 + 1].width() + 0.5 >= required, + "a proportional range fits every bound and inside sample with its padding: {places}, {fixed}, {text}, {boxes:?}" + ); + } + if places == 0 { + assert!(boxes[0].width() > boxes[2].width() + 1.0, "the fixture really uses unequal-width Body digits for 100 and 111: {boxes:?}"); + } + } } #[trial] diff --git a/docs/contract-api.md b/docs/contract-api.md index 08caf938b..f099aaba1 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2702,7 +2702,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `craft_ui::primitives::GridLook`: `pub struct GridLook`. What the lines of a grid read from the tokens: the line colour and width, and the dash and gap lengths. - `pub fn of(tokens: &UiTokens) -> Self`. The grid look of `tokens`. - `craft_ui::primitives::GridStroke`: `pub enum GridStroke { Solid, Dashed, Dots }`. How the lines of a grid are drawn. -- `craft_ui::primitives::HAlign`: `pub enum HAlign { Start, Center, End }`. Where the lines of a multi-line run sit within the run's width. +- `craft_ui::primitives::HAlign`: `pub enum HAlign { Start, Center, End }`. Horizontal placement in reading order: within a text run's width, or a text input's room. - `craft_ui::primitives::Handle`: `pub struct Handle`. The handle painter. - `pub fn shapes(look: &HandleLook, shape: HandleShape, center: Pos2, state: &StateSet) -> Vec`. The shapes of a handle of `shape` centred on `center`, filled for `state`. - `craft_ui::primitives::HandleShape`: `pub enum HandleShape { Square, Circle, Diamond }`. The outline of a handle. @@ -2795,7 +2795,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `pub const fn key(self) -> PartKey`. The part key. - `craft_ui::primitives::TextLayout`: `pub struct TextLayout { pub galley: Arc, pub elided: bool, pub full: String, pub first_baseline: f32, pub runs: Vec, pub rotation: f32 }`. A laid-out run. - `pub fn size(&self) -> egui::Vec2`. The galley size. -- `craft_ui::primitives::TextOptions`: `pub struct TextOptions { pub placeholder: Option