Adapt number presentation to next and measure proportional ranges

This commit is contained in:
skylar
2026-11-17 22:43:12 +01:00
parent 3f60bb042c
commit 3dd1f11771
4 changed files with 76 additions and 25 deletions
+1 -9
View File
@@ -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<V: NumberValue + 'static> Component for NumberField<'_, V> {
const ROLE: Role = Role::SPIN_BUTTON;
@@ -462,8 +455,7 @@ impl<V: NumberValue + 'static> 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));
}
+17 -9
View File
@@ -131,6 +131,22 @@ impl<V> Clone for Ruled<V> {
}
impl<V: NumberValue> Ruled<V> {
/// 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<Item = String> {
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<V: NumberValue> Codec for Ruled<V> {
}
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())
}
}
@@ -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<RefCell<Vec<Rect>>> = 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<RefCell<Vec<Rect>>> = 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]
+2 -2
View File
@@ -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<Shape>`. 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<Galley>, pub elided: bool, pub full: String, pub first_baseline: f32, pub runs: Vec<LayoutRun>, 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<Label>, pub lines: Option<usize>, pub limit: Option<usize>, pub mask: bool, pub live: bool, pub clear_on_escape: bool, pub mono: bool, pub role: TypeRole, pub ink: Option<Ink>, pub tab_inserts: bool, pub complete: Option<Arc<dyn Completer>>, pub complete_on_enter: bool, pub replace_selection: Option<String>, pub commit_on: &'static [char], pub enabled: bool, pub steps_value: bool, pub select_on_focus: bool, pub submits: bool, pub mixed: bool, pub centred: bool, pub arrows_from_end: bool, pub unparsed: Option<Message>, pub own_menu: bool }`. How a text part behaves beyond its codec.
- `craft_ui::primitives::TextOptions`: `pub struct TextOptions { pub placeholder: Option<Label>, pub lines: Option<usize>, pub limit: Option<usize>, pub mask: bool, pub live: bool, pub clear_on_escape: bool, pub mono: bool, pub role: TypeRole, pub ink: Option<Ink>, pub tab_inserts: bool, pub complete: Option<Arc<dyn Completer>>, pub complete_on_enter: bool, pub replace_selection: Option<String>, pub commit_on: &'static [char], pub enabled: bool, pub steps_value: bool, pub select_on_focus: bool, pub submits: bool, pub mixed: bool, pub align: HAlign, pub arrows_from_end: bool, pub unparsed: Option<Message>, pub own_menu: bool }`. How a text part behaves beyond its codec.
- `pub fn new() -> Self`. Options with every default.
- `craft_ui::primitives::TextOutcome`: `pub struct TextOutcome<V> { pub rect: Rect, pub draft: Option<String>, pub value: Option<V>, pub layout: Option<super::TextLayout>, pub caret_visible: bool, pub invalid: bool, pub committed_tag: Option<u32>, pub composing: bool, pub completions: Vec<super::Completion> }`. A text part's result this pass.
- `pub const fn new(rect: Rect) -> Self`. An outcome over `rect` with no draft or value.