ui-widgets: NumberLook::Inline sets a number field's value and unit as one run at its start (720 pt, 0°, 100%)

This commit is contained in:
bflatastic
2026-11-24 12:33:34 +07:00
parent f2ee94bfc4
commit 8da5ec92a5
7 changed files with 234 additions and 40 deletions
+6
View File
@@ -467,6 +467,12 @@ impl Units {
self.template(kind).replace("{n}", "").trim().to_owned()
}
/// The text before and after the number in the user's language, spacing included: `("", " mm")`, `("", "%")`.
pub fn affixes(&self, kind: UnitKind) -> (String, String) {
let template = self.template(kind);
template.split_once("{n}").map_or_else(|| (String::new(), template.to_owned()), |(before, after)| (before.to_owned(), after.to_owned()))
}
/// The digits after the decimal mark `n` needs within `decimals`: the fewest that show it as it rounds at the most.
fn digits(n: f64, decimals: &RangeInclusive<usize>) -> usize {
let (least, most) = (*decimals.start(), *decimals.end());
+2 -1
View File
@@ -19,7 +19,8 @@ pub use chips::{ChipCodec, ChipField, ChipFieldOutput, ChipFieldStyle, ChipWords
pub use hex::{HexCodec, HexField};
pub use linked::{LinkMode, LinkedFields, LinkedFieldsStyle, LinkedLayout, LinkedOutput, LinkedWords, follow_equal, follow_ratio, link_toggle};
pub use number::{
NamedOr, NumberField, NumberName, NumberOutput, NumberPick, NumberStepper, NumberStyle, NumberValue, RangeAlert, StepArrows, UnitPlacement,
NamedOr, NumberField, NumberLook, NumberName, NumberOutput, NumberPick, NumberStepper, NumberStyle, NumberValue, RangeAlert, StepArrows,
UnitPlacement,
};
pub use selectable_text::{SelectableStyle, SelectableText};
pub use text_field::TextField;
+82 -22
View File
@@ -16,7 +16,7 @@ use crate::contract::{
PartsCx, Pointer as _, Props as _, Role, Scrub, Sizing, Styled as _, WordSetCx as _,
};
use crate::primitives::{TextOptions, TextRun};
use crate::runtime::env::{Label, LengthUnits, UnitKind, Units};
use crate::runtime::env::{EnvView, Label, LengthUnits, UnitKind, Units};
use crate::runtime::frame;
use crate::style::{ComponentStyle, StyleColor, StyleCx, SurfaceLook, TextLook, TypeRole};
use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps};
@@ -70,6 +70,21 @@ pub enum StepArrows {
Leading,
}
/// How a number field sets its value and unit. An app sets it once at its root (`RootEnv::values`); the default is
/// the centred number.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::runtime::env::EnvValue, crate::contract::MemoProps)]
#[env(style)]
#[non_exhaustive]
pub enum NumberLook {
/// The number centred in the mono face, the unit apart at the end of the value area in caption text, so a column
/// of fields lines its units up; a percentage stands against its sign at the end.
#[default]
Centred,
/// The number and its unit as one run ("720 pt", "0°", "100%") at the field's start, in the interface face and
/// the value's colour: editing shows the same text, and the caret and the selection go through the whole run.
Inline,
}
/// The placeholder of a mixed field.
const BLANK: &str = "\u{2014}";
@@ -190,6 +205,8 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
lengths: Option<LengthUnits>,
/// How many shown units make one stored unit, read from the env in measure and parts; 1 for a plain field.
scale: f64,
/// The scope's look, read from the env in measure and parts.
look: NumberLook,
options: TextOptions,
positive_only: bool,
scrub: bool,
@@ -268,6 +285,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
max_decimals: None,
lengths: None,
scale: 1.0,
look: NumberLook::Centred,
options: TextOptions::default(),
positive_only: false,
scrub: false,
@@ -326,22 +344,59 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
Rule::new(range.as_ref(), self.step)
}
/// Reads a length field's scale from stored to shown from the env.
fn settle_lengths(&mut self, units: &Units) {
/// Reads the scope's look and a length field's scale from stored to shown from the env. The status bar's zoom
/// well keeps its own look.
fn settle(&mut self, env: &EnvView<'_>) {
self.look = if self.status_zoom { NumberLook::Centred } else { env.get() };
if let Some(lengths) = self.lengths {
self.scale = units.length_scale(lengths).unwrap_or(1.0);
self.scale = env.units().length_scale(lengths).unwrap_or(1.0);
}
}
/// The unit drawn inside the field after the number: the field's own, else the symbol of its unit kind; none when
/// the host draws it after the field.
/// Whether the field draws its unit inside the box, not the host after the field.
fn unit_inside(&self) -> bool {
!self.status_zoom && self.unit_placement == UnitPlacement::Inside
}
/// The unit drawn apart inside the field after the number: the field's own, else the symbol of its unit kind;
/// none when the host draws it after the field or the number's run holds it.
fn shown_unit(&self, units: &Units) -> Option<Label> {
if self.status_zoom || self.unit_placement == UnitPlacement::After {
if !self.unit_inside() || self.look == NumberLook::Inline {
return None;
}
self.unit.clone().or_else(|| self.unit_kind.map(|kind| units.symbol(kind).into()))
}
/// The text the number's run holds around the number: the status zoom's sign; in the inline look the unit kind's
/// unit word, else the field's own unit, against the number when it is one sign ("%", "°") and after a space
/// otherwise.
fn affixes(&self, env: &EnvView<'_>) -> Option<(String, String)> {
if self.status_zoom {
return Some((String::new(), env.units().symbol(UnitKind::Percent)));
}
if !self.unit_inside() || self.look != NumberLook::Inline {
return None;
}
match (&self.unit, self.unit_kind) {
(Some(unit), _) => {
let unit = env.resolve(unit);
let mut chars = unit.as_str().chars();
let sign = chars.next().is_some_and(|c| !c.is_alphanumeric()) && chars.next().is_none();
Some((String::new(), if sign { unit.as_str().to_owned() } else { format!(" {}", unit.as_str()) }))
}
(None, Some(kind)) => Some(env.units().affixes(kind)),
(None, None) => None,
}
}
/// The face the number is set in: the mono face, or the interface's label face in the inline look.
fn value_role(&self) -> TypeRole {
match self.look {
NumberLook::Centred => TypeRole::Mono,
NumberLook::Inline => TypeRole::Label,
}
}
/// The unit drawn this pass. A mixed value shows the dash alone: a unit beside it would claim a measure the
/// selection does not have.
fn painted_unit(&self, cx: &Cx<'_, Self>) -> Option<Label> {
@@ -420,16 +475,16 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
.collect()
}
fn ruled(&self, units: &Units, mixed: bool, names: Vec<(u32, String)>) -> Ruled<V> {
fn ruled(&self, env: &EnvView<'_>, mixed: bool, names: Vec<(u32, String)>) -> Ruled<V> {
Ruled {
inner: self.number_codec(units),
inner: self.number_codec(&env.units()),
rule: self.rule(),
snap: self.snap_typed,
decimals: self.commit_decimals,
mixed,
positive_only: self.positive_only,
names,
suffix: self.status_zoom.then(|| units.symbol(UnitKind::Percent)),
affixes: self.affixes(env),
scale: self.scale,
value: PhantomData,
}
@@ -585,8 +640,8 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
self.settle_lengths(&cx.env.units());
let codec = self.ruled(&cx.env.units(), false, self.names(|row| cx.env.resolve(&row.label().clone())));
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
@@ -601,7 +656,7 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
// Text editors draw their hint in the proportional face.
(Cow::Borrowed(BLANK), self.options.role)
} else {
(codec.sample(shown.unwrap_or(&blank)), TypeRole::Mono)
(codec.sample(shown.unwrap_or(&blank)), self.value_role())
};
let mut text = cx.field_text(&TextRun::new(sample.as_ref()).role(role));
if content {
@@ -622,7 +677,7 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
self.settle_lengths(&cx.env.units());
self.settle(&cx.env);
self.track = cx.tokens.size.length.track;
let rtl = cx.flow.is_rtl();
let chevrons = self.chevrons(&cx.words::<TextWords>());
@@ -630,8 +685,8 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
self.trailing = self.after_text(cx, &chevrons);
let names = self.names(|row| cx.env.resolve(&row.label().clone()));
self.value_width = cx.value().map_or(0.0, |value| {
let text = self.ruled(&cx.env.units(), false, names).format(value);
cx.field_text(&TextRun::new(&text).role(TypeRole::Mono)).x
let text = self.ruled(&cx.env, false, names).format(value);
cx.field_text(&TextRun::new(&text).role(self.value_role())).x
});
let placed = self.laid_out(cx.style, cx.content_rect, rtl);
if let Some((_, slot)) = self.leading_at(&placed, false) {
@@ -643,10 +698,15 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
cx.part(key, half).sense(Sense::CLICK | Sense::KEEP_FOCUS).pointer_only("ArrowUp and ArrowDown step the value");
}
let text = placed.text;
// A percentage reads "100.0%": the number stands against its sign, not in the middle of the room.
self.options.centred = !self.is_percent();
self.options.end_aligned = self.is_percent();
self.options.mono = true;
// A percentage reads "100.0%": the number stands against its sign, not in the middle of the room. The inline
// run starts at the field's start.
let centred = self.look == NumberLook::Centred;
self.options.centred = centred && !self.is_percent();
self.options.end_aligned = centred && self.is_percent();
self.options.mono = centred;
if !centred {
self.options.role = self.value_role();
}
self.options.steps_value = self.presets.is_none() && self.popup_slider.is_none();
let shown = cx.value();
if self.options.placeholder.is_none() {
@@ -660,7 +720,7 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
}
let names = self.names(|row| cx.env.resolve(&row.label().clone()));
let blank = V::blank().unwrap_or_else(|| V::of_number(self.rule().blank()));
cx.text(text_part::<V>(), text, &self.ruled(&cx.env.units(), shown.is_none(), names), shown.unwrap_or(&blank), &self.options);
cx.text(text_part::<V>(), text, &self.ruled(&cx.env, shown.is_none(), names), shown.unwrap_or(&blank), &self.options);
let slider_reason =
if self.presets.is_some() { "Alt+Down opens the presets list; the slider opens by pointer" } else { "Alt+Down opens the slider" };
let chevron_rects = &placed.trailing[placed.trailing.len() - chevrons.len()..];
@@ -837,7 +897,7 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
/// The value as the field shows it: its ruled codec's text, in the shown unit, a name as its presets row's label.
fn word_value(&self, value: &V, cx: &Cx<'_, Self>) -> Option<String> {
let names = self.names(|row| cx.env.resolve(&row.label().clone()));
Some(self.ruled(&cx.env.units(), false, names).format(value))
Some(self.ruled(&cx.env, false, names).format(value))
}
/// The edit, the preset picked, and what the committed text's parse learned: its unit, whether the range held it
+20 -15
View File
@@ -112,7 +112,9 @@ pub(super) struct Ruled<V> {
pub(super) mixed: bool,
pub(super) positive_only: bool,
pub(super) names: Vec<(u32, String)>,
pub(super) suffix: Option<String>,
/// The unit written before and after the number in the text itself (the status zoom's "100%", the inline look's
/// "720 pt"): shown, typed over and read back with the number.
pub(super) affixes: Option<(String, String)>,
/// How many shown units make one stored unit (1 for a field that shows what it holds).
pub(super) scale: f64,
pub(super) value: PhantomData<fn() -> V>,
@@ -128,7 +130,7 @@ impl<V> Clone for Ruled<V> {
mixed: self.mixed,
positive_only: self.positive_only,
names: self.names.clone(),
suffix: self.suffix.clone(),
affixes: self.affixes.clone(),
scale: self.scale,
value: PhantomData,
}
@@ -146,17 +148,20 @@ impl<V: NumberValue> Ruled<V> {
v.number().filter(|number| number.is_finite()).map(|number| number * self.scale)
}
fn with_suffix(&self, mut text: String) -> String {
if let Some(suffix) = &self.suffix
&& !text.is_empty()
{
text.push_str(suffix);
/// `text` with the unit written around it; empty text stays empty.
fn written(&self, text: String) -> String {
match &self.affixes {
Some((before, after)) if !text.is_empty() => format!("{before}{text}{after}"),
_ => text,
}
text
}
fn without_suffix<'a>(&self, text: &'a str) -> &'a str {
self.suffix.as_deref().and_then(|suffix| text.trim_end().strip_suffix(suffix)).unwrap_or(text)
/// `text` without the unit written around it, where it is there.
fn unwritten<'a>(&self, text: &'a str) -> &'a str {
let Some((before, after)) = &self.affixes else { return text };
let text = text.trim();
let text = text.strip_prefix(before.trim()).unwrap_or(text);
text.strip_suffix(after.trim()).unwrap_or(text)
}
/// The name `text` spells, as a value of the field's type.
@@ -176,7 +181,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
}
match v.named().and_then(|id| self.names.iter().find(|(name, _)| *name == id)) {
Some((_, label)) => label.clone(),
None => self.with_suffix(self.inner.format(&self.shown(v))),
None => self.written(self.inner.format(&self.shown(v))),
}
}
@@ -193,7 +198,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
if text.trim().is_empty() && (self.mixed || V::blank().is_none()) {
return Err(NotAValue);
}
let (read, mut note) = self.inner.parse_tagged(self.without_suffix(text), &self.shown(start))?;
let (read, mut note) = self.inner.parse_tagged(self.unwritten(text), &self.shown(start))?;
match read {
Some(number) => {
if self.positive_only && number <= 0.0 {
@@ -207,7 +212,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
}
fn applies_as_typed(&self, text: &str) -> bool {
!self.snap && !self.mixed && is_plain(text) && matches!(self.inner.parse(self.without_suffix(text), &None), Ok(Some(_)))
!self.snap && !self.mixed && is_plain(self.unwritten(text)) && matches!(self.inner.parse(self.unwritten(text), &None), Ok(Some(_)))
}
fn filter(&self, c: char) -> bool {
@@ -217,7 +222,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
fn normalise(&self, text: &str, v: &V) -> String {
match v.named() {
Some(_) => self.format(v),
None => self.with_suffix(self.inner.normalise(self.without_suffix(text), &self.shown(v))),
None => self.written(self.inner.normalise(self.unwritten(text), &self.shown(v))),
}
}
@@ -231,7 +236,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
// 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.with_suffix(codec.widest(&(self.rule.low..=self.rule.high))))
Cow::Owned(self.written(codec.widest(&(self.rule.low..=self.rule.high))))
}
None => Cow::Owned(self.format(current)),
}
+51 -2
View File
@@ -1,11 +1,11 @@
//! Stories of `NumberField`.
use super::{NamedOr, NumberField, NumberName, NumberPick, StepArrows, UnitPlacement};
use super::{NamedOr, NumberField, NumberLook, NumberName, NumberPick, StepArrows, UnitPlacement};
use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Validity};
use crate::display::Text;
use crate::form::{Field, FieldGroup};
use crate::layout_components::Row;
use crate::runtime::env::{Env, LengthUnits, Message, UnitKind};
use crate::runtime::env::{Env, LengthUnits, Message, UnitKind, with_env};
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, pointer, story};
use craft_behavior::{Mixed, NumberCodec, Reader};
use craft_theme::ControlSize;
@@ -206,3 +206,52 @@ fn number_field_named_length(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
fn number_field_snapped(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
NumberField::new("Size", data.bind("snapped", Some(SIZE))).range(RANGE).step(5.0).snap_typed(true).show(ui).edit.into()
}
/// Fields in the inline look ([`NumberLook::Inline`]): the number and its unit one run at the field's start, at rest,
/// mixed and disabled. The drive types into the first, so its caret and selection run through the unit too.
fn inline_fields(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let lengths = LengthUnits::new(UnitKind::Points, UnitKind::Points, 72.0);
let out = with_env(
ui,
|overrides| {
overrides.values.set(NumberLook::Inline);
},
|ui| {
FieldGroup::new("Inline number fields")
.show(ui, |ui, _| {
let first = row("Length").show(ui, |ui, _| NumberField::length("Width", data.bind("width", Some(720.0)), lengths).show(ui).edit);
row("Angle").show(ui, |ui, _| {
NumberField::new("Angle", data.bind("angle", Some(0.0))).range(0.0..=360.0).unit_kind(UnitKind::Degrees).show(ui);
});
row("Percent").show(ui, |ui, _| {
NumberField::new("Opacity", data.bind("opacity", Some(100.0))).range(RANGE).unit("%").popup_slider(RANGE).show(ui);
});
row("Mixed").show(ui, |ui, _| {
NumberField::length("Height", data.bind_mixed("mixed", Mixed::<Option<f64>>::Mixed), lengths).show(ui);
});
row("Disabled").show(ui, |ui, _| {
NumberField::length("Depth", Bind::bound(&mut Some(64.0)), lengths).enabled(false).show(ui);
});
first.inner
})
.inner
},
);
out.flatten().map(StoryOutput::from).unwrap_or_default()
}
#[story(NumberField<'static>, covers = [], drive = Drive::Type("42"), title = "Inline unit")]
fn number_field_inline(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
inline_fields(ui, data)
}
/// Focuses the first field with Tab: its whole run selected.
fn focus_first(fixture: &mut Fixture) {
fixture.key(Key::Tab, Modifiers::NONE);
fixture.idle(2);
}
#[story(NumberField<'static>, covers = [], drive = Drive::Custom(focus_first), title = "Inline unit, focused")]
fn number_field_inline_focused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
inline_fields(ui, data)
}
+1
View File
@@ -9,6 +9,7 @@ pub(crate) mod linked;
pub(crate) mod mixed_blank;
pub(crate) mod number;
pub(crate) mod number_length;
pub(crate) mod number_look;
pub(crate) mod number_scrub_step;
pub(crate) mod rtl_paragraph;
pub(crate) mod selectable;
@@ -0,0 +1,72 @@
//! The number field's inline look (`NumberLook::Inline`): the number and its unit are one run of the text part, so
//! editing reaches the unit's text as it reaches the number's.
use craft_ui::contract::{Bind, Props as _, Show as _};
use craft_ui::runtime::env::{LengthUnits, UnitKind};
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::{NumberField, NumberLook};
use egui::{Id, Key, Modifiers, Rect};
use std::cell::Cell;
use std::rc::Rc;
/// A length field in points under the inline look, its value, id and rect.
fn inline_field() -> (Fixture, Rc<Cell<Option<f64>>>, Rc<Cell<Id>>, Rc<Cell<Rect>>) {
let (value, id, rect) = (Rc::new(Cell::new(Some(720.0))), Rc::new(Cell::new(Id::NULL)), Rc::new(Cell::new(Rect::NOTHING)));
let (v, i, r) = (value.clone(), id.clone(), rect.clone());
let mut fixture = Fixture::new(move |ui| {
let mut shown = v.get();
let lengths = LengthUnits::new(UnitKind::Points, UnitKind::Points, 72.0);
let out = NumberField::length("Width", Bind::bound(&mut shown), lengths).id_salt("width").show(ui);
v.set(shown);
i.set(out.response.id);
r.set(out.response.rect);
});
fixture.root_value(NumberLook::Inline);
fixture.settle();
(fixture, value, id, rect)
}
/// The field's text as the tree reads it, and the runs painted inside the field.
fn shown(fixture: &Fixture, id: Id, rect: Rect) -> (String, Vec<String>) {
let text = fixture.tree().value(id).unwrap_or_default().to_owned();
let runs = fixture.texts().iter().filter(|run| rect.contains_rect(run.rect)).map(|run| run.text.clone()).collect();
(text, runs)
}
/// At rest the field paints one run, the number with its unit, from the field's start; the unit is no run of its own.
#[trial]
fn an_inline_field_paints_its_number_and_unit_as_one_run_at_its_start() {
let (fixture, _, id, rect) = inline_field();
let (text, runs) = shown(&fixture, id.get(), rect.get());
assert!(text.starts_with("720") && text.len() > "720".len(), "the field's text holds the number and its unit: {text:?}");
assert_eq!(runs, [text.clone()], "the field paints its text as one run, no unit apart");
let run = fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or(Rect::NOTHING);
assert!(run.center().x < rect.get().center().x, "the run starts at the field's start: {run:?} in {:?}", rect.get());
}
/// Focus selects the whole run, unit included; typed text replaces it and commits, and the unit comes back with the
/// new number. A caret edit inside the run keeps the unit's text and commits the edited number.
#[trial]
fn an_inline_field_edits_its_whole_run_and_commits_the_number() {
let (mut fixture, value, id, rect) = inline_field();
let (before, _) = shown(&fixture, id.get(), rect.get());
fixture.click_at(rect.get().center());
fixture.key(Key::A, Modifiers::COMMAND);
let selection = fixture.tree().text_selection(id.get()).map(|(anchor, focus)| anchor.1.abs_diff(focus.1));
assert_eq!(selection, Some(before.chars().count()), "select all covers the number and its unit");
fixture.type_text("36");
fixture.key(Key::Enter, Modifiers::NONE);
fixture.settle();
assert_eq!(value.get(), Some(36.0), "the typed number commits");
let (after, runs) = shown(&fixture, id.get(), rect.get());
assert_eq!(after.strip_prefix("36"), before.strip_prefix("720"), "the unit follows the new number: {after:?}");
assert_eq!(runs, [after.clone()], "the field shows the same one run");
fixture.key(Key::Home, Modifiers::NONE);
fixture.key(Key::Delete, Modifiers::NONE);
fixture.type_text("4");
assert_eq!(fixture.tree().value(id.get()).map(|text| text.strip_prefix("46") == after.strip_prefix("36")), Some(true));
fixture.key(Key::Enter, Modifiers::NONE);
fixture.settle();
assert_eq!(value.get(), Some(46.0), "the number edited inside the run commits without its unit");
}