From da14b63ff8a4f2b36e25d7b7f6a206d4c3136b40 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 21:27:10 +0700 Subject: [PATCH] appearance-w2: net change of 2 commits - appearance-w2: written from its sheet - appearance-w2: repair 1 --- crates/ui-contract/src/contract/cx/item.rs | 4 +- .../ui-contract/src/contract/items/hooks.rs | 79 +++++++++-- .../ui-contract/tests/it/collection/list.rs | 124 +++++++++++++++++- crates/ui-widgets/src/list/view.rs | 16 ++- crates/ui-widgets/src/tile_grid/grid.rs | 51 +++++-- .../ui-widgets/src/tile_grid/grid/stories.rs | 10 ++ crates/ui-widgets/src/tile_grid/headers.rs | 13 +- crates/ui-widgets/tests/it/list.rs | 73 +++++++++++ crates/ui-widgets/tests/it/tile_grid/grid.rs | 39 +++++- 9 files changed, 369 insertions(+), 40 deletions(-) diff --git a/crates/ui-contract/src/contract/cx/item.rs b/crates/ui-contract/src/contract/cx/item.rs index a031d90d6..54bac99f4 100644 --- a/crates/ui-contract/src/contract/cx/item.rs +++ b/crates/ui-contract/src/contract/cx/item.rs @@ -43,6 +43,7 @@ pub struct ItemCx<'a, 'r, K> { pub(crate) id: Id, pub(crate) memory: &'a mut MemoryStage, pub(crate) tip: Option>, + pub(crate) detail: Option>, pub(crate) openers: Vec, pub(crate) item: Id, pub(crate) cells: Vec<(craft_behavior::ColumnKey, Rect)>, @@ -78,8 +79,7 @@ impl<'r, K> ItemCx<'_, 'r, K> { /// Shows `body` under the item, across the content width, in a child `Ui` with id `sub(item_id, "detail")`. It adds /// its height to the item's slot, which keeps its last shown height out of view. pub fn detail(&mut self, body: impl FnOnce(&mut Ui) + 'r) { - let _ = body; - todo!("ap.AP12") + self.detail = Some(Box::new(body)); } /// The opener for the item's part `part`: after the collection is shown, `CollectionResponse::opener` gives the diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 70ab4c2c1..354250b19 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -29,6 +29,9 @@ use egui::{Context, Id, Pos2, Rect, Ui, UiBuilder, Vec2}; use std::rc::Rc; use std::sync::Arc; +/// How far a detail row's recorded height may differ from the height its pass placed it by before the pass runs again. +const DETAIL_EPS: f32 = 0.01; + impl ShapeHooks for ItemsHooks<'_, '_, C> { fn shape(&self) -> ShapeKind { ShapeKind::Item @@ -596,6 +599,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { cells, grid: grid.as_ref(), tip: None, + detail: None, openers: Vec::new(), item: item_id, memory: &mut *cx.core.memory, @@ -604,6 +608,9 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let item = (self.item)(&key, &mut icx); let mut item = comp.dress(item, &state); let tip = icx.tip.take(); + let detail = icx.detail.take(); + debug_assert!(detail.is_none() || layout.is_auto(at), "an item's detail needs an auto-height row; a grid and a fixed-height row ignore it"); + let detail = detail.filter(|_| layout.is_auto(at)); let openers = std::mem::take(&mut icx.openers); drop(icx); item = Props::id(item, item_id); @@ -638,16 +645,22 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { Some((row_ui, installed)) } }; + // The height of the leaf of a row with a detail body; the slot is the leaf and the body. + let mut leaf_height: Option = None; // A row is a run or a member, so one of the two is there. if let Some((measure_ui, _)) = row_ui.as_ref().or(members_ui.as_ref()) { - if layout.is_auto(at) && !self.measured_for_reveal.contains(&at) { + if layout.is_auto(at) && (detail.is_some() || !self.measured_for_reveal.contains(&at)) { let measured = item.measure_in(measure_ui, Proposal::Width(row.width())).y; #[cfg(feature = "testing")] crate::runtime::measure::count_row_measure(&ctx, rows::measured_id(id, &key)); - rows::record_measure(&ctx, id, rows::measured_id(id, &key), Vec2::new(row.width(), measured)); - if measured != row.height() { - Arc::make_mut(&mut layout).set_height(at, measured); - row = self.screen(&layout, rect, at, offset, rtl); + if detail.is_some() { + leaf_height = Some(measured); + } else { + rows::record_measure(&ctx, id, rows::measured_id(id, &key), Vec2::new(row.width(), measured)); + if measured != row.height() { + Arc::make_mut(&mut layout).set_height(at, measured); + row = self.screen(&layout, rect, at, offset, rtl); + } } } if let Some(column) = &fit { @@ -664,20 +677,39 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { row = self.screen(&layout, rect, at, offset, rtl); } } - shown_rows.push(ShownRow::new(key.clone(), row, shown_cells.clone())); + let leaf = leaf_height.map_or(row, |height| Rect::from_min_size(row.min, Vec2::new(row.width(), height))); + shown_rows.push(ShownRow::new(key.clone(), leaf, shown_cells.clone())); let Some((mut row_ui, installed)) = row_ui else { debug_assert!(tip.is_none(), "a member of a collection's run takes no rich tooltip"); + debug_assert!(detail.is_none(), "a member of a collection's run takes no detail body"); let shown = shown_rows.len() - 1; members.push(Member { at, key, item, row, clip, flags, position, renaming: state.renaming, openers, shown }); continue; }; let out = match tip { - Some(tip) => item.show_at_with_tip(&mut row_ui, row, tip), - None => item.show_at(&mut row_ui, row), + Some(tip) => item.show_at_with_tip(&mut row_ui, leaf, tip), + None => item.show_at(&mut row_ui, leaf), }; + if let Some(body) = detail { + // The body's stops follow the leaf's: it shows inside the item's scope, under the leaf. + let below = Rect::from_min_size(Pos2::new(row.min.x, leaf.max.y), Vec2::new(row.width(), f32::INFINITY)); + let builder = UiBuilder::new().max_rect(below).layout(child::column_layout(rtl)).scope_id(sub(item_id, "detail")); + let mut body_ui = alloc::child(&mut row_ui, builder); + body_ui.set_clip_rect(clip); + body(&mut body_ui); + let total = leaf.height() + body_ui.min_rect().height(); + rows::record_measure(&ctx, id, rows::measured_id(id, &key), Vec2::new(row.width(), total)); + if (total - row.height()).abs() > DETAIL_EPS { + Arc::make_mut(&mut layout).set_height(at, total); + // The rows after this one were placed by the old height: the pass runs again with the new one. + if !row_ui.is_sizing_pass() && !crate::runtime::measure::active(&ctx) { + crate::runtime::egui::sizing::request_discard(&ctx, crate::runtime::egui::sizing::Rerun::Layout); + } + } + } // After the row is shown: its toggle cells have recorded their names by then. self.report_toggle_cells(&ctx, (id, item_id), (at, &key), (shown_cells.as_slice(), cx.core.resolved.enabled), &cx.core.env); - let label = out.label_rect().unwrap_or(row); + let label = out.label_rect().unwrap_or(leaf); self.slow_click_label(&key, label); crate::runtime::keys::redirect_node(&ctx, item_id, id, ITEM_NODE.at(key_hash(&key))); if let Some(row) = shown_rows.last_mut() { @@ -863,6 +895,16 @@ impl ItemsHooks<'_, '_, C> { } impl ItemsHooks<'_, '_, C> { + /// Goes on renaming after a Shift+Enter commit: the field holds the applied name `name`, selected whole when focus + /// is requested again, and the next commit is its own undo step. + fn continue_rename(&mut self, ctx: &Context, name: String) { + self.renaming.draft = name; + self.renaming.focused = false; + self.renaming.proposed = false; + self.renaming.gesture = crate::runtime::edit::next_gesture_id(ctx); + self.refocus = false; + } + /// The rename editor of the row `(at, key)` being renamed, over its label rect `label`, and the end of the rename /// it reports. pub(super) fn rename_row( @@ -884,6 +926,7 @@ impl ItemsHooks<'_, '_, C> { self.renaming.focused = true; } let gesture = self.renaming.gesture; + let shifted = editor.submitted && editor.submit_mods.shift; let before = Mixed::Same(Rename { key: key.clone(), name: name.clone() }); // The editor's gesture end, if the pass has one, ends the rename. let end = editor.events.iter().rev().find(|event| matches!(event, EditEvent::Commit { .. } | EditEvent::Cancel { .. })).cloned(); @@ -909,8 +952,13 @@ impl ItemsHooks<'_, '_, C> { } Some(EditEvent::Commit { after, .. }) => { let after = Rename { key: key.clone(), name: after }; + let applied = after.name.clone(); self.events.push(CollectionEvent::Rename(EditEvent::commit(gesture, before, after))); - self.ended_rename = true; + if shifted { + self.continue_rename(ctx, applied); + } else { + self.ended_rename = true; + } } Some(EditEvent::Cancel { reason, .. }) => { self.events.push(CollectionEvent::Rename(EditEvent::cancel(gesture, reason, Some(before)))); @@ -919,12 +967,17 @@ impl ItemsHooks<'_, '_, C> { // Enter on a proposed draft nobody typed in commits it. Enter on the row's own name opens no edit run: the // rename ends with no event and no undo step, as a text field's empty commit does. None if editor.submitted => { + let applied = self.renaming.draft.clone(); if self.renaming.proposed { - let after = Rename { key: key.clone(), name: self.renaming.draft.clone() }; + let after = Rename { key: key.clone(), name: applied.clone() }; self.events.push(CollectionEvent::Rename(EditEvent::commit(gesture, before, after))); } - self.ended_rename = true; - self.refocus = true; + if shifted { + self.continue_rename(ctx, applied); + } else { + self.ended_rename = true; + self.refocus = true; + } } None if editor.left_by_tab.is_some() => { self.events.push(CollectionEvent::Rename(EditEvent::cancel(gesture, CancelReason::Blur, Some(before)))); diff --git a/crates/ui-contract/tests/it/collection/list.rs b/crates/ui-contract/tests/it/collection/list.rs index 78bc6cf1d..4e462b52c 100644 --- a/crates/ui-contract/tests/it/collection/list.rs +++ b/crates/ui-contract/tests/it/collection/list.rs @@ -1,14 +1,14 @@ //! The list trials: wheel chaining, keys and selection, and large sources. use super::kit::{Count, Dismissed, List, ROW_H, Row, Words}; -use craft_behavior::{Selection, SelectionChange}; +use craft_behavior::{DisplayOrder, ItemSource, Selection, SelectionChange, SizeHint}; use craft_keymap::{Chord, Mods}; use craft_ui::contract::{Bind, CollectionEvent, CollectionResponse, Props as _, SelectMode, Show as _, ShowCollection as _}; use craft_ui::runtime::focus::{FocusTarget, request}; use craft_ui::runtime::keys; use craft_ui::testing::layout::in_region; use craft_ui::testing::{Frames, input, pointer, trial}; -use egui::{Event, Id, Key, Modifiers, Pos2, Rect, Ui, Vec2}; +use egui::{Event, Id, Key, Modifiers, Pos2, Rect, Sense, Ui, Vec2}; use std::cell::{Cell, RefCell}; const VIEW: Vec2 = Vec2::new(300.0, 200.0); @@ -418,6 +418,126 @@ fn a_million_row_layout_places_and_hits_the_last_row_exactly() { assert!(seen.leads().contains(&(COUNT - 1)), "a press at the last row's centre hits it"); } +/// `n` rows whose height comes from their content, so a row can take a detail body under it. +struct Detailed(usize); + +impl DisplayOrder for Detailed { + fn len(&self) -> usize { + self.0 + } + + fn key(&self, at: usize) -> usize { + at + } + + fn index_of(&self, key: &usize) -> Option { + (*key < self.0).then_some(*key) + } +} + +impl ItemSource for Detailed { + fn size_hint(&self, _: usize) -> SizeHint { + SizeHint::Auto + } +} + +/// A row's detail body takes room under it: the rows after it move down by its height, a press in it is its own and +/// selects nothing, and the slot is as tall again once the row scrolls back into view. +#[trial] +fn a_detail_body_takes_room_under_its_row_and_keeps_its_presses() { + const DETAIL: f32 = 40.0; + const WITH: usize = 1; + let source = Detailed(ROWS); + let seen = Seen::default(); + let rects = RefCell::new(vec![Rect::NOTHING; ROWS]); + let body = Cell::new(Rect::NOTHING); + let pressed = Cell::new(false); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + let list = List::new(SelectMode::Single).id_salt("list"); + seen.take(list.show_items(ui, &source, &mut |key, cx| { + rects.borrow_mut()[*key] = cx.rect; + if *key == WITH { + let (body, pressed) = (&body, &pressed); + cx.detail(move |ui| { + let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), DETAIL), Sense::click()); + body.set(rect); + if response.clicked() { + pressed.set(true); + } + }); + } + Row::new() + })); + }); + }; + let gap = |at: usize| rects.borrow()[at + 1].min.y - rects.borrow()[at].min.y; + frames.idle(3, &mut show); + let leaf = gap(0); + assert!((gap(WITH) - leaf - DETAIL).abs() < SAME, "the row with a body is as tall as its leaf and the body: {} vs {leaf} + {DETAIL}", gap(WITH)); + assert!((gap(WITH + 1) - leaf).abs() < SAME, "the rows after it keep their height"); + + pointer::click(&mut frames, body.get().center(), &mut show); + assert!(pressed.get(), "a press in the body reaches the body"); + assert!(seen.selections().is_empty(), "and leaves the selection alone"); + + frames.frame(vec![pointer::moved(seen.rect.get().center())], &mut show); + for _ in 0..3 { + frames.frame(vec![pointer::wheel(-100_000.0)], &mut show); + } + assert!(seen.range().start > WITH, "the row scrolled out of view"); + for _ in 0..3 { + frames.advance(craft_behavior::GESTURE_GAP); + frames.frame(vec![pointer::wheel(100_000.0)], &mut show); + } + frames.idle(2, &mut show); + assert_eq!(seen.range().start, 0, "the list is back at its first row"); + assert!((gap(WITH) - leaf - DETAIL).abs() < SAME, "the slot keeps its height after it was out of view: {}", gap(WITH)); +} + +/// A click with the modifiers held. +fn click_with(frames: &mut Frames, at: Pos2, mods: Modifiers, show: &mut impl FnMut(&mut Ui)) { + frames.hold(mods); + pointer::click(frames, at, &mut *show); + frames.hold(Modifiers::NONE); +} + +/// Shift+Cmd on a click adds the range from the anchor to the selection and keeps the anchor, so a later plain Shift +/// click still ranges from the first click. +#[trial] +fn shift_cmd_adds_the_range_and_keeps_the_anchor() { + let words = Words::flat(&labels()); + let seen = Seen::default(); + let selection = RefCell::new(Selection::::default()); + let rects = RefCell::new(vec![Rect::NOTHING; 6]); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + let mut held = selection.borrow().clone(); + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + let list = List::new(SelectMode::Multi).id_salt("list").selection(Bind::bound(&mut held)); + seen.take(list.show_items(ui, &words, &mut |key, cx| { + rects.borrow_mut()[*key] = cx.rect; + Row::new() + })); + }); + *selection.borrow_mut() = held; + }; + let sorted = || { + let mut items = selection.borrow().items.clone(); + items.sort_unstable(); + items + }; + frames.idle(3, &mut show); + let at = |row: usize| rects.borrow()[row].center(); + click_with(&mut frames, at(1), Modifiers::NONE, &mut show); + assert_eq!(sorted(), vec![1], "a plain click selects the row"); + click_with(&mut frames, at(4), Modifiers::COMMAND | Modifiers::SHIFT, &mut show); + assert_eq!(sorted(), vec![1, 2, 3, 4], "Shift+Cmd adds the range from the anchor"); + click_with(&mut frames, at(0), Modifiers::SHIFT, &mut show); + assert_eq!(sorted(), vec![0, 1], "the anchor stayed on the first click"); +} + /// A press the focused list takes as a move or a stacking move is gone from egui's input, where the app reads its /// own shortcuts: one press, one action. A chord the list does not take still reaches the app. #[trial] diff --git a/crates/ui-widgets/src/list/view.rs b/crates/ui-widgets/src/list/view.rs index 97f43c188..90da62275 100644 --- a/crates/ui-widgets/src/list/view.rs +++ b/crates/ui-widgets/src/list/view.rs @@ -83,14 +83,8 @@ pub struct List<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { /// The kept rows are in order of how well they match the query. #[prop] ranked: bool, - /// Which end of the rows the list stays at while rows are added: `End` follows the newest row as long as the user - /// left the scroll at the end. - #[prop] - #[allow(dead_code)] // P3(appearance-w2): dp.C6 - scroll_anchor: crate::contract::ScrollAnchor, /// Whether every group after the first starts below a full-width divider row instead of a titled group row. #[prop] - #[allow(dead_code)] // P3(appearance-w2): ap.AP6 group_heads: crate::tile_grid::GroupHeads, } @@ -115,7 +109,6 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> { row_menu: false, filter: None, ranked: false, - scroll_anchor: crate::contract::ScrollAnchor::Start, group_heads: crate::tile_grid::GroupHeads::Titled, } .label(label) @@ -150,6 +143,14 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> { self } + /// Which end of the rows the list stays at while rows are added: `End` follows the newest row as long as the user + /// left the scroll at the end. + #[must_use] + pub fn scroll_anchor(mut self, anchor: crate::contract::ScrollAnchor) -> Self { + self.items.scroll_anchor = anchor; + self + } + /// A row drag carries `map` of it, for the drop targets of type `P`; a row the map gives `None` for does not drag /// unless a reorder rule is set. The drag stays one session with one ghost. #[must_use] @@ -246,6 +247,7 @@ impl Collection for List<'_, K> { fn dress<'r>(&self, row: Self::Item<'r>, state: &RowState) -> Self::Item<'r> { let row = row.rows(self.items.row_height).sub_row(state); + let row = if self.group_heads == crate::tile_grid::GroupHeads::Rule && row.group.is_some() { row.rule(true) } else { row }; if self.row_menu { row.row_menu() } else { row } } diff --git a/crates/ui-widgets/src/tile_grid/grid.rs b/crates/ui-widgets/src/tile_grid/grid.rs index 24e835674..b2bc623c6 100644 --- a/crates/ui-widgets/src/tile_grid/grid.rs +++ b/crates/ui-widgets/src/tile_grid/grid.rs @@ -29,6 +29,7 @@ use craft_behavior::{ }; use craft_keymap::{Chord, Key, Mods}; use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2, pos2, vec2}; +use std::borrow::Cow; use std::cell::RefCell; use std::hash::Hash; @@ -272,7 +273,6 @@ pub struct TileGrid<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { /// How the groups are set apart: `Rule` starts every group after the first below a full-width divider row in place /// of its titled head. #[prop] - #[allow(dead_code)] // P3(appearance-w2): ap.AP6 group_heads: GroupHeads, /// The layout of this pass, kept for the headers' parts and paint. laid: RefCell>, @@ -421,6 +421,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { } let aspect = if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 }; let tail_height = self.items.row_height.of(cx); + let groups = self.shown_groups(); let recipe = self.items.rows_stamp.map(|stamp| Recipe { stamp, width, @@ -430,7 +431,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { justified: self.justified, around, group_header: spacing.group_header, - groups: self.groups.iter().map(|group| (group.start, group.count, group.open)).collect(), + groups: groups.iter().map(|group| (group.start, group.count, group.open)).collect(), tail: (self.tail.len(), tail_height), }); if let (Some(previous), Some(recipe)) = (previous, &recipe) @@ -441,7 +442,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { } let layout = if self.justified || !self.groups.is_empty() || !self.tail.is_empty() { let tiling = if self.justified { Tiling::justified(side) } else { Tiling::cards(side, aspect) }; - let mut arrangement = arrange(&aspects_of(source), self.groups, width, tiling, spacing, around); + let mut arrangement = arrange(&aspects_of(source), &groups, width, tiling, spacing, around); arrangement.add_tail(self.tail.len(), tail_height, width, spacing); GridLayout::arranged(arrangement, width, around) } else { @@ -485,6 +486,19 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { self.laid.borrow().as_ref().and_then(|layout| layout.arrangement().map(|arrangement| arrangement.tail_from())) } + /// The groups as they show: under `Rule` every group is open, whatever the app declared. + fn shown_groups(&self) -> Cow<'a, [TileGroup]> { + match self.group_heads { + GroupHeads::Titled => Cow::Borrowed(self.groups), + GroupHeads::Rule => Cow::Owned(self.groups.iter().map(|group| group.clone().open(true)).collect()), + } + } + + /// Group headers open and close their group: only titled heads do. + fn collapses(&self) -> bool { + self.collapsible && self.group_heads == GroupHeads::Titled + } + fn group_rect(rect: Rect, view: Rect, rtl: bool) -> Rect { if rtl { Rect::from_min_max(pos2(view.min.x + view.max.x - rect.max.x, rect.min.y), pos2(view.min.x + view.max.x - rect.min.x, rect.max.y)) @@ -497,7 +511,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { /// disclosure column the grid owns when the groups open and close. fn header_row(&self, group: &TileGroup, state: RowState) -> ListRow<'static> { let mut row = ListRow::new(group.title.clone()).heading().rows(self.items.row_height).node(false).depth(group.depth).state(state); - if self.collapsible { + if self.collapses() { row = row.group(group.open).disclosure_by_host(); } if let Some(icon) = &group.icon { @@ -531,7 +545,9 @@ impl Component for TileGrid<'_, K> self.placed_tail.clear(); let Some(arrangement) = self.laid.borrow().as_ref().and_then(|layout| layout.arrangement().cloned()) else { return }; let (view, offset, rtl) = (cx.content_rect, cx.offset(), cx.flow.is_rtl()); - let pinned = arrangement.pinned(offset.y as f32); + let rule = self.group_heads == GroupHeads::Rule; + // A rule has nothing to pin. + 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; for (group, header) in arrangement.headers.iter().enumerate() { @@ -544,6 +560,11 @@ impl Component for TileGrid<'_, K> if !rect.intersects(clip) { continue; } + if rule { + // A divider takes no press and no stop: it is placed for its paint only. + self.placed.push(Placed { group, rect, pinned: false, toggle: false }); + continue; + } let column = self .header_row(declared, RowState::default()) .disclosure_at(&cx.style.header, rect, rtl, &|run| cx.layout_at(run, f32::INFINITY).size().x); @@ -601,7 +622,7 @@ impl Component for TileGrid<'_, K> } } } - let placed = self.placed.clone(); + let placed = if self.group_heads == GroupHeads::Rule { Vec::new() } else { self.placed.clone() }; for Placed { group, rect, .. } in placed { let Some(declared) = self.groups.get(group) else { continue }; let part = section_part(&declared.key); @@ -610,7 +631,7 @@ impl Component for TileGrid<'_, K> if let Some(result) = cx.part_if_declared(part) && let PressPhase::Release { start, click: true, .. } = result.press.phase { - let mods = result.press.mods; + let mods = crate::runtime::pointer::frame(&cx.core.ctx).pick_mods; self.events.push(match start.button { PointerButton::Secondary => { GridEvent::GroupMenu { group, at: if cx.flow.is_rtl() { rect.right_bottom() } else { rect.left_bottom() } } @@ -620,7 +641,7 @@ impl Component for TileGrid<'_, K> } else if cx.part_activated(part) == Some(FireSource::Access) { self.events.push(GridEvent::GroupPicked { group, mods: Mods::NONE }); } - if self.collapsible && cx.part_activated(toggle).is_some() { + if self.collapses() && cx.part_activated(toggle).is_some() { self.events.push(GridEvent::GroupOpen { group, open: !open }); } } @@ -634,7 +655,7 @@ impl Component for TileGrid<'_, K> self.tail_clicked.push(key.clone()); } } - if self.collapsible { + if self.collapses() { while let Some(request) = cx.intents().take_access() { let Some(target) = request.target else { continue }; let wanted = match request.action { @@ -665,7 +686,7 @@ impl Component for TileGrid<'_, K> let node = access.node(section_part(&group.key), Role::HEADING); node.level(GROUP_LEVEL); node.name = Name::Text(if group.detail.is_empty() { group.title.clone() } else { format!("{}, {}", group.title, group.detail) }); - if self.collapsible { + if self.collapses() { node.expanded = Some(group.open); } } @@ -684,6 +705,12 @@ impl Component for TileGrid<'_, K> for placed in &self.placed { let Some(group) = self.groups.get(placed.group) else { continue }; let rect = placed.rect; + if self.group_heads == GroupHeads::Rule { + if placed.group > 0 { + ui.draw().edge_rule(RuleKind::Divider, rect, RectSide::Top); + } + continue; + } if placed.pinned { let draw = ui.draw(); draw.fill(&PaintShape::Rect(rect, CornerRadius::ZERO), style.pinned); @@ -714,7 +741,7 @@ impl Component for TileGrid<'_, K> let selected = self.rated(&cx); let mut response = cx.collection_response(); let mut events = self.events; - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame(&cx.core.ctx).pick_mods; let group_of = |key: &K| self.groups.iter().position(|group| group.key == *key); let is_tail = |key: &K| self.tail.iter().any(|row| row.key == *key); let mut kept = Vec::with_capacity(response.events.len()); @@ -796,7 +823,7 @@ impl Collection for TileGrid<'_, K /// places. fn filtered<'s>(&self, source: &'s dyn ItemSource, _: &crate::runtime::env::Env) -> Option + 's>> { (!self.groups.is_empty() || !self.tail.is_empty()) - .then(|| Box::new(Outline::new(source, self.groups, self.tail, self.collapsible)) as Box + 's>) + .then(|| Box::new(Outline::new(source, &self.shown_groups(), self.tail, self.collapses(), self.group_heads)) as Box + 's>) } fn item_layout(&self, source: &dyn ItemSource, width: f32, cx: &StyleCx<'_>) -> GridLayout { diff --git a/crates/ui-widgets/src/tile_grid/grid/stories.rs b/crates/ui-widgets/src/tile_grid/grid/stories.rs index f5aa44780..21a0e212b 100644 --- a/crates/ui-widgets/src/tile_grid/grid/stories.rs +++ b/crates/ui-widgets/src/tile_grid/grid/stories.rs @@ -153,3 +153,13 @@ fn tile_grid_groups(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { } out.into() } + +#[story(TileGrid<'static, usize>, covers = [], drive = Drive::Never)] +fn tile_grid_rule_heads(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let groups = [ + TileGroup::new(GROUP_KEYS[0], 0, 12, "October 2026"), + TileGroup::new(GROUP_KEYS[1], 12, 8, "September 2026"), + TileGroup::new(GROUP_KEYS[2], 20, 10, "August 2026"), + ]; + grid(ui, data, TileGrid::new("Library").groups(&groups).group_heads(super::GroupHeads::Rule), 30, 1.0).into() +} diff --git a/crates/ui-widgets/src/tile_grid/headers.rs b/crates/ui-widgets/src/tile_grid/headers.rs index 6f0ad957a..8b7b770df 100644 --- a/crates/ui-widgets/src/tile_grid/headers.rs +++ b/crates/ui-widgets/src/tile_grid/headers.rs @@ -2,6 +2,7 @@ //! The item step sees this source, so a header or a tail row is a row it can put the lead on, and the layout places //! the rows by the same positions. +use super::GroupHeads; use super::layout::{Slot, TailRow, TileGroup, group_spans, headers_through, outline_position, slot_at}; use craft_behavior::{ColumnKey, DisplayOrder, ItemSource, SizeHint}; use std::borrow::Cow; @@ -23,14 +24,16 @@ pub(super) struct Outline<'s, K> { /// The keys of the tail rows. tail: Vec, collapsible: bool, + /// Under `Rule` a header is a divider: it is a row of the outline but no stop. + heads: GroupHeads, } impl<'s, K: Clone> Outline<'s, K> { - pub(super) fn new(inner: &'s dyn ItemSource, groups: &[TileGroup], tail: &[TailRow], collapsible: bool) -> Self { + pub(super) fn new(inner: &'s dyn ItemSource, groups: &[TileGroup], tail: &[TailRow], collapsible: bool, heads: GroupHeads) -> Self { let spans = group_spans(groups, inner.len()); let headers = groups.iter().map(|group| Header { key: group.key.clone(), open: group.open }).collect(); let tail = tail.iter().map(|row| row.key.clone()).collect(); - Outline { inner, headers, starts: spans.iter().map(|span| span.start).collect(), tail, collapsible } + Outline { inner, headers, starts: spans.iter().map(|span| span.start).collect(), tail, collapsible, heads } } fn slot(&self, at: usize) -> Slot { @@ -94,7 +97,11 @@ impl DisplayOrder for Outline<'_, K> { } fn section_stop(&self, at: usize) -> bool { - self.is_section(at) + match self.slot(at) { + Slot::Header(_) => self.heads == GroupHeads::Titled, + Slot::Tail(_) => true, + Slot::Tile(_) => false, + } } fn section_stops_before(&self, at: usize) -> usize { diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index aba1b5699..1fb3b10e2 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -155,6 +155,79 @@ fn pointer_commands_name_the_thumbnail_and_leave_the_selection() { assert!(!seen.borrow().iter().any(|event| matches!(event, CollectionEvent::Selection { .. })), "the selection is left alone"); // P3(mechanical): dp.C12 } +/// A thumbnails-only row is its thumbnails: no label band, so it is narrower than a plain row, it paints no label, and +/// the label is still its accessible name. +#[trial] +fn a_thumbnails_only_row_is_as_wide_as_its_thumbnails_and_named_by_its_label() { + use craft_ui::list::ThumbSize; + use egui::Rect; + use std::cell::Cell; + let (only, plain) = (Rc::new(Cell::new(Rect::NOTHING)), Rc::new(Cell::new(Rect::NOTHING))); + let (only_in, plain_in) = (only.clone(), plain.clone()); + let mut fixture = Fixture::new(move |ui| { + let keys = [0_usize, 1]; + let source = keyed(&keys, |key: &usize| *key); + let _ = List::new("Masks").show_items(ui, &source, &mut |key, _| { + let at = *key; + let (only, plain) = (only_in.clone(), plain_in.clone()); + let row = ListRow::new(NAMES[at]).thumb(ThumbSize::Medium, move |_, rect| if at == 0 { only.set(rect) } else { plain.set(rect) }); + if at == 0 { row.thumbnails_only() } else { row } + }); + }); + fixture.room(Vec2::new(300.0, 200.0)); + fixture.settle(); + let (row, other) = (fixture.by_label(NAMES[0]).expect("the row is named by its label").rect, fixture.by_label(NAMES[1]).expect("the plain row").rect); + let picture = only.get(); + assert!(row.contains_rect(picture), "the row holds its thumbnail: {row:?} {picture:?}"); + assert!(row.width() < other.width(), "the row is no wider than its thumbnails: {} vs {}", row.width(), other.width()); + assert!(row.width() < 2.0 * picture.width() && row.height() < 2.0 * picture.height(), "the row is as large as its thumbnail: {row:?} {picture:?}"); + let texts = fixture.texts(); + assert!(!texts.iter().any(|text| text.text == NAMES[0]), "the row paints no label"); + assert!(texts.iter().any(|text| text.text == NAMES[1]), "the plain row paints its label"); +} + +/// 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] +fn a_part_drag_starts_only_with_the_primary_button() { + use craft_ui::list::{RowDragSpot, ThumbSize, ThumbTarget}; + use craft_ui::testing::pointer; + use egui::{Event, Pos2, Rect}; + use std::cell::Cell; + let seen: Events = Rc::new(RefCell::new(Vec::new())); + let picture = Rc::new(Cell::new(Rect::NOTHING)); + let (held, painted) = (seen.clone(), picture.clone()); + let mut fixture = Fixture::new(move |ui| { + let keys = [0_usize]; + let source = keyed(&keys, |key: &usize| *key); + let out = List::new("Layers").show_items(ui, &source, &mut |key, _| { + let painted = painted.clone(); + ListRow::new(NAMES[*key]) + .thumb(ThumbSize::Medium, move |_, rect| painted.set(rect)) + .part_drag(RowDragSpot::Thumb(ThumbTarget::First), 7_u32) + }); + held.borrow_mut().extend(out.events); + }); + fixture.settle(); + let from = picture.get().center(); + let primary: fn(Pos2, bool) -> Event = |at, down| if down { pointer::press(at) } else { pointer::release(at) }; + let buttons: [fn(Pos2, bool) -> Event; 3] = [pointer::secondary, pointer::middle, primary]; + let mut started = Vec::new(); + for button in buttons { + seen.borrow_mut().clear(); + fixture.frame(vec![pointer::moved(from)]); + fixture.frame(vec![button(from, true)]); + for step in 1..=4 { + fixture.frame(vec![pointer::moved(from + Vec2::new(10.0 * step as f32, 0.0))]); + } + fixture.frame(vec![button(from + Vec2::new(40.0, 0.0), false)]); + fixture.settle(); + started.push(seen.borrow().iter().filter(|event| matches!(event, CollectionEvent::Item(_, RowEvent::PartDrag(_)))).count()); + } + assert_eq!(started[..2], [0, 0], "a secondary and a middle drag start no part drag"); + assert!(started[2] > 0, "the primary drag starts it"); +} + /// A click on the selected event deselects it, so the details under the log close. #[trial] fn a_click_on_the_selected_event_deselects_it() { diff --git a/crates/ui-widgets/tests/it/tile_grid/grid.rs b/crates/ui-widgets/tests/it/tile_grid/grid.rs index 870c6c476..7a5b41ec1 100644 --- a/crates/ui-widgets/tests/it/tile_grid/grid.rs +++ b/crates/ui-widgets/tests/it/tile_grid/grid.rs @@ -1,6 +1,12 @@ //! The tile grid's layout: justified rows fill the width with whole cards (picture and what the tile adds around it). -use craft_ui::tile_grid::{Around, ArrangeSpacing, TileGroup, Tiling, arrange}; +use craft_behavior::keyed; +use craft_ui::contract::ShowCollection as _; +use craft_ui::testing::Fixture; +use craft_ui::tile_grid::{Around, ArrangeSpacing, GridEvent, GroupHeads, Tile, TileGrid, TileGroup, Tiling, arrange}; +use egui::Vec2; +use std::cell::RefCell; +use std::rc::Rc; const WIDTH: f32 = 400.0; const ROW: f32 = 100.0; @@ -41,3 +47,34 @@ fn a_leading_group_header_sits_at_the_top_edge_and_ungrouped_tiles_keep_the_inse let loose = arrange::(&aspects, &[], WIDTH, Tiling::justified(ROW), spacing(), Around::default()); assert!((loose.rows[0].top - INSET).abs() < EPS, "tiles that open the grid keep the inset above them"); } + +/// Under `GroupHeads::Rule` a head is a divider: it paints no title, a click on it reports no group event, and a group +/// declared closed still shows its tiles; the group's title stays the heading's name. +#[craft_ui::testing::trial] +fn rule_group_heads_take_no_title_no_tab_stop_and_never_close() { + let events = Rc::new(RefCell::new(Vec::new())); + let held = events.clone(); + let mut fixture = Fixture::new(move |ui| { + let keys: Vec = (0..9).collect(); + let source = keyed(&keys, |key: &usize| *key); + let groups = [ + TileGroup::new(100usize, 0, 3, "Alpha"), + TileGroup::new(101usize, 3, 3, "Beta").open(false), + TileGroup::new(102usize, 6, 3, "Gamma"), + ]; + let out = TileGrid::new("Library") + .groups(&groups) + .collapsible() + .group_heads(GroupHeads::Rule) + .show_items(ui, &source, &mut |key, _| Tile::new(format!("Tile {}", key + 1))); + held.borrow_mut().extend(out.events); + }); + fixture.room(Vec2::new(600.0, 600.0)); + fixture.settle(); + assert!(!fixture.texts().iter().any(|text| text.text == "Beta"), "a rule head paints no title"); + assert!(fixture.by_label("Tile 4").is_some(), "a group declared closed is open under Rule"); + let head = fixture.by_label("Beta").expect("the heading keeps its name").rect; + fixture.click_at(head.center()).settle(); + let grouped = events.borrow().iter().any(|event| matches!(event, GridEvent::GroupOpen { .. } | GridEvent::GroupPicked { .. } | GridEvent::GroupMenu { .. })); + assert!(!grouped, "a click on a rule reports no group event: {:?}", events.borrow()); +}