Content-sized number fields line up their values and units across a column group: a field's body shares the group's columns other than its labels

This commit is contained in:
aiongg
2026-11-13 18:25:43 +00:00
parent 5a0f8a6cdd
commit 35b57473e3
6 changed files with 180 additions and 42 deletions
+18 -12
View File
@@ -497,26 +497,30 @@ pub(super) enum LabelColumns {
/// The body's rows read the group around the container, as the rows directly in the group do. `sized`: the
/// container shows at the width it measures (`ColumnGroup::through`).
Through { sized: bool },
/// A labelled container's body: its rows read no label column of the group around, and share its other columns
/// (`ColumnGroup::field`).
Field,
/// The body lays out apart from the group around it, and its rows read none.
Apart,
}
impl LabelColumns {
/// The part `props`'s body takes. A labelled container's body is its field's control, whose labels stay its own, as
/// is a roving group's (one control over its members: a radio group); a body on a mount of its own (a popup, a
/// dialog, a pane), one with a scroll region (a view of its own, as a bar's) and a grid (whose columns align its
/// cells) lay out apart. Every other body (a section, a box, a stack, a row)
/// passes the group through.
/// The part `props`'s body takes. A labelled container's body is its field's control, whose labels stay its own
/// while its other columns are the group's. A roving group's body (one control over its members: a radio group),
/// a body on a mount of its own (a popup, a dialog, a pane), one with a scroll region (a view of its own, as a
/// bar's) and a grid (whose columns align its cells) lay out apart. Every other body (a section, a box, a stack, a
/// row) passes the group through.
pub(super) fn of(props: &ContainerProps, sized: bool) -> Self {
if props.label_column {
LabelColumns::Own
} else if props.label.is_some()
|| props.roving.is_some()
let apart = props.roving.is_some()
|| props.mount != Mount::Inline
|| props.scroll.is_some()
|| matches!(props.layout, crate::layout::BodyLayout::Grid { .. })
{
|| matches!(props.layout, crate::layout::BodyLayout::Grid { .. });
if props.label_column {
LabelColumns::Own
} else if apart {
LabelColumns::Apart
} else if props.label.is_some() {
LabelColumns::Field
} else {
LabelColumns::Through { sized }
}
@@ -536,7 +540,8 @@ pub(super) struct LabelsFound {
}
/// Runs `body`, offered `room`, under the label columns `columns`: in a column group named `labels` under the container
/// `id`, so the labelled rows directly inside share the widest label; through to the group around; or behind a barrier.
/// `id`, so the labelled rows directly inside share the widest label; through to the group around; as a field's
/// control, which shares the group's columns other than its labels; or behind a barrier.
/// An own group opens at the `seed` widths a first run of the rows settled.
pub(super) fn shared_labels<R>(
ui: &mut Ui,
@@ -561,6 +566,7 @@ pub(super) fn shared_labels<R>(
found.reached = reached;
result
}
LabelColumns::Field => ColumnGroup::field(ui, body),
LabelColumns::Apart => ColumnGroup::barrier(ui, body),
}
}
+51 -20
View File
@@ -115,26 +115,42 @@ enum Frame {
/// `early`: per column, the narrowest width a row of a `sized` Through frame inside read in a measuring run.
/// `depth`: the measuring runs open when the group opened (`layout_memory::depth`).
Group { id: Id, widest: Columns, beyond: HashMap<Vec<ColumnKey>, f32>, early: Columns, room: Option<f32>, depth: usize },
/// A plain container's body in the group `group`: its rows read and report that group's widths, as the rows
/// A plain container's body in the group around it: its rows read and report that group's widths, as the rows
/// directly in the group do. Their reaches past the columns stay here, and the container hands them on to the
/// frame around it (`Reached`). `room`: the width the container was offered. `sized`: the container shows at the
/// width it measured (content-sized and not held by a content column), so a measure of it at a column narrower
/// than the group's final one would stand in the real run; a held body shows across the column whatever it
/// measured, and a body given its width takes the room.
Through { id: Id, group: Id, beyond: HashMap<Vec<ColumnKey>, f32>, room: f32, sized: bool },
Through { id: Id, beyond: HashMap<Vec<ColumnKey>, f32>, room: f32, sized: bool },
/// A labelled container's body: the field's control. Its labels stay its own, so rows inside read no label
/// column; every other column (a content-sized number field's value and unit) they share with the group around.
Field,
/// No group: rows inside read none, whatever group is open outside.
Barrier,
}
/// Whether `column` is one the label step puts labels in.
fn labels(column: &ColumnKey) -> bool {
*column == LABELS || *column == GLYPHS
}
impl Open {
/// The group a row in the innermost open frame reads its widths from, and the frame its reaches past the columns
/// go to; `None` when no group is open or a barrier is.
fn innermost(&self) -> Option<(Id, Id)> {
match self.0.last()? {
Frame::Group { id, .. } => Some((*id, *id)),
Frame::Through { id, group, .. } => Some((*group, *id)),
Frame::Barrier => None,
/// The group a row in the innermost open frame reads `columns` from, and the frame its reaches past them go to;
/// `None` when no group is open, a barrier is, or a field's body is and `columns` holds a label column.
fn innermost(&self, columns: &[ColumnKey]) -> Option<(Id, Id)> {
let mut frame = None;
for open in self.0.iter().rev() {
match open {
Frame::Group { id, .. } => return Some((*id, frame.unwrap_or(*id))),
Frame::Through { id, .. } => {
frame.get_or_insert(*id);
}
Frame::Field if columns.iter().any(labels) => return None,
Frame::Field => {}
Frame::Barrier => return None,
}
}
None
}
}
@@ -224,8 +240,18 @@ impl ColumnGroup {
/// Runs `rows` with no group open: a labelled row inside reads no column, whatever group is open outside. A
/// component's own label steps run in one, and the bodies that lay out apart from the group (`shared_labels`).
pub fn barrier<R>(ui: &mut Ui, rows: impl FnOnce(&mut Ui) -> R) -> R {
Self::framed(ui, Frame::Barrier, rows)
}
/// Runs the `rows` of a labelled container's body: they read no label column, and share every other column with
/// the group around, so the values of content-sized fields line up across the group's fields.
pub(crate) fn field<R>(ui: &mut Ui, rows: impl FnOnce(&mut Ui) -> R) -> R {
Self::framed(ui, Frame::Field, rows)
}
fn framed<R>(ui: &mut Ui, frame: Frame, rows: impl FnOnce(&mut Ui) -> R) -> R {
let ctx = ui.ctx().clone();
pass_state::with::<Open, _>(&ctx, |open| open.0.push(Frame::Barrier));
pass_state::with::<Open, _>(&ctx, |open| open.0.push(frame));
let result = rows(ui);
pass_state::with::<Open, _>(&ctx, |open| open.0.pop());
result
@@ -237,16 +263,19 @@ impl ColumnGroup {
/// measuring run returns how far the rows reached past the columns.
pub(crate) fn through<R>(ui: &mut Ui, id: Id, room: f32, sized: bool, rows: impl FnOnce(&mut Ui) -> R) -> (R, Option<Reached>) {
let ctx = ui.ctx().clone();
let Some((group, _)) = pass_state::with::<Open, _>(&ctx, |open| open.innermost()) else { return (Self::barrier(ui, rows), None) };
pass_state::with::<Open, _>(&ctx, |open| open.0.push(Frame::Through { id, group, beyond: HashMap::new(), room, sized }));
if pass_state::with::<Open, _>(&ctx, |open| open.innermost(&[])).is_none() {
return (Self::barrier(ui, rows), None);
}
pass_state::with::<Open, _>(&ctx, |open| open.0.push(Frame::Through { id, beyond: HashMap::new(), room, sized }));
let result = rows(ui);
let Some(Frame::Through { beyond, .. }) = pass_state::with::<Open, _>(&ctx, |open| open.0.pop()) else { return (result, None) };
if !crate::runtime::measure::active(&ctx) || beyond.is_empty() {
return (result, None);
}
let reached = beyond.into_iter().map(|(columns, past)| {
let reached = beyond.into_iter().filter_map(|(columns, past)| {
let (group, _) = pass_state::with::<Open, _>(&ctx, |open| open.innermost(&columns))?;
let width = columns.iter().map(|column| current_width(&ctx, group, column)).sum();
(columns, width, past)
Some((columns, width, past))
});
(result, Some(Reached(reached.collect())))
}
@@ -277,16 +306,18 @@ impl ColumnGroup {
/// The row reports `content`.
#[doc(hidden)]
pub fn ambient_width(ctx: &Context, column: &ColumnKey, content: f32) -> Option<f32> {
let (group, _) = pass_state::with::<Open, _>(ctx, |open| open.innermost())?;
let (group, _) = pass_state::with::<Open, _>(ctx, |open| open.innermost(std::slice::from_ref(column)))?;
let width = shared_width(ctx, group, column, content);
// A row of a body that shows at its measured width reads the column into that measure: the group notes how
// narrow, so its scope can tell the measure from one at its final width.
// narrow, so its scope can tell the measure from one at its final width. A field's control read through its
// body is such a row: it shows at the width it measured.
if crate::runtime::measure::active(ctx) {
pass_state::with::<Open, _>(ctx, |open| {
let mut sized = false;
for frame in open.0.iter_mut().rev() {
match frame {
Frame::Through { sized: through, .. } => sized |= *through,
Frame::Field => sized = true,
Frame::Group { id, early, .. } if *id == group => {
if sized {
let read = early.entry(column.clone()).or_insert(width);
@@ -302,10 +333,10 @@ pub fn ambient_width(ctx: &Context, column: &ColumnKey, content: f32) -> Option<
Some(width)
}
/// The width the innermost open frame's container was offered, `None` when no group is open or a barrier is, or the
/// container recorded none.
/// The width the innermost open frame's container was offered, `None` when no label group is open, a barrier or a
/// field's body is, or the container recorded none.
pub(crate) fn ambient_room(ctx: &Context) -> Option<f32> {
pass_state::with::<Open, _>(ctx, |open| match open.0.last() {
pass_state::with::<Open, _>(ctx, |open| match open.0.last().filter(|_| open.innermost(std::slice::from_ref(&LABELS)).is_some()) {
Some(Frame::Group { room, .. }) => *room,
Some(Frame::Through { room, .. }) => Some(*room),
_ => None,
@@ -318,7 +349,7 @@ pub(crate) fn ambient_room(ctx: &Context) -> Option<f32> {
/// happens where no group is open or a barrier is.
#[doc(hidden)]
pub fn report_beyond(ctx: &Context, columns: &[ColumnKey], past: f32) {
if let Some((_, frame)) = pass_state::with::<Open, _>(ctx, |open| open.innermost()) {
if let Some((_, frame)) = pass_state::with::<Open, _>(ctx, |open| open.innermost(columns)) {
report(ctx, frame, Report::Beyond(columns.to_vec(), past));
}
}
+13 -1
View File
@@ -7,7 +7,7 @@ use crate::contract::{MeasureCx, PaintUi, Props as _};
use crate::primitives::{IconSpec, Span, TextRun};
use crate::runtime::env::Label;
use crate::style::{StyleColor, TypeRole};
use craft_behavior::{Flow, PartKey};
use craft_behavior::{ColumnKey, Flow, PartKey};
use craft_theme::ControlSize;
use egui::{Rect, Vec2, vec2};
use smallvec::SmallVec;
@@ -67,6 +67,18 @@ impl Adornment {
self
}
/// A text adornment that takes the width of `column` in the column group open around the field, at least its own
/// run, so a column of fields gives it one width and its text starts at one place. Outside a group, and for a
/// glyph or a button, it is returned as it is. Measure it first ([`Adornment::measured`]).
pub fn in_column(mut self, ctx: &egui::Context, column: &ColumnKey) -> Adornment {
if let Kind::Text { size, .. } = &mut self.kind
&& let Some(width) = crate::layout::ambient_width(ctx, column, size.x)
{
size.x = size.x.max(width);
}
self
}
/// The run of a text adornment.
fn run(label: &Label, role: TypeRole, mono: bool) -> TextRun<'_> {
let span = Span::new(label.as_str());
+25 -6
View File
@@ -20,7 +20,7 @@ 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};
use craft_behavior::{
Codec, HitLevel, HitPriority, Metrics, NavMove, NumberCodec, PartKey, PressPhase, Sense, ValueDrag, decimals_for_step, wheel_step,
Codec, ColumnKey, HitLevel, HitPriority, Metrics, NavMove, NumberCodec, PartKey, PressPhase, Sense, ValueDrag, decimals_for_step, wheel_step,
};
use craft_theme::{Stateful, States};
use egui::{Rect, Vec2};
@@ -38,6 +38,12 @@ pub use value::{NamedOr, NumberName, NumberOutput, NumberPick, NumberValue};
/// The step of an arrow press, the wheel and a scrub when the field sets none.
const DEFAULT_STEP: f64 = 1.0;
/// The columns content-sized fields share in a column group (a `FieldGroup`): the widest value and the widest unit,
/// so their values and units line up across the group's fields.
const VALUES: ColumnKey = ColumnKey::new("number_values");
const UNITS: ColumnKey = ColumnKey::new("number_units");
/// The placeholder of a mixed field.
const BLANK: &str = "\u{2014}";
@@ -51,6 +57,11 @@ fn non_finite<V: NumberValue>(value: Option<&V>) -> bool {
value.is_some_and(|v| v.named().is_none() && v.number().is_some_and(|number| !number.is_finite()))
}
/// Whether the host sized the field to its content (`Sizing::Content`).
fn content_sized<C: Component>(cx: &MeasureCx<'_, C>) -> bool {
cx.resolved.sizing() == Some(Sizing::Content)
}
/// The chevron that opens the presets list.
const PRESETS: PartKey = PartKey::new("presets");
/// The chevron that opens the popup slider.
@@ -304,9 +315,14 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
}
/// The unit, measured, then the chevrons: what sits after the text. The unit stands apart at the end of the value
/// area, so units line up in a column of fields and the number centres in the room before its unit.
/// area, so units line up in a column of fields and the number centres in the room before its unit. A
/// content-sized field's unit is as wide as the widest of its column group's.
fn after_text(&self, cx: &MeasureCx<'_, Self>, chevrons: &[(PartKey, Label)]) -> Vec<Adornment> {
let unit = self.unit.iter().map(|unit| Adornment::text(unit.clone(), cx.style.unit.role).apart().measured(cx));
let shared = content_sized(cx);
let unit = self.unit.iter().map(|unit| {
let unit = Adornment::text(unit.clone(), cx.style.unit.role).apart().measured(cx);
if shared { unit.in_column(cx.ui.ctx(), &UNITS) } else { unit }
});
let chevrons =
chevrons.iter().map(|(key, name)| Adornment::button(*key, crate::controls::disclosure::DisclosureGlyph::dropdown(), name.clone()));
unit.chain(chevrons).collect()
@@ -366,10 +382,13 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
// 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.
let content = cx.resolved.sizing() == Some(Sizing::Content);
// 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);
let sample = cx.value().map_or(Cow::Borrowed(""), |value| codec.sample(value));
let text = cx.field_text(&TextRun::new(sample.as_ref()).role(TypeRole::Mono));
let mut text = cx.field_text(&TextRun::new(sample.as_ref()).role(TypeRole::Mono));
if content {
text.x = crate::layout::ambient_width(cx.ui.ctx(), &VALUES, text.x).map_or(text.x, |width| width.max(text.x));
}
let chevrons = self.chevrons(&cx.words::<TextWords>());
self.leading = Self::before_text(cx);
self.trailing = self.after_text(cx, &chevrons);
+72 -2
View File
@@ -1,12 +1,14 @@
//! A group's label column reaches the labelled rows of the plain containers inside it: a stack, a row, a nested
//! box. A nested group keeps its own column, and a field's control keeps its own labels.
//! box. A nested group keeps its own column, and a field's control keeps its own labels. The value and unit columns
//! of content-sized number fields reach through a field's body.
use super::group::Group;
use super::kit::{Dial, Seen};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, ContainerProps, LabelScheme, Props as _, Show as _, ShowContainer as _, SideLabel};
use craft_ui::contract::{Bind, ContainerProps, LabelScheme, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::runtime::env::UnitKind;
use craft_ui::testing::{Fixture, Frames, last_pass_measuring_runs, trial};
use craft_ui::text::NumberField;
use egui::Rect;
@@ -21,6 +23,18 @@ fn number(ui: &mut egui::Ui, caption: &'static str) {
});
}
/// A field `caption` holding a content-sized number field over `range`, with `unit` after the number.
fn sized(ui: &mut egui::Ui, caption: &'static str, range: std::ops::RangeInclusive<f64>, unit: Option<UnitKind>) {
Field::new(caption).show(ui, |ui, _| {
let field = NumberField::new(caption, Bind::given(Some(8.0))).range(range.clone()).sizing(Sizing::Content);
match unit {
Some(unit) => field.unit_kind(unit),
None => field,
}
.show(ui);
});
}
fn control(fixture: &Fixture, name: &str) -> Rect {
fixture.by_label(name).unwrap_or_else(|| panic!("{name:?} names its control")).rect
}
@@ -113,3 +127,59 @@ fn a_row_before_the_groups_widest_label_measures_at_its_final_column() {
let runs = last_pass_measuring_runs(fixture.ctx());
assert!(runs.is_empty(), "a settled frame takes the kept measurements: {runs:?}");
}
/// Content-sized number fields share the widest value and the widest unit across the fields of a group: they end at
/// one edge and their units start at one place, "°" beside "%" and "-128" beside "100"; the same fields outside a
/// group keep their own widths.
#[trial]
fn content_sized_fields_line_up_their_values_and_units_across_a_group() {
let mut fixture = Fixture::new(|ui| {
FieldGroup::new("HSB").show(ui, |ui, _| {
sized(ui, "Hue", 0.0..=360.0, Some(UnitKind::Degrees));
sized(ui, "Saturation", 0.0..=100.0, Some(UnitKind::Percent));
});
FieldGroup::new("Lab").show(ui, |ui, _| {
sized(ui, "L", 0.0..=100.0, None);
sized(ui, "a", -128.0..=127.0, None);
});
Stack::new().show(ui, |ui, _| {
sized(ui, "Lightness", 0.0..=100.0, None);
sized(ui, "Green-red", -128.0..=127.0, None);
});
});
fixture.settle();
for (one, other) in [("Hue", "Saturation"), ("L", "a")] {
let (one, other) = (control(&fixture, one), control(&fixture, other));
assert!((one.max.x - other.max.x).abs() <= SLACK, "the fields of a group end at one edge: {one:?} {other:?}");
}
let (degrees, percent) = (caption(&fixture, "°"), caption(&fixture, "%"));
assert!((degrees.min.x - percent.min.x).abs() <= SLACK, "the units start at one place: {degrees:?} {percent:?}");
let (short, long) = (control(&fixture, "Lightness"), control(&fixture, "Green-red"));
assert!(long.width() > short.width() + SLACK, "outside a group each field takes its own value: {short:?} {long:?}");
}
/// A field that measured before a wider value of a later field in its group shows at the group's width, and a
/// content-sized row around it makes room: the member after the row's stack starts clear of both fields, and a
/// settled frame measures nothing again.
#[trial]
fn a_field_before_the_groups_widest_value_shows_at_its_width() {
let mut fixture = Fixture::new(|ui| {
FieldGroup::new("Channels").show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
sized(ui, "L", 0.0..=100.0, None);
sized(ui, "a", -12800.0..=12700.0, None);
});
Button::new("Link").show(ui);
});
});
});
fixture.settle();
let (first, wide) = (control(&fixture, "L"), control(&fixture, "a"));
assert!((first.max.x - wide.max.x).abs() <= SLACK, "the first field takes the later field's width: {first:?} {wide:?}");
let link = fixture.by_label("Link").expect("the link button is shown").rect;
assert!(link.min.x >= wide.max.x - SLACK, "the row's next member starts clear of the fields: {link:?} {wide:?}");
fixture.frame(vec![]);
let runs = last_pass_measuring_runs(fixture.ctx());
assert!(runs.is_empty(), "a settled frame takes the kept measurements: {runs:?}");
}
+1 -1
View File
@@ -38,7 +38,7 @@ One row per name in the author table (Overview) and per `pub` item a component a
| `CollectionProps` | A collection's plain data | `craft_ui::contract` | 17.1 |
| `CollectionResponse` | A collection's output | `craft_ui::contract` | 17.6 |
| Column, `ColumnSpec` | A `ColumnSpec` in `CollectionProps.columns` | `craft_ui::contract` | 17.1 |
| `ColumnGroup` | Rows that are not one `Grid` (`Field` rows) sharing the widest label per column key, by the same function as a `Grid` `Content` column | `craft_ui::layout` | 6.3 |
| `ColumnGroup` | Rows that are not one `Grid` (`Field` rows) sharing the widest label per column key, by the same function as a `Grid` `Content` column. A field's control keeps its own labels and shares the group's other columns: content-sized number fields line up their values and units across the group | `craft_ui::layout` | 6.3 |
| `ColumnWidth`, `ColumnKey` | A column's width rule | craft-behavior | 17.1, 6.3 |
| Command scope | A `CommandScope`, live while a container declaring it is live | craft-keymap | 11.3 |
| `CommandRef`, `CommandKind`, `ModalRule` | A command's id, its kind (`Command`, `Toggle`, `Radio`, `Tool`, `Momentary`) and whether it fires while a dialog is open | craft-keymap | 11.2 |