Merge pull request #4128 from dotCooCoo/fix/popover-padding-menu-spacing

ui-widgets: popovers pad as panels, menu samples and grid headers clear their neighbors
This commit is contained in:
FredApps authored and GitHub committed 2026-11-28 22:55:05 +01:00
commit ebda2539af
14 files changed
+238 -36

No files matched your search

+2 -2
View File
@@ -6,7 +6,7 @@ use crate::AreaMode;
use craft_behavior::{EditEvent, EditEvents, Metrics, PartKey, Sense};
use craft_theme::Srgba;
use craft_ui::contract::{
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPUP_PAD, PaintUi, PartsCx,
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPOVER_PAD, PaintUi, PartsCx,
Pattern, Props as _, Role, Show as _, ShowContainer as _, pad_of,
};
use craft_ui::popover::Popover;
@@ -77,7 +77,7 @@ fn start_point(geometry: Geometry, start: Option<Srgba>) -> Pos2 {
/// The popover's top left, so that the start colour's point in the area sits at `at`.
fn origin(tokens: &UiTokens, at: Pos2, start: Option<Srgba>) -> Pos2 {
let point = start_point(Geometry::of(tokens), start);
let pad = pad_of(tokens, POPUP_PAD);
let pad = pad_of(tokens, POPOVER_PAD);
pos2(at.x - pad - point.x, at.y - pad - point.y)
}
@@ -9,8 +9,8 @@ pub(crate) mod stories;
use super::space::canvas_space;
use crate::contract::overlay::{Dismiss, LayerRole, Outside};
use crate::contract::{
Access, Bind, Common, Component, Cx, MeasureCx, Name, NoValue, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _,
Props as _, Rename, Role, Show as _,
Access, Bind, Common, Component, Cx, MeasureCx, Name, NoValue, Outcome, Overlay, OverlayUi, Overlays as _, POPUP_PAD, PaintUi, PartsCx,
Pointer as _, Props as _, Rename, Role, Show as _,
};
use crate::primitives::{Checker, CheckerArea, PaintShape, PaintSlot, Rule, StrokeColor, StrokeWidth, TextRun, paint_surround};
use crate::runtime::env::Label;
@@ -590,7 +590,8 @@ impl Component for Pasteboard<'_> {
let layer = Overlay::popover()
.dismiss(Dismiss::new().outside(Outside::Keep))
.focus(FocusPolicy::POPUP.initial(Initial::First))
.role(LayerRole::InPlaceEditor);
.role(LayerRole::InPlaceEditor)
.pad(POPUP_PAD);
let layer = match field.or(state.shown) {
Some(rect) => layer.placed(rect),
None => layer,
+5 -1
View File
@@ -162,9 +162,13 @@ pub enum PadEdges {
Inline,
}
/// The padding of every popup surface around its content.
/// The padding of a menu's or a list's popup surface around its rows, which carry their own inset.
pub const POPUP_PAD: Pad = Pad::Control;
/// The padding of a popover's surface around its content: `space.pad.regular`, as a panel's, so controls stand clear of
/// its edge.
pub const POPOVER_PAD: Pad = Pad::Regular;
/// How a container's size follows its content.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
+2 -2
View File
@@ -70,8 +70,8 @@ pub use container::InBar;
pub use container::InMenu;
pub use container::{
BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion,
LeastWidth, Mount, MoveBandCursor, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, QuietHeader, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator,
SectionRhythm, ShellPane, Sizing, ThemeScope, WrapWidth,
LeastWidth, Mount, MoveBandCursor, Notch, POPOVER_PAD, POPUP_PAD, Pad, PadEdges, PaneEdge, QuietHeader, Scroll, ScrollAnchor, ScrollAxes,
ScrollIndicator, SectionRhythm, ShellPane, Sizing, ThemeScope, WrapWidth,
};
pub use craft_tracked::{PlainData, Revision, Tracked};
pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract};
@@ -2,6 +2,7 @@
use super::opener::{Opener, Trigger};
use super::place::{Anchor, DragBounds, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare};
use crate::contract::{POPOVER_PAD, POPUP_PAD, Pad};
use crate::runtime::access::PopupKind;
use crate::runtime::focus::{FocusPolicy, Initial};
use crate::runtime::motion::{MotionSpec, spec};
@@ -146,6 +147,10 @@ pub struct Overlay {
/// Whether a container mounted as this layer scrolls its body vertically. Off for a layer whose body fills it and
/// manages its own scrolling (a dock tree); a body that is one collection uses `collection_body` instead.
pub body_scroll: bool,
/// The padding [`OverlayUi::show`](super::OverlayUi::show) puts around a popup's body closure: `POPUP_PAD` for the
/// rows of a menu or a list, which carry their own inset, and `POPOVER_PAD` for a popover's content. A container
/// mounted as the layer takes its own padding from its props.
pub pad: Pad,
/// Whether the layer's move band moves the OS window the layer is shown in, in place of the layer: the chrome a
/// modal puts over the part of a title bar it covers. The layer stays where it is placed.
pub moves_window: bool,
@@ -203,6 +208,7 @@ impl Overlay {
bounds: None,
opacity: 1.0,
body_scroll: true,
pad: POPUP_PAD,
moves_window: false,
moved_by_app: false,
continue_move: None,
@@ -240,11 +246,12 @@ impl Overlay {
}
/// A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window,
/// taking focus in. It closes when the focus moves out of it.
/// taking focus in. It closes when the focus moves out of it. Its content stands `POPOVER_PAD` in from the edges.
pub fn popover() -> Overlay {
let mut overlay = Overlay::base(Rank::Popup, Overlay::below(), OverlayFit::Content, OwnerClass::Popup, FocusPolicy::POPUP);
overlay.dismiss = Dismiss::new().focus_left(true);
overlay.min_width = MinWidth::Anchor;
overlay.pad = POPOVER_PAD;
overlay
}
@@ -442,6 +449,12 @@ impl Overlay {
self
}
/// Sets the padding [`OverlayUi::show`](super::OverlayUi::show) puts around a popup's body closure.
pub fn pad(mut self, pad: Pad) -> Overlay {
self.pad = pad;
self
}
/// Sets the layer's opacity, from 0 (invisible) to 1.
pub fn opacity(mut self, opacity: f32) -> Overlay {
self.opacity = opacity;
@@ -6,8 +6,7 @@ use super::placement::PopupRegion;
use super::popups::{PopupHandle, PopupLayer, with_popups};
use super::props::Overlay;
use crate::contract::{
BodyCx, Common, Component, Container, ContainerProps, Cx, Inner, Internal, Mount, NoValue, Outcome, POPUP_PAD, Props as _, Resolved, Role,
ShowContainer,
BodyCx, Common, Component, Container, ContainerProps, Cx, Inner, Internal, Mount, NoValue, Outcome, Props as _, Resolved, Role, ShowContainer,
};
use crate::runtime::access::PopupShown;
use crate::runtime::egui::areas::{self};
@@ -89,8 +88,8 @@ impl<'a> OverlayUi<'a> {
});
}
/// Shows the popup while its handle is open, on a popup surface, inside `POPUP_PAD`; the content is a body closure.
/// `None` while closed.
/// Shows the popup while its handle is open, on a popup surface, inside the overlay's `pad` (`POPUP_PAD` for a menu
/// or a list, `POPOVER_PAD` for a popover); the content is a body closure. `None` while closed.
///
/// The popup is a layer container sized from its content: its body is measured in this pass before the layer is
/// placed, so a popup whose content changes is placed by its new size in the pass that shows it. A child that fills
@@ -122,7 +121,7 @@ impl<'a> OverlayUi<'a> {
}
.body_scroll(false);
let label = self.resolved.label_value.clone();
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(POPUP_PAD).mount(Mount::Layer(overlay));
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(overlay.pad).mount(Mount::Layer(overlay));
let container = PopupBody { common: Common::new(), props: ContainerProps { owner: Some(owner), ..props } }.label(label);
self.show_container_with(popup, container, body).and_then(|shown| shown.inner)
}
@@ -227,7 +226,7 @@ impl Outcome for PopupBodyOutput {
}
/// The layer container [`OverlayUi::show`] shows a popup's body closure in: content-sized, on a popup surface inside
/// `POPUP_PAD`, its memory owned by the component that shows the popup. It adds no node of its own: the layer's node
/// the overlay's `pad`, its memory owned by the component that shows the popup. It adds no node of its own: the layer's node
/// is the popup's.
#[derive(crate::contract::Component)]
#[component(container, unregistered)]
+9 -5
View File
@@ -142,7 +142,7 @@ pub struct MenuItemStyle {
/// The detail line under the label, in `text.muted`.
#[style(text)]
detail: TextLook,
/// The least space between the label and the shortcut: `space.gap.section`.
/// The least space between the label and the shortcut, and between the label and a sample: `space.gap.section`.
shortcut_gap: f32,
/// The gap between a submenu and its parent menu: `space.gap.tight`.
submenu_gap: f32,
@@ -478,7 +478,7 @@ impl<'a> MenuItem<'a> {
let side = cx.icon();
let command = cx.command();
let (mark, icon) = self.lead_columns(cx.ui.ctx(), side, cx.gap(), command, level);
let sample = self.sample_column(cx.ui.ctx(), line, cx.gap());
let sample = self.sample_column(cx.ui.ctx(), line, cx.style.shortcut_gap.max(cx.gap()));
let trail = if self.submenu { side } else { self.keys(command).map_or(0.0, |keys| cx.face(keys).x) };
Columns { mark, icon, sample, trail }
}
@@ -705,7 +705,8 @@ impl Component for MenuItem<'_> {
let detail_height = detail_run.as_ref().map_or(0.0, |run| draw.layout(run, f32::INFINITY).size().y);
let trail = if self.submenu { side } else { cx.part_if_declared(SHORTCUT).map_or(0.0, |part| part.rect.width()) };
let line = label_line(cx.content_rect, detail_height);
let sample_column = self.sample_column(&cx.core.ctx, line.height(), gap);
let sample_gap = cx.style.shortcut_gap.max(gap);
let sample_column = self.sample_column(&cx.core.ctx, line.height(), sample_gap);
let columns = Columns { mark: mark_column, icon: icon_column, sample: sample_column, trail };
let placed = self.place(&columns, line, rtl, cx.style.shortcut_gap.max(gap));
let ink = cx.resolve(&cx.style.icon.color);
@@ -747,8 +748,11 @@ impl Component for MenuItem<'_> {
// Samples start at one edge of the shared column, after its gap, so a level's samples line up; a sample-only
// row's sample takes the label's room and the column.
if let Some((aspect, face)) = &self.sample {
let rect =
if self.sample_only { placed.label.union(placed.sample) } else { Flow::new(placed.sample, rtl).span(gap, aspect.of(line.height())) };
let rect = if self.sample_only {
placed.label.union(placed.sample)
} else {
Flow::new(placed.sample, rtl).span(sample_gap, aspect.of(line.height()))
};
face.paint(&ui.content_painter(cx), rect);
}
if self.submenu {
@@ -5,7 +5,7 @@ use super::{Calendar, CalendarView, DatePrecision, PickedDate, offered};
use crate::buttons::Link;
use crate::choice::Segmented;
use crate::contract::{
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Entry, HeaderRegion, Mount, Overlay, POPUP_PAD, Props as _,
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Entry, HeaderRegion, Mount, Overlay, POPOVER_PAD, Props as _,
Remember as _, Role, Show as _, ShowContainer as _, Trigger, WordSetCx as _, clicked,
};
use crate::layout::RowAlign;
@@ -170,7 +170,7 @@ impl<'a> CalendarPopover<'a> {
/// `value` is a bound or kept binding: a given binding is never written, and the output carries no edit to report.
pub fn new(label: impl Into<Label>, open: Bind<'a, bool>, value: Bind<'a, Option<PickedDate>>) -> Self {
let props =
ContainerProps::new().surface(SurfaceKind::Popup).pad(POPUP_PAD).header(HeaderRegion::new()).mount(Mount::Layer(Overlay::popover()));
ContainerProps::new().surface(SurfaceKind::Popup).pad(POPOVER_PAD).header(HeaderRegion::new()).mount(Mount::Layer(Overlay::popover()));
CalendarPopover {
common: Common::new(),
props,
+2 -2
View File
@@ -2,7 +2,7 @@
use crate::contract::overlay::{Anchor, Dismiss, OverlayFit};
use crate::contract::{
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, Overlay, POPUP_PAD, Pad, Props as _, Role, SaveKey,
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, Overlay, POPOVER_PAD, Pad, Props as _, Role, SaveKey,
Trigger,
};
use crate::runtime::env::Label;
@@ -84,7 +84,7 @@ pub struct Popover<'a> {
impl<'a> Popover<'a> {
/// A popover named `label`, open while `open` is true.
pub fn new(label: impl Into<Label>, open: Bind<'a, bool>) -> Self {
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(POPUP_PAD).mount(Mount::Layer(Overlay::popover()));
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(POPOVER_PAD).mount(Mount::Layer(Overlay::popover()));
Popover { common: Common::new(), props, open, closed: None }.label(label)
}
+19 -10
View File
@@ -693,14 +693,18 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
let pinned = if rule { None } else { arrangement.pinned(offset.y as f32) };
let shift = view.min.to_vec2() - vec2(offset.x as f32, offset.y as f32);
let clip = area;
// Headers and tail rows end at the scroll bar while it shows, so a header's detail stays clear of it.
let clear = cx.rows_view().unwrap_or(view);
let clear_of_bar = |rect: Rect| Rect::from_x_y_ranges(rect.min.x.max(clear.min.x)..=rect.max.x.min(clear.max.x), rect.y_range());
for (group, header) in arrangement.headers.iter().enumerate() {
let (rect, held) = match pinned {
Some((at, lifted)) if at == group => (lifted, true),
_ => (*header, false),
};
let rect = Self::group_rect(rect.translate(shift), view, rtl);
let rect = clear_of_bar(Self::group_rect(rect.translate(shift), view, rtl));
let Some(declared) = self.groups.get(group) else { continue };
if !rect.intersects(clip) {
// A view narrower than the header's inset and the bar leaves the header no width, and it takes no part.
if rect.width() <= 0.0 || !rect.intersects(clip) {
continue;
}
if rule {
@@ -721,8 +725,8 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
}
}
for (at, (row, rect)) in self.tail.iter().zip(&arrangement.tails).enumerate() {
let rect = Self::group_rect(rect.translate(shift), view, rtl);
if !rect.intersects(clip) {
let rect = clear_of_bar(Self::group_rect(rect.translate(shift), view, rtl));
if rect.width() <= 0.0 || !rect.intersects(clip) {
continue;
}
self.placed_tail.push((at, rect));
@@ -883,11 +887,14 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
let selected = group.selectable && cx.collection_selection().is_some_and(|held| held.contains(&group.key));
let state = RowState { emphasized: lead == Some(Slot::Header(placed.group)), ..RowState::default() };
let header = self.header_row(group, state);
ui.face(section_part(&group.key), if selected { header.selected(true) } else { header });
if placed.toggle {
let disclosure = Disclosure::new(Bind::given(group.open)).node(false).label(group.title.clone());
ui.face(TOGGLE.at(placed.group as u64), disclosure);
}
// The header's text is cut at its end, which stops at the scroll bar while the bar shows.
ui.clipped(rect, |ui| {
ui.face(section_part(&group.key), if selected { header.selected(true) } else { header });
if placed.toggle {
let disclosure = Disclosure::new(Bind::given(group.open)).node(false).label(group.title.clone());
ui.face(TOGGLE.at(placed.group as u64), disclosure);
}
});
}
for &(at, rect) in &self.placed_tail {
let row = &self.tail[at];
@@ -895,7 +902,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
ui.draw().edge_rule(RuleKind::Divider, rect, RectSide::Top);
}
let state = RowState { emphasized: lead == Some(Slot::Tail(at)), ..RowState::default() };
ui.face(section_part(&row.key), ListRow::new(row.label.clone()).rows(self.items.row_height).node(false).state(state));
ui.clipped(rect, |ui| {
ui.face(section_part(&row.key), ListRow::new(row.label.clone()).rows(self.items.row_height).node(false).state(state));
});
}
// The gap under the pointer shows where an insertion lands; the part's state layer shows hover and focus.
for &(at, rect) in &self.placed_gaps {
+27
View File
@@ -90,6 +90,33 @@ fn a_row_sample_sits_between_the_label_and_the_shortcut_and_mirrors() {
}
}
/// A row whose label sets the menu's width keeps `space.gap.section` between the label and its sample, as between the
/// label and a shortcut, so a font's name does not run into its sample.
#[trial]
fn a_wide_label_keeps_the_section_gap_before_its_sample() {
const LABEL: &str = "A family name long enough to set the width of the whole menu";
let cells = Cells::default();
let painted = cells.clone();
let section = Rc::new(Cell::new(0.0));
let seen = Rc::clone(&section);
let mut fixture = Fixture::new(move |ui| {
seen.set(craft_ui::runtime::env::Env::of(ui).tokens.tokens().space.gap.section);
Menu::inline("Fonts").show(ui, |ui, _| {
let painted = painted.clone();
let face = FacePaint::new(1, move |_, rect| {
painted.lock().unwrap().insert(1, rect);
});
MenuItem::new(LABEL).sample(ThumbAspect::new(4, 1), face).show(ui);
});
});
fixture.settle();
let label = run(&fixture, LABEL).expect("the label is painted");
let sample = cells.lock().unwrap().get(&1).copied().expect("the sample is painted");
let (gap, section) = (sample.min.x - label.max.x, section.get());
assert!(section > 0.0, "the tokens give a section gap");
assert!(gap >= section - 0.5, "the sample stands {gap} after the label, under the section gap {section}: {label:?} then {sample:?}");
}
/// The app commands the shortcut trial's rows bind, each with a chord.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "menuRowsTrial")]
@@ -7,6 +7,7 @@ use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::pickers::{CalendarPopover, CalendarView, DatePicker, DatePrecision, PickedDate};
use craft_ui::runtime::env::Env;
use craft_ui::testing::Fixture;
use craft_ui::testing::snapshot::layer_rects;
use egui::{Key, Modifiers, Ui};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -113,6 +114,55 @@ fn the_calendar_popover_follows_a_value_set_while_it_is_open() {
follows(&mut fixture, &value, &titles, "the date picker's calendar");
}
/// How far the calendar's Previous button stands in from the start edge of the popup layer that holds it. The end
/// edge is left out: a date picker's popup is at least as wide as its field, so it can be wider than the calendar.
fn calendar_inset(fixture: &Fixture) -> f32 {
let previous = fixture.by_label("Previous").expect("the calendar's previous button is shown").rect;
let layers = layer_rects(fixture.ctx());
let popup = layers
.iter()
.copied()
.filter(|rect| rect.contains_rect(previous))
.min_by(|a, b| a.area().total_cmp(&b.area()))
.unwrap_or_else(|| panic!("no layer holds the calendar's previous button {previous:?}: {layers:?}"));
previous.left() - popup.left()
}
/// The date picker's calendar stands as far in from its popup's start edge as the calendar popover's does, the regular
/// pad: both are popovers.
#[craft_ui::testing::trial]
fn the_date_pickers_calendar_pads_as_the_calendar_popover() {
let pad = Rc::new(Cell::new(0.0));
let seen = Rc::clone(&pad);
let mut fixture = Fixture::new(move |ui| {
seen.set(Env::of(ui).tokens.tokens().space.pad.regular);
let opener = Button::new("Due").show(ui);
let mut open = true;
let mut now = Some(PickedDate::day(YEAR, AUGUST, 14));
CalendarPopover::new("Due date", Bind::bound(&mut open), Bind::bound(&mut now))
.precisions(&[DatePrecision::Day])
.opened_by(&opener)
.show(ui, |_, _| {});
});
fixture.room(egui::vec2(600.0, 500.0)).settle();
let popover = calendar_inset(&fixture);
let mut fixture = Fixture::new(move |ui| {
let mut now = Some(PickedDate::day(YEAR, AUGUST, 14));
DatePicker::new("From", Bind::bound(&mut now)).precisions(&[DatePrecision::Day]).show(ui);
});
fixture.room(egui::vec2(600.0, 500.0)).idle(10);
fixture.key(Key::Tab, Modifiers::NONE);
fixture.key(Key::ArrowDown, Modifiers::ALT);
fixture.idle(4);
let picker = calendar_inset(&fixture);
let pad = pad.get();
assert!(pad > 0.0, "the tokens give a regular pad");
assert!((popover - pad).abs() <= 0.5, "the calendar popover's calendar stands {popover} in, not the regular pad {pad}");
assert!((picker - popover).abs() <= 0.5, "the date picker's calendar stands {picker} in from its start edge, the calendar popover's {popover}");
}
/// A date format keeps the weeks starting where the app puts them, whatever the locale says.
#[craft_ui::testing::trial]
fn a_date_format_starts_its_weeks_where_the_app_says() {
@@ -173,6 +173,34 @@ fn a_document_popup_list_aligns_its_rows_with_the_opener() {
assert!((row.left() - opener.left()).abs() <= 1.0 && (row.right() - opener.right()).abs() <= 1.0, "row {row:?}, opener {opener:?}");
}
/// A popover's content stands `space.pad.regular` in from every edge of its surface, as a panel's does.
#[trial]
fn a_popover_pads_its_content_as_a_panel() {
let mut open = true;
let pad = Rc::new(Cell::new(0.0));
let seen = Rc::clone(&pad);
let mut fixture = Fixture::new(move |ui| {
seen.set(craft_ui::runtime::env::Env::of(ui).tokens.tokens().space.pad.regular);
let opener = Button::new("Open").show_at(ui, OPENER).response;
Popover::new("Options", Bind::bound(&mut open)).opened_by(&opener).show(ui, |ui, _| {
Button::new("Snap").show(ui);
});
});
fixture.room(Vec2::new(600.0, 400.0)).settle();
let popover = fixture.by_label("Options").expect("the popover").rect;
let snap = fixture.by_label("Snap").expect("the popover's button").rect;
let pad = pad.get();
assert!(pad > 0.0, "the tokens give a regular pad");
for (edge, inset) in [
("left", snap.left() - popover.left()),
("top", snap.top() - popover.top()),
("right", popover.right() - snap.right()),
("bottom", popover.bottom() - snap.bottom()),
] {
assert!((inset - pad).abs() <= 0.5, "the {edge} inset is {inset}, not the regular pad {pad}: {snap:?} in {popover:?}");
}
}
/// A scrolling page taller than the window: an "Open" button that opens a popup list of `ROWS` rows while `open`, then
/// `PAGE` buttons. The rows the list activates go to `activated`.
fn page(open: Rc<Cell<bool>>, activated: Rc<RefCell<Vec<usize>>>) -> Fixture {
+69 -2
View File
@@ -9,8 +9,10 @@ use craft_ui::display::Text;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::{ThumbAspect, ToggleState};
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Fixture, pointer};
use craft_ui::tile_grid::{Around, ArrangeSpacing, GridEvent, GridZoom, GroupHeads, Tile, TileGrid, TileGroup, TileZoom, Tiling, ZoomStep, arrange};
use craft_ui::testing::{Fixture, Target, pointer};
use craft_ui::tile_grid::{
Around, ArrangeSpacing, GridEvent, GridZoom, GroupHeads, TailRow, Tile, TileGrid, TileGroup, TileZoom, Tiling, ZoomStep, arrange,
};
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -87,6 +89,71 @@ fn rule_group_heads_take_no_title_no_tab_stop_and_never_close() {
assert!(!grouped, "a click on a rule reports no group event: {:?}", events.borrow());
}
const DETAIL: &str = "128 tiles";
const MORE: &str = "More tiles";
/// A grid of `tiles` tiles in the group "Alpha", followed by the tail row "More tiles", in a room `width` points wide
/// and 400 points high.
fn headed_grid(tiles: usize, width: f32) -> Fixture {
let mut fixture = Fixture::new(move |ui| {
let keys: Vec<usize> = (0..tiles).collect();
let source = keyed(&keys, |key: &usize| *key);
let groups = [TileGroup::new(1000usize, 0, tiles, "Alpha").detail(DETAIL)];
let tail = [TailRow::new(2000usize, MORE)];
let _ = TileGrid::new("Library").groups(&groups).tail(&tail).show_items(ui, &source, &mut |key, _| Tile::new(format!("Tile {key}")));
});
fixture.room(Vec2::new(width, 400.0));
fixture.settle();
fixture
}
/// Where a group header's detail is painted and the header's heading node lies, in a grid of `tiles` tiles in a room
/// 300 points wide and 400 points high.
fn header_detail(tiles: usize) -> (Rect, Rect) {
let fixture = headed_grid(tiles, 300.0);
let detail = fixture.texts().iter().find(|run| run.text == DETAIL).map(|run| run.rect).expect("the header's detail is painted");
let head = fixture.by_label("Alpha, 128 tiles").expect("the header's heading node").rect;
(detail, head)
}
/// While the grid scrolls, a group header ends at its scroll bar, so the detail at the header's end stays clear of it.
#[craft_ui::testing::trial]
fn a_group_header_ends_at_the_scroll_bar() {
let (still, still_head) = header_detail(3);
let (scrolled, scrolled_head) = header_detail(TILES);
assert!(scrolled_head.right() < still_head.right() - 1.0, "the header ends before the bar: {scrolled_head:?} against {still_head:?}");
assert!(scrolled.right() < still.right() - 1.0, "the detail moves clear of the bar: {scrolled:?} against {still:?}");
assert!(scrolled.right() <= scrolled_head.right() + 0.5, "and stays inside its header: {scrolled:?} in {scrolled_head:?}");
}
/// While the grid scrolls, a header's face and a tail row's face are cut at the scroll bar, so text laid out past the
/// row's end is not painted under the bar.
#[craft_ui::testing::trial]
fn header_and_tail_faces_are_cut_at_the_scroll_bar() {
let mut fixture = headed_grid(TILES, 300.0);
let head = fixture.by_label("Alpha, 128 tiles").expect("the header's heading node").rect;
let detail = fixture.texts().iter().find(|run| run.text == DETAIL).map(|run| run.clip).expect("the header's detail is painted");
assert!(detail.right() <= head.right() + 0.5, "the detail's clip ends at the header's end: {detail:?} in {head:?}");
let center = fixture.shown().center();
fixture.frame(vec![pointer::moved(center), pointer::wheel(-100_000.0)]);
fixture.settle();
let row = fixture.by_label(MORE).expect("the tail row is in view at the end").rect;
let label = fixture.texts().iter().find(|run| run.text == MORE).map(|run| run.clip).expect("the tail row's label is painted");
assert!(label.right() <= row.right() + 0.5, "the tail row's clip ends at the row's end: {label:?} in {row:?}");
}
/// In a grid too narrow to hold a header beside its scroll bar, the header and the tail row take no part, so no
/// press lands on an empty row.
#[craft_ui::testing::trial]
fn a_grid_too_narrow_for_its_rows_places_no_empty_rows() {
let mut fixture = headed_grid(TILES, 8.0);
let empty = |target: Option<Target>| target.is_some_and(|target| target.rect.width() <= 0.0);
assert!(!empty(fixture.by_label("Alpha, 128 tiles")), "the header is not placed with no width");
fixture.frame(vec![pointer::moved(fixture.shown().center()), pointer::wheel(-100_000.0)]);
fixture.settle();
assert!(!empty(fixture.by_label(MORE)), "the tail row is not placed with no width");
}
/// A grid in a stack beside another takes its rows' height in the row's measuring run, so the stack holds the whole
/// grid and what follows it: a button under the grid takes clicks.
#[craft_ui::testing::trial]