From 1299dc7c345af95c68aae7759ac81d989888a13e Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 21:54:55 +0100 Subject: [PATCH] Size number ranges by shaped width A field over a range is sized for the widest value the range can show, which a mono face makes its longest one. In the inline look the value is painted in the proportional label face, where a shorter value can shape wider than a longer one ("100" beside "111"), so the field kept the room of whichever candidate `NumberCodec::widest` counted longest and cut off the other. The measurement piece is taken from #1793 by @skylartaylor. `Ruled::samples` gives those candidates apart, at most four, each written with its unit, and `NumberField::measure` measures every one in the face it paints and keeps the widest, for the plain and the derived value alike; the blank branch is unchanged. `Codec::sample` keeps its character- count choice for the callers that use it. A trial sizes a range whose two ends are three characters each in the inline look against fields over no range, which are sized by their own value alone: the range must find the room of the wider end. --- crates/ui-widgets/src/text/number.rs | 32 ++++++++----- crates/ui-widgets/src/text/number/rule.rs | 29 +++++++---- crates/ui-widgets/tests/it/text/mod.rs | 1 + .../ui-widgets/tests/it/text/number_width.rs | 48 +++++++++++++++++++ 4 files changed, 88 insertions(+), 22 deletions(-) create mode 100644 crates/ui-widgets/tests/it/text/number_width.rs diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index c1bd4db826..2f06e14b92 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -26,7 +26,6 @@ use craft_behavior::{ }; use craft_theme::{Rgba, Stateful, States}; use egui::{CornerRadius, Rect, Vec2}; -use std::borrow::Cow; use std::marker::PhantomData; use std::ops::RangeInclusive; @@ -718,26 +717,33 @@ impl Component for NumberField<'_, V> { fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { self.settle(&cx.env); let codec = self.ruled(&cx.env, false, self.names(|row| cx.env.resolve(&row.label().clone()))); - // The value area holds the widest value the field shows (the range's ends at the codec's precision, or at the - // places it commits when it rounds what it commits, or the value when the range is open) with the caret and the unit, at most one number cell; a longer value scrolls - // inside it. The inside label and the chevrons take their own room beside it, each as `place` gives it. The - // field is never narrower than a cell, so a column of short fields ends at one edge. A content-sized field - // takes its whole value and has no floor; in a column group its value area is the group's widest. + // The value area holds the widest value the field shows, shaped in the face it paints (the range's ends at the + // codec's precision, or at the places it commits when it rounds what it commits, or the value when the range is + // open) with the caret and the unit, at most one number cell; a longer value scrolls inside it. The inside + // label and the chevrons take their own room beside it, each as `place` gives it. The field is never narrower + // than a cell, so a column of short fields ends at one edge. A content-sized field takes its whole value and + // has no floor; in a column group its value area is the group's widest. 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 shown = cx.value(); let no_zoom_value = self.status_zoom && self.shows_blank(shown); - let (sample, role) = if no_zoom_value { + let mut text = if no_zoom_value { // Text editors draw their hint in the proportional face. - (Cow::Borrowed(BLANK), self.options.role) - } else if self.derives(shown) { - // A derived value is sized as it shows at rest, in parentheses with its unit. - (Cow::Owned(self.derived_text(&codec.sample(shown.unwrap_or(&blank)), &cx.env.units())), self.value_role()) + cx.field_text(&TextRun::new(BLANK).role(self.options.role)) } else { - (codec.sample(shown.unwrap_or(&blank)), self.value_role()) + // Every value the field is sized for, shaped in the face it paints: a proportional face sets a shorter + // value wider than a longer one ("100" beside "111"), so the widest of them takes the value area. A derived + // value is sized as it shows at rest, in parentheses with its unit. + let derived = self.derives(shown); + let role = self.value_role(); + let units = cx.env.units(); + codec + .samples(shown.unwrap_or(&blank)) + .map(|sample| if derived { self.derived_text(sample.as_str(), &units) } else { sample }) + .map(|sample| cx.field_text(&TextRun::new(sample.as_str()).role(role))) + .fold(Vec2::ZERO, Vec2::max) }; - let mut text = cx.field_text(&TextRun::new(sample.as_ref()).role(role)); 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 4368203c97..13ec69b1b8 100644 --- a/crates/ui-widgets/src/text/number/rule.rs +++ b/crates/ui-widgets/src/text/number/rule.rs @@ -138,6 +138,25 @@ impl Clone for Ruled { } impl Ruled { + /// The texts the field is sized for: both ends of the range and the number one place of the last decimal just + /// inside each, at most four, each written with its unit; for a name or an open range, the value alone. These are + /// the candidates [`NumberCodec::widest`] weighs by character count, kept apart so a field can weigh them by the + /// width they take in the face it paints. + pub(super) fn samples(&self, current: &V) -> impl Iterator { + let samples: Vec = if current.named().is_none() && self.rule.low.is_finite() && self.rule.high.is_finite() { + // A field that rounds what it commits shows no more places than that. + 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)); + let written = |number: f64| self.written(codec.format(&Some(number))); + [Some(low), Some(high), inside(low, high), inside(high, low)].into_iter().flatten().map(written).collect() + } else { + vec![self.format(current)] + }; + samples.into_iter() + } + 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))) @@ -231,14 +250,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(self.written(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/mod.rs b/crates/ui-widgets/tests/it/text/mod.rs index 57a72fe228..0382b549b6 100644 --- a/crates/ui-widgets/tests/it/text/mod.rs +++ b/crates/ui-widgets/tests/it/text/mod.rs @@ -14,6 +14,7 @@ pub(crate) mod number_length; pub(crate) mod number_look; pub(crate) mod number_scrub_step; pub(crate) mod number_select; +pub(crate) mod number_width; pub(crate) mod rtl_paragraph; pub(crate) mod selectable; pub(crate) mod step_arrows; diff --git a/crates/ui-widgets/tests/it/text/number_width.rs b/crates/ui-widgets/tests/it/text/number_width.rs new file mode 100644 index 0000000000..e11dfe9c0d --- /dev/null +++ b/crates/ui-widgets/tests/it/text/number_width.rs @@ -0,0 +1,48 @@ +//! A number field is sized by the shaped width of the widest value it shows, not by the longest text. + +use craft_ui::contract::{Bind, Props as _, Show as _, Sizing}; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::{NumberField, NumberLook}; +use std::cell::Cell; +use std::rc::Rc; + +/// The ends of a range whose two texts are the same length and different widths: the inline look sets the number in +/// the proportional face, where "1" is narrower than "0", so "100" is wider than "111". +const LOW: f64 = 100.0; +const HIGH: f64 = 111.0; + +/// The widths of three content-sized fields in the inline look: one over the range showing its low end, and one over +/// no range for each end, which is sized by that value alone. +fn widths() -> [f32; 3] { + let shown = Rc::new(Cell::new([0.0; 3])); + let seen = shown.clone(); + let mut fixture = Fixture::new(move |ui| { + let width = |ui: &mut egui::Ui, value: Option, ranged: bool, salt: &'static str| { + let mut field = NumberField::new("N", Bind::given(value)).fixed_decimals(0).sizing(Sizing::Content).id_salt(salt); + if ranged { + field = field.range(LOW..=HIGH); + } + field.show(ui).response.rect.width() + }; + seen.set([width(ui, Some(LOW), true, "range"), width(ui, Some(LOW), false, "low"), width(ui, Some(HIGH), false, "high")]); + }); + fixture.root_value(NumberLook::Inline); + fixture.settle(); + shown.get() +} + +/// A field over a range is as wide as the widest value the range can show, measured in the face it paints. Both ends +/// of this range are three characters long, so a field sized by the longest text is sized by only one of them: "100" +/// and "111" set at different widths in the proportional label face, and the field over the range keeps the narrower +/// one's room, so its text is clipped whenever it shows the wider value. The fields over no range are sized by their +/// own value alone, which gives the room each end needs; the field over the range must find at least that much. +/// +/// Without the fix `Ruled::sample` keeps whichever candidate `NumberCodec::widest` counts longest, which for two ends +/// of three characters is the last of them, "111": the first assertion passes and the second fails. +#[trial] +fn a_range_is_sized_by_the_shaped_width_of_every_value_it_shows() { + let [ranged, low, high] = widths(); + assert!(low > high + 1.0, "the label face sets 100 wider than 111: {low} against {high}"); + assert!(ranged + 0.5 >= low, "the range is as wide as its wider end: {ranged} against {low}"); + assert!(ranged + 0.5 >= high, "the range is as wide as its other end: {ranged} against {high}"); +}