Revealed trailing parts and the list's row menu: trailing_part_revealed shows a part on a hovered or selected row, while it has focus or while its menu is open; List::row_menu gives every row a More button whose click asks for the row's menu as a secondary click does

This commit is contained in:
aiongg
2026-11-12 14:32:41 +00:00
parent 1ae7661643
commit eb8dfdb97f
17 changed files with 154 additions and 16 deletions
+1
View File
@@ -20,6 +20,7 @@ pub use drag::{SweepApply, SweepStep};
pub use header::ColumnCommands;
#[doc(hidden)]
pub use header::put_toggle_names;
pub use press::item_part_open;
#[doc(hidden)]
pub use request::lead_position;
pub use request::request_rename;
@@ -6,7 +6,7 @@ use super::members::Member;
use super::{Held, ITEM_NODE, ItemsHooks, LastLayout, Lead, Placement, Renaming, Rows, SCROLL, Scrolled, View, key_hash, section_part};
use super::{request, rows};
use crate::contract::ValueOf;
use crate::contract::collection::{CollectionEvent, Gestures, OpenChange, Rename, RowState, ShownRow};
use crate::contract::collection::{CollectionEvent, ContextMenuRequest, Gestures, OpenChange, Rename, RowState, ShownRow};
use crate::contract::cx::{BodyCx, Pointer as _};
use crate::contract::run::{Measuring, ShapeHooks, ShowAt};
use crate::contract::steps::ShapeKind;
@@ -591,6 +591,9 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
if let Some(ask) = out.open_request() {
self.events.push(CollectionEvent::Open(OpenChange { key: key.clone(), open: ask.open, all: ask.all }));
}
if let Some(at) = out.menu_request() {
self.events.push(CollectionEvent::ContextMenu(ContextMenuRequest { key: key.clone(), at: self.on_screen(at), column: None }));
}
if let Some(event) = out.into_event() {
self.events.push(CollectionEvent::Item(key.clone(), event));
}
@@ -2,7 +2,7 @@
//! arena, updated, painted and finished at their rows, reported as sub-nodes of the collection.
use super::{ITEM_NODE, ItemsHooks, key_hash};
use crate::contract::collection::{CollectionEvent, OpenChange, ShownRow};
use crate::contract::collection::{CollectionEvent, ContextMenuRequest, OpenChange, ShownRow};
use crate::contract::run;
use crate::contract::{Collection, Component as _, Cx, Internal, ItemOpener, ItemOutput as _, Meta as _};
use crate::primitives::sensing::{self, MemberSpec};
@@ -86,6 +86,9 @@ impl<'r, C: Collection> ItemsHooks<'_, 'r, C> {
if let Some(ask) = output.open_request() {
self.events.push(CollectionEvent::Open(OpenChange { key: key.clone(), open: ask.open, all: ask.all }));
}
if let Some(at) = output.menu_request() {
self.events.push(CollectionEvent::ContextMenu(ContextMenuRequest { key: key.clone(), at: self.on_screen(at), column: None }));
}
if let Some(event) = output.into_event() {
self.events.push(CollectionEvent::Item(key.clone(), event));
}
+12 -1
View File
@@ -300,9 +300,20 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
pointer: ctx.pointer_latest_pos(),
..response::MemberView::default()
};
let response = response::member(ui, sub(opener.item, ("opener", opener.part)), rect, enabled, view);
let response = response::member(ui, opener_id(opener.item, opener.part), rect, enabled, view);
Some((opener, response))
})
.collect()
}
}
/// The id of the response `CollectionResponse::opener` gives for the part `part` of the item `item`.
fn opener_id(item: Id, part: craft_behavior::PartRef) -> Id {
sub(item, ("opener", part))
}
/// Whether a menu or popover hung from the part `part` of the item `item` (`ItemCx::part_opener`) is open: an item
/// keeps such a part shown while its menu is.
pub fn item_part_open(ctx: &Context, item: Id, part: impl Into<craft_behavior::PartRef>) -> bool {
crate::contract::overlay::container_open::opened_from(ctx, opener_id(item, part.into()))
}
+1 -1
View File
@@ -73,7 +73,7 @@ pub use held::Held;
pub use items::lead_position;
#[doc(hidden)]
pub use items::put_toggle_names;
pub use items::{ColumnCommands, SweepApply, SweepStep, request_rename, section_part};
pub use items::{ColumnCommands, SweepApply, SweepStep, item_part_open, request_rename, section_part};
#[doc(hidden)]
pub use label::colon_of;
pub use label::{CellWidth, FieldLabelRole, FieldLayout, GlyphLabel, LabelAlign, LabelKind, Scrub, SideLabel};
+1 -1
View File
@@ -5,7 +5,7 @@
pub use crate::runtime::overlay::{OpenFilter, any_open, family, is_open, request_close, top};
mod container_open;
pub(crate) mod container_open;
mod dismissal;
mod host;
mod opener;
@@ -56,6 +56,11 @@ pub(crate) fn opener_open(stage: &mut MemoryStage, first: &Opener) -> bool {
open
}
/// Whether the container hung from the opener `opener` (the id of its response) is open, as its slot holds it.
pub(crate) fn opened_from(ctx: &egui::Context, opener: Id) -> bool {
MemoryStage::peek_session::<OpenerOpen>(ctx, sub(opener, "opens")).open
}
/// Writes the opener's slot: the container closed itself (Escape, a press outside, a row ran).
pub(crate) fn set_opener_open(stage: &mut MemoryStage, opener: &Opener, open: bool) {
stage.session::<OpenerOpen>(sub(opener.id, "opens")).open = open;
@@ -535,6 +535,12 @@ pub trait ItemOutput<E>: Outcome {
None
}
/// The item asks for its menu from one of its parts (a row's "More" button): where the menu hangs, in the item's
/// layer. The collection reports it as `CollectionEvent::ContextMenu`, as it does a secondary click on the row.
fn menu_request(&self) -> Option<egui::Pos2> {
None
}
/// The rect of the item's label, where a rename editor goes; `None` puts it over the whole row.
fn label_rect(&self) -> Option<egui::Rect> {
None
+5
View File
@@ -368,6 +368,11 @@ impl MemoryStage {
store::peek_clone::<Wrapped<SHOWN, T>>(ctx, id).map(|wrapped| wrapped.0).unwrap_or_default()
}
/// Read-only access to a session slot, as `peek` does for a shown one.
pub(crate) fn peek_session<T: Slot>(ctx: &Context, id: Id) -> T {
store::peek_clone::<Wrapped<SESSION, T>>(ctx, id).map(|wrapped| wrapped.0).unwrap_or_default()
}
/// Read-only access to a saved slot, as `peek` does for a shown one.
#[doc(hidden)]
pub fn peek_saved<T: Slot>(ctx: &Context, key: &SaveKey) -> T {
+23 -1
View File
@@ -222,6 +222,8 @@ pub struct ListRow<'a> {
pub(super) check: Option<bool>,
pub(super) event: Option<RowEvent>,
pub(super) open: Option<OpenChange<()>>,
/// The row's menu button was clicked: where the menu hangs.
pub(super) menu: Option<egui::Pos2>,
pub(super) label_rect: Rect,
}
@@ -277,6 +279,7 @@ impl<'a> ListRow<'a> {
check: None,
event: None,
open: None,
menu: None,
label_rect: Rect::NOTHING,
}
.label(label)
@@ -434,10 +437,29 @@ impl<'a> ListRow<'a> {
!self.trailing.iter().any(|held| matches!(&held.item, TrailingItem::Part { part: have, .. } if *have == part)),
"trailing part {part:?} is already in the row"
);
self.trailing.push(Trailing { item: TrailingItem::Part { part, face, name: name.into(), enabled: true }, optional: false });
self.trailing.push(Trailing { item: TrailingItem::Part { part, face, name: name.into(), enabled: true, revealed: false }, optional: false });
self
}
/// A trailing part as [`trailing_part`](Self::trailing_part) adds one, shown only on a hovered or selected row,
/// while it has focus or while the menu it opens (`ItemCx::part_opener`) is open: a row's "More" button. It keeps
/// its place and takes a press where it is hidden.
#[must_use]
pub fn trailing_part_revealed(mut self, part: TrailingPart, face: TrailingFace, name: impl Into<Label>) -> Self {
self = self.trailing_part(part, face, name);
if let Some(Trailing { item: TrailingItem::Part { revealed, .. }, .. }) = self.trailing.last_mut() {
*revealed = true;
}
self
}
/// The row's "More" button, a [revealed](Self::trailing_part_revealed) part named "More ({row})": a click on it
/// asks for the row's menu, which the collection reports as `CollectionEvent::ContextMenu` hung from the button.
#[must_use]
pub fn row_menu(self) -> Self {
self.trailing_part_revealed(TrailingPart::MENU, TrailingFace::Icon(IconSpec::svg(craft_behavior::IconId::new("more"))), Label::Empty)
}
/// A component at the trailing end, in the width of a short field, that always shows: a field that edits a
/// value of the row. The row shows `field` in its slot and hands its output to `output` in the pass it is shown. The
/// field's stop joins the row's roving group like the row's focusable parts (Forward from the row enters it, Tab leaves the collection); it takes the keys it
+6
View File
@@ -55,6 +55,8 @@ pub struct RowOutput {
/// The disclosure of a group row was clicked: the state it asks for. The collection reports it as
/// `CollectionEvent::Open`, as it does the keys.
pub open: Option<OpenChange<()>>,
/// The row's menu button was clicked: where the menu hangs, in the row's layer.
pub menu: Option<egui::Pos2>,
/// Where the label and detail are drawn, the full height of the row.
pub label: Rect,
}
@@ -76,6 +78,10 @@ impl ItemOutput<RowEvent> for RowOutput {
self.open.clone()
}
fn menu_request(&self) -> Option<egui::Pos2> {
self.menu
}
fn label_rect(&self) -> Option<Rect> {
Some(self.label)
}
+12 -3
View File
@@ -8,11 +8,11 @@ use super::thumb::{RowThumb, target_at};
use super::trailing::{TrailingFace, TrailingItem, trailing_run};
use crate::buttons::IconButton;
use crate::choice::Checkbox;
use crate::contract::{Bind, Cx, PaintUi, Pointer as _, Props as _, Styled as _};
use crate::contract::{Bind, Cx, PaintUi, Pointer as _, Props as _, Styled as _, item_part_open};
use crate::controls::disclosure::Disclosure;
use crate::list::toggle::{ToggleFace, ToggleState};
use crate::primitives::{Draw, HAlign, IconSpec, PaintShape, Span, StrokeWidth, TextRun, Wrap};
use crate::style::{Ink, StyleColor};
use crate::style::{Flags, Ink, StyleColor};
use craft_behavior::{Flow, IconId, Mixed};
use craft_theme::ControlSize;
use egui::{CornerRadius, Pos2, Rect, Vec2};
@@ -20,6 +20,7 @@ use egui::{CornerRadius, Pos2, Rect, Vec2};
impl ListRow<'_> {
pub(super) fn paint_trailing(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>, placed: &Placed) {
let side = Vec2::splat(cx.style.sizes.icon);
let selected = cx.resolved.selected == Some(true) || cx.env.facts_of(cx.id).is_some_and(|facts| facts.flags.contains(Flags::SELECTED));
for (at, (trailing, slot)) in self.trailing.iter_mut().zip(&placed.items).enumerate() {
let Some(slot) = slot else { continue };
let shape = Rect::from_center_size(slot.center(), side);
@@ -37,8 +38,16 @@ impl ListRow<'_> {
show(ui, at, Rect::from_center_size(slot.center(), Vec2::new(slot.width(), cx.style.sizes.row)));
}
}
TrailingItem::Part { part, face, enabled, .. } => {
TrailingItem::Part { part, face, enabled, revealed, .. } => {
let key = TRAILING.at(u64::from(part.0));
let shown = !*revealed
|| cx.response.hovered()
|| selected
|| cx.part_state(key).flags.contains(Flags::FOCUSED)
|| item_part_open(&cx.ctx, cx.id, key);
if !shown {
continue;
}
match face {
TrailingFace::Icon(icon) => ui.face(key, IconButton::new(icon.clone()).focusable(false).enabled(*enabled)),
TrailingFace::Disclosure { open } => ui.face(key, Disclosure::new(Bind::given(*open)).node(false).enabled(*enabled)),
+17 -4
View File
@@ -6,7 +6,7 @@ use super::paint::draw_clip_arrow;
use super::placement::Sizes;
use super::style::{FillKey, ListRowStyle, RowForm, fill_of, row_ink_of, selected_outline};
use super::thumb::{RowThumb, target_at};
use super::trailing::{TrailingFace, TrailingItem};
use super::trailing::{TrailingFace, TrailingItem, TrailingPart};
use super::{ListRow, RowInk};
use crate::contract::{
Access, Bind, Component, Cx, DragPreview, MeasureCx, Name, OpenChange, PaintUi, PartsCx, Pointer as _, Props as _, Role, RowPressed, Styled as _,
@@ -246,7 +246,8 @@ impl Component for ListRow<'_> {
cx.part(TRAILING_ICON.at(at as u64), shape).tooltip(name.clone());
}
TrailingItem::Part { part, name, enabled: true, .. } => {
cx.part(TRAILING.at(u64::from(part.0)), shape).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name.clone());
let name = self.part_name(*part, name, &cx.words::<ListWords>(), cx.resolved.label);
cx.part(TRAILING.at(u64::from(part.0)), shape).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name);
focusable = true;
}
TrailingItem::Part { part, name, enabled: false, .. } => {
@@ -308,7 +309,11 @@ impl Component for ListRow<'_> {
let TrailingItem::Part { part, .. } = &trailing.item else { continue };
let key = TRAILING.at(u64::from(part.0));
if let Some(source) = cx.part_activated(key) {
self.event = Some(RowEvent::Trailing { part: *part, mods: part_mods(cx, key, source) });
if *part == TrailingPart::MENU {
self.menu = Some(cx.part(key).rect.left_bottom());
} else {
self.event = Some(RowEvent::Trailing { part: *part, mods: part_mods(cx, key, source) });
}
}
}
}
@@ -396,6 +401,7 @@ impl Component for ListRow<'_> {
access.node(TRAILING_ICON.at(at as u64), Role::IMAGE).name = Name::Text(name.as_str().to_owned());
}
TrailingItem::Part { part, face, name, .. } => {
let name = self.part_name(*part, name, &words, label);
let node = access.node(TRAILING.at(u64::from(part.0)), Role::BUTTON);
node.name = Name::Text(name.as_str().to_owned());
if let TrailingFace::Disclosure { open } = face {
@@ -465,7 +471,7 @@ impl Component for ListRow<'_> {
}
fn finish(self, cx: Cx<'_, Self>) -> RowOutput {
RowOutput { response: cx.response.clone(), event: self.event, open: self.open, label: self.label_rect }
RowOutput { response: cx.response.clone(), event: self.event, open: self.open, menu: self.menu, label: self.label_rect }
}
}
@@ -476,3 +482,10 @@ fn part_mods(cx: &Cx<'_, ListRow<'_>>, part: PartRef, source: FireSource) -> Mod
_ => Mods::NONE,
}
}
impl ListRow<'_> {
/// The name of the trailing part `part`: the one given, or "More ({row})" for the row's menu button.
fn part_name(&self, part: TrailingPart, name: &Label, words: &ListWords, row: &str) -> Label {
if part == TrailingPart::MENU { Label::from(named(&words.more, row)) } else { name.clone() }
}
}
+6 -2
View File
@@ -12,6 +12,9 @@ use egui::Rect;
pub struct TrailingPart(pub(super) u16);
impl TrailingPart {
/// The row's own menu button (`ListRow::row_menu`).
pub const MENU: TrailingPart = TrailingPart(u16::MAX);
/// The part numbered `n`.
pub const fn new(n: u16) -> Self {
TrailingPart(n)
@@ -48,8 +51,9 @@ pub(in crate::list) enum TrailingItem<'a> {
Text { text: Label, name: Option<Label> },
/// An icon of the row's icon size, named for the screen reader and the tooltip.
Icon { icon: IconSpec<'static>, name: Label },
/// A pressable face of the row's icon size.
Part { part: TrailingPart, face: TrailingFace, name: Label, enabled: bool },
/// A pressable face of the row's icon size; a `revealed` one shows only on a hovered or selected row, while it has
/// focus or while the menu it opens is open.
Part { part: TrailingPart, face: TrailingFace, name: Label, enabled: bool, revealed: bool },
/// A component of its own, shown in a short field's width; its stop joins the row's group and it takes its own keys.
Hosted(Option<HostedShow<'a>>),
}
+10 -1
View File
@@ -7,7 +7,7 @@ use super::predicate::{DropTest, RowTest, RowText, SourceTest};
use super::{ListRow, RowEvent};
use crate::contract::{
Access, ActivateOn, Bind, BindMut, Collection, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, EditResponse,
LeadOnOpen, ListDrag, Props as _, Role, SelectMode, Sizing,
LeadOnOpen, ListDrag, Props as _, Role, RowState, SelectMode, Sizing,
};
use crate::runtime::env::{Env, Label};
use crate::style::{ComponentStyle, StyleCx};
@@ -73,6 +73,10 @@ pub struct List<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// The list is a listbox of options: the popup of a value picker.
#[prop(flag)]
listbox: bool,
/// Every row has a "More" button, shown on a hovered or selected row and while its menu is open, that asks for the
/// row's menu as a secondary click does (`CollectionEvent::ContextMenu`). The menu's Rename sends `request_rename`.
#[prop(flag)]
row_menu: bool,
/// The rows the query keeps, set by `filter`.
filter: Option<Filter<'a, K>>,
/// The kept rows are in order of how well they match the query.
@@ -97,6 +101,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> {
accepts: None,
takes_files: false,
listbox: false,
row_menu: false,
filter: None,
ranked: false,
}
@@ -205,6 +210,10 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for List<'_, K> {
if self.tree { layout.tree() } else { layout }
}
fn dress<'r>(&self, row: Self::Item<'r>, _: &RowState) -> Self::Item<'r> {
if self.row_menu { row.row_menu() } else { row }
}
fn rename_draft(&self, key: &K) -> Option<String> {
self.rename_draft.as_ref().and_then(|draft| draft.text(key))
}
+1
View File
@@ -27,5 +27,6 @@ craft_ui::words! {
collapse: "listRow.collapse" = "Collapse {row}";
expand_tip: "listRow.expandTip" = "Expand (Alt-click: all groups)";
collapse_tip: "listRow.collapseTip" = "Collapse (Alt-click: all groups)";
more: "listRow.more" = "More ({row})";
}
}
+40
View File
@@ -49,3 +49,43 @@ fn a_rename_draft_opens_the_field_with_it_and_without_one_the_field_holds_the_na
assert_eq!(opened_with(empty_for_first, 0).as_deref(), Some(""), "the draft opens the field empty");
assert_eq!(opened_with(empty_for_first, 1).as_deref(), Some(NAMES[1]), "a row without a draft opens with its name");
}
/// The shapes drawn wholly inside a small square around `at`: an icon's, not a row fill's.
fn drawn_at(shapes: &[egui::Shape], at: egui::Pos2) -> usize {
let square = egui::Rect::from_center_size(at, Vec2::splat(24.0));
shapes.iter().filter(|shape| square.contains_rect(shape.visual_bounding_rect())).count()
}
/// A list's row menu button shows on the selected row and on the hovered one, not on another; a click on it asks for
/// that row's menu.
#[trial]
fn the_row_menu_button_shows_on_the_hovered_and_selected_rows_and_asks_for_the_row_menu() {
use craft_behavior::Selection;
use craft_ui::contract::Bind;
let seen = Rc::new(RefCell::new(Vec::new()));
let held = seen.clone();
let mut fixture = Fixture::new(move |ui| {
let keys = [0_usize, 1, 2];
let source = keyed(&keys, |key: &usize| *key).with_text(|key| std::borrow::Cow::Borrowed(NAMES[*key]));
let list = List::new("Artboards").selection(Bind::given(Selection::single(1))).row_menu();
let out = list.show_items(ui, &source, &mut |key, _| ListRow::new(NAMES[*key]));
held.borrow_mut().extend(out.events);
});
fixture.room(Vec2::new(300.0, 200.0));
fixture.settle();
let button = |fixture: &Fixture, row: usize| fixture.by_label(&format!("More ({})", NAMES[row])).expect("each row has its menu button").center();
let (first, second, third) = (button(&fixture, 0), button(&fixture, 1), button(&fixture, 2));
let rest = fixture.frame_shapes();
assert!(drawn_at(&rest, second) > 0, "the selected row shows its button");
assert_eq!(drawn_at(&rest, first), 0, "a row neither hovered nor selected shows none");
fixture.frame(vec![craft_ui::testing::pointer::moved(third)]);
let hovered = fixture.frame_shapes();
assert!(drawn_at(&hovered, third) > 0, "the hovered row shows its button");
assert_eq!(drawn_at(&hovered, first), 0, "another row still shows none");
seen.borrow_mut().clear();
fixture.click_at(first).settle();
assert!(
seen.borrow().iter().any(|event| matches!(event, CollectionEvent::ContextMenu(request) if request.key == 0)),
"a click on the button asks for its row's menu"
);
}