diff --git a/crates/browse/src/ui/relink/dialog.rs b/crates/browse/src/ui/relink/dialog.rs index 0ac1cf88d..0ce388572 100644 --- a/crates/browse/src/ui/relink/dialog.rs +++ b/crates/browse/src/ui/relink/dialog.rs @@ -862,6 +862,7 @@ impl Model { .select(SelectMode::Single) .selection(Bind::bound(&mut selection)) .sort(self.layout.sort.clone()) + .sizing(Sizing::FillWidth) .show_items(ui, &source, &mut |&row, icx| { let data = &rows[row]; ListRow::new(data.owner.clone()) diff --git a/crates/dialogs/src/ui/file_list.rs b/crates/dialogs/src/ui/file_list.rs index 96f61f80e..8d767a371 100644 --- a/crates/dialogs/src/ui/file_list.rs +++ b/crates/dialogs/src/ui/file_list.rs @@ -246,20 +246,13 @@ impl<'a> FileListPicker<'a> { let source = Rows::new(paths); let mut selection = now.selected.as_ref().filter(|path| paths.contains(path)).map_or_else(Selection::default, |path| Selection::single(path.clone())); - let events = Stack::new() - .surface(SurfaceKind::Sunken) - .pad(Pad::Control) - .show(ui, |ui, _| { - let list = List::new(words.files.clone()).id_salt("files"); - let list = if folder { - list.select(SelectMode::None) - } else { - list.select(SelectMode::Single).deletable(true).reorder(ReorderRule::new()).selection(Bind::bound(&mut selection)) - }; - list.show_items(ui, &source, &mut |path, _| file_row(path, info)).events - }) - .inner - .unwrap_or_default(); + let list = List::new(words.files.clone()).id_salt("files").surface(SurfaceKind::Sunken).pad(Pad::Control); + let list = if folder { + list.select(SelectMode::None) + } else { + list.select(SelectMode::Single).deletable(true).reorder(ReorderRule::new()).selection(Bind::bound(&mut selection)) + }; + let events = list.show_items(ui, &source, &mut |path, _| file_row(path, info)).events; if folder { return; } diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 785c7ea38..4ed80add0 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -356,23 +356,23 @@ impl<'a> GlyphsPanel<'a> { Text::new(words.recent.clone()).show(ui); let recent: Vec = state.recent.iter().filter_map(|g| g.chars().next()).collect(); let mut activated: Option = None; - let strip = Stack::new().fill_width().surface(SurfaceKind::Sunken).pad(Pad::Control).show(ui, |ui, _| { - TileGrid::::new(words.recent.clone()) - .thumb_size(ThumbSize::Medium) - .zoom(RECENT_ZOOM) - .caption(CaptionPlace::None) - .select(SelectMode::Single) - .activate(ActivateOn::Click) - .sizing(craft_ui::contract::Sizing::FillWidth) - .show_items(ui, &Chars(&recent), &mut |key, _| { - let c = recent[*key]; - let name = words.cell.fill(&[("char", &c.to_string()), ("code", &code(c))]); - Tile::new(name).thumb(ThumbAspect::SQUARE, paint(&face_family, &face_style, c)) - }) - .response - .events - }); - for event in strip.inner.unwrap_or_default() { + let strip = TileGrid::::new(words.recent.clone()) + .thumb_size(ThumbSize::Medium) + .zoom(RECENT_ZOOM) + .caption(CaptionPlace::None) + .select(SelectMode::Single) + .activate(ActivateOn::Click) + .sizing(craft_ui::contract::Sizing::FillWidth) + .surface(SurfaceKind::Sunken) + .pad(Pad::Control) + .show_items(ui, &Chars(&recent), &mut |key, _| { + let c = recent[*key]; + let name = words.cell.fill(&[("char", &c.to_string()), ("code", &code(c))]); + Tile::new(name).thumb(ThumbAspect::SQUARE, paint(&face_family, &face_style, c)) + }) + .response + .events; + for event in strip { if let CollectionEvent::Activate(key) = event && let Some(c) = recent.get(key) { diff --git a/crates/text/src/ui/spelling.rs b/crates/text/src/ui/spelling.rs index 70d49b622..2a39be04a 100644 --- a/crates/text/src/ui/spelling.rs +++ b/crates/text/src/ui/spelling.rs @@ -252,22 +252,15 @@ impl CheckSpellingDialog { let source = keyed(&positions, |at: &usize| *at); let mut selection = suggestions.iter().position(|s| s.as_str() == change_to.as_str()).map_or_else(Selection::default, Selection::single); - let events = Stack::new() - .fill_width() + let events = List::new(words.suggestions.clone()) + .select(SelectMode::Single) + .sizing(Sizing::FillWidth) .surface(SurfaceKind::Sunken) .pad(Pad::Control) - .show(ui, |ui, _| { - List::new(words.suggestions.clone()) - .select(SelectMode::Single) - // A `Fill` list measures its rows in the content-sized dialog and spans the well. - .sizing(Sizing::Fill) - .natural_height(true) - .selection(Bind::bound(&mut selection)) - .show_items(ui, &source, &mut |at, _| ListRow::new(suggestions[*at].clone())) - .events - }) - .inner - .unwrap_or_default(); + .natural_height(true) + .selection(Bind::bound(&mut selection)) + .show_items(ui, &source, &mut |at, _| ListRow::new(suggestions[*at].clone())) + .events; for event in events { match event { CollectionEvent::Selection(SelectionChange::Set(rows)) => { diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 0a5afe8dc..82c7d652d 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -116,7 +116,7 @@ impl<'b> BodyHooks<'b> { let (x, y) = (sizing != Sizing::Content, sizing == Sizing::Fill); match (at, &props.mount) { (ShowAt::Rect(_), _) => (true, true), - (ShowAt::Flow, Mount::Inline) => (x && !env.content.0 && !self.held(props, env), y && !env.content.1), + (ShowAt::Flow, Mount::Inline) => (x && env.gives_width(), y && !env.content.1), (ShowAt::Flow, _) => (x, y), } } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 752914b5d..b8edb695d 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -20,7 +20,7 @@ use crate::runtime::env::WheelScope; use crate::runtime::env::{AppValues, ArenaId, Env, ItemFacts}; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::{focus, keys, layout_memory, lazy, overlay, wheel}; -use crate::style::{ComponentStyle as _, ScrollBarKind, StyleCx, SurfaceKind, scroll_bar_look, surface_style}; +use crate::style::{ComponentStyle as _, ScrollBarKind, StyleCx, SurfaceKind, UiTokens, scroll_bar_look, surface_style}; use craft_behavior::{ Axis, CancelReason, EditEvent, Intent, ItemLayout, Mixed, Proposal, ScrollPos, ScrollSpan, SelectionModel, Sense, WheelRoom, WheelTaker, }; @@ -180,8 +180,11 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { ShowAt::Flow => crate::layout::flow_room(ui), }; self.room = room; - let content = Env::of(ui).content; - self.from_content = (content.0 && crate::runtime::measure::active(ui.ctx()), content.1); + let env = Env::of(ui); + let room = Self::inner_room(comp, &env.tokens, room); + // Where the enclosing body does not give the width, a measuring run takes the collection's width from its + // content, whether it fills or fills the width, as a container does. + self.from_content = (!env.gives_width() && crate::runtime::measure::active(ui.ctx()), env.content.1); self.header.measure(scx); self.header.read_content(ui.ctx(), id); let bounded = room.x.is_finite(); @@ -233,40 +236,37 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let empty = if self.source.is_empty() { comp.empty_height(width, ui, scx) } else { 0.0 }; let rows = self.content.y.max(empty).max(floor); let height = cap.map_or(rows, |cap| rows.min(cap)) + self.header.height; + // Under a body that does not give the width, the layout above was made at the enclosing room: the measuring + // run offers the width from content instead. + let from_content = self.from_content.0 && !self.content_sized(comp); if !(self.scrolls && room.y.is_finite()) { - // Under a body sized from its content, a `Fill` collection offers its least width here too: the body - // has no room of its own to hand it, and the layout above was made at the enclosing room. - if self.from_content.0 && comp.props(Internal::new()).sizing == Sizing::Fill { - let wide = if self.header.has_columns() { self.header.least_width() } else { self.largest_in(comp, ui, id, room).x.min(room.x) }; - return Vec2::new(wide, height); - } - return Vec2::new(self.content.x, height); + let wide = if from_content { self.width_from_content(comp, ui, id, room, item, scx) } else { self.content.x }; + return Vec2::new(wide, height); } // A scrolling collection in a bounded room: `Content` takes its rows up to the room, `Fill` the room. + let wide = if self.content_sized(comp) { + self.content.x + } else if from_content { + self.width_from_content(comp, ui, id, room, item, scx) + } else { + 0.0 + }; match comp.props(Internal::new()).sizing { - // Under a body sized from its content, a measuring run takes the columns' least width and the rows up to - // the room, as a content-sized collection does: the body has no room of its own to hand it. - Sizing::Fill => { - let (x, y) = self.from_content; - let wide = if !x { - 0.0 - } else if self.header.has_columns() { - self.header.least_width() - } else { - self.largest_in(comp, ui, id, room).x.min(room.x) - }; - Vec2::new(wide, if y || self.capped { height.min(room.y) } else { 0.0 }) - } - Sizing::Content | Sizing::FillWidth => Vec2::new(if self.content_sized(comp) { self.content.x } else { 0.0 }, height.min(room.y)), + // Under a body sized from its content along the height, the rows take up to the room, as a content-sized + // collection's do: the body has no room of its own to hand it. + Sizing::Fill => Vec2::new(wide, if self.from_content.1 || self.capped { height.min(room.y) } else { 0.0 }), + Sizing::Content | Sizing::FillWidth => Vec2::new(wide, height.min(room.y)), } } + fn pad(&self, comp: &C, tokens: &UiTokens) -> f32 { + Self::props_pad(comp, tokens) + } + fn sized(&self, comp: &C, _: &Ui, _: Id, size: Vec2) -> Vec2 { let sizing = comp.props(Internal::new()).sizing; - // Only a `Fill` collection measures its width from its content under a content-sized body; `FillWidth` takes - // the room it is given on every run. - let width_from_content = self.from_content.0 && sizing == Sizing::Fill; - let width = if self.room.x.is_finite() && !self.content_sized(comp) && !width_from_content { self.room.x.max(size.x) } else { size.x }; + // A collection that measured its width from its content takes that width; the column it sits in holds it. + let width = if self.room.x.is_finite() && !self.content_sized(comp) && !self.from_content.0 { self.room.x.max(size.x) } else { size.x }; let height = match (self.scrolls && self.room.y.is_finite(), sizing) { (true, Sizing::Fill) if !self.from_content.1 && !self.capped => self.room.y, (true, Sizing::Fill) => size.y.min(self.room.y), diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index 0a02bd9d9..22988709a 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -11,6 +11,7 @@ use crate::runtime::access::SetPosition; use crate::runtime::env::{Env, ItemFacts}; use crate::runtime::layout_memory; use crate::runtime::memory::{MemoryStage, sub}; +use crate::style::{StyleCx, UiTokens}; use craft_behavior::Proposal; use craft_behavior::layout_memory::measure_tolerance; use egui::{Id, Pos2, Rect, Ui, Vec2}; @@ -22,6 +23,26 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { comp.props(Internal::new()).sizing == Sizing::Content } + /// The padding the collection's props add on every side of its rows (`ShapeHooks::pad`). + pub(super) fn props_pad(comp: &C, tokens: &UiTokens) -> f32 { + crate::contract::pad_of(tokens, comp.props(Internal::new()).pad) + } + + /// The room the header and rows lay out in: `room` less the padding the props add on both sides. Step 5 adds the + /// padding back and step 7 insets the content rect by it. + pub(super) fn inner_room(comp: &C, tokens: &UiTokens, room: Vec2) -> Vec2 { + (room - Vec2::splat(2.0 * Self::props_pad(comp, tokens))).max(Vec2::ZERO) + } + + /// The width a collection that fills the width takes where it is not given one, in a measuring run under a body + /// sized from its content: the header's least width, else its largest row's, at least the width it asks for + /// (`Collection::ideal_width`), up to `room`. The column it sits in holds it at that width and shows it across + /// the width the column settles on. + pub(super) fn width_from_content(&mut self, comp: &C, ui: &Ui, id: Id, room: Vec2, item: Option, scx: &StyleCx<'_>) -> f32 { + let rows = if self.header.has_columns() { self.header.least_width() } else { self.largest_in(comp, ui, id, room).x }; + rows.max(comp.ideal_width(item, scx)).min(room.x) + } + /// 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. @@ -37,6 +58,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { ShowAt::Rect(rect) => rect.size(), ShowAt::Flow => crate::layout::flow_room(at.ui), }; + let room = Self::inner_room(comp, &at.env.tokens, room); if self.source.is_empty() || (room.x.is_finite() && !self.content_sized(comp) && !comp.measures_items() && !self.header.has_content_columns()) { return; diff --git a/crates/ui-contract/src/contract/props.rs b/crates/ui-contract/src/contract/props.rs index 48ab5773d..474b94a8d 100644 --- a/crates/ui-contract/src/contract/props.rs +++ b/crates/ui-contract/src/contract/props.rs @@ -218,6 +218,8 @@ pub struct Resolved<'p> { pub(crate) ltr_axis: bool, /// `Common.sizing`: a leaf's own sizing. pub(crate) sizing: Option, + /// The padding the shape's props add on every side, over the style's: a collection's `ContainerProps::pad`. + pub(crate) pad: f32, /// `Common.description`. pub(crate) description: Option<&'p str>, /// `Common.tooltip`. diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 55a917a42..67dfa6b7a 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -17,7 +17,7 @@ use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::overlay::CloseReason; use crate::runtime::reads::{self, BindKey, Sample}; use crate::runtime::{commands, focus, inspect, keys, memory}; -use crate::style::{Ink, StateSet, StyleCx, StyleView}; +use crate::style::{Ink, StateSet, StyleCx, StyleView, UiTokens}; use craft_behavior::{Flow, Input, KeyRole, NavMove, PartRef, PressState, Proposal, Roving, Sense}; use craft_theme::Variant; use egui::{Context, Id, Pos2, Rect, Response, Ui, Vec2}; @@ -190,6 +190,12 @@ pub(crate) trait ShapeHooks { (false, false) } + /// The padding the shape's props add on every side of the content, over the style's (`Resolved::pad`): step 5 + /// adds it to the measured size and step 7 insets the content rect by it. + fn pad(&self, _comp: &C, _tokens: &UiTokens) -> f32 { + 0.0 + } + /// What the shape adds to the content size at step 5, before padding and `min_size`. fn extent(&mut self, _comp: &C, _ui: &Ui, _at: ShowAt, _id: Id, _scx: &StyleCx<'_>) -> Vec2 { Vec2::ZERO @@ -485,6 +491,7 @@ pub(crate) trait Erased { fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2; fn arena(&self) -> bool; fn extent(&mut self, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2; + fn pad(&self, tokens: &UiTokens) -> f32; fn host(&mut self, at: HostCx<'_>) -> Box; fn record(&mut self, stage: &mut MemoryStage, ctx: &Context, id: Id); } @@ -835,7 +842,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h // 7 parts p.trace.mark(Step::Parts); let flow = Flow::new(rect, rtl); - let content_rect = flow.inset(metrics.padding); + let content_rect = flow.inset(steps::padding(&metrics, resolved.pad)); let mut parts = PartsStep { decls: Default::default(), rovings: Vec::new(), scrolls: Vec::new(), text: super::text::TextStep::default() }; if !inert && facts.text() { parts.text.commit_now = focus::commit_now(&ctx) == Some(id); @@ -1126,7 +1133,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h /// Step 5's size for `input`: what the component measures plus `extent`, padded and bounded by its style. fn measured(t: &mut dyn Erased, input: &MeasureIn<'_>, style: &dyn StyleView, resolved: &Resolved<'_>, extent: Vec2) -> (Vec2, Inputs) { let (content, inputs) = t.measure_content(input, resolved); - (steps::measure(style, input, content, extent, resolved.sizing), inputs) + (steps::measure(style, input, content, extent, resolved), inputs) } /// The pipeline: steps 1 to 17 for one component, whatever its type and shape. @@ -1160,7 +1167,7 @@ pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option, proposa let mixed = t.peek_value(ui.ctx(), id, step1.command.as_deref()); let scx = steps::style_cx(ui.ctx(), &env, &step1); let style = t.style(ui.ctx(), &scx); - let resolved = steps::resolved(id, &step1, &common); + let resolved = Resolved { pad: t.pad(&env.tokens), ..steps::resolved(id, &step1, &common) }; let (at, width) = match proposal { Proposal::Width(width) => (ShowAt::Flow, Some(width)), Proposal::Size(size) => (ShowAt::Rect(Rect::from_min_size(ui.available_rect_before_wrap().min, size)), None), diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 189b8a0fe..5cb2236b7 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -18,7 +18,7 @@ use crate::runtime::layout_memory::Inputs; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::overlay::CloseReason; use crate::runtime::reads::{self, BindKey}; -use crate::style::{Flags, StateSet, StyleCx, StyleView}; +use crate::style::{Flags, StateSet, StyleCx, StyleView, UiTokens}; use craft_behavior::{EditEvent, Flow, ItemSource, KeyRole, PartRef, Proposal, Roving, Sense}; use craft_theme::Variant; use egui::{Context, Id, Rect, Ui, Vec2}; @@ -191,6 +191,10 @@ impl Erased for Typed<'_, '_, C> { self.hooks.extent(self.comp.get_ref(), ui, at, id, scx) } + fn pad(&self, tokens: &UiTokens) -> f32 { + self.hooks.pad(self.comp.get_ref(), tokens) + } + fn host(&mut self, at: HostCx<'_>) -> Box { self.hooks.host(self.comp.get_ref(), at) } diff --git a/crates/ui-contract/src/contract/steps.rs b/crates/ui-contract/src/contract/steps.rs index 1230153af..73421637a 100644 --- a/crates/ui-contract/src/contract/steps.rs +++ b/crates/ui-contract/src/contract/steps.rs @@ -29,7 +29,7 @@ pub(crate) use finish::{before_finish, inert_response, record_size, value_change pub(super) use id::measuring; pub(crate) use id::{draft, id, keeping_ids}; pub(crate) use label::scrub_by_label; -pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_cx}; +pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_cx, padding}; pub(crate) use paint::{fade, paint_focus, paint_part_layers, paint_surface, surface_ink}; pub(crate) use parts::{PartsStep, check_parts, declares_none}; pub(crate) use place::place; diff --git a/crates/ui-contract/src/contract/steps/apply.rs b/crates/ui-contract/src/contract/steps/apply.rs index 66003e35a..6755d4c05 100644 --- a/crates/ui-contract/src/contract/steps/apply.rs +++ b/crates/ui-contract/src/contract/steps/apply.rs @@ -174,7 +174,7 @@ pub(crate) fn rerun_after_edit( let resized = if leaf { earlier.samples.iter().any(|sample| { let input = MeasureIn { ui: input.ui, env: input.env, proposal: sample.proposal, room: sample.room }; - measure(style, &input, p.measure_content(&input, resolved).0, Vec2::ZERO, resolved.sizing) != sample.took + measure(style, &input, p.measure_content(&input, resolved).0, Vec2::ZERO, resolved) != sample.took }) } else { earlier.measured diff --git a/crates/ui-contract/src/contract/steps/env.rs b/crates/ui-contract/src/contract/steps/env.rs index 897a5ae39..61e1e0c93 100644 --- a/crates/ui-contract/src/contract/steps/env.rs +++ b/crates/ui-contract/src/contract/steps/env.rs @@ -64,6 +64,7 @@ pub(crate) fn resolved<'p>(id: Id, step: &'p EnvStep, common: &'p Common) -> Res default_stop: common.default_stop, ltr_axis: common.ltr_axis, sizing: common.sizing, + pad: 0.0, description: common.description.as_deref(), tooltip: common.tooltip.as_ref(), doc_key: common.doc_key, diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index e18df81e0..da9fc6fc5 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -6,7 +6,7 @@ use crate::contract::{Component, Resolved, Sizing, ValueOf}; use crate::runtime::env::Env; use crate::runtime::layout_memory::{self, Inputs}; use crate::style::{ComponentStyle, StyleView}; -use craft_behavior::Proposal; +use craft_behavior::{Insets, Metrics, Proposal}; use egui::{Ui, Vec2}; /// What step 5 reads besides the component. @@ -33,11 +33,12 @@ pub(crate) fn measure_content( /// Step 5, measure: the `content` size plus padding, then `max(min_size)`, and for any proposal but `Min` at least the /// ideal width, up to the room, unless the component is sized to its content (`sizing`, a leaf's `Sizing::Content`). /// At `Min` a least width the style sets takes the place of `min_size`'s width. `extent` is what the shape adds to the -/// content: a body's remembered size or a collection's content size. -pub(crate) fn measure(style: &dyn StyleView, input: &MeasureIn<'_>, content: Vec2, extent: Vec2, sizing: Option) -> Vec2 { - let metrics = style.metrics(); +/// content: a body's remembered size or a collection's content size. The padding is the style's and the props' (`padding`). +pub(crate) fn measure(style: &dyn StyleView, input: &MeasureIn<'_>, content: Vec2, extent: Vec2, resolved: &Resolved<'_>) -> Vec2 { + let (metrics, sizing) = (style.metrics(), resolved.sizing); let content = content + extent; - let padding = Vec2::new(metrics.padding.start + metrics.padding.end, metrics.padding.top + metrics.padding.bottom); + let padding = padding(&metrics, resolved.pad); + let padding = Vec2::new(padding.start + padding.end, padding.top + padding.bottom); let floor = match (input.proposal, metrics.least_width) { (Proposal::Min, Some(least)) => Vec2::new(least, metrics.min_size.y), _ => metrics.min_size, @@ -49,6 +50,13 @@ pub(crate) fn measure(style: &dyn StyleView, input: &MeasureIn<'_>, content: Vec size } +/// The padding between the component's edge and its content: the style's, and `pad` on every side that the shape's +/// props add (`Resolved::pad`). +pub(crate) fn padding(metrics: &Metrics, pad: f32) -> Insets { + let padding = metrics.padding; + Insets::new(padding.start + pad, padding.end + pad, padding.top + pad, padding.bottom + pad) +} + /// The read view `measure` and `parts` get. Its room is the content's: the parent's room less the padding /// `measure` adds. pub(crate) fn measure_cx<'a, C: Component>( @@ -57,7 +65,7 @@ pub(crate) fn measure_cx<'a, C: Component>( resolved: &'a Resolved<'a>, value: Option<&'a ValueOf>, ) -> MeasureCx<'a, C> { - let padding = ComponentStyle::metrics(style).padding; + let padding = padding(&ComponentStyle::metrics(style), resolved.pad); MeasureCx { env: input.env.view(), style, diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 256558d88..1fd09ad75 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -273,6 +273,13 @@ impl Scoped { crate::style::control_metrics(&self.tokens, size, self.line_ratio) } + /// Whether the enclosing body gives a child that fills the width its width: it does not size from its content and + /// is no content column. Elsewhere such a child measures from its content and the column holds it at the width + /// the column settles on. + pub(crate) const fn gives_width(&self) -> bool { + !self.content.0 && !self.content_column + } + /// Ends the layout room of the enclosing body: its flow grid and content column. pub(crate) fn start_room(&mut self) { self.grid = None; diff --git a/crates/ui-macros/src/props.rs b/crates/ui-macros/src/props.rs index e1a490bb6..a79d2442a 100644 --- a/crates/ui-macros/src/props.rs +++ b/crates/ui-macros/src/props.rs @@ -206,6 +206,7 @@ const COLLECTION: &[Forwarded] = &[ const CONTAINER: &[Forwarded] = &[ ("command_scope", "::craft_ui::runtime::commands::CommandScope", "Commands of `scope` reach the component while focus is in it."), ("surface", "::craft_ui::style::SurfaceKind", "The surface painted behind the body."), + ("pad", "::craft_ui::contract::Pad", "The padding tier between the edge and the content."), ("live", "::craft_ui::contract::Politeness", "The body is a live region announced with this politeness."), ("end", "::craft_ui::contract::EndRegion", "The region at the line's end edge, outside the body scroll."), ("position", "::craft_ui::contract::SetPosition", "The component's place in its set, for assistive technology."), diff --git a/crates/ui-panels/src/sections/panel.rs b/crates/ui-panels/src/sections/panel.rs index 610b9bf95..5d74166e0 100644 --- a/crates/ui-panels/src/sections/panel.rs +++ b/crates/ui-panels/src/sections/panel.rs @@ -145,13 +145,6 @@ impl<'a> Panel<'a> { self } - /// The padding tier around the body, regular by default. A header band keeps its own inset. - #[must_use] - pub fn pad(mut self, pad: Pad) -> Self { - self.props = self.props.pad(pad); - self - } - /// The action parts at the end of the header, in reading order. #[must_use] pub fn actions(mut self, actions: impl IntoIterator) -> Self { diff --git a/crates/ui-widgets/tests/it/layout/fill_column.rs b/crates/ui-widgets/tests/it/layout/fill_column.rs index dcc34b240..8fd2fabeb 100644 --- a/crates/ui-widgets/tests/it/layout/fill_column.rs +++ b/crates/ui-widgets/tests/it/layout/fill_column.rs @@ -1,11 +1,14 @@ //! Fill propagates down a column whose width is given: a content-sized column there passes the width on, so its fill //! children take it and the column with them. Where the width comes from content (a popover's body, a row) the -//! column holds its fill children and shows them across the width it settles on. +//! column holds its fill children and shows them across the width it settles on. A collection that fills the width +//! follows the same rule as a container. +use craft_behavior::keyed; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing}; use craft_ui::display::{Divider, Text}; use craft_ui::layout_components::{Row, Stack}; +use craft_ui::list::{List, ListRow}; use craft_ui::popover::Popover; use craft_ui::table::{MetadataGroup, MetadataRow, MetadataTable}; use craft_ui::testing::{Frames, last_pass_measuring_runs, measuring_runs, trial}; @@ -120,3 +123,68 @@ fn a_content_column_that_passes_its_width_measures_as_often_as_a_fill_width_one( assert_eq!(hug, fill, "the content column measures as often as the fill-width one"); assert!(hug_settled.is_empty() && fill_settled.is_empty(), "a settled frame measures nothing: {hug_settled:?} {fill_settled:?}"); } + +const ROWS: [&str; 2] = ["Exposure", "ISO"]; + +/// A column of a long heading over a fill-width list of short rows, or over a fill-width stack of the same rows when +/// `list` is false. Records the widths of the column, the heading and the list or stack. +fn list_column(ui: &mut Ui, list: bool, seen: &Cell<(f32, f32, f32)>) { + let shown = Stack::new().id_salt("column").show(ui, |ui, _| { + let text = Text::new(LONG).show(ui).rect.width(); + let filled = if list { + let keys = [0_usize, 1]; + let source = keyed(&keys, |key: &usize| *key); + let rows = List::new("Rows").sizing(Sizing::FillWidth).natural_height(true); + rows.show_items(ui, &source, &mut |key, _| ListRow::new(ROWS[*key])).response.rect.width() + } else { + let stack = Stack::new().fill_width().id_salt("rows").show(ui, |ui, _| ROWS.iter().for_each(|row| _ = Text::new(*row).show(ui))); + stack.output.rect.width() + }; + (text, filled) + }); + if let Some((text, filled)) = shown.inner { + seen.set((shown.output.rect.width(), text, filled)); + } +} + +/// A fill-width collection follows the column it sits in: in a popover's column it measures from its rows, never sets +/// the column's width and shows across it; in a column given its width it takes that width. +#[trial] +fn a_fill_width_list_is_held_in_a_content_column_and_takes_a_given_one() { + let seen = Cell::new((0.0, 0.0, 0.0)); + Frames::new().idle(4, |ui| { + Popover::new("Column", Bind::given(true)).show(ui, |ui, _| list_column(ui, true, &seen)); + }); + let (column, text, list) = seen.get(); + assert!(column > 0.0, "the popover shows its column"); + assert!((column - text).abs() <= SNAP, "the column is as wide as its heading, not the screen: {column} vs {text}"); + assert!((list - column).abs() <= SNAP, "the list shows across the column: {list} vs {column}"); + + let given_seen = Cell::new((0.0, 0.0, 0.0)); + let room = given(&mut Frames::new(), 4, |ui| list_column(ui, true, &given_seen)); + let (_, _, list) = given_seen.get(); + assert!((list - room).abs() <= SNAP, "in a given column the list takes the width it is given: {list} vs {room}"); +} + +/// Holding a fill-width list costs the column no measuring run of its own: it measures as often as the same column +/// holding a fill-width stack, and a settled frame measures nothing. +#[trial] +fn a_column_holding_a_fill_width_list_measures_as_often_as_one_holding_a_stack() { + let runs = |list: bool| { + let mut frames = Frames::new(); + let seen = Cell::new((0.0, 0.0, 0.0)); + let show = |frames: &mut Frames, n: usize| { + frames.idle(n, |ui| { + Popover::new("Column", Bind::given(true)).show(ui, |ui, _| list_column(ui, list, &seen)); + }); + }; + show(&mut frames, 1); + let first: u32 = measuring_runs(&frames.ctx).iter().map(|(_, runs)| runs).sum(); + show(&mut frames, 5); + (first, last_pass_measuring_runs(&frames.ctx)) + }; + let ((list, list_settled), (stack, stack_settled)) = (runs(true), runs(false)); + assert!(stack > 0, "the first frame measures the column"); + assert!(list <= stack, "the list's column measures no more than the stack's: {list} vs {stack}"); + assert!(list_settled.is_empty() && stack_settled.is_empty(), "a settled frame measures nothing: {list_settled:?} {stack_settled:?}"); +} diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index e629f2d7a..82160f0f4 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -517,3 +517,60 @@ fn a_list_paints_the_surface_its_props_name() { "a sunken fill covers the list {list:?}: {seen:?}" ); } + +/// What a table of the three names shows with `pad`: its rect, its header cell's, its first row's and its empty +/// text's (the text of an empty table of the same props), and the pad in points. +fn padded(pad: craft_ui::contract::Pad) -> (egui::Rect, egui::Rect, egui::Rect, egui::Rect, f32) { + use craft_behavior::{ColumnKey, ColumnWidth}; + use craft_ui::contract::{ColumnSpec, pad_of}; + use craft_ui::runtime::env::Env; + use craft_ui::table::Table; + use std::cell::Cell; + const EMPTY: &str = "No artboards"; + let shown = Rc::new(Cell::new((egui::Rect::NOTHING, 0.0))); + let rig = |keys: &'static [usize], shown: Rc>| { + let mut fixture = Fixture::new(move |ui| { + let source = keyed(keys, |key: &usize| *key); + let columns = vec![ColumnSpec::new(ColumnKey::new("name"), "Name", ColumnWidth::Controls(4.0))]; + let table = Table::new("Artboards", columns).pad(pad).empty(EMPTY).natural_height(true); + let out = table.show_items(ui, &source, &mut |key, icx| ListRow::new(NAMES[*key]).cells(icx.cells())); + shown.set((out.response.rect, pad_of(&Env::of(ui).tokens, pad))); + }); + fixture.room(Vec2::new(300.0, 200.0)); + fixture.settle(); + fixture + }; + let fixture = rig(&[0, 1, 2], shown.clone()); + let (table, points) = shown.get(); + let header = fixture.by_label("Name").expect("the header cell shows").rect; + let row = fixture.by_label(NAMES[0]).expect("the first row shows").rect; + let mut empty = rig(&[], shown); + fn text_at(shapes: &[egui::Shape], text: &str) -> Option { + shapes.iter().find_map(|shape| match shape { + egui::Shape::Vec(inner) => text_at(inner, text), + egui::Shape::Text(shown) if shown.galley.text() == text => Some(shown.visual_bounding_rect()), + _ => None, + }) + } + let text = text_at(&empty.frame_shapes(), EMPTY).expect("the empty table says so"); + (table, header, row, text, points) +} + +/// A table's padding lies between its edge and everything it draws: the header, the rows and the empty text start the +/// pad further in than in an unpadded table. +#[trial] +fn a_padded_table_draws_its_header_rows_and_empty_text_inside_the_pad() { + use craft_ui::contract::Pad; + let (table, header, row, empty, pad) = padded(Pad::Control); + let (bare, bare_header, bare_row, bare_empty, _) = padded(Pad::None); + assert!(pad > 0.0, "the control pad is a width"); + let inside = table.shrink(pad - 0.5); + for (name, rect) in [("header", header), ("row", row), ("empty text", empty)] { + assert!(inside.contains_rect(rect), "the {name} {rect:?} sits inside the pad of {table:?}"); + } + let start = |rect: egui::Rect, of: egui::Rect| rect.left() - of.left(); + assert!((start(header, table) - start(bare_header, bare) - pad).abs() <= 1.0, "the header starts the pad further in"); + assert!((start(row, table) - start(bare_row, bare) - pad).abs() <= 1.0, "the rows start the pad further in"); + assert!((start(empty, table) - start(bare_empty, bare) - pad).abs() <= 1.0, "the empty text starts the pad further in"); + assert!((header.top() - table.top() - (bare_header.top() - bare.top()) - pad).abs() <= 1.0, "the header starts the pad lower"); +}