Grid columns keep their least: a column that takes its room leaves the others theirs

A grid's measuring run measures each content column in the room the other
columns leave at their least. When the columns do not fit beside each other,
it asks every column for its least in a probe sweep (every leaf at its least,
no column bounded) and measures once more: a content column in the room the
others leave at their least, a fill column never below its least. Columns
whose leasts do not fit beside each other are laid out one under another
across the room, so no column is cut. The leasts and the stacked layout are
recorded for the real run.

A wrapped text's least is its widest word: a line breaks between words.

FontsPanelView's list column and ColorPicker Full's channel column no longer
collapse at card width.
This commit is contained in:
aiongg
2026-11-12 14:32:41 +00:00
parent dfd18d09a3
commit 52e81f80ae
5 changed files with 298 additions and 58 deletions
+101 -15
View File
@@ -31,7 +31,8 @@ pub fn resolve_columns(columns: &[ColumnWidth], content: &[f32], room: f32, gap:
widths
}
/// What a `Grid` pass measured: the widest child per column and the tallest per row.
/// What a `Grid` pass measured: the widest child per column and the tallest per row, and the least each column
/// takes when the grid asked its columns for it.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct GridMeasure {
@@ -39,12 +40,22 @@ pub struct GridMeasure {
pub columns: Vec<f32>,
/// The tallest child of each row.
pub rows: Vec<f32>,
/// The least width of each column: what its widest cell takes with every leaf at its least. Empty when the grid
/// did not ask; a column with no entry has no least.
pub least: Vec<f32>,
}
impl GridMeasure {
/// A measurement of `columns` and `rows`.
pub const fn new(columns: Vec<f32>, rows: Vec<f32>) -> Self {
GridMeasure { columns, rows }
GridMeasure { columns, rows, least: Vec::new() }
}
/// The measurement with the least width of each column.
#[must_use]
pub fn with_least(mut self, least: Vec<f32>) -> Self {
self.least = least;
self
}
}
@@ -59,30 +70,92 @@ pub struct GridCursor {
fills: Vec<bool>,
gap: Vec2,
widths: Vec<f32>,
/// The least width of each column, which the room of every other column leaves it.
least: Vec<f32>,
/// Whether the cells measure in no bound along x: the sweep that asks the columns for their least.
unbounded: bool,
/// Whether each `Content` column measures in the room the others leave at their least, whatever the columns before
/// it took.
alone: bool,
last_rows: Vec<f32>,
next: usize,
measured: GridMeasure,
}
impl GridCursor {
/// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`.
/// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A
/// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share
/// does not go below it.
pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self {
let widths = resolve_columns(columns, &last.columns, flow.rect().width(), gap.x);
let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0);
let content: Vec<f32> = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect();
let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x)
.into_iter()
.enumerate()
.map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width })
.collect();
let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect();
GridCursor { flow, columns: columns.to_vec(), fills, gap, widths, last_rows: last.rows.clone(), next: 0, measured: GridMeasure::default() }
GridCursor {
flow,
columns: columns.to_vec(),
fills,
gap,
widths,
least: (0..columns.len()).map(least).collect(),
unbounded: false,
alone: false,
last_rows: last.rows.clone(),
next: 0,
measured: GridMeasure::default(),
}
}
/// A cursor for a measuring run under a body sized from its content: each `Fill` column of `columns` is placed
/// as a `Content` column, taking the width its cells take, while the room of the cells after it stays what the
/// fill column leaves them.
pub fn sized_by_content(flow: Flow, columns: &[ColumnWidth], gap: Vec2, rows: &[f32]) -> Self {
let kinds: Vec<ColumnWidth> =
columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect();
let mut cursor = Self::new(flow, &kinds, gap, &GridMeasure::new(Vec::new(), rows.to_vec()));
/// fill column leaves them. `last` gives the rows and the columns' least.
pub fn sized_by_content(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self {
let mut cursor = Self::new(flow, &as_content(columns), gap, &GridMeasure::new(Vec::new(), last.rows.clone()).with_least(last.least.clone()));
cursor.fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect();
cursor
}
/// A cursor for the sweep that asks each column for its least: every column but a `Fixed` one is placed as a
/// `Content` column whose cells measure in no bound along x, so each column measures its widest cell.
pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self {
let mut cursor = Self::new(flow, &as_content(columns), gap, &GridMeasure::default());
cursor.unbounded = true;
cursor
}
/// The cursor with each `Content` column measuring in the room the other columns leave at their least, whatever
/// the columns before it took: each column asks for what it would take alone, so `short` tells whether the
/// columns fit beside each other.
#[must_use]
pub fn each_alone(mut self) -> Self {
self.alone = true;
self
}
/// Whether the columns, as this sweep measured them, do not fit beside each other: the columns that do not share
/// the room left take more than the room, or a cell of a `Fill` column took more than its share. Such a grid asks
/// its columns for their least; any other grid keeps what it measured.
pub fn short(&self) -> bool {
let room = self.flow.rect().width();
if self.columns.len() < 2 || !room.is_finite() {
return false;
}
let measured = &self.measured.columns;
let gaps = self.gap.x * self.columns.len().saturating_sub(1) as f32;
let kept: f32 =
(self.columns.iter().zip(measured)).filter(|(kind, _)| !matches!(kind, ColumnWidth::Fill { .. })).map(|(_, width)| *width).sum();
// Half a point: less than a pixel shows at any scale the box runs.
if kept + gaps > room + 0.5 {
return true;
}
let shares = resolve_columns(&self.columns, measured, room, self.gap.x);
(self.fills.iter().zip(measured).zip(shares)).any(|((fill, took), share)| *fill && *took > share + 0.5)
}
/// The cell of the next child, whose measured size is `size`.
pub fn cell(&mut self, size: Vec2) -> Rect {
let count = self.columns.len().max(1);
@@ -112,10 +185,17 @@ impl GridCursor {
let count = self.columns.len().max(1);
let (column, _, _, top) = self.next_place();
let width = match self.columns.get(column) {
Some(ColumnWidth::Content) if self.unbounded => f32::INFINITY,
Some(ColumnWidth::Content) => {
let kept: f32 = (self.fills.iter().zip(&self.widths).enumerate())
.filter(|(at, (fill, _))| *at != column && !**fill)
.map(|(_, (_, width))| *width)
// Every other column keeps at least its least: a column that fills keeps only that, and so does a
// content column when each column measures alone.
let kept: f32 = (self.columns.iter().zip(&self.fills).zip(&self.widths).zip(&self.least).enumerate())
.filter(|(at, _)| *at != column)
.map(|(_, (((kind, fill), width), least))| match kind {
_ if *fill => *least,
ColumnWidth::Content if self.alone => *least,
_ => *width,
})
.sum();
let gaps = self.gap.x * count.saturating_sub(1) as f32;
(self.flow.rect().width() - kept - gaps).max(0.0)
@@ -130,7 +210,8 @@ impl GridCursor {
pub fn region(&self) -> Rect {
let (_, _, start, top) = self.next_place();
let room = self.room();
let span = self.flow.span(start, room.x);
// An unbounded cell is placed in the flow's rect; only its room has no bound.
let span = self.flow.span(start, if room.x.is_finite() { room.x } else { self.flow.rect().width() });
Rect::from_min_size(Pos2::new(span.min.x, self.flow.rect().top() + top), room)
}
@@ -179,6 +260,11 @@ impl GridCursor {
}
}
/// `columns` with each `Fill` column as a `Content` column.
fn as_content(columns: &[ColumnWidth]) -> Vec<ColumnWidth> {
columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -190,7 +276,7 @@ mod tests {
#[test]
fn a_content_cell_after_a_fill_cell_measures_in_the_whole_height_and_the_width_fixed_columns_leave() {
let columns = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::Fixed(100.0)];
let last = GridMeasure { columns: vec![0.0, 50.0, 0.0], rows: vec![100.0] };
let last = GridMeasure::new(vec![0.0, 50.0, 0.0], vec![100.0]);
let mut cursor = GridCursor::new(flow(false), &columns, Vec2::ZERO, &last);
assert_eq!(cursor.room(), Vec2::new(150.0, 100.0), "the fill cell measures in its own column");
cursor.cell(Vec2::new(150.0, 100.0));
+112 -41
View File
@@ -539,13 +539,124 @@ fn row_id(grid: Id, index: usize) -> Id {
sub(grid, ("row", index))
}
fn least_id(grid: Id, index: usize) -> Id {
sub(grid, ("least", index))
}
/// What the grid measured in this pass's measuring run.
fn measured_tracks(ctx: &egui::Context, sizing: bool, grid: Id, columns: usize) -> GridMeasure {
let rows = this_pass(ctx, sizing, sub(grid, "rows")).map_or(0, |count| count.x as usize);
let least: Vec<f32> = (0..columns).map_while(|i| this_pass(ctx, sizing, least_id(grid, i)).map(|size| size.x)).collect();
GridMeasure::new(
(0..columns).map(|i| this_pass(ctx, sizing, column_id(grid, i)).map_or(0.0, |size| size.x)).collect(),
(0..rows).map(|i| this_pass(ctx, sizing, row_id(grid, i)).map_or(0.0, |size| size.y)).collect(),
)
.with_least(least)
}
/// The one column a grid lays its cells in, one under another, when its columns do not fit beside each other.
const STACKED: &[ColumnWidth] = &[ColumnWidth::fill(1.0)];
/// Runs `body`, the cells of the `Grid` body `id` over `columns`, in `ui`.
///
/// A measuring run sweeps the cells once, each `Content` column in the room the other columns leave at their least
/// (`GridCursor::each_alone`). When the columns do not fit beside each other (`GridCursor::short`), it sweeps them again
/// as a probe, every leaf at its least and no column bounded, which gives each column its least, and then once more:
/// each column keeps at least its least, a `Content` column measuring in the room the others leave at theirs. When
/// the leasts do not fit beside each other, that last sweep lays the cells out one under another across the room
/// instead, so no column is cut. The real run places the cells from the widths, leasts and layout the measuring run
/// recorded.
fn run_grid<R>(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec2, mut body: impl FnMut(&mut Ui) -> R) -> R {
let ctx = ui.ctx().clone();
let rtl = env.direction.is_rtl();
let layout = child::column_layout(rtl);
// One sweep of the cells in `ui` with the cursor `make` gives the flow of `ui`'s layout; returns what the cursor
// measured.
let mut sweep = |ui: &mut Ui, scoped: &Env, make: &dyn Fn(Flow) -> GridCursor| {
let top = ui.available_rect_before_wrap().top();
let cursor = make(Flow::new(ui.available_rect_before_wrap(), rtl));
pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.insert(id, Cursor::Grid(cursor)));
let installed = Env::install_for(ui, scoped.derive_local(|scoped| scoped.grid = Some(id)));
let inner = body(ui);
Env::restore(&ctx, installed);
let cursor = match pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.remove(&id)) {
Some(Cursor::Grid(cursor)) => Some(cursor),
_ => None,
};
let short = cursor.as_ref().is_some_and(GridCursor::short);
let measured = cursor.map(|cursor| cursor.measured().clone()).unwrap_or_default();
// Cells place from last pass's rows, so a measuring run's rows all start at the top: the grid reaches as far
// down as the rows this pass measured, whichever pass it is.
let rows = measured.rows.iter().sum::<f32>() + gap.y * measured.rows.len().saturating_sub(1) as f32;
alloc::reach_down_to(ui, top + rows);
(inner, measured, short)
};
if !measure::active(&ctx) {
let stacked = this_pass(&ctx, false, sub(id, "stacked")).is_some_and(|stacked| stacked.x > 0.0);
let columns = if stacked { STACKED } else { columns };
let last = measured_tracks(&ctx, false, id, columns.len());
return child::block(ui, None, layout, |ui| sweep(ui, env, &|flow| GridCursor::new(flow, columns, gap, &last)).0).0;
}
// A measuring run under a body sized from its content gives each fill column the width its cells take, as a
// content column: the room it would share is not the body's to claim.
let content_run = env.content.0;
let cursor = |columns: &[ColumnWidth], last: &GridMeasure, flow: Flow| match content_run {
true => GridCursor::sized_by_content(flow, columns, gap, last),
false => GridCursor::new(flow, columns, gap, last),
};
let none = GridMeasure::default();
let (inner, measured, rect, short) = crate::contract::keeping_ids(&ctx, || {
let mut first = ui.new_child(egui::UiBuilder::new().layout(layout));
let (inner, measured, short) = sweep(&mut first, env, &|flow| cursor(columns, &none, flow).each_alone());
((inner, measured, first.min_rect(), short), short)
});
let record = |measured: &GridMeasure, least: &[f32], stacked: bool, room: Vec2| {
for (i, width) in measured.columns.iter().enumerate() {
found(&ctx, true, column_id(id, i), room, Vec2::new(*width, 0.0));
}
for (i, width) in least.iter().enumerate() {
found(&ctx, true, least_id(id, i), room, Vec2::new(*width, 0.0));
}
for (i, height) in measured.rows.iter().enumerate() {
found(&ctx, true, row_id(id, i), room, Vec2::new(0.0, *height));
}
found(&ctx, true, sub(id, "rows"), room, Vec2::new(measured.rows.len() as f32, 0.0));
found(&ctx, true, sub(id, "stacked"), room, Vec2::new(f32::from(u8::from(stacked)), 0.0));
};
if !short {
ui.advance_cursor_after_rect(rect);
record(&measured, &[], false, ui.available_rect_before_wrap().size());
return inner;
}
#[cfg(feature = "testing")]
measure::count_least(&ctx, id);
let probe = env.derive_local(|scoped| {
scoped.unbounded.0 = true;
scoped.least = true;
});
let least = crate::contract::keeping_ids(&ctx, || {
let least = layout_memory::probing(&ctx, || {
let mut least = ui.new_child(egui::UiBuilder::new().layout(layout));
sweep(&mut least, &probe, &|flow| GridCursor::unbounded(flow, columns, gap)).1.columns
});
(least, true)
});
// A fixed column is as wide as the app made it, whatever its cells take.
let least: Vec<f32> = (columns.iter().enumerate())
.map(|(i, kind)| match kind {
ColumnWidth::Fixed(width) => *width,
_ => least.get(i).copied().unwrap_or(0.0),
})
.collect();
let gaps = gap.x * columns.len().saturating_sub(1) as f32;
let stacked = least.iter().sum::<f32>() + gaps > ui.available_rect_before_wrap().width() + 0.5;
let (columns, last) = match stacked {
true => (STACKED, GridMeasure::default()),
false => (columns, GridMeasure::default().with_least(least.clone())),
};
let (inner, measured, _) = child::block(ui, None, layout, |ui| sweep(ui, env, &|flow| cursor(columns, &last, flow))).0;
record(&measured, &last.least, stacked, ui.available_rect_before_wrap().size());
inner
}
/// What this pass's measuring run found under `id`. A measuring run itself reads nothing.
@@ -696,46 +807,6 @@ pub(crate) fn run_body_measured<R>(
}
(inner, (*align != RowAlign::Start).then(|| took.width()))
}
BodyLayout::Grid { columns } => {
let inner = child::block(ui, None, child::column_layout(rtl), |ui| {
let top = ui.available_rect_before_wrap().top();
let last = measured_tracks(&ctx, sizing, id, columns.len());
let content_run = measure::active(&ctx) && env.content.0;
// A measuring run under a body sized from its content gives each fill column the width its cells
// take, as a content column: the room it would share is not the body's to claim.
let cursor = if content_run {
GridCursor::sized_by_content(Flow::new(ui.available_rect_before_wrap(), rtl), columns, gap, &last.rows)
} else {
GridCursor::new(Flow::new(ui.available_rect_before_wrap(), rtl), columns, gap, &last)
};
pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.insert(id, Cursor::Grid(cursor)));
let installed = Env::install_for(ui, env.derive_local(|scoped| scoped.grid = Some(id)));
let inner = body(ui);
Env::restore(&ctx, installed);
// Cells place from last pass's rows, so a measuring run's rows all start at the top: the grid reaches
// as far down as the rows this pass measured, whichever pass it is.
let rows = pass_state::with::<Cursors, _>(&ctx, |cursors| match cursors.0.get(&id) {
Some(Cursor::Grid(cursor)) => {
cursor.measured().rows.iter().sum::<f32>() + gap.y * cursor.measured().rows.len().saturating_sub(1) as f32
}
_ => 0.0,
});
alloc::reach_down_to(ui, top + rows);
inner
})
.0;
if let Some(Cursor::Grid(cursor)) = pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.remove(&id)) {
let measured = cursor.measured();
let room = ui.available_rect_before_wrap().size();
for (i, width) in measured.columns.iter().enumerate() {
found(&ctx, sizing, column_id(id, i), room, Vec2::new(*width, 0.0));
}
for (i, height) in measured.rows.iter().enumerate() {
found(&ctx, sizing, row_id(id, i), room, Vec2::new(0.0, *height));
}
found(&ctx, sizing, sub(id, "rows"), room, Vec2::new(measured.rows.len() as f32, 0.0));
}
(inner, None)
}
BodyLayout::Grid { columns } => (run_grid(ui, env, id, columns, gap, body), None),
}
}
+9 -2
View File
@@ -147,9 +147,16 @@ impl Component for Text {
_ => layout.size(),
};
}
let role = cx.style.text.role;
if cx.proposal == Proposal::Min && self.elide == Elide::Off {
// At its least a wrapped text is its widest word: a line breaks between words, never inside one.
let widest =
cx.resolved.label.split_whitespace().map(|word| cx.layout_at(&self.run(role, word), f32::INFINITY).size().x).fold(0.0, f32::max);
return Vec2::new(widest, cx.layout_at(&self.run(role, cx.resolved.label), widest).size().y);
}
// At its least an elided line is the ellipsis.
let band = if cx.proposal == Proposal::Min && self.elide != Elide::Off { 0.0 } else { wrap.unwrap_or(f32::INFINITY) };
let layout = cx.layout_at(&self.run(cx.style.text.role, cx.resolved.label), band);
let band = if cx.proposal == Proposal::Min { 0.0 } else { wrap.unwrap_or(f32::INFINITY) };
let layout = cx.layout_at(&self.run(role, cx.resolved.label), band);
// A cut line takes the whole room: its width must not follow where the last glyph happened to fit.
match cx.room {
Some(room) if layout.elided => Vec2::new(room, layout.size().y),
@@ -0,0 +1,75 @@
//! The columns of a grid keep their least: a column whose content takes the room it is offered (wrapping text, a
//! picture) leaves the others theirs, and a grid whose columns do not fit even at their least lays its cells out one
//! under another.
use craft_behavior::ColumnWidth;
use craft_ui::contract::{Show as _, ShowContainer as _};
use craft_ui::display::Text;
use craft_ui::layout_components::{Grid, Stack};
use craft_ui::testing::{Frames, shrink_least_runs, trial};
use egui::{Rect, Ui, Vec2};
use std::cell::Cell;
const SNAP: f32 = 1.0;
const LONG: &str = "A sentence that wraps at whatever width its column is offered, however wide that is";
const WORD: &str = "Brightness";
const HALVES: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content];
const SIDE_AND_MAIN: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::fill(1.0)];
/// Shows `ui` in a stack `width` wide for a few frames.
fn in_room(width: f32, mut ui_fn: impl FnMut(&mut Ui)) -> Frames {
let mut frames = Frames::new();
frames.idle(4, |ui| {
let rect = Rect::from_min_size(ui.available_rect_before_wrap().min, Vec2::new(width, 600.0));
Stack::new().fill().show_at(ui, rect, |ui, _| ui_fn(ui));
});
frames
}
/// The rects of the two cells of a grid over `columns`: `first` in the first, a single word in the second.
fn cells(columns: &'static [ColumnWidth], width: f32, first: &'static str) -> (Rect, Rect, Frames) {
let seen = Cell::new((Rect::NOTHING, Rect::NOTHING));
let frames = in_room(width, |ui| {
Grid::new(columns).show(ui, |ui, _| {
let a = Text::new(first).show(ui).rect;
let b = Text::new(WORD).show(ui).rect;
seen.set((a, b));
});
});
let (a, b) = seen.get();
(a, b, frames)
}
/// The width of `WORD` on one line.
fn word_width() -> f32 {
let seen = Cell::new(0.0);
let _ = in_room(800.0, |ui| seen.set(Text::new(WORD).show(ui).rect.width()));
seen.get()
}
#[trial]
fn a_column_that_takes_its_room_leaves_the_next_column_its_least() {
let word = word_width();
for columns in [HALVES, SIDE_AND_MAIN] {
let (wrap, next, frames) = cells(columns, 400.0, LONG);
assert!(next.width() >= word - SNAP, "the second column keeps its widest word");
assert!(wrap.right() <= next.left() + SNAP, "the wrapping column ends before the next one starts");
assert!(next.right() <= 400.0 + SNAP, "both columns fit the room");
assert!(shrink_least_runs(&frames.ctx).iter().all(|(_, count)| *count == 1), "a short grid asks its columns once a run");
}
}
#[trial]
fn a_grid_that_fits_asks_no_column_for_its_least() {
let (_, _, frames) = cells(HALVES, 400.0, "Exposure");
assert!(shrink_least_runs(&frames.ctx).is_empty(), "a grid whose columns fit measures once");
}
#[trial]
fn a_grid_whose_columns_do_not_fit_at_their_least_stacks_them() {
let word = word_width();
let room = word * 1.5;
let (first, second, _) = cells(HALVES, room, WORD);
assert!(second.top() >= first.bottom() - SNAP, "the second cell goes under the first");
assert!(first.right() <= room + SNAP && second.right() <= room + SNAP, "no cell runs past the room");
}
+1
View File
@@ -1,6 +1,7 @@
mod fill_column;
mod fill_share;
mod fonts;
mod grid_least;
mod nested;
mod room_height;
mod row_room;