Table columns: a Content column is as wide as its widest cell, which rows report from their measure; a double click on a column's edge fits it to its widest cell in view; MetadataTable's name column fits its names up to a third of the table

This commit is contained in:
aiongg
2026-11-12 14:32:47 +00:00
parent 2e4d8c6026
commit 868c3ca47a
11 changed files with 350 additions and 68 deletions
@@ -77,6 +77,9 @@ pub struct ColumnSpec {
/// The header's tooltip: the column's long name where the header text abbreviates it. Without one the header shows
/// the header row's help.
pub tip: Option<Label>,
/// The most of the collection's width a `Content` column takes, as a share: a name column as wide as its widest
/// name, at most a third of the table.
pub max_share: Option<f32>,
}
/// Where a column's content sits.
@@ -106,6 +109,7 @@ impl ColumnSpec {
first_descending: false,
icon: None,
tip: None,
max_share: None,
}
}
@@ -159,6 +163,13 @@ impl ColumnSpec {
self
}
/// A `Content` column takes at most `share` of the collection's width.
#[must_use]
pub fn at_most(mut self, share: f32) -> Self {
self.max_share = Some(share);
self
}
/// The header's tooltip.
#[must_use]
pub fn tip(mut self, tip: impl Into<Label>) -> Self {
@@ -88,6 +88,13 @@ impl<C: Component> MeasureCx<'_, C> {
self.resolved.label_value.clone()
}
/// Reports, from the `Ideal` measure of a collection's item, the width its content in `column` takes unclipped,
/// its padding included. The collection sizes its `Content` columns by the widest it hears and fits a column to it
/// on a double click on the column's edge. Outside such a measure it does nothing.
pub fn cell_width(&self, column: &craft_behavior::ColumnKey, width: f32) {
crate::runtime::measure::report_cell_width(self.ui.ctx(), column, width);
}
/// Lays `run` out in the content's room, as `Draw::text` will paint it.
pub fn layout(&self, run: &TextRun<'_>) -> TextLayout {
self.layout_at(run, self.room.unwrap_or(f32::INFINITY))
+93 -32
View File
@@ -16,13 +16,14 @@ use crate::runtime::access::items::{HeaderCell, report_header};
use crate::runtime::commands::{self, CommandRef, CommandSet, CommandState};
use crate::runtime::egui::{alloc, child};
use crate::runtime::env::{Env, Label};
use crate::runtime::layout_memory;
use crate::runtime::memory::{MemoryStage, sub};
use crate::runtime::words::HeaderWords;
use crate::style::{ComponentStyle, ResizeLineLook, ScrollBarKind, StateSet, StyleColor, StyleCx, TypeRole, resize_line_look, scroll_bar_look};
use craft_behavior::grid::resolve_columns;
use craft_behavior::{
Axis, ColumnKey, ColumnWidth, CursorIcon, DropOperation, Flow, HitLevel, HitPriority, IconId, Insets, Intent, Metrics, NavMove, NavShape,
PartKey, PointerButton, PressPhase, Roving, Sense,
PartKey, PointerButton, PressPhase, Proposal, Roving, Sense,
};
use egui::{Align, Context, Id, Pos2, Rect, Response, Ui, UiBuilder, Vec2};
@@ -99,6 +100,11 @@ fn recorded_toggle_names(ctx: &Context, item: Id) -> Option<std::sync::Arc<[(Col
crate::runtime::egui::memory::peek_clone::<ToggleNames>(ctx, sub(item, "toggle_names")).map(|ToggleNames(names)| names)
}
/// The id the widest cell of the `Content` column `key` of the collection `id` is recorded under.
pub(super) fn content_id(id: Id, key: &ColumnKey) -> Id {
sub(id, ("column_content", hash_of(key)))
}
/// What the header keeps in session memory under the collection's id.
#[derive(Clone, Debug, Default)]
pub(super) struct HeaderMemory {
@@ -126,6 +132,11 @@ pub(super) struct Header {
pub(super) height: f32,
memory: HeaderMemory,
specs: Vec<ColumnSpec>,
/// The widest cell of each `Content` column among all rows, or its header label when wider, from the items'
/// measure of this pass (`content_id`); zero for the other columns and while unknown.
content: Vec<f32>,
/// The column a double click on its edge fits to its widest cell in view, with its width as shown.
pub(super) fit: Option<(ColumnKey, f32)>,
/// The app's sort, drawn on the header and advanced by a press.
sort: Option<ColumnSort>,
/// `CollectionProps.header`: the row is built when some column has a header text.
@@ -154,6 +165,7 @@ impl Header {
let mut specs = props.columns.to_vec();
let order = &self.memory.order;
specs.sort_by_key(|spec| order.iter().position(|key| *key == spec.key).unwrap_or(usize::MAX));
self.content = vec![0.0; specs.len()];
self.specs = specs;
}
@@ -179,38 +191,75 @@ impl Header {
}
}
/// The width of each column, in display order, in a row `room` wide.
/// The width of each column, in display order, in a row `room` wide: a `Content` column its widest cell (capped by
/// its `max_share` of `room`), and the `Fill` columns share what is left.
fn widths(&self, room: f32) -> Vec<f32> {
let kinds: Vec<ColumnWidth> = self.specs.iter().map(|spec| self.width_of(spec)).collect();
let content = vec![self.min; kinds.len()];
let content: Vec<f32> = self.content.iter().map(|wide| wide.max(self.min)).collect();
let kinds: Vec<ColumnWidth> = self
.specs
.iter()
.zip(&content)
.map(|(spec, wide)| match (self.width_of(spec), spec.max_share) {
(ColumnWidth::Content, Some(share)) if room > 0.0 => ColumnWidth::Fixed(wide.min(share * room)),
(kind, _) => kind,
})
.collect();
resolve_columns(&kinds, &content, room, 0.0)
}
/// The widths for a collection `width` wide whose widest row measured `widest` this pass: the `Content` columns take
/// what that row leaves beside the fixed and control columns (at most what `width` leaves), split evenly, and share
/// no room with the `Fill` columns.
fn widths_measured(&self, width: f32, widest: f32) -> Vec<f32> {
let kinds: Vec<ColumnWidth> = self.specs.iter().map(|spec| self.width_of(spec)).collect();
let is_content = |kind: &ColumnWidth| matches!(kind, ColumnWidth::Content);
let count = kinds.iter().filter(|kind| is_content(kind)).count();
let content = vec![self.min; kinds.len()];
if count == 0 {
return resolve_columns(&kinds, &content, width, 0.0);
}
let apart: Vec<ColumnWidth> = kinds.iter().map(|kind| if is_content(kind) { ColumnWidth::Fixed(0.0) } else { *kind }).collect();
let others: f32 =
resolve_columns(&apart, &content, width, 0.0).iter().zip(&kinds).filter(|(_, kind)| !is_content(kind)).map(|(wide, _)| *wide).sum();
let each = (widest - others).min(width - others).max(self.min) / count as f32;
let sized: Vec<ColumnWidth> = kinds.iter().map(|kind| if is_content(kind) { ColumnWidth::Fixed(each) } else { *kind }).collect();
resolve_columns(&sized, &content, width, 0.0)
/// Reads the widest cell of each `Content` column the items' measure recorded in this pass under the collection `id`.
pub(super) fn read_content(&mut self, ctx: &Context, id: Id) {
self.content = self
.specs
.iter()
.map(|spec| {
let measured = matches!(spec.width, ColumnWidth::Content).then(|| layout_memory::measured(ctx, content_id(id, &spec.key))).flatten();
measured.map_or(0.0, |measured| measured.took.x)
})
.collect();
}
/// The least width the columns take together: a fixed column its width, every other column its least width.
/// Whether some column takes the width of its widest cell.
pub(super) fn has_content_columns(&self) -> bool {
self.specs.iter().any(|spec| matches!(spec.width, ColumnWidth::Content))
}
/// The `Content` columns with their keys, in display order.
pub(super) fn content_columns(&self) -> impl Iterator<Item = (usize, &ColumnKey)> + '_ {
self.specs.iter().enumerate().filter(|(_, spec)| matches!(spec.width, ColumnWidth::Content)).map(|(at, spec)| (at, &spec.key))
}
/// The width of the header label of the column at display position `at`, its insets and sort mark included; zero
/// while the header row is not shown.
pub(super) fn label_width(&self, ui: &Ui, env: &crate::runtime::env::EnvView<'_>, at: usize) -> f32 {
let Some(spec) = self.specs.get(at).filter(|_| self.height > 0.0) else { return 0.0 };
let text = env.resolve(&spec.header).as_str().to_owned();
HeaderText::new(Label::from(text), self.inset, self.sort_of(&spec.key)).measure_in(ui, Proposal::Ideal).x
}
/// The width the columns take side by side with nothing to share: a fixed column its width, a `Content` column its
/// widest cell, every other column its least width.
pub(super) fn content_width(&self) -> f32 {
self.specs
.iter()
.zip(&self.content)
.map(|(spec, wide)| match self.width_of(spec) {
ColumnWidth::Fixed(width) => width,
ColumnWidth::Content => wide.max(self.min),
_ => self.min,
})
.sum()
}
/// The least width the columns take together: a fixed column its width, an uncapped `Content` column its widest
/// cell, every other column its least width.
pub(super) fn least_width(&self) -> f32 {
self.specs
.iter()
.map(|spec| match self.width_of(spec) {
.zip(&self.content)
.map(|(spec, wide)| match self.width_of(spec) {
ColumnWidth::Fixed(width) => width,
ColumnWidth::Content if spec.max_share.is_none() => wide.max(self.min),
_ => self.min,
})
.sum()
@@ -267,11 +316,6 @@ impl Header {
self.specs.iter().map(|spec| spec.key.clone()).zip(self.widths(room)).collect()
}
/// The columns for a collection sized from its widest row, `width` wide (see `widths_measured`).
pub(super) fn columns_measured(&self, width: f32, widest: f32) -> Vec<(ColumnKey, f32)> {
self.specs.iter().map(|spec| spec.key.clone()).zip(self.widths_measured(width, widest)).collect()
}
/// Step 7: one focusable part per column, a resize grip at the end edge of each resizable one, and the group.
pub(super) fn parts<C: Component>(&mut self, pcx: &mut PartsCx<'_, C>) {
self.cells.clear();
@@ -306,7 +350,7 @@ impl Header {
Rect::from_min_max(Pos2::new(rect.max.x - grip, rect.min.y), rect.max)
};
pcx.part(GRIP.at(hash), edge)
.sense(Sense::DRAG)
.sense(Sense::DRAG | Sense::CLICK)
.priority(HitPriority::new(HitLevel::Body, 1))
.cursor(CursorIcon::ResizeHorizontal)
.pointer_only("Resize Column… resizes from the keyboard");
@@ -351,6 +395,15 @@ impl Header {
self.events.push(ColumnEvent::Resized { key: key.clone(), width });
}
/// Fits the column a double click on its edge asked for (`fit`) to `widest`, the widest of its cells among the
/// rows in view, or to its header label when that is wider.
pub(super) fn apply_fit(&mut self, ui: &Ui, env: &crate::runtime::env::EnvView<'_>, widest: f32) {
let Some((key, shown)) = self.fit.take() else { return };
let Some(at) = self.specs.iter().position(|spec| spec.key == key) else { return };
let label = self.label_width(ui, env, at);
self.resize(&key, widest.max(label), shown);
}
/// Moves `key` to display position `to`: the session order changes and the move is reported.
fn move_to(&mut self, key: &ColumnKey, to: usize) {
let mut order: Vec<ColumnKey> = self.specs.iter().map(|spec| spec.key.clone()).collect();
@@ -417,6 +470,9 @@ impl Header {
cx.start_drag(ColumnDrag { table: id, key: key.clone() }, DragPreview::None);
}
if resizable {
if cx.part(GRIP.at(hash)).press.double_pressed() {
self.fit = Some((key.clone(), rect.width()));
}
match cx.part(GRIP.at(hash)).press.phase {
PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } => {
let from = match &self.memory.grab {
@@ -570,14 +626,19 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
pub(super) fn header_step(&mut self, cx: &mut Cx<'_, C>) -> bool {
let (id, rtl) = (cx.core.id, cx.core.flow.is_rtl());
let held = self.header.update(cx, id, rtl);
for event in self.header.events.drain(..) {
self.events.push(CollectionEvent::Column(event));
}
self.take_column_events();
for menu in self.header.menus.drain(..) {
self.events.push(CollectionEvent::HeaderMenu(menu));
}
held
}
/// The header's column events join the collection's.
pub(super) fn take_column_events(&mut self) {
for event in self.header.events.drain(..) {
self.events.push(CollectionEvent::Column(event));
}
}
}
/// The style of a header label: the sort mark's size and its gap after the text, the label's ink (the sorted
+20 -4
View File
@@ -183,8 +183,8 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
let content = Env::of(ui).content;
self.from_content = (content.0 && crate::runtime::measure::active(ui.ctx()), content.1);
self.header.measure(scx);
self.header.read_content(ui.ctx(), id);
let bounded = room.x.is_finite();
let mut widest = 0.0;
let item = comp.measures_items().then(|| layout_memory::measured(ui.ctx(), sub(id, "largest")).map(|measured| measured.took)).flatten();
let width = match (bounded, self.content_sized(comp)) {
(true, false) => room.x,
@@ -199,14 +199,17 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
// An unbounded room (a horizontally scrolling body) takes the widest row, as a content-sized collection does.
(_, _) => {
let floor = overlay::drawing_parent(ui.ctx()).map_or(0.0, |layer| crate::contract::overlay::floor_width(ui.ctx(), layer));
widest = layout_memory::measured(ui.ctx(), sub(id, "largest")).map_or(0.0, |measured| measured.took.x);
widest.max(comp.ideal_width(item, scx)).max(floor).min(room.x)
let widest = layout_memory::measured(ui.ctx(), sub(id, "largest")).map_or(0.0, |measured| measured.took.x);
// Columns side by side at their own widths: a `Content` column takes its widest cell, not the share of
// the widest row it would get.
let columns = if self.header.has_columns() { self.header.content_width() } else { 0.0 };
widest.max(columns).max(comp.ideal_width(item, scx)).max(floor).min(room.x)
}
};
let previous = self.layout.take().or_else(|| self.previous.take()).map(|held| Arc::try_unwrap(held).unwrap_or_else(|held| (*held).clone()));
let mut layout = comp.item_layout_from(previous, self.source, width, item, scx);
if self.header.has_columns() {
layout.set_columns(&if self.content_sized(comp) { self.header.columns_measured(width, widest) } else { self.header.columns(width) });
layout.set_columns(&self.header.columns(width));
}
let ctx = ui.ctx();
rows::measured_heights(ctx, id, |height| layout.measured(&|at| height(rows::measured_id(id, &self.source.key(at)))));
@@ -460,6 +463,9 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
// widget above it takes the hover as it does for the rows' parts.
let hover_at = crate::primitives::sensing::read_outcome(&ctx, ArenaId::new(cx.core.id)).hover.and(ctx.pointer_latest_pos());
let menu_open = self.drags.menu.is_some() && crate::contract::overlay::container_open::opened_from(&ctx, cx.core.id);
// A double click on a column's edge fits the column to its widest cell among the rows built here, in view.
let fit = self.header.fit.as_ref().map(|(column, _)| column.clone());
let mut fit_widest = 0.0_f32;
let place_rows = |ui: &mut Ui| {
// The items of a collection whose items are members of its run share one `Ui` under the collection's env.
let members_ui = C::MEMBERS.then(|| {
@@ -594,6 +600,12 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
row = self.screen(&layout, rect, at, offset, rtl);
}
}
if let Some(column) = &fit {
let (_, cells) = crate::runtime::measure::cell_widths(&ctx, || item.measure_in(measure_ui, Proposal::Ideal));
if let Some((_, width)) = cells.iter().find(|(held, _)| held == column) {
fit_widest = fit_widest.max(*width);
}
}
if layout.auto_widths() {
let ideal = item.measure_in(measure_ui, Proposal::Ideal).x;
let min = item.measure_in(measure_ui, Proposal::Min).x;
@@ -652,6 +664,10 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
}
None => place_rows(ui),
}
if self.header.fit.is_some() {
self.header.apply_fit(ui, &cx.core.env, fit_widest);
self.take_column_events();
}
self.paint_marquee(ui, env, &layout, (rect, offset, rtl));
focus::register_row_groups(&ctx, id, rtl, row_groups);
self.shown = shown_rows;
@@ -1,8 +1,8 @@
//! The largest item of a collection: the widest row of a content-sized collection, the cell of a collection that
//! sizes its items from their measure. Measured, recorded, kept while the items' inputs hold, and read back.
use super::rows;
use super::{ItemsHooks, key_hash};
use super::{header, rows};
use crate::contract::body::EnvFacts;
use crate::contract::collection::RowState;
use crate::contract::run::{Measuring, ShowAt};
@@ -22,22 +22,23 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
comp.props(Internal::new()).sizing == Sizing::Content
}
/// The largest ideal size of the rows in this pass: each row is built as `content` builds it, with its column
/// cells at the widths the header resolves with no room to share (a fixed or toggle column at its own width),
/// and measured without allocating.
fn largest_row(&mut self, comp: &C, ui: &Ui, id: Id) -> Vec2 {
/// The largest ideal size of the rows in this pass, and the widest cell each column's items reported: each row is
/// built as `content` builds it, with its column cells at the widths the header resolves with no room to share (a
/// fixed or toggle column at its own width), and measured without allocating.
fn largest_row(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) {
let ctx = ui.ctx().clone();
crate::contract::steps::measuring(&ctx, || self.largest_row_in(comp, ui, id))
}
/// Builds the rows once to measure the largest and records it under `sub(id, "largest")` for `extent`, when this
/// pass's width comes from the rows or the collection `measures_items`.
/// pass's width comes from the rows, the collection `measures_items`, or a column takes its widest cell's width.
pub(super) fn record_largest(&mut self, comp: &C, at: &Measuring<'_, '_>, id: Id) {
let room = match at.at {
ShowAt::Rect(rect) => rect.size(),
ShowAt::Flow => crate::layout::flow_room(at.ui),
};
if self.source.is_empty() || (room.x.is_finite() && !self.content_sized(comp) && !comp.measures_items()) {
if self.source.is_empty() || (room.x.is_finite() && !self.content_sized(comp) && !comp.measures_items() && !self.header.has_content_columns())
{
return;
}
self.header.measure(at.scx);
@@ -46,7 +47,8 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
/// The largest row in the room `room`: what a record of this pass under `sub(id, "largest")` found when it serves
/// the room (`Measured::serves`), else what the measure kept from an earlier pass gives while the items' inputs
/// hold, else the rows built and measured now, recorded there and kept. The caller measures the header first.
/// hold, else the rows built and measured now, recorded there and kept. The widest cell of each `Content` column,
/// or its header label when wider, is recorded with it (`header::content_id`). The caller measures the header first.
pub(super) fn largest_in(&mut self, comp: &C, ui: &Ui, id: Id, room: Vec2) -> Vec2 {
let ctx = ui.ctx().clone();
let key = sub(id, "largest");
@@ -72,8 +74,15 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
if inputs.is_some() {
layout_memory::begin_measure(&ctx, key);
}
let largest = self.largest_row(comp, ui, id);
let (largest, cells) = self.largest_row(comp, ui, id);
layout_memory::emit_record(&ctx, key, layout_memory::Measured::new(room, largest));
let env = Env::of(ui);
let content: Vec<(usize, craft_behavior::ColumnKey)> = self.header.content_columns().map(|(at, key)| (at, key.clone())).collect();
for (at, column) in content {
let widest = cells.iter().find(|(held, _)| *held == column).map_or(0.0, |(_, width)| *width);
let wide = widest.max(self.header.label_width(ui, &env.view(), at));
layout_memory::emit_record(&ctx, header::content_id(id, &column), layout_memory::Measured::new(room, Vec2::new(wide, 0.0)));
}
if let Some(inputs) = inputs {
layout_memory::end_measure(&ctx, key, inputs);
}
@@ -95,7 +104,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
})
}
fn largest_row_in(&mut self, comp: &C, ui: &Ui, id: Id) -> Vec2 {
fn largest_row_in(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) {
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let mut memory = MemoryStage::open_peek(&ctx, id);
@@ -105,6 +114,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
let toggles: Vec<craft_behavior::ColumnKey> = self.header.toggle_columns().map(|(key, _)| key).collect();
let len = self.source.len();
let mut largest = Vec2::ZERO;
let mut widest: Vec<(craft_behavior::ColumnKey, f32)> = Vec::new();
for at in 0..len {
if self.source.section_stop(at) {
continue;
@@ -152,10 +162,17 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
scoped.item_facts = Some(std::sync::Arc::new(facts));
}),
);
largest = largest.max(item.measure_in(ui, Proposal::Ideal));
let (size, cells) = crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, Proposal::Ideal));
largest = largest.max(size);
for (column, width) in cells {
match widest.iter_mut().find(|(held, _)| *held == column) {
Some((_, held)) => *held = held.max(width),
None => widest.push((column, width)),
}
}
Env::restore(&ctx, installed);
}
largest
(largest, widest)
}
}
+24
View File
@@ -6,6 +6,30 @@ use super::egui::memory as store;
use super::pass_state;
use egui::{Context, Id};
/// The widths per column the items measured inside `cell_widths` report, innermost call last.
#[derive(Default)]
struct CellWidths(Vec<Vec<(craft_behavior::ColumnKey, f32)>>);
/// Runs `measure` (one item's measure) and returns what it returned with the widest content it reported for each
/// column (`MeasureCx::cell_width`).
pub(crate) fn cell_widths<R>(ctx: &Context, measure: impl FnOnce() -> R) -> (R, Vec<(craft_behavior::ColumnKey, f32)>) {
store::with::<CellWidths, _>(ctx, |open| open.0.push(Vec::new()));
let out = measure();
let widths = store::with::<CellWidths, _>(ctx, |open| open.0.pop()).unwrap_or_default();
(out, widths)
}
/// Records `width` for `column` in the innermost open `cell_widths`; outside one it does nothing.
pub(crate) fn report_cell_width(ctx: &Context, column: &craft_behavior::ColumnKey, width: f32) {
store::with::<CellWidths, _>(ctx, |open| {
let Some(widths) = open.0.last_mut() else { return };
match widths.iter_mut().find(|(held, _)| held == column) {
Some((_, held)) => *held = held.max(width),
None => widths.push((column.clone(), width)),
}
});
}
/// How many measuring runs enclose the running code of a context.
#[derive(Default)]
pub(crate) struct Measuring(u32);
@@ -386,10 +386,12 @@ impl Shown<'_> {
.collect();
let source = keyed(&order[..], |at: &usize| *at).with_text(|at| Cow::Owned(list[*at].name(mode).into_owned()));
let by = if work.descending { ColumnSort::descending(work.sort.column()) } else { ColumnSort::ascending(work.sort.column()) };
let out = Table::<usize>::new(words.contributors_tab.clone(), columns.clone()).select(SelectMode::Single).sort(Some(by)).show_items(
ui,
&source,
&mut |key, icx| {
let out = Table::<usize>::new(words.contributors_tab.clone(), columns.clone())
.select(SelectMode::Single)
.sort(Some(by))
// The rows are the credits named by `mode`: their measure holds while it does, whatever the order.
.rows_stamp(mode as u64)
.show_items(ui, &source, &mut |key, icx| {
let contributor = &list[*key];
let mut row = ListRow::new(contributor.name(mode).into_owned())
.cells(icx.cells())
@@ -400,8 +402,7 @@ impl Shown<'_> {
row = row.cell(sort.column(), writer.cell(*sort, contributor));
}
row
},
);
});
for event in out.events {
match event {
CollectionEvent::Column(ColumnEvent::Sort { key, descending, .. }) => {
@@ -439,13 +440,17 @@ impl Shown<'_> {
.collect();
let order: Vec<usize> = (0..models.len()).collect();
let source = keyed(&order[..], |at: &usize| *at).with_text(|at| Cow::Owned(models[*at].company.to_string()));
let _ = Table::<usize>::new(words.models_tab.clone(), columns.clone()).select(SelectMode::None).show_items(ui, &source, &mut |key, icx| {
let model = &models[*key];
let mut row = ListRow::new(model.company.to_string()).cells(icx.cells()).columns(&columns).striped(icx.row.striped);
for column in ModelColumn::ALL.iter().filter(|column| **column != ModelColumn::Company) {
row = row.cell(column.key(), column.cell(model, total, writer));
}
row
});
let _ = Table::<usize>::new(words.models_tab.clone(), columns.clone()).select(SelectMode::None).rows_stamp(0).show_items(
ui,
&source,
&mut |key, icx| {
let model = &models[*key];
let mut row = ListRow::new(model.company.to_string()).cells(icx.cells()).columns(&columns).striped(icx.row.striped);
for column in ModelColumn::ALL.iter().filter(|column| **column != ModelColumn::Company) {
row = row.cell(column.key(), column.cell(model, total, writer));
}
row
},
);
}
}
+21 -1
View File
@@ -158,7 +158,11 @@ impl Component for ListRow<'_> {
None => label,
};
let label = label.max(self.below_width(sizes));
Vec2::new(probe.ideal_width + toggles - sizes.min_label + label.max(sizes.min_label) + self.indent_full(sizes), height)
let own = probe.ideal_width - sizes.min_label + label.max(sizes.min_label) + self.indent_full(sizes);
if cx.proposal == Proposal::Ideal {
self.report_cell_widths(cx, own);
}
Vec2::new(own + toggles, height)
}
fn sense(&self) -> Sense {
@@ -531,6 +535,22 @@ fn part_mods(cx: &Cx<'_, ListRow<'_>>, part: PartRef, source: FireSource) -> Mod
}
impl ListRow<'_> {
/// Reports the width of the row's content in each of its columns (`MeasureCx::cell_width`): `own` for the label
/// column, which holds everything but the toggle and text cells, and a text cell's line with its insets. A toggle
/// cell's column has its own width.
fn report_cell_widths(&self, cx: &MeasureCx<'_, Self>, own: f32) {
if let Some(column) = self.label_column(&self.cells) {
cx.cell_width(column, own);
}
let inset = 2.0 * cx.style.sizes.cell_inset;
for text in &self.texts {
if self.cells.iter().any(|(column, _)| *column == text.column) {
let line = cx.layout_at(&TextRun::new(text.text.as_str()).role(cx.style.cell.role), f32::INFINITY).size().x;
cx.cell_width(&text.column, line + inset);
}
}
}
/// Measures each hosted component not yet measured in this pass, for its slot.
fn measure_hosted(&mut self, cx: &MeasureCx<'_, Self>) {
for (at, trailing) in self.trailing.iter_mut().enumerate() {
+6 -5
View File
@@ -21,8 +21,8 @@ use std::sync::Arc;
const SHOW: ColumnKey = ColumnKey::new("show");
const NAME: ColumnKey = ColumnKey::new("name");
const VALUE: ColumnKey = ColumnKey::new("value");
/// The value column is this many times as wide as the name column.
const VALUE_SHARE: f32 = 2.0;
/// The name column is as wide as its widest name, at most this share of the table.
const NAME_SHARE: f32 = 1.0 / 3.0;
/// One field: its name and its value, as the app formats them.
#[derive(Clone, Debug, PartialEq, Eq, Props)]
@@ -123,7 +123,8 @@ impl Outcome for MetadataTableOutput {
/// A key and value table in groups: a search field over the rows keeps the fields whose name or value matches the
/// typed text, and a check column marks the keys the app shows as columns. The search field drives the rows: ArrowDown moves
/// the lead to the first row and Enter activates it, while focus stays in the field.
/// the lead to the first row and Enter activates it, while focus stays in the field. The name column is as wide as its
/// widest name, at most a third of the table; the values take the rest and wrap.
///
/// ```ignore
/// let out = MetadataTable::new("All metadata", &groups).filter(Bind::bound(&mut dialog.search)).show(ui);
@@ -242,8 +243,8 @@ impl<'a> MetadataTable<'a> {
let empty = if groups.iter().all(|group| group.rows.is_empty()) { words.none.clone() } else { words.no_match.clone() };
let mut columns = vec![
ColumnSpec::new(NAME, words.name.clone(), ColumnWidth::fill(1.0)),
ColumnSpec::new(VALUE, words.value.clone(), ColumnWidth::fill(VALUE_SHARE)),
ColumnSpec::new(NAME, words.name.clone(), ColumnWidth::Content).at_most(NAME_SHARE),
ColumnSpec::new(VALUE, words.value.clone(), ColumnWidth::fill(1.0)),
];
if choose.is_some() {
columns
+1
View File
@@ -27,6 +27,7 @@ mod runtime;
mod suite_rtl;
mod suite_rules;
mod suite_title;
mod table;
mod tabs;
mod text;
mod tile_grid;
+119
View File
@@ -0,0 +1,119 @@
//! The table's header row and column widths: a double click on a column's edge fits the column to its widest cell in
//! view, and the metadata table's name column follows its widest name up to a third of the table.
use craft_behavior::{ColumnKey, ColumnWidth, keyed};
use craft_ui::contract::{CollectionEvent, ColumnEvent, ColumnSpec, ShowCollection as _};
use craft_ui::list::ListRow;
use craft_ui::table::{MetadataGroup, MetadataRow, MetadataTable, Table};
use craft_ui::testing::{Fixture, Room, trial};
use egui::{Pos2, Rect};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
const NAME: ColumnKey = ColumnKey::new("name");
const SIZE: ColumnKey = ColumnKey::new("size");
const LONG: &str = "A file name far longer than the column it starts in";
/// A table of `names` whose name column starts `controls` control heights wide; the app applies the widths the
/// table reports. Returns the fixture and the column events seen.
fn files(names: &'static [&'static str], controls: f32) -> (Fixture, Rc<RefCell<Vec<ColumnEvent>>>) {
let events = Rc::new(RefCell::new(Vec::new()));
let width: Rc<Cell<Option<f32>>> = Rc::new(Cell::new(None));
let seen = events.clone();
let mut fixture = Fixture::new(move |ui| {
let name = width.get().map_or(ColumnWidth::Controls(controls), ColumnWidth::Fixed);
let columns = vec![ColumnSpec::new(NAME, "Name", name).resizable(), ColumnSpec::new(SIZE, "Size", ColumnWidth::Controls(4.0)).resizable()];
let keys: Vec<usize> = (0..names.len()).collect();
let source = keyed(&keys, |key: &usize| *key);
let out = Table::new("Files", columns).show_items(ui, &source, &mut |key, icx| ListRow::new(names[*key]).cells(icx.cells()));
for event in out.events {
if let CollectionEvent::Column(column) = event {
if let ColumnEvent::Resized { key, width: wide } = &column
&& *key == NAME
{
width.set(Some(*wide));
}
seen.borrow_mut().push(column);
}
}
});
fixture.in_room(Room::Dialog).settle();
(fixture, events)
}
fn elided(fixture: &Fixture, text: &str) -> bool {
fixture.texts().iter().find(|painted| painted.text == text).is_some_and(|painted| painted.elided)
}
/// Double clicks the end edge of the header cell `label`; returns the cell's width before.
fn fit(fixture: &mut Fixture, label: &str) -> f32 {
let cell = fixture.by_label(label).expect("the header cell's node").rect;
let edge = Pos2::new(cell.right() - 1.0, cell.center().y);
fixture.click_at(edge).click_at(edge).settle();
cell.width()
}
fn resized(events: &RefCell<Vec<ColumnEvent>>) -> Option<f32> {
events.borrow().iter().rev().find_map(|event| match event {
ColumnEvent::Resized { key, width } if *key == NAME => Some(*width),
_ => None,
})
}
/// A double click on a narrow column's edge widens it until its longest name in view shows whole; on a wide column of
/// short names it narrows it, never below its header label.
#[trial]
fn a_double_click_on_a_column_edge_fits_the_column_to_its_widest_cell() {
let (mut fixture, events) = files(&["A", LONG], 2.0);
assert!(elided(&fixture, LONG), "the long name is cut in the narrow column");
let before = fit(&mut fixture, "Name");
let after = resized(&events).expect("the fit reports the column's new width");
assert!(after > before, "the column grew: {before} -> {after}");
assert!(!elided(&fixture, LONG), "the long name shows whole");
assert!(events.borrow().iter().all(|event| !matches!(event, ColumnEvent::Sort { .. })), "the double click sorts nothing");
let (mut fixture, events) = files(&["A", "B"], 12.0);
let before = fit(&mut fixture, "Name");
let after = resized(&events).expect("the fit reports the column's new width");
assert!(after < before, "the column narrowed to its short names: {before} -> {after}");
assert!(!elided(&fixture, "Name"), "the header label still shows whole");
}
/// The left edge of the painted run `text`.
fn left_of(fixture: &Fixture, text: &str) -> f32 {
fixture.texts().iter().find(|painted| painted.text == text).map(|painted| painted.rect.left()).expect("the text was painted")
}
/// A metadata table of one group with `names`, each with the value "v{n}"; returns the fixture and the table's rect.
fn metadata(names: &'static [&'static str]) -> (Fixture, Rc<Cell<Rect>>) {
let rect = Rc::new(Cell::new(Rect::NOTHING));
let held = rect.clone();
let mut fixture = Fixture::new(move |ui| {
let rows = names.iter().enumerate().map(|(at, name)| MetadataRow::new(*name, format!("v{at}"))).collect();
let groups = vec![MetadataGroup::new("Camera", rows)];
held.set(MetadataTable::new("Metadata", &groups).show(ui).table.response.rect);
});
fixture.in_room(Room::Dialog).settle();
(fixture, rect)
}
/// The name column is as wide as its widest name while that is narrower than a third of the table, and a third of the
/// table when a name is wider. An idle table measures its rows once, not every pass.
#[trial]
fn the_metadata_name_column_fits_its_widest_name_up_to_a_third_of_the_table() {
let (mut short, rect) = metadata(&["ISO", "Exposure"]);
let table = rect.get();
assert!(!elided(&short, "Exposure"), "a short name shows whole");
let short_value = left_of(&short, "v1");
let name_end = short.texts().iter().find(|painted| painted.text == "Exposure").expect("the name was painted").rect.right();
let padding = short_value - name_end;
assert!(short_value - table.left() < table.width() / 3.0, "short names leave the values more than two thirds");
short.idle(2);
assert!(craft_ui::runtime::measure::widest_runs(short.ctx()).is_empty(), "an idle table keeps its rows' measure");
let (long, _) = metadata(&["ISO", LONG]);
assert!(elided(&long, LONG), "a name wider than a third of the table is cut");
let long_value = left_of(&long, "v1");
assert!(long_value > short_value, "a longer name widens the name column");
assert!(long_value - table.left() <= table.width() / 3.0 + padding, "the name column stops at a third of the table");
}