diff --git a/crates/behavior/src/item_layout.rs b/crates/behavior/src/item_layout.rs index 9c26a1c0e7..b29a32b993 100644 --- a/crates/behavior/src/item_layout.rs +++ b/crates/behavior/src/item_layout.rs @@ -116,6 +116,10 @@ pub trait ItemLayout { /// The viewport and scroll offset the grid view describes. Layouts without a grid ignore it. fn set_view(&mut self, _viewport: Vec2, _offset: ScrollPos) {} + + /// Item `at` is as wide as it measured, `width` from the start edge, in a layout that gives every item one width; + /// `None` gives it that width again. Its rect and its hit test take the width. Layouts of other widths ignore it. + fn set_fit(&mut self, _at: usize, _width: Option) {} } /// Lines (rows or columns) with a default size, the lines whose size differs and their prefix sums, so the start @@ -342,12 +346,14 @@ pub struct SpanLayout { /// Whether the rows form a tree: arrows expand, collapse and step to the parent. pub tree: bool, rows: Option, + /// The rows as wide as they measured (`set_fit`), by position. + fits: BTreeMap, } impl SpanLayout { /// One row of `row_h` per entry of `source`, `width` wide, with no columns. pub fn new(source: &dyn DisplayOrder, width: f32, row_h: f32) -> Self { - Self { row_h, count: source.len(), width, columns: Vec::new(), tree: false, rows: None } + Self { row_h, count: source.len(), width, columns: Vec::new(), tree: false, rows: None, fits: BTreeMap::new() } } /// Rows as tall as `source` says: `Height` and `Rect` are the app's, `Aspect` follows the width, and `Auto` @@ -364,7 +370,12 @@ impl SpanLayout { row_h, ); let auto = hints.iter().map(|hint| matches!(hint, SizeHint::Auto)).collect(); - Self { row_h, count: hints.len(), width, columns: Vec::new(), tree: false, rows: Some(Sized { lines, auto }) } + Self { row_h, count: hints.len(), width, columns: Vec::new(), tree: false, rows: Some(Sized { lines, auto }), fits: BTreeMap::new() } + } + + /// The width of row `at`: the rows', or less where it is as wide as it measured. + fn width_of(&self, at: usize) -> f32 { + self.fits.get(&at).map_or(self.width, |fit| fit.min(self.width)) } fn top(&self, at: usize) -> f64 { @@ -416,16 +427,20 @@ impl ItemLayout for SpanLayout { fn rect(&self, at: usize, offset: ScrollPos) -> Rect { let top = (self.top(at) - offset.y) as f32; - Rect::from_min_size(Pos2::new(-(offset.x as f32), top), Vec2::new(self.width, self.height(at))) + Rect::from_min_size(Pos2::new(-(offset.x as f32), top), Vec2::new(self.width_of(at), self.height(at))) } fn hit(&self, point: Pos2, offset: ScrollPos) -> Option { let y = f64::from(point.y) + offset.y; - if let Some(rows) = &self.rows { - return (0.0..rows.lines.total()).contains(&y).then(|| rows.lines.at(y) as usize).filter(|&at| at < self.count); - } - let at = (y / f64::from(self.row_h)).floor(); - (at >= 0.0 && (at as usize) < self.count).then_some(at as usize) + let at = match &self.rows { + Some(rows) => (0.0..rows.lines.total()).contains(&y).then(|| rows.lines.at(y) as usize).filter(|&at| at < self.count), + None => { + let at = (y / f64::from(self.row_h)).floor(); + (at >= 0.0 && (at as usize) < self.count).then_some(at as usize) + } + }; + // A row as wide as it measured takes no point past its end. + at.filter(|&at| !self.fits.contains_key(&at) || f64::from(point.x) + offset.x < f64::from(self.width_of(at))) } fn column_count(&self) -> usize { @@ -460,6 +475,13 @@ impl ItemLayout for SpanLayout { } } + fn set_fit(&mut self, at: usize, width: Option) { + match width { + Some(width) => self.fits.insert(at, width), + None => self.fits.remove(&at), + }; + } + fn nav(&self) -> NavShape { if self.tree { NavShape::Tree } else { NavShape::Flat } } @@ -880,4 +902,19 @@ mod tests { assert!(!layout.shown(7) && layout.shown(6)); assert_eq!(layout.hit(Pos2::new(1.0, 5.0), ScrollPos { x: 0.0, y: 180.0 }), Some(8)); } + + /// A row as wide as it measured is that wide from the start edge and takes no point past its end; the rows around + /// it keep the layout's width, and `None` gives it that width again. + #[test] + fn a_fitted_span_row_is_as_wide_as_it_measured_and_hit_only_inside() { + let mut layout = SpanLayout::new(&crate::item_source::keyed(&[0_u8, 1, 2], |key| *key), 300.0, 20.0); + layout.set_fit(1, Some(60.0)); + let (row, other) = (layout.rect(1, ScrollPos::default()), layout.rect(2, ScrollPos::default())); + assert!(row.width() < other.width() && row.left() == other.left(), "the row is narrower from the start edge: {row:?} {other:?}"); + assert_eq!(layout.hit(Pos2::new(row.center().x, row.center().y), ScrollPos::default()), Some(1), "inside the row hits it"); + assert_eq!(layout.hit(Pos2::new(row.right() + 10.0, row.center().y), ScrollPos::default()), None, "past its end hits nothing"); + assert_eq!(layout.hit(Pos2::new(row.right() + 10.0, other.center().y), ScrollPos::default()), Some(2), "the next row keeps its width"); + layout.set_fit(1, None); + assert_eq!(layout.rect(1, ScrollPos::default()).width(), other.width(), "None gives the row the layout's width again"); + } } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index a8d020d4ff..1426431778 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -533,7 +533,8 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { } let measured_size = measured_size.filter(|size| (size.x - row.width()).abs() <= tolerance); if layout.is_auto(at) && (detail.is_some() || measured_size.is_none() || restated) { - let measured = item.measure_in(measure_ui, Proposal::Width(row.width())).y; + let size = item.measure_in(measure_ui, Proposal::Width(row.width())); + let measured = size.y; #[cfg(feature = "testing")] crate::runtime::measure::count_row_measure(&ctx, rows::measured_id(id, &key)); if detail.is_some() { @@ -543,8 +544,12 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { if measured_size.is_some_and(|before| (before.y - measured).abs() > tolerance) { layout_memory::ask_discard(&ctx); } - if measured != row.height() { - Arc::make_mut(&mut layout).set_height(at, measured); + let fit = rows::fits(&item).then_some(size.x); + let refit = rows::keep_fit(&ctx, id, key_hash(&key), fit); + if measured != row.height() || refit { + let held = Arc::make_mut(&mut layout); + held.set_height(at, measured); + held.set_fit(at, fit); row = self.screen(&layout, rect, at, offset, rtl); } } @@ -999,6 +1004,7 @@ impl ItemsHooks<'_, '_, C> { } let ctx = ui.ctx(); rows::measured_heights(ctx, id, |height| layout.measured(&|at| height(rows::measured_id(id, &self.source.key(at))))); + rows::restore_fits(ctx, id, &mut layout, self.source.len(), |at| key_hash(&self.source.key(at))); if layout.auto_widths() { rows::measured_widths(ctx, id, |width| { for at in 0..self.source.len() { diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index 4c5f87f5a0..7b1b72af77 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -141,7 +141,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { continue; } let row = RowMeasure::new(at, Rect::ZERO, cells.clone()); - let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row, |measure, _| measure(Proposal::Ideal)); + let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row, |measure, _, _| measure(Proposal::Ideal)); largest = largest.max(size); for (column, width) in cells { match widest.iter_mut().find(|(held, _)| *held == column) { @@ -155,9 +155,9 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { /// Builds the item of `row.at` as the collection `id` builds it, with the row state `row.state` and flags /// `row.flags`, under `installed` (`view` is what the item builder sees), and hands `measure` a measure of it that - /// does not allocate: its size at a proposal and the widths its column cells reported, and whether the item declared - /// a detail body, which the measure leaves out. The item is built once however many proposals `measure` asks. Item - /// memory goes to `memory`. + /// does not allocate: its size at a proposal and the widths its column cells reported, whether the item declared + /// a detail body, which the measure leaves out, and whether it is as wide as it measures (`rows::fits`). The item is + /// built once however many proposals `measure` asks. Item memory goes to `memory`. pub(super) fn measure_row( &mut self, comp: &C, @@ -165,7 +165,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { (id, view, installed): (Id, EnvView<'_>, &Env), memory: &mut MemoryStage, row: RowMeasure, - measure: impl FnOnce(&mut dyn FnMut(Proposal) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>), bool) -> R, + measure: impl FnOnce(&mut dyn FnMut(Proposal) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>), bool, bool) -> R, ) -> R { let ctx = ui.ctx().clone(); let RowMeasure { at, rect, cells, state, flags, tree } = row; @@ -200,6 +200,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { let item = (self.item)(&key, &mut icx); let detail = icx.detail.is_some(); let mut item = Props::id(comp.dress(item, &state), item_id); + let fits = rows::fits(&item); let facts = ItemFacts { item: item_id, flags, @@ -219,7 +220,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { scoped.item_facts = Some(std::sync::Arc::new(facts)); }), ); - let measured = measure(&mut |proposal| crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, proposal)), detail); + let measured = measure(&mut |proposal| crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, proposal)), detail, fits); Env::restore(&ctx, env); measured } @@ -299,13 +300,17 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { let row_width = layout.rect(at, ScrollPos::default()).width(); let (widths, height, detail) = layout_memory::boundary(&ctx, true, || { crate::contract::steps::measuring(&ctx, || { - self.measure_row(comp, measuring.ui, installed, memory, row_measure, |measure, detail| { + self.measure_row(comp, measuring.ui, installed, memory, row_measure, |measure, detail, fits| { // A row of auto widths takes its ideal width unless the fit over every row's widths shrinks it: // its height is measured there, and again only where the fit settles on another width. A row - // with a detail body is as high as its leaf and its body, which the shown row records. + // with a detail body is as high as its leaf and its body, which the shown row records. A row + // sized to its content is as wide as it measures there. let widths = wide.then(|| Vec2::new(measure(Proposal::Ideal).0.x, measure(Proposal::Min).0.x)); let row_width = widths.map_or(row_width, |widths| widths.x); - let height = (!detail && (high || wide)).then(|| Vec2::new(row_width, measure(Proposal::Width(row_width)).0.y)); + let height = (!detail && (high || wide)).then(|| { + let size = measure(Proposal::Width(row_width)).0; + (Vec2::new(row_width, size.y), fits.then_some(size.x)) + }); (widths, height, detail) }) }) @@ -318,11 +323,14 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { rows::record_measure(&ctx, id, width_id, widths); layout.set_width(at, widths.x, widths.y); } - if let Some(height) = height { + if let Some((height, fit)) = height { #[cfg(feature = "testing")] crate::runtime::measure::count_row_measure(&ctx, height_id); rows::record_measure(&ctx, id, height_id, height); layout.set_height(at, height.y); + if rows::keep_fit(&ctx, id, key_hash(&key), fit) { + layout.set_fit(at, fit); + } } } } diff --git a/crates/ui-contract/src/contract/items/reveal.rs b/crates/ui-contract/src/contract/items/reveal.rs index e7a1b92e93..ad564a8780 100644 --- a/crates/ui-contract/src/contract/items/reveal.rs +++ b/crates/ui-contract/src/contract/items/reveal.rs @@ -1,7 +1,7 @@ //! Bringing a row into view: a requested reveal and the scroll that does it. use super::measure::{Known, RowMeasure}; -use super::{ItemsHooks, rows}; +use super::{ItemsHooks, key_hash, rows}; use crate::contract::Collection; use crate::contract::collection::LeadSource; use crate::runtime::env::{Env, EnvView}; @@ -78,14 +78,21 @@ impl ItemsHooks<'_, '_, C> { let odd = striped && self.stripe_run(None, row).is_multiple_of(2) && !self.source.is_section(row); let (state, flags) = self.known_row(row, known, odd); let measure = RowMeasure { at: row, rect, cells, state, flags, tree }; - let (size, _) = crate::contract::steps::measuring(&ctx, || { - self.measure_row(comp, ui, (id, view_env, installed), &mut memory, measure, |measure, _| measure(Proposal::Width(rect.width()))) + let (size, fits) = crate::contract::steps::measuring(&ctx, || { + self.measure_row(comp, ui, (id, view_env, installed), &mut memory, measure, |measure, _, fits| { + (measure(Proposal::Width(rect.width())).0, fits) + }) }); - let height_id = rows::measured_id(id, &self.source.key(row)); + let key = self.source.key(row); + let height_id = rows::measured_id(id, &key); #[cfg(feature = "testing")] crate::runtime::measure::count_row_measure(&ctx, height_id); rows::record_measure(&ctx, id, height_id, Vec2::new(rect.width(), size.y)); Arc::make_mut(layout).set_height(row, size.y); + let fit = fits.then_some(size.x); + if rows::keep_fit(&ctx, id, key_hash(&key), fit) { + Arc::make_mut(layout).set_fit(row, fit); + } measured.push(row); } let content = layout.content_size(); diff --git a/crates/ui-contract/src/contract/items/rows.rs b/crates/ui-contract/src/contract/items/rows.rs index bcde9f9a25..7073522072 100644 --- a/crates/ui-contract/src/contract/items/rows.rs +++ b/crates/ui-contract/src/contract/items/rows.rs @@ -2,7 +2,7 @@ //! lead column (17.7) and auto-height rows measured into `LayoutMemory` (17.3, I1). use super::{ItemsHooks, key_hash}; -use crate::contract::{Collection, Cx, SelectMode}; +use crate::contract::{Collection, Cx, Internal, Meta, SelectMode, Sizing}; use crate::runtime::egui::memory as store; use crate::runtime::memory::sub; use crate::runtime::{focus, lazy}; @@ -73,6 +73,52 @@ pub(super) fn record_measure(ctx: &Context, collection: Id, id: Id, size: Vec2) lazy::remember(ctx, collection, id, size); } +/// Whether a row measured as `item` is as wide as it measured: it is sized to its content (`Sizing::Content`). +pub(super) fn fits(item: &impl Meta) -> bool { + item.common(Internal::new()).sizing == Some(Sizing::Content) +} + +/// The id the width of an auto row as wide as it measured is kept under; 0 once it is not. +fn measured_fit_id(collection: Id, key: u64) -> Id { + sub(collection, ("row_fit", key)) +} + +/// The id of the mark that a row of the collection `collection` was as wide as it measured. +fn fits_id(collection: Id) -> Id { + sub(collection, "row_fits") +} + +/// Keeps that the auto row `key` (its key hash) of the collection `collection` is `fit` wide, the width it measured, or +/// no longer as wide as it measured, for the passes that place the row without measuring it (`restore_fits`). Returns +/// whether that differs from what was kept, which this pass's layout took: only then does the caller set it there. +pub(super) fn keep_fit(ctx: &Context, collection: Id, key: u64, fit: Option) -> bool { + let id = measured_fit_id(collection, key); + let kept = lazy::reading(ctx, collection, |read| read(id).map(|(size, _)| size.x).filter(|width| *width > 0.0)); + if kept == fit { + return false; + } + record_measure(ctx, collection, id, Vec2::new(fit.unwrap_or(0.0), 0.0)); + if fit.is_some() { + record_measure(ctx, collection, fits_id(collection), Vec2::splat(1.0)); + } + true +} + +/// Sets in `layout` the widths of the rows of the collection `collection` that were as wide as they measured when last +/// measured, `key(at)` giving each row's key hash. Only a collection that had such a row reads them. +pub(super) fn restore_fits(ctx: &Context, collection: Id, layout: &mut L, rows: usize, key: impl Fn(usize) -> u64) { + lazy::reading(ctx, collection, |read| { + if read(fits_id(collection)).is_none() { + return; + } + for at in 0..rows { + if let Some((fit, _)) = read(measured_fit_id(collection, key(at))).filter(|(fit, _)| fit.x > 0.0) { + layout.set_fit(at, Some(fit.x)); + } + } + }); +} + impl ItemsHooks<'_, '_, C> { /// The row-child move of 17.5, tried before the navigation core: Forward on the lead row enters its first /// focusable child or part. A closed parent expands instead, a row with no children leaves the move to the diff --git a/crates/ui-widgets/src/list/row.rs b/crates/ui-widgets/src/list/row.rs index 7419b7cd44..723d81447b 100644 --- a/crates/ui-widgets/src/list/row.rs +++ b/crates/ui-widgets/src/list/row.rs @@ -200,9 +200,7 @@ pub struct ListRow<'a> { /// and mirrors. #[prop] pub(super) corner_mark: bool, - /// The row is its thumbnails and their link glyphs, with no label band, and as wide and high as they are. The label - /// stays the accessible name. - #[prop(flag)] + /// The row is its thumbnails and their link glyphs (`thumbnails_only`). pub(super) thumbnails_only: bool, /// The full-height bar at the start of the row's content (`stripe`). pub(super) stripe: Option<(crate::style::DataColor, crate::primitives::StrokeWidth)>, @@ -445,6 +443,17 @@ impl<'a> ListRow<'a> { row } + /// The row is its thumbnails and their link glyphs, with no label band, and as wide and high as they are: it is + /// sized to its content (`Sizing::Content`), so a collection's row takes no more of its width than they do. The + /// label stays the accessible name. + #[must_use] + pub fn thumbnails_only(self) -> Self { + use crate::contract::Props as _; + let mut row = self.sizing(crate::contract::Sizing::Content); + row.thumbnails_only = true; + row + } + /// A line between groups of rows, as a menu's separator: a spacer (no item, no sense, no AccessKit node; mark its /// position `ItemSource::is_section`) as high as the divider rule and the room around it, drawing the rule. pub fn separator() -> Self { diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index da019fcc77..8465cdcc5f 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -190,6 +190,34 @@ fn a_thumbnails_only_row_is_as_wide_as_its_thumbnails_and_named_by_its_label() { assert!(texts.iter().any(|text| text.text == NAMES[1]), "the plain row paints its label"); } +/// A thumbnails-only row keeps its width in the frames that place it without measuring it, and a press past its +/// thumbnails is a press on no row: only a press on the row picks it. +#[trial] +fn a_press_past_a_thumbnails_only_row_picks_nothing() { + use craft_ui::list::ThumbSize; + let seen: Events = Rc::new(RefCell::new(Vec::new())); + let held = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + let keys = [0_usize, 1]; + let source = keyed(&keys, |key: &usize| *key); + let out = List::new("Masks").show_items(ui, &source, &mut |key, _| { + let row = ListRow::new(NAMES[*key]).thumb(ThumbSize::Medium, |_, _| {}); + if *key == 0 { row.thumbnails_only() } else { row } + }); + held.borrow_mut().extend(out.events); + }); + fixture.room(Vec2::new(300.0, 200.0)).settle(); + fixture.idle(3); + let (row, other) = (fixture.by_label(NAMES[0]).expect("the row").rect, fixture.by_label(NAMES[1]).expect("the plain row").rect); + assert!(row.width() < other.width(), "the row stays as wide as its thumbnails: {row:?} {other:?}"); + let picks = |seen: &Events| seen.borrow().iter().filter(|event| matches!(event, CollectionEvent::Selection { .. })).count(); + seen.borrow_mut().clear(); + fixture.click_at(egui::pos2(row.right() + 20.0, row.center().y)).settle(); + assert_eq!(picks(&seen), 0, "a press past the thumbnails picks no row: {:?}", seen.borrow()); + fixture.click_at(row.center()).settle(); + assert!(picks(&seen) > 0, "a press on the row picks it: {:?}", seen.borrow()); +} + /// A drag on a thumbnail that carries a part drag starts with the primary button only: a secondary and a middle drag /// start no session and report no `PartDrag`. #[trial]