diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index b7a0d27f7..fa2756b26 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -15,7 +15,7 @@ use crate::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, Entry, Focus as _, Input, MeasureCx, Numeric, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Role, Scrub, Sizing, Styled as _, WordSetCx as _, }; -use crate::primitives::{TextOptions, TextRun}; +use crate::primitives::{Span, TextOptions, TextRun}; use crate::runtime::env::{Label, LengthUnits, UnitKind, Units}; use crate::style::{ComponentStyle, StyleColor, StyleCx, SurfaceLook, TextLook, TypeRole}; use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps}; @@ -208,7 +208,9 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { fixed_decimals: None, lengths: None, scale: 1.0, - options: TextOptions::default(), + // The value sits in the middle of its room in the monospace face, the presentation every number field has + // had; `centred` and `mono` let a caller choose either independently. + options: TextOptions { centred: true, mono: true, ..TextOptions::default() }, scrub: false, track: 0.0, picked: None, @@ -241,6 +243,25 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { self } + /// Where the value sits in the room the field leaves for it: in the middle (the default), or at the logical reading + /// start, the edge the text is read from — the left edge in a left-to-right interface, the right edge in a + /// right-to-left one. The unit keeps its place at the end of the field either way, so a column of fields lines its + /// units up whichever presentation its values take. + #[must_use] + pub fn centred(mut self, centred: bool) -> Self { + self.options.centred = centred; + self + } + + /// The face the value is set in: monospace, whose digits share one advance so values keep their places as they + /// change (the default), or the UI body face. The face is the one the field measures its value in, paints it in and + /// edits it in, so the room a value takes is the room its text and caret fill. + #[must_use] + pub fn mono(mut self, mono: bool) -> Self { + self.options.mono = mono; + self + } + /// The range and step in the shown unit. fn rule(&self) -> Rule { let range = self.range.as_ref().map(|range| range.start() * self.scale..=range.end() * self.scale); @@ -391,6 +412,14 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { decimals: self.shown_decimals(), } } + + /// The run the value is measured in: the role and the face of the text part's options, which is the one rule the + /// text adapter lays the shown and edited text out by (`tokens.font` reads the mono face from the span, else the + /// role's). A measure that named the face by itself would size a proportional field's value in the mono face. + 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; @@ -435,7 +464,7 @@ impl Component for NumberField<'_, V> { // 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(&TextRun::new(sample.as_ref()).role(TypeRole::Mono)); + let mut text = cx.field_text(&self.value_run(sample.as_ref())); if content { text.x = crate::layout::ambient_width(cx.ui.ctx(), &VALUES, text.x).map_or(text.x, |width| width.max(text.x)); } @@ -465,8 +494,6 @@ impl Component for NumberField<'_, V> { cx.label_part(*slot); } let text = placed.text; - self.options.centred = true; - self.options.mono = true; self.options.steps_value = self.presets.is_none() && self.popup_slider.is_none(); let shown = cx.value(); if self.options.placeholder.is_none() { diff --git a/crates/ui-widgets/src/text/number/stories.rs b/crates/ui-widgets/src/text/number/stories.rs index 737428191..d81283609 100644 --- a/crates/ui-widgets/src/text/number/stories.rs +++ b/crates/ui-widgets/src/text/number/stories.rs @@ -109,6 +109,31 @@ fn number_field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { out.inner.flatten().map(StoryOutput::from).unwrap_or_default() } +/// The two presentation choices on their own and together: the value centred or started at the reading start, set in the +/// monospace face or the UI body face, over the same range. +#[story(NumberField<'static>, covers = [], drive = Drive::Type("42"))] +fn number_field_presentation(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let out = FieldGroup::new("Number field presentation").show(ui, |ui, _| { + let first = row("Centred, mono") + .show(ui, |ui, _| NumberField::new("Centred, mono", Bind::bound(data.value("centred_mono", Some(SIZE)))).range(RANGE).show(ui).edit); + row("Started, mono").show(ui, |ui, _| { + NumberField::new("Started, mono", Bind::bound(data.value("started_mono", Some(SIZE)))).range(RANGE).centred(false).show(ui); + }); + row("Centred, proportional").show(ui, |ui, _| { + NumberField::new("Centred, proportional", Bind::bound(data.value("centred_ui", Some(SIZE)))).range(RANGE).mono(false).show(ui); + }); + row("Started, proportional").show(ui, |ui, _| { + NumberField::new("Started, proportional", Bind::bound(data.value("started_ui", Some(SIZE)))) + .range(RANGE) + .centred(false) + .mono(false) + .show(ui); + }); + first.inner + }); + out.inner.flatten().map(StoryOutput::from).unwrap_or_default() +} + #[story(NumberField<'static>, covers = [LongText], drive = Drive::Never)] fn number_field_long(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { NumberField::new("Size", Bind::bound(data.value("long", Some(HUGE)))).show(ui).edit.into() diff --git a/crates/ui-widgets/tests/it/text/mod.rs b/crates/ui-widgets/tests/it/text/mod.rs index d6e55d6f6..d8487c79c 100644 --- a/crates/ui-widgets/tests/it/text/mod.rs +++ b/crates/ui-widgets/tests/it/text/mod.rs @@ -8,6 +8,7 @@ mod linked; mod mixed_blank; mod number; mod number_length; +mod number_presentation; mod selectable; mod text_field; mod widths; diff --git a/crates/ui-widgets/tests/it/text/number_presentation.rs b/crates/ui-widgets/tests/it/text/number_presentation.rs new file mode 100644 index 000000000..c57f89665 --- /dev/null +++ b/crates/ui-widgets/tests/it/text/number_presentation.rs @@ -0,0 +1,237 @@ +//! Where a number field puts its value and the face it sets it in: `centred` and `mono`, either of them off, on their +//! own and together, in measure, paint and editing. + +use craft_behavior::Mixed; +use craft_i18n::Direction; +use craft_ui::contract::{Bind, Props as _, Show as _, Sizing}; +use craft_ui::runtime::env::UnitKind; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::NumberField; +use egui::{FontFamily, Key, Modifiers, Rect, Shape}; +use std::cell::RefCell; +use std::rc::Rc; + +/// The texts a frame painted, each with where it lies and the face it is set in. +fn painted(shapes: &[Shape]) -> Vec<(String, Rect, FontFamily, f32)> { + shapes + .iter() + .filter_map(|shape| match shape { + Shape::Text(text) => { + let font = text.galley.job.sections.first()?.format.font_id.clone(); + let rect = text.galley.rect.translate(text.pos.to_vec2()); + Some((text.galley.job.text.clone(), rect, font.family, font.size)) + } + _ => None, + }) + .collect() +} + +/// The painted run of `text` that lies inside `field`, from the frame's shapes. +fn run<'a>(runs: &'a [(String, Rect, FontFamily, f32)], field: Rect, text: &str) -> Option<&'a (String, Rect, FontFamily, f32)> { + runs.iter().find(|run| run.0 == text && field.expand(1.0).contains_rect(run.1)) +} + +/// The rect of the value `text` a frame of `fixture` painted inside `field`. +fn value_in(fixture: &Fixture, field: Rect, text: &str) -> Rect { + let found = fixture.texts().iter().find(|run| run.text == text && field.expand(1.0).contains_rect(run.rect)); + match found { + Some(run) => run.rect, + None => panic!("{field:?} paints no {text}: {:?}", fixture.texts().iter().map(|run| run.text.clone()).collect::>()), + } +} + +/// The rect of the one run inside `field` that is not the value `text`: the field's unit. +fn beside_in(fixture: &Fixture, field: Rect, text: &str) -> Rect { + let found = fixture.texts().iter().find(|run| run.text != text && field.expand(1.0).contains_rect(run.rect)); + match found { + Some(run) => run.rect, + None => panic!("{field:?} paints no unit beside {text}: {:?}", fixture.texts().iter().map(|run| run.text.clone()).collect::>()), + } +} + +/// Two settled fields of one presentation: "5" and "100" over one range and of one width, so where the fields put them +/// says where that presentation puts values of other widths. +struct Pair { + fixture: Fixture, + fields: Vec, +} + +impl Pair { + fn new(started: bool, direction: Option) -> Pair { + let boxes: Rc>> = Rc::default(); + let b = boxes.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut v = b.borrow_mut(); + v.clear(); + for (at, value) in [5.0, 100.0].into_iter().enumerate() { + v.push(NumberField::new("N", Bind::given(Some(value))).range(0.0..=100.0).centred(!started).id_salt(at).show(ui).response.rect); + } + }); + if let Some(direction) = direction { + fixture.direction(direction); + } + fixture.settle(); + let fields = boxes.borrow().clone(); + Pair { fixture, fields } + } + + /// The rects of the two values, "5" and "100". + fn values(&self) -> [Rect; 2] { + [value_in(&self.fixture, self.fields[0], "5"), value_in(&self.fixture, self.fields[1], "100")] + } +} + +/// The presentation every number field has had: the value centred in the room the field leaves for it, in the monospace +/// face. A value of another width keeps its centre, and `centred(false)` starts it at the reading start instead, which in +/// a left-to-right interface is the field's left edge. +#[trial] +fn a_field_centres_its_value_in_the_mono_face_unless_told_to_start_it() { + let mut centred = Pair::new(false, None); + let started = Pair::new(true, None); + let (c, s) = (centred.values(), started.values()); + assert!((c[0].center().x - c[1].center().x).abs() <= 0.5, "centred values of other widths share a centre: {c:?}"); + assert!((c[0].left() - c[1].left()).abs() > 2.0, "centred values of other widths start at other places: {c:?}"); + assert!((s[0].left() - s[1].left()).abs() <= 0.5, "started values share the reading start: {s:?}"); + assert!(s[1].left() < started.fields[1].center().x - 2.0, "a started value sits at the field's start, not its centre: {:?}", s[1]); + // The default presentation sets the value in the monospace face: both fields' values are mono runs. + let runs = painted(¢red.fixture.frame_shapes()); + let values: Vec<&(String, Rect, FontFamily, f32)> = runs.iter().filter(|run| run.0 == "5" || run.0 == "100").collect(); + assert_eq!(values.len(), 2, "the two fields paint their two values: {runs:?}"); + assert!(values.iter().all(|run| run.2 == FontFamily::Monospace), "a value is set in the mono face by default: {runs:?}"); +} + +/// `mono(false)` sets the value in the UI body face, and the face is the one the field measures its value in too: a +/// content-sized field is its value, its caret and its padding wide, so the room the field takes is the room its text +/// fills in either face. +#[trial] +fn the_mono_choice_sets_the_face_the_field_paints_and_measures() { + let boxes: Rc>> = Rc::default(); + let b = boxes.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut v = b.borrow_mut(); + v.clear(); + for (at, mono) in [true, false].into_iter().enumerate() { + v.push(NumberField::new("N", Bind::given(Some(111.0))).mono(mono).sizing(Sizing::Content).id_salt(at).show(ui).response.rect); + } + }); + fixture.settle(); + let fields = boxes.borrow().clone(); + let runs = painted(&fixture.frame_shapes()); + let family = |field: Rect| run(&runs, field, "111").map(|run| run.2.clone()); + assert_eq!(family(fields[0]), Some(FontFamily::Monospace), "a field sets its value in the mono face by default: {runs:?}"); + assert_eq!(family(fields[1]), Some(FontFamily::Proportional), "mono(false) sets the value in the UI body face: {runs:?}"); + let room = |field: Rect| { + let value = value_in(&fixture, field, "111"); + assert!(field.expand(1.0).contains_rect(value), "the field is as wide as the value it measured: {value:?} in {field:?}"); + // The padding and the caret's room are the field's own in either face; the value is all that the face changes. + field.width() - value.width() + }; + let (mono, proportional) = (room(fields[0]), room(fields[1])); + // The box and the text are laid out at the points the field's measure gives them, so a face the measure missed would + // leave a different room around the value by the whole of an advance. + assert!((mono - proportional).abs() <= 1.0, "the field measures the face it paints: {mono} beside {proportional}"); +} + +/// A started value keeps the field's unit where the field always put it: at the end, apart from the number, so a column +/// of fields still lines its units up. +#[trial] +fn a_started_value_keeps_its_unit_at_the_end_of_the_field() { + let boxes: Rc>> = Rc::default(); + let b = boxes.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut v = b.borrow_mut(); + v.clear(); + for (at, value) in [5.0, 100.0].into_iter().enumerate() { + let field = NumberField::new("N", Bind::given(Some(value))).range(0.0..=100.0).unit_kind(UnitKind::Percent).centred(false).id_salt(at); + v.push(field.show(ui).response.rect); + } + }); + fixture.settle(); + let fields = boxes.borrow().clone(); + let numbers = [value_in(&fixture, fields[0], "5"), value_in(&fixture, fields[1], "100")]; + let units = [beside_in(&fixture, fields[0], "5"), beside_in(&fixture, fields[1], "100")]; + assert!((numbers[0].left() - numbers[1].left()).abs() <= 0.5, "started values share the reading start beside a unit: {numbers:?}"); + assert!((units[0].right() - units[1].right()).abs() <= 0.5, "the units end at one place from the field's end: {units:?}"); + assert!(numbers[1].right() < units[1].left(), "the unit stands apart from the number: {numbers:?} {units:?}"); +} + +/// A started value follows a right-to-left interface: the reading start is the field's right edge there, and a centred +/// value keeps the field's centre whatever the direction. +#[trial] +fn a_started_value_follows_a_right_to_left_interface() { + let centred = Pair::new(false, Some(Direction::Rtl)); + let started = Pair::new(true, Some(Direction::Rtl)); + let (c, s) = (centred.values(), started.values()); + assert!((c[0].center().x - c[1].center().x).abs() <= 0.5, "centred values share a centre under right-to-left: {c:?}"); + assert!((s[0].right() - s[1].right()).abs() <= 0.5, "started values share the reading start, the right edge, under right-to-left: {s:?}"); + assert!(s[1].right() > started.fields[1].center().x + 2.0, "a started value sits at the field's right edge: {:?}", s[1]); +} + +/// The caret sits beside the value wherever the field puts it: after the last digit at End and before the first at Home, +/// inside the field's own box, centred or started, mono or not. An editing field lays its text out as its measure did. +#[trial] +fn the_caret_follows_the_value_wherever_the_field_puts_it() { + for (centred, mono) in [(true, true), (false, true), (false, false)] { + let boxes: Rc>> = Rc::default(); + let b = boxes.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut v = b.borrow_mut(); + v.clear(); + v.push( + NumberField::new("N", Bind::given(Some(100.0))) + .centred(centred) + .mono(mono) + .sizing(Sizing::Content) + .id_salt("n") + .show(ui) + .response + .rect, + ); + }); + fixture.settle(); + let field = boxes.borrow()[0]; + let value = value_in(&fixture, field, "100"); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + fixture.key(Key::End, Modifiers::NONE); + let end = fixture.ime().expect("a field in edit reports its caret").caret; + fixture.key(Key::Home, Modifiers::NONE); + let home = fixture.ime().expect("a field in edit reports its caret").caret; + let which = format!("centred {centred}, mono {mono}"); + assert!((end.min.x - value.right()).abs() <= 1.5, "the caret at End sits after the value {value:?}: {end:?} ({which})"); + assert!((home.min.x - value.left()).abs() <= 1.5, "the caret at Home sits before the value {value:?}: {home:?} ({which})"); + assert!( + field.expand(1.5).contains_rect(end) && field.expand(1.5).contains_rect(home), + "the caret stays in the field {field:?}: {end:?} {home:?} ({which})" + ); + } +} + +/// A mixed field's dash and a disabled field's value are presented like any other value: `centred(false)` starts them at +/// the reading start too, so a field keeps its look when it holds no value or cannot be edited. +#[trial] +fn a_mixed_or_disabled_field_keeps_the_presentation_it_is_given() { + let boxes: Rc>> = Rc::default(); + let b = boxes.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut v = b.borrow_mut(); + v.clear(); + let mut mixed = Mixed::>::Mixed; + v.push(NumberField::new("Mixed", Bind::bound_mixed(&mut mixed)).range(0.0..=100.0).centred(false).id_salt("mixed").show(ui).response.rect); + v.push( + NumberField::new("Off", Bind::given(Some(100.0))).range(0.0..=100.0).centred(false).enabled(false).id_salt("off").show(ui).response.rect, + ); + }); + fixture.settle(); + let fields = boxes.borrow().clone(); + let dash = { + let found = fixture.texts().iter().find(|run| fields[0].expand(1.0).contains_rect(run.rect)).map(|run| run.rect); + match found { + Some(rect) => rect, + None => panic!("a mixed field paints its dash: {:?}", fixture.texts().iter().map(|run| run.text.clone()).collect::>()), + } + }; + assert!(dash.left() < fields[0].center().x - 2.0, "the mixed dash starts at the field's start: {dash:?} in {:?}", fields[0]); + let value = value_in(&fixture, fields[1], "100"); + assert!(value.left() < fields[1].center().x - 2.0, "a disabled value starts at the field's start: {value:?} in {:?}", fields[1]); +}