diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 2ab15f72bf..b8933d6690 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -243,7 +243,8 @@ pub(crate) struct TextEnv<'a> { /// The baseline of a control's line of `role` whose centre line lies at `centre`: where a one-line text of `role` in /// its own face sits with its row centred on the centre line, as `Draw::text` centres a line in a taller rect. Every /// text in the line sits on it, whatever its face or size: a select's face, a field's mono digits and the smaller unit -/// after them. +/// after them. A text part set at a size of the caller's own is the one text that centres its own row on its part +/// instead, since a row taller than the role's would carry the part's text out of it (`TextOptions::size`). pub(crate) fn line_baseline(ctx: &Context, env: &TextEnv<'_>, role: TypeRole, centre: f32) -> f32 { let line = TextRun::new("x").role(role).layout(ctx, env, f32::INFINITY); centre - line.size().y / 2.0 + line.first_baseline diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index 5abdc1bac0..bca14179b7 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -79,7 +79,8 @@ pub struct TextOptions { pub role: TypeRole, /// The text size in points in place of the role's, for text whose size is the user's to choose (a document /// editor's text size); the face stays the role's. `None` takes the role's size. The component sizes the part for - /// it, since a role's line height no longer measures the text. + /// it, since a role's line height no longer measures the text: a single-line part centres that row on the part + /// rather than on the role's baseline, which a row taller than the role's would leave. pub size: Option, /// A multi-line text starts at the top of its part; unset, it is centred on the part's height, as a single line is. pub top: bool, diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 9bcb7c1ac5..57154e41a9 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -48,7 +48,8 @@ pub(crate) struct Edit<'a> { /// is not clipped to `rect`. pub galley: Option>, /// The screen y of the baseline a single line without a laid-out galley sits on: its control's line's, which a - /// text in another face (mono digits) shares. `None` centres the line's row on the rect's centre line. + /// text in another face (mono digits) shares. `None` centres the line's row on the rect's centre line, and a text + /// whose size is the caller's own is centred there whatever this says. pub baseline: Option, /// How far a multi-line text taller than `rect` is scrolled up inside it, in points; the text part owns the offset /// (`text_adapter`), and a single line or a laid-out galley ignores it. @@ -159,7 +160,8 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) let hint_text = hint.map(|hint| egui::RichText::new(hint).font(FontId::proportional(font_id.size))); // A single-line edit runs in a rect one text row tall, or the part's height when that is taller, placed so the // text's baseline is `baseline`, else centred on the part's centre line. egui centres the row in the rect, whatever - // row it allocates from the rect's top. + // row it allocates from the rect's top. A text whose size is the caller's own is centred on the part too: its row is + // taller than the role's, so the role's baseline would lift the row and its clip out of the top of the part. let rect = if multiline || galley.is_some() { rect } else { @@ -174,7 +176,10 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) }; let row = probe.size().y; let first_baseline = probe.rows.first().and_then(|placed| placed.row.glyphs.first().map(|glyph| placed.pos.y + glyph.pos.y)); - let centre = match baseline.zip(first_baseline) { + // The row sits on the control's baseline, which every text of the line shares. A size of the caller's own sets + // a row taller than the role's that this baseline would carry out of the part's top, so that row is centred on + // the part's centre line instead, where the role's own row sits. + let centre = match baseline.zip(first_baseline).filter(|_| size.is_none()) { Some((baseline, first)) => baseline - first + row / 2.0, None => rect.center().y, }; diff --git a/crates/ui-contract/tests/it/text/mod.rs b/crates/ui-contract/tests/it/text/mod.rs index 67ebf9abe0..a30a7cbd14 100644 --- a/crates/ui-contract/tests/it/text/mod.rs +++ b/crates/ui-contract/tests/it/text/mod.rs @@ -3,3 +3,4 @@ pub(crate) mod editor; pub(crate) mod input_cap; pub(crate) mod memo; pub(crate) mod resting; +pub(crate) mod sized; diff --git a/crates/ui-contract/tests/it/text/sized.rs b/crates/ui-contract/tests/it/text/sized.rs new file mode 100644 index 0000000000..8b5b69ca04 --- /dev/null +++ b/crates/ui-contract/tests/it/text/sized.rs @@ -0,0 +1,126 @@ +//! A single-line text part set at a size of the caller's own: its row is taller than the role's and still lies in the +//! part, on the part's centre line where the role's own row sits. + +use craft_behavior::{PartKey, PlainText, Sense}; +use craft_ui::contract::{ + Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _, +}; +use craft_ui::primitives::{TextKey, TextOptions}; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Rect, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; + +const TEXT: PartKey = PartKey::new("text"); + +/// A size of the caller's own, well above the body role's: its row is much taller than the role's. +const LARGE: f32 = 40.0; + +/// A part far taller than the text it shows, to read off the row the text takes. +const ROOMY: f32 = 200.0; + +/// Half a point: rects compared across passes may round apart by that much. +const SNAP: f32 = 0.5; + +/// What the trial's paint read of the text part: the part's rect. +#[derive(Clone, Copy, Debug, Default)] +struct Painted { + part: Option, +} + +/// A single-line text part showing a value at a size the caller sets. +#[derive(Component)] +struct Sized<'a> { + #[common] + common: Common, + value: Bind<'a, String>, + size: Option, + height: f32, + painted: &'a RefCell, +} + +impl Component for Sized<'_> { + const ROLE: Role = Role::TEXT_INPUT; + const INPUT: Input = Input::Text; + const OVERLAYS: bool = false; + type Style = PlainStyle; + type Output = EditResponse; + + fn style(_: &StyleCx<'_>, _: SizedStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS + } + + /// The part's room: a component sizes the part for a text of the caller's own size, as tall as its row. + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(240.0, self.height) + } + + fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { + let options = TextOptions { size: self.size, ..TextOptions::default() }; + let (shown, rect) = (cx.value().cloned().unwrap_or_default(), cx.content_rect); + cx.text(TextKey::::new(TEXT), rect, &PlainText, &shown, &options); + } + + fn bind(&mut self) -> Option> { + Some(self.value.reborrow()) + } + + fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + if let Some(outcome) = cx.text(&TextKey::::new(TEXT)) { + self.painted.borrow_mut().part = Some(outcome.rect); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> EditResponse { + cx.edit_response() + } +} + +/// The part "42" is shown in at `size` in a part `height` tall, its painted row, and the clip the row is painted under. +fn sized(size: Option, height: f32) -> (Fixture, Rect, Rect, Rect) { + let (value, painted) = (Rc::new(RefCell::new(String::from("42"))), Rc::new(RefCell::new(Painted::default()))); + let (shown, read) = (value.clone(), painted.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut held = shown.borrow_mut(); + Sized { common: Common::new(), value: Bind::bound(&mut *held), size, height, painted: &read }.id_salt("sized").show(ui); + }); + fixture.settle(); + let part = painted.borrow().part.expect("the text part is laid out"); + let (row, clip) = { + let painted = fixture.texts().iter().find(|text| text.text == "42").expect("the value is painted"); + (painted.rect, painted.clip) + }; + (fixture, part, row, clip) +} + +/// A size of the caller's own sets a row taller than the role's, and the part a component sizes for it is as tall as +/// that row. The row keeps its place in the part, centred on the part's centre line where the role's own row sits, and +/// the clip that follows it stays inside: a baseline taken from the role would carry the taller row above the part's +/// top. Without a size the role's row keeps its place. +#[trial] +fn a_single_line_part_set_at_its_own_size_keeps_its_row_in_its_part() { + // A part far taller than the text shows what the row it lays out takes, and how much room a measure leaves the part. + let (_, roomy, taken, _) = sized(Some(LARGE), ROOMY); + let row_room = taken.height() + (ROOMY - roomy.height()); + let (_sized, part, row, clip) = sized(Some(LARGE), row_room); + let (_role, role_part, role_row, _) = sized(None, ROOMY); + assert!((part.height() - row.height()).abs() <= SNAP, "the part is as tall as the sized row: {part:?} vs {row:?}"); + assert!(row.height() > role_row.height() * 1.5, "{LARGE} points sets a taller row than the role's: {row:?} vs {role_row:?}"); + assert!( + role_row.top() >= role_part.top() - SNAP && role_row.bottom() <= role_part.bottom() + SNAP, + "the role's row lies in its part: {role_row:?} in {role_part:?}" + ); + assert!((role_row.center().y - role_part.center().y).abs() <= SNAP, "the role's row is centred on its part: {role_row:?} in {role_part:?}"); + assert!(row.top() >= part.top() - SNAP && row.bottom() <= part.bottom() + SNAP, "the sized row lies in its part: {row:?} in {part:?}"); + assert!((row.center().y - part.center().y).abs() <= SNAP, "the sized row is centred on its part: {row:?} in {part:?}"); + assert!( + clip.top() >= part.top() - SNAP && clip.bottom() <= part.bottom() + SNAP, + "the sized text is not clipped by a rect beyond the part: {clip:?} in {part:?}" + ); +} diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index e73b2966f3..a8a8dff820 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -842,9 +842,11 @@ impl Component for NumberField<'_, V> { // moves by a share of it. let decimals = self.decimals().max(decimals_for_step(step)); let scale = self.scale; - let mut scrub = - Scrub::new(drag, move |value: &V| value.number().unwrap_or(0.0) * scale, move |number| V::of_number(round_to(number, decimals) / scale)) - .on_field(); + // The rounded value is kept in the range after the rounding: a drag that runs into a range end finer than the + // decimals it rounds to carries the value past it (0.005 to 0.01), and the range holds the write at its end, + // as a typed value does. + let kept = move |number: f64| V::of_number(rule.settle(round_to(number, decimals)) / scale); + let mut scrub = Scrub::new(drag, move |value: &V| value.number().unwrap_or(0.0) * scale, kept).on_field(); if self.scrub { scrub = scrub.by_label(); } diff --git a/crates/ui-widgets/tests/it/text/number_scrub_step.rs b/crates/ui-widgets/tests/it/text/number_scrub_step.rs index 1e2a630f79..61506fb08e 100644 --- a/crates/ui-widgets/tests/it/text/number_scrub_step.rs +++ b/crates/ui-widgets/tests/it/text/number_scrub_step.rs @@ -50,6 +50,34 @@ fn a_separate_scrub_rate_keeps_fine_key_and_wheel_steps() { assert_eq!(value.get(), Some(80.02), "one wheel notch still adds one hundredth"); } +/// A field of `range`, `step` and `decimals` decimals, shown in its own `Field` so its caption scrubs it. +fn caption_field(start: f64, range: std::ops::RangeInclusive, step: f64, decimals: usize) -> (Fixture, Rc>>) { + let value = Rc::new(Cell::new(Some(start))); + let shown = Rc::clone(&value); + let mut fixture = Fixture::new(move |ui| { + Field::new("Opacity").side(SideLabel::new().scrub(true)).show(ui, |ui, _| { + let mut current = shown.get(); + NumberField::new("Opacity", Bind::bound(&mut current)).range(range.clone()).step(step).fixed_decimals(decimals).scrub_by_label().show(ui); + shown.set(current); + }); + }); + fixture.settle(); + (fixture, value) +} + +/// A scrub that runs into the end of a range finer than the decimals it rounds to keeps its write in the range: the +/// drag stops at the range's end, 0.005, which the write's decimals (two, from the step) round to 0.01, so the write +/// keeps the range's end after rounding, as a typed value does, rather than sending the value past its range. +#[trial] +fn a_scrub_into_a_range_finer_than_the_precision_keeps_the_range_end() { + let (mut fixture, value) = caption_field(0.0, 0.0..=0.005, 0.01, 0); + let caption = fixture.texts().iter().find(|text| text.text == "Opacity").expect("the visible scrub caption").rect; + fixture.drag_at(caption.center(), vec2(60.0, 0.0)).settle(); + let scrubbed = value.get().expect("the field holds a value"); + assert!(scrubbed > 0.0, "the drag moved the value to the end of the range: {scrubbed}"); + assert!(scrubbed <= 0.005, "a scrub stays in the field's range: {scrubbed}"); +} + #[trial] fn an_omitted_or_invalid_scrub_rate_uses_the_field_step() { for rate in [None, Some(0.0), Some(-1.0), Some(f64::NAN), Some(f64::INFINITY)] {