From c3bed2526b6c27aedbc86e32e7b0b8a69f1a500e Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 15 Nov 2026 04:46:05 +0000 Subject: [PATCH] framework-01-w7: net change of 10 commits - framework-01-w7: written from its sheet - framework-01-w7: lead fixes from blocked.md (dwell markers, CollectionKind::Rested, ColumnWidth::fill) - framework-01-w7: review fixes (review-1) - framework-01-w7: the out-of-view header trial reaches the header by Tab and Shift+Tab (fw01 round 2) - framework-01-w7: a proposed rename draft commits on Enter (tools round) - framework-01-w7: the untyped-rename trial requests the rename with the list's usize key (tools run round) - framework-01-w7: the lead follows the pointer in a pass that holds a move event, the pointer entering over a row included (tools run round) - Revert "framework-01-w7: the lead follows the pointer in a pass that holds a move event, the pointer entering over a row included (tools run round)" - framework-01-w7: the lead follows the pointer in a pass that holds a move event, the pointer entering over a row included; a selection event reports only a change of the selection (tools run round) - framework-01-w7: the hover position reads the root's hovered response alone (top run round) --- crates/ui-contract/src/contract/items.rs | 23 +-- .../ui-contract/src/contract/items/header.rs | 71 +++++-- .../ui-contract/src/contract/items/hooks.rs | 80 ++++++-- crates/ui-contract/src/contract/items/lead.rs | 113 ++++++++--- .../ui-contract/src/contract/items/rename.rs | 7 +- crates/ui-contract/src/contract/overlay.rs | 1 - .../src/contract/overlay/popups.rs | 1 - .../ui-contract/src/contract/steps/settle.rs | 10 +- crates/ui-contract/src/testing/story.rs | 4 +- .../ui-contract/tests/it/collection/rows.rs | 110 +++++++++- .../ui-contract/tests/it/collection/table.rs | 190 +++++++++++++++++- crates/ui-widgets/src/list/view.rs | 2 +- 12 files changed, 509 insertions(+), 103 deletions(-) diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index 8f60bbc4c..5c454f16c 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -2,7 +2,7 @@ pub(super) mod rows; -use super::collection::{CollectionEvent, LeadSource, ShownRow}; +use super::collection::{CollectionEvent, ColumnLayout, LeadSource, ShownRow}; use super::{Collection, ItemFn}; use crate::runtime::egui::areas; use craft_behavior::{Axis, GestureId, ItemSource, ScrollPos, TypeAhead}; @@ -79,11 +79,6 @@ struct Scrolled { anchor: Option, } -#[derive(Clone, Default)] -struct View { - view: Option<[f32; 4]>, -} - #[derive(Clone)] struct Lead { key: Option, @@ -92,11 +87,13 @@ struct Lead { column: usize, /// The `CollectionProps.rows_stamp` of the pass that last set the lead. stamp: Option, + /// The lead `CollectionEvent::Rested` was reported for: one report per lead change. + rested: Option, } impl Default for Lead { fn default() -> Self { - Lead { key: None, at: 0, column: 0, stamp: None } + Lead { key: None, at: 0, column: 0, stamp: None, rested: None } } } @@ -106,11 +103,13 @@ struct Renaming { draft: String, gesture: GestureId, focused: bool, + /// The field opened with a draft the collection proposed that differs from the row's text. + proposed: bool, } impl Default for Renaming { fn default() -> Self { - Renaming { key: None, draft: String::new(), gesture: GestureId::default(), focused: false } + Renaming { key: None, draft: String::new(), gesture: GestureId::default(), focused: false, proposed: false } } } @@ -175,12 +174,11 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { offset_at_read: f64, offset_x: f64, offset_x_at_read: f64, - /// The part of a reveal the rows showed, passed on to the scroll owner around the collection. - pass_on: Option, /// The scroll position named by content, kept with an offset the framework holds (`Scrolled`). anchor: Option, anchor_at_read: Option, - last: View, + /// The bound column layout as the read step found it; `None` while the header keeps its own memory. + column_layout_at_read: Option, lead: Lead, renaming: Renaming, ended_rename: bool, @@ -247,10 +245,9 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { offset_at_read: 0.0, offset_x: 0.0, offset_x_at_read: 0.0, - pass_on: None, anchor: None, anchor_at_read: None, - last: View::default(), + column_layout_at_read: None, lead: Lead::default(), renaming: Renaming::default(), ended_rename: false, diff --git a/crates/ui-contract/src/contract/items/header.rs b/crates/ui-contract/src/contract/items/header.rs index 06d500094..929555b48 100644 --- a/crates/ui-contract/src/contract/items/header.rs +++ b/crates/ui-contract/src/contract/items/header.rs @@ -3,7 +3,8 @@ use super::ItemsHooks; use crate::contract::collection::{ - CollectionEvent, CollectionProps, ColumnAlign, ColumnEvent, ColumnKind, ColumnRequest, ColumnSort, ColumnSpec, HeaderMenuRequest, ToggleColumn, + CollectionEvent, CollectionProps, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRequest, ColumnSort, ColumnSpec, HeaderMenuRequest, + ToggleColumn, }; use crate::contract::reorder::{self, Gap}; use crate::contract::{ @@ -23,7 +24,7 @@ use crate::style::{ComponentStyle, ResizeLineLook, ScrollBarKind, StateSet, Styl use craft_behavior::grid::resolve_columns; use craft_behavior::{ Axis, ColumnKey, ColumnWidth, CursorIcon, DropOperation, Flow, HitLevel, HitPriority, IconId, Insets, Intent, Metrics, NavMove, NavShape, - PartKey, PointerButton, PressPhase, Proposal, Roving, Sense, + PartKey, PartRef, PointerButton, PressPhase, Proposal, Roving, Sense, }; use egui::{Align, Context, Id, Pos2, Rect, Response, Ui, UiBuilder, Vec2}; @@ -123,12 +124,9 @@ pub(crate) struct HeaderFacts { /// What the header keeps in session memory under the collection's id. #[derive(Clone, Debug, Default)] pub(super) struct HeaderMemory { - /// Column keys in display order; empty until the user moves one. - order: Vec, - /// User widths of `Content` and `Fill` columns. - widths: Vec<(ColumnKey, f32)>, - /// Columns the user hid from the header menu. - hidden: Vec, + /// The user's arrangement: the display order (empty until the user moves a column), the user widths of `Content` + /// and `Fill` columns and the columns hidden from the header menu. Empty while the collection binds its layout. + layout: ColumnLayout, /// The header menu the user asked for, whose column a command acts on when no header part holds focus, and the /// frame it was requested in. The menu is gone once no layer that takes keys is open a frame after its request. menu: Option<(HeaderMenuRequest, u64)>, @@ -148,6 +146,8 @@ pub(super) struct Header { /// The header row's height, zero while no column has a header. pub(super) height: f32, memory: HeaderMemory, + /// The collection binds its column layout (`column_layout`): the binding holds the arrangement, not the memory. + bound: bool, specs: Vec, /// The widest cell of each `Content` column among all rows, or its header label when wider, from the items' /// measure of this pass (`content_id`); zero for the other columns and while unknown. @@ -183,15 +183,20 @@ fn hash_of(key: &ColumnKey) -> u64 { } impl Header { - /// Step 4: the columns in their display order and the header's session memory. - pub(super) fn read(&mut self, stage: &mut MemoryStage, id: Id, props: &CollectionProps) { + /// Step 4: the columns in their display order and the header's session memory. A `bound` layout (the + /// collection's `column_layout`) is the arrangement; the session memory keeps the menu and the resizes. + pub(super) fn read(&mut self, stage: &mut MemoryStage, id: Id, props: &CollectionProps, bound: Option) { self.memory = stage.session::(sub(id, "columns")).clone(); + self.bound = bound.is_some(); + if let Some(layout) = bound { + self.memory.layout = layout; + } self.sort = props.sort.clone(); self.on = props.header; self.hideable = props.columns.iter().filter(|spec| spec.hideable).map(|spec| spec.key.clone()).collect(); - let hidden = &self.memory.hidden; + let hidden = &self.memory.layout.hidden; let mut specs: Vec = props.columns.iter().filter(|spec| !(spec.hideable && hidden.contains(&spec.key))).cloned().collect(); - let order = &self.memory.order; + let order = &self.memory.layout.order; specs.sort_by_key(|spec| order.iter().position(|key| *key == spec.key).unwrap_or(usize::MAX)); self.content = vec![0.0; specs.len()]; self.specs = specs; @@ -217,7 +222,7 @@ impl Header { let width = if spec.width == ColumnWidth::Toggle { ColumnWidth::Fixed(self.toggle) } else { spec.width.in_unit(self.unit) }; match width { fixed @ ColumnWidth::Fixed(_) => fixed, - _ => self.memory.widths.iter().find(|(key, _)| *key == spec.key).map_or(spec.width, |(_, width)| ColumnWidth::Fixed(*width)), + _ => self.memory.layout.widths.iter().find(|(key, _)| *key == spec.key).map_or(spec.width, |(_, width)| ColumnWidth::Fixed(*width)), } } @@ -444,6 +449,24 @@ impl Header { self.cells.iter().position(|cell| self.specs[cell.spec].key == *key) } + /// The full rect of the header cell whose part index is `hash`, in view or not. + fn cell_rect(&self, hash: u64) -> Option { + self.cells.iter().find(|cell| cell.hash == hash).map(|cell| cell.rect) + } + + /// How far a focus move to `part` moves the sideways offset the header and the rows share, so its whole cell + /// shows in the header's view: `None` for a part that is no header cell, or a cell already in view. + pub(super) fn reveal_x(&self, part: PartRef, rtl: bool) -> Option { + if part.key != HEADER { + return None; + } + let rect = self.cell_rect(part.index?)?; + let (by, _) = crate::contract::steps::reveal_move(rect, self.view()?); + // The offset runs from the reading start: in a right-to-left header a larger offset moves the cells right. + let by = if rtl { -by.x } else { by.x }; + (by != 0.0).then_some(f64::from(by)) + } + fn sort(&mut self, key: &ColumnKey) { let descending = match &self.sort { Some(sort) if sort.key == *key => !sort.descending, @@ -462,9 +485,9 @@ impl Header { .iter() .any(|spec| spec.key == *key && matches!(spec.width, ColumnWidth::Fixed(_) | ColumnWidth::Controls(_) | ColumnWidth::Toggle)); if !owned_by_app { - match self.memory.widths.iter_mut().find(|(held, _)| held == key) { + match self.memory.layout.widths.iter_mut().find(|(held, _)| held == key) { Some((_, held)) => *held = width, - None => self.memory.widths.push((key.clone(), width)), + None => self.memory.layout.widths.push((key.clone(), width)), } } self.events.push(ColumnEvent::Resized { key: key.clone(), width }); @@ -489,7 +512,7 @@ impl Header { } let moved = order.remove(from); order.insert(to, moved); - self.memory.order = order; + self.memory.layout.order = order; self.events.push(ColumnEvent::Moved { key: key.clone(), to }); } @@ -632,13 +655,13 @@ impl Header { for request in requests { match request { ColumnRequest::Shown(key, shown) => { - if !self.hideable.contains(&key) || shown != self.memory.hidden.contains(&key) { + if !self.hideable.contains(&key) || shown != self.memory.layout.hidden.contains(&key) { continue; } if shown { - self.memory.hidden.retain(|held| *held != key); + self.memory.layout.hidden.retain(|held| *held != key); } else { - self.memory.hidden.push(key.clone()); + self.memory.layout.hidden.push(key.clone()); } let unsorted = !shown && self.sort.as_ref().is_some_and(|sort| sort.key == key); self.events.push(ColumnEvent::Shown { key, shown }); @@ -667,7 +690,7 @@ impl Header { HeaderFacts { asked: self.asked, menu: self.memory.menu.as_ref().map(|(menu, _)| menu.clone()), - hidden: self.memory.hidden.clone(), + hidden: self.memory.layout.hidden.clone(), enabled: ColumnCommands::ALL.into_iter().filter(|&command| target.is_some_and(|at| self.allowed(command, at, rtl))).collect(), } } @@ -773,8 +796,14 @@ impl Header { cx.active_part().filter(|part| part.key == HEADER).and_then(|part| self.cells.iter().position(|cell| Some(cell.hash) == part.index)) } + /// The session memory this pass leaves. A bound layout stays the binding's alone: the memory keeps an empty one. pub(super) fn persist(&self) -> HeaderMemory { - self.memory.clone() + if self.bound { HeaderMemory { layout: ColumnLayout::default(), ..self.memory.clone() } } else { self.memory.clone() } + } + + /// The user's column arrangement as this pass left it. + pub(super) fn layout(&self) -> &ColumnLayout { + &self.memory.layout } } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index a9eb8a859..bad7ca125 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -4,11 +4,11 @@ use super::drag::Drags; use super::geometry::bar_track; use super::header::HeaderMemory; use super::members::Member; -use super::{Held, ITEM_NODE, ItemsHooks, LastLayout, Lead, Placement, Renaming, Rows, SCROLL, Scrolled, View, key_hash, section_part}; +use super::{Held, ITEM_NODE, ItemsHooks, LastLayout, Lead, Placement, Renaming, Rows, SCROLL, Scrolled, key_hash, section_part}; use super::{request, rows}; use crate::contract::ValueOf; use crate::contract::collection::{ - CollectionEvent, ContextMenuRequest, DropAt, Gestures, ItemsOut, OpenChange, PendingDrop, Rename, RowState, ShownRow, + CollectionEvent, ColumnLayout, ContextMenuRequest, DropAt, Gestures, ItemsOut, OpenChange, PendingDrop, Rename, RowState, ShownRow, }; use crate::contract::cx::{BodyCx, Pointer as _}; use crate::contract::run::{Measuring, ShapeHooks, ShowAt}; @@ -98,7 +98,12 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { }; self.selection_at_read = self.selection.clone(); self.previous = stage.session::>(sub(id, "item_layout")).0.take(); - self.header.read(stage, id, comp.items()); + let bound = comp.column_layout().map(|bind| match bind.get() { + Some(Mixed::Same(layout)) => layout, + _ => ColumnLayout::default(), + }); + self.column_layout_at_read = bound.clone(); + self.header.read(stage, id, comp.items(), bound); self.drags = stage.session::>(sub(id, "drags")).clone(); self.lead = stage.session::>(sub(id, "lead")).clone(); // A collection in a layer starts from `lead_on_open` at every opening of the layer, not only the first. @@ -119,7 +124,6 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.lead.key = self.selection.lead().filter(|key| self.index_of(key).is_some()).cloned(); } self.renaming = stage.session::>(sub(id, "rename")).clone(); - self.last = stage.recall::(sub(id, "view")); let scrolled = match comp.scroll() { Some(bind) => match bind.get() { Some(Mixed::Same(pos)) => Scrolled { y: pos.y, x: pos.x, anchor: None }, @@ -150,15 +154,6 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.events.push(CollectionEvent::Zoom { factor: share.zoom, about }); } } - if let (Some(rect), Some(bounds)) = - (if quiet { crate::contract::peek_reveal(&ctx, id) } else { crate::contract::take_reveal(&ctx, id) }, self.last.view) - { - // The rows scroll along y only: the reveal moves them along it and passes the rest on. - let view = Rect::from_min_max(Pos2::new(f32::NEG_INFINITY, bounds[1]), Pos2::new(f32::INFINITY, bounds[3])); - let (by, shown) = crate::contract::steps::reveal_move(rect, view); - self.offset += f64::from(by.y); - self.pass_on = (!quiet).then_some(shown); - } } } @@ -265,10 +260,14 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { Self::props_pad(comp, tokens) } - fn sized(&self, comp: &C, _: &Ui, _: Id, size: Vec2) -> Vec2 { + fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { let sizing = comp.props(Internal::new()).sizing; // 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 width = if self.content_sized(comp) || self.from_content.0 { + size.x + } else { + crate::layout::body::fill_size(ui, id, Axis::X, size.x, self.room.x, true) + }; 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), @@ -344,14 +343,30 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { if let Some(range) = cx.scroll_moved(SCROLL) { self.offset = range.start; } - if let Some(shown) = self.pass_on.take() { - crate::contract::Focus::reveal(cx, shown); + if self.scrolls { + // A descendant's reveal, left for this pass: taken against this pass's rows (peeked while measuring). + let (ctx, id) = (cx.core.ctx.clone(), cx.core.id); + let quiet = cx.core.memory.is_peek() || crate::runtime::measure::active(&ctx); + if let Some(asked) = if quiet { crate::contract::peek_reveal(&ctx, id) } else { crate::contract::take_reveal(&ctx, id) } { + // The rows scroll along y only: the reveal moves them along it and passes the rest on. + let along = Rect::from_min_max(Pos2::new(f32::NEG_INFINITY, rect.min.y), Pos2::new(f32::INFINITY, rect.max.y)); + let (by, shown) = crate::contract::steps::reveal_move(asked, along); + self.offset += f64::from(by.y); + if !quiet { + crate::contract::Focus::reveal(cx, shown); + } + } } self.offset = self.offset.clamp(0.0, self.max_offset(view)); let header_held = self.header_step(cx); self.offset_x = self.offset_x.clamp(0.0, f64::from((self.content.x - rect.width()).max(0.0))); self.open_lead(comp); self.follow_lead_source(); + // A lead set in place (from the selection, `open_lead`, a row that left) has not rested yet: a lead that comes + // back to a row it rested on before reports the rest again. + if self.lead.rested != self.lead.key { + self.lead.rested = None; + } let lead_at = self.lead.key.as_ref().and_then(|key| self.index_of(key)); let props = comp.items().clone(); let Some(layout) = self.layout.take() else { return }; @@ -364,6 +379,9 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { if props.lead_follows_hover { self.hover_lead(comp, cx, &layout, seen); } + if props.select_under_drag { + self.drag_select(comp, cx, &layout, seen); + } self.drag_step(comp, cx, &layout, (rect, offset, rtl), &props); self.marquee_step(comp, cx, &layout, (rect, offset, rtl), &props); self.navigate(comp, cx, &layout, view, header_held); @@ -378,6 +396,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.requested_rename(comp, cx, &props, &layout); self.requested_reveal(comp, &layout); self.type_ahead(comp, cx, &layout, lead_at); + self.rest_lead(cx, &layout, seen); request::record_lead(&cx.core.ctx, cx.core.id, self.lead.key.as_ref().and_then(|key| self.index_of(key))); if let Some(at) = self.page_reveal.take().filter(|&at| layout.shown(at)) { cx.core.reveal = Some(self.screen(&layout, rect, at, ScrollPos::default(), rtl)); @@ -753,8 +772,16 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { fn settle(&mut self, comp: &mut C, cx: &mut Cx<'_, C>) { let id = cx.core.id; - // A collection's focus move reveals through its lead (`page_reveal`), never the collection's whole rect. - crate::runtime::focus::take_reveal_of(&cx.core.ctx, id); + // A collection's focus move reveals through its lead (`page_reveal`), never the collection's whole rect. A + // header cell's reveal moves the sideways offset the header and the rows share, to show the whole cell. + if let Some(Some(part)) = focus::take_reveal_of(&cx.core.ctx, id) + && self.scrolls + && let Some(by) = self.header.reveal_x(part, cx.core.flow.is_rtl()) + { + let max = f64::from((self.content.x - self.rows_rect(cx).width()).max(0.0)); + self.offset_x = (self.offset_x + by).clamp(0.0, max); + crate::runtime::egui::repaint::request(&cx.core.ctx); + } if self.scrolls && (self.offset != self.offset_at_read || self.offset_x != self.offset_x_at_read || self.anchor != self.anchor_at_read) { match comp.scroll() { Some(mut bind) => { @@ -776,6 +803,13 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.header.apply_requests(&cx.core.ctx, requests, cx.core.flow.is_rtl()); self.take_column_events(); } + if let Some(before) = self.column_layout_at_read.take() + && *self.header.layout() != before + && let Some(mut bind) = comp.column_layout() + { + let (label, doc_key) = (cx.core.label_arc(), cx.core.resolved.doc_key); + bind.apply(&EditEvent::set(Mixed::Same(before), self.header.layout().clone(), label, doc_key)); + } *cx.core.memory.session::(sub(id, "columns")) = self.header.persist(); *cx.core.memory.session::>(sub(id, "drags")) = self.drags.clone(); self.header.report(&cx.core.ctx, id, cx); @@ -874,9 +908,13 @@ impl ItemsHooks<'_, '_, C> { self.events.push(CollectionEvent::Rename(EditEvent::cancel(gesture, reason, Some(before)))); self.ended_rename = true; } - // Enter on a name nobody typed in opens no edit run: the rename ends with no event and no undo step, as a - // text field's empty commit does. + // 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 => { + if self.renaming.proposed { + let after = Rename { key: key.clone(), name: self.renaming.draft.clone() }; + self.events.push(CollectionEvent::Rename(EditEvent::commit(gesture, before, after))); + } self.ended_rename = true; self.refocus = true; } diff --git a/crates/ui-contract/src/contract/items/lead.rs b/crates/ui-contract/src/contract/items/lead.rs index 9861a26c3..d78d489ef 100644 --- a/crates/ui-contract/src/contract/items/lead.rs +++ b/crates/ui-contract/src/contract/items/lead.rs @@ -1,21 +1,25 @@ //! The lead and the selection: picks, ranges, and where the lead starts and follows. use super::{ItemsHooks, Placement}; -use crate::contract::collection::{CollectionEvent, LeadOnOpen, LeadSource, SelectMode}; +use crate::contract::collection::{CollectionEvent, LeadOnOpen, LeadSource, ListDrag, SelectMode}; use crate::contract::{Collection, Cx}; -use crate::runtime::env::ArenaId; -use craft_behavior::{Flow, ItemLayout, SelectionChange, SelectionModel}; +use craft_behavior::{Flow, ItemLayout, PointerEvent, SelectionChange, SelectionModel}; use egui::{Pos2, Rect, Vec2}; +use std::any::TypeId; impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { pub(super) fn select_mode(comp: &C) -> SelectMode { comp.items().select } - /// Reports and applies a selection change. + /// Applies a selection change and reports it when it changes the selection: a press on the row a hover already + /// selected reports nothing. pub(super) fn change(&mut self, change: SelectionChange) { + let before = self.selection.clone(); self.selection.apply(change.clone()); - self.events.push(CollectionEvent::Selection(change)); + if self.selection != before { + self.events.push(CollectionEvent::Selection(change)); + } } pub(super) fn range(&self, from: usize, to: usize) -> Vec { @@ -23,11 +27,32 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { if from <= to { keys.collect() } else { keys.rev().collect() } } + /// Moves the lead to row `to`. A lead a key moved has rested at once: no timer runs for it. pub(super) fn move_lead(&mut self, to: usize, by: LeadSource) { + let key = self.place_lead(to, by); + if matches!(by, LeadSource::Keys) { + self.report_rest(key); + } + } + + /// Places the lead on row `to` and reports the move, with no rest: the lead's key. + fn place_lead(&mut self, to: usize, by: LeadSource) -> C::Key { let key = self.source.key(to); + if self.lead.key.as_ref() != Some(&key) { + self.lead.rested = None; + } self.lead.key = Some(key.clone()); self.lead.at = to; - self.events.push(CollectionEvent::LeadMoved { key, by }); + self.events.push(CollectionEvent::LeadMoved { key: key.clone(), by }); + key + } + + /// Reports `CollectionEvent::Rested` for the lead `key`, once per lead change. + fn report_rest(&mut self, key: C::Key) { + if self.lead.rested.as_ref() != Some(&key) { + self.lead.rested = Some(key.clone()); + self.events.push(CollectionEvent::Rested(key)); + } } /// The position of `key`: the lead's last position is tried first, so the common lookups of a pass do not scan. @@ -88,24 +113,18 @@ impl ItemsHooks<'_, '_, C> { } } - /// The row under `pos` (screen space) in the rows' placement `at`: the pointer-to-row mapping of `hover_lead`, - /// which `hover_lead` and the drag-select step both call. - #[allow(dead_code)] // P3(framework-01-w7): cw.C43 - pub(super) fn row_under(&self, layout: &C::ItemLayout, at: Placement, pos: Pos2) -> Option { - let _ = (layout, at, pos); - todo!("cw.C43") + /// The pointer's position, in screen space, while it is over the collection. + fn hovered_pos(cx: &Cx<'_, C>) -> Option { + crate::runtime::pointer::frame(&cx.core.ctx).pos.filter(|_| cx.core.response.hovered()) } - /// The lead follows a moving pointer over the rows, and the selection follows the lead the way it does for the - /// arrow keys. - pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement) { + /// The row under `pos` (screen space) in the rows' placement `at`: the pointer-to-row mapping of `hover_lead`, + /// which `hover_lead`, the rest check and the drag-select step all call. + pub(super) fn row_under(&self, layout: &C::ItemLayout, at: Placement, pos: Pos2) -> Option { let Placement { rect, offset, rtl } = at; - let frame = crate::runtime::pointer::frame(&cx.core.ctx); - let hovered = cx.core.response.hovered() || crate::primitives::sensing::read_outcome(&cx.core.ctx, ArenaId::new(cx.core.id)).hover.is_some(); - let Some(pos) = frame.pos.filter(|_| hovered && frame.delta != Vec2::ZERO) else { return }; let pos = self.xf.map_or(pos, |map| map.to_layer(pos)); if !rect.contains(pos) { - return; + return None; } let local = pos - rect.min.to_vec2(); let local = if layout.mirrors() && rtl { @@ -113,16 +132,62 @@ impl ItemsHooks<'_, '_, C> { } else { local }; - if let Some(row) = layout.hit(local, offset).filter(|&row| self.source.enabled(row) && !self.source.is_section(row) && layout.shown(row)) - && self.lead.key.as_ref() != Some(&self.source.key(row)) - { + layout.hit(local, offset).filter(|&row| self.source.enabled(row) && !self.source.is_section(row) && layout.shown(row)) + } + + /// The lead follows a moving pointer over the rows, and the selection follows the lead the way it does for the + /// arrow keys. A pass moves the pointer when it holds a move event: the pointer entering over a row moves the lead + /// with no movement to measure, and a modifier change under a resting pointer leaves the lead where the keys put it. + pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement) { + let moved = crate::runtime::pointer::with_pass_pointer(&cx.core.ctx, |pass| { + pass.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. })) + }); + if !moved { + return; + } + let Some(row) = Self::hovered_pos(cx).and_then(|pos| self.row_under(layout, at, pos)) else { return }; + if self.lead.key.as_ref() != Some(&self.source.key(row)) { self.move_lead(row, LeadSource::Pointer); self.pick(comp, row, false, false); } } + /// The pointer resting on the lead row for the tooltip delay reports `CollectionEvent::Rested`, once per lead + /// change. Motion inside the row does not restart the timer, as for a tooltip. + pub(super) fn rest_lead(&mut self, cx: &mut Cx<'_, C>, layout: &C::ItemLayout, at: Placement) { + let lead = self.lead.key.clone(); + let over = Self::hovered_pos(cx).and_then(|pos| self.row_under(layout, at, pos)); + let held = lead.is_some() && self.lead.rested != lead && over.is_some_and(|row| lead.as_ref() == Some(&self.source.key(row))); + let (ctx, id) = (cx.core.ctx.clone(), cx.core.id); + if crate::contract::overlay::dwell(&ctx, &mut *cx.core.memory, id, "rest", held, crate::contract::tooltip::DELAY) + && let Some(key) = lead + { + self.report_rest(key); + } + } + + /// While a drag session another source started runs over the rows (its payload is neither this collection's row + /// drag nor a kind it takes), the unselected row under the pointer becomes the lead and the selection. The drag + /// holds the pointer, so the row comes from the pointer's position, not the collection's hover. + pub(super) fn drag_select(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement) { + let ctx = &cx.core.ctx; + if !crate::runtime::drag::running(ctx) + || crate::runtime::drag::active_of(ctx, TypeId::of::>()).is_some() + || comp.drops().iter().any(|kind| crate::runtime::drag::active_of(ctx, kind.payload()).is_some()) + { + return; + } + let Some(row) = crate::runtime::pointer::frame(ctx).pos.and_then(|pos| self.row_under(layout, at, pos)) else { return }; + if self.holds(row) { + return; + } + self.move_lead(row, LeadSource::Pointer); + self.pick(comp, row, false, false); + } + /// A lead whose key left the source moves to the key now in its place, else the one before it. The selection is - /// the host's: a row that left (deleted, or hidden by a filter) is not replaced by its neighbour. + /// the host's: a row that left (deleted, or hidden by a filter) is not replaced by its neighbour. The user did not + /// move the lead, so the new lead does not rest at once. pub(super) fn follow_lead_source(&mut self) { let len = self.source.len(); if let Some(key) = self.lead.key.clone() @@ -130,7 +195,7 @@ impl ItemsHooks<'_, '_, C> { { self.lead.key = None; if len > 0 { - self.move_lead(self.lead.at.min(len - 1), LeadSource::Keys); + self.place_lead(self.lead.at.min(len - 1), LeadSource::Keys); } } else if let Some(at) = self.lead.key.as_ref().and_then(|key| self.index_of(key)) { self.lead.at = at; diff --git a/crates/ui-contract/src/contract/items/rename.rs b/crates/ui-contract/src/contract/items/rename.rs index c5e329712..492487ba5 100644 --- a/crates/ui-contract/src/contract/items/rename.rs +++ b/crates/ui-contract/src/contract/items/rename.rs @@ -10,11 +10,14 @@ impl ItemsHooks<'_, '_, C> { /// Opens the rename field of the item at `at`, with the draft the collection gives for it, else the item's text. pub(super) fn begin_rename(&mut self, comp: &C, cx: &mut Cx<'_, C>, at: usize) { let key = self.source.key(at); - let draft = comp.rename_draft(&key).or_else(|| self.source.text(at).map(|text| text.into_owned())).unwrap_or_default(); + let text = self.source.text(at).map(|text| text.into_owned()); + let proposal = comp.rename_draft(&key); + let proposed = proposal.as_ref().is_some_and(|draft| text.as_ref() != Some(draft)); + let draft = proposal.or(text).unwrap_or_default(); let gesture = crate::runtime::edit::next_gesture_id(&cx.core.ctx); let before = Rename { key: key.clone(), name: draft.clone() }; self.events.push(CollectionEvent::Rename(EditEvent::begin(gesture, Mixed::Same(before), cx.core.label_arc(), None))); - self.renaming = Renaming { key: Some(key), draft, gesture, focused: false }; + self.renaming = Renaming { key: Some(key), draft, gesture, focused: false, proposed }; } /// A rename requested from outside (`request_rename`): the lead moves to the item, the item is revealed and its diff --git a/crates/ui-contract/src/contract/overlay.rs b/crates/ui-contract/src/contract/overlay.rs index d044cf56c..b6a1ec531 100644 --- a/crates/ui-contract/src/contract/overlay.rs +++ b/crates/ui-contract/src/contract/overlay.rs @@ -25,7 +25,6 @@ pub use opener::{Opener, Trigger}; pub use place::{Anchor, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare}; pub use placement::PopupRegion; pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_for}; -#[allow(unused_imports)] // P3(framework-01-w7): fx.F71 decision, `dwell` for `items/lead.rs` pub(crate) use popups::dwell; pub use popups::{HOLD, Overlays, PopupHandle}; pub(crate) use popups::{apply_closes, begin_owner, open_map, popup_shown, popups_shown, write_open}; diff --git a/crates/ui-contract/src/contract/overlay/popups.rs b/crates/ui-contract/src/contract/overlay/popups.rs index 00fa3ecd0..268a0423d 100644 --- a/crates/ui-contract/src/contract/overlay/popups.rs +++ b/crates/ui-contract/src/contract/overlay/popups.rs @@ -307,7 +307,6 @@ fn pointer_in_popup(ctx: &Context, popup: Id) -> bool { struct Dwell(Option); /// Whether `held` has lasted `delay` seconds, timed in the slot `name` of `id`; asks for a pass at the deadline. -// P3(framework-01-w7): fx.F71 decision, `dwell` crate-visible for `items/lead.rs` pub(crate) fn dwell(ctx: &Context, stage: &mut MemoryStage, id: Id, name: &'static str, held: bool, delay: f64) -> bool { let now = frame::clock(ctx); let since = stage.shown::(sub(id, name)); diff --git a/crates/ui-contract/src/contract/steps/settle.rs b/crates/ui-contract/src/contract/steps/settle.rs index 119528513..cbff5a0c0 100644 --- a/crates/ui-contract/src/contract/steps/settle.rs +++ b/crates/ui-contract/src/contract/steps/settle.rs @@ -18,17 +18,19 @@ pub(crate) fn settle(comp: &mut C, cx: &mut Cx<'_, C>) -> ValueEdi } } let edit = apply_values(comp, cx); - let owner = cx.core.id; + let id = cx.core.id; if C::OVERLAYS { - crate::contract::overlay::write_open(&mut *cx.core.memory, owner); + crate::contract::overlay::write_open(&mut *cx.core.memory, id); } - if let Some(part) = focus::take_reveal_of(&cx.core.ctx, owner) { + if let Some(part) = focus::take_reveal_of(&cx.core.ctx, id) { // Focus on a part reveals the part, as a pin of a canvas overlay that spans the canvas. let rect = part.and_then(|part| cx.core.results.get(&(part.key, part.index))).map_or(cx.core.rect, |result| result.rect); cx.core.reveal.get_or_insert(rect); } + // The nearest scroll owner under the rect may be the component itself (a collection takes the wheel): a reveal it + // passes on goes to the owner around it, never back to itself. if let Some(rect) = cx.core.reveal.take() - && let Some(owner) = cx.core.env.scroll_owner().or_else(|| wheel::nearest_scroll_owner(&cx.core.ctx, rect)) + && let Some(owner) = cx.core.env.scroll_owner().or_else(|| wheel::nearest_scroll_owner(&cx.core.ctx, rect).filter(|&found| found != id)) { pass_state::with::(&cx.core.ctx, |reveals| reveals.0.push(Reveal { owner, to: RevealTo::Rect(rect) })); repaint::request(&cx.core.ctx); diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index bf8106002..74d3264cc 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -426,6 +426,8 @@ pub enum CollectionKind { Selection, /// The lead moved. LeadMoved, + /// The pointer rested on an item. + Rested, /// Enter or a double click on an item. Activate, /// A double click on the empty space. @@ -469,7 +471,7 @@ impl CollectionKind { CollectionEvent::Selection(_) => CollectionKind::Selection, CollectionEvent::LeadMoved { .. } => CollectionKind::LeadMoved, CollectionEvent::Activate(_) => CollectionKind::Activate, - CollectionEvent::Rested(_) => todo!("fx.F71"), // P3(framework-01-w7): fx.F71 + CollectionEvent::Rested(_) => CollectionKind::Rested, CollectionEvent::EmptyActivated => CollectionKind::EmptyActivated, CollectionEvent::EmptyContextMenu { .. } => CollectionKind::EmptyContextMenu, CollectionEvent::EdgePressed { .. } => CollectionKind::EdgePressed, diff --git a/crates/ui-contract/tests/it/collection/rows.rs b/crates/ui-contract/tests/it/collection/rows.rs index 3685818b3..127494095 100644 --- a/crates/ui-contract/tests/it/collection/rows.rs +++ b/crates/ui-contract/tests/it/collection/rows.rs @@ -1,13 +1,14 @@ //! The row trials: rows with focusable children, cell selection in a sheet, rows of measured heights and a lead that //! leaves the source. -use super::kit::{Count, Dismissed, List, ROW_H, RowOut}; +use super::kit::{Count, Dismissed, List, ROW_H, RowOut, Words}; use craft_behavior::{ - CellAt, CellRange, CellSelection, ColumnKey, ItemSource, PartKey, Selection, SelectionModel as _, Sense, SheetLayout, SpanLayout, keyed, + CellAt, CellRange, CellSelection, ColumnKey, EditEvent, EditEvents, ItemSource, PartKey, ScrollPos, Selection, SelectionModel as _, Sense, + SheetLayout, SpanLayout, keyed, }; use craft_ui::contract::{ - Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, Focus as _, MeasureCx, - PartsCx, Props as _, Role, SelectMode, ShowCollection as _, + Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, EditResponse, Focus as _, + MeasureCx, PartsCx, Props as _, Role, SelectMode, ShowCollection as _, request_rename, }; use craft_ui::runtime::focus::{FocusTarget, request}; use craft_ui::style::StyleCx; @@ -131,7 +132,10 @@ struct Probe<'a> { props: ContainerProps, items: CollectionProps, selection: Option>>, + scroll: Option>, auto: bool, + /// The rename draft every row proposes, and whether the rename field reports Enter. + rename: Option<(&'a str, &'a Cell)>, } impl<'a> Probe<'a> { @@ -141,14 +145,28 @@ impl<'a> Probe<'a> { props: ContainerProps::new().sizing(craft_ui::contract::Sizing::Fill), items: CollectionProps::new().select(select), selection: None, + scroll: None, auto: false, + rename: None, } } + /// Rows rename with `draft` proposed; the field reports Enter while `enter` is set. + fn renaming(mut self, draft: &'a str, enter: &'a Cell) -> Self { + self.items = self.items.rename(true); + self.rename = Some((draft, enter)); + self + } + fn auto(mut self) -> Self { self.auto = true; self } + + fn scrolled(mut self, scroll: Bind<'a, ScrollPos>) -> Self { + self.scroll = Some(scroll); + self + } } impl Component for Probe<'_> { @@ -160,6 +178,10 @@ impl Component for Probe<'_> { PlainStyle::default() } + fn scroll(&mut self) -> Option> { + self.scroll.as_mut().map(Bind::reborrow) + } + fn finish(self, mut cx: Cx<'_, Self>) -> Self::Output { cx.collection_response() } @@ -183,6 +205,17 @@ impl Collection for Probe<'_> { fn item_layout(&self, source: &dyn ItemSource, width: f32, _: &StyleCx<'_>) -> SpanLayout { if self.auto { SpanLayout::sized(source, width, ROW_H) } else { SpanLayout::new(source, width, ROW_H) } } + + fn rename_draft(&self, _: &usize) -> Option { + self.rename.map(|(draft, _)| draft.to_owned()) + } + + fn rename_editor(&mut self, ui: &mut Ui, _: Bind<'_, String>, label: Rect, _: &str) -> Option> { + let (_, enter) = self.rename?; + let mut editor = EditResponse::lifted(ui.allocate_rect(label, egui::Sense::hover()), EditEvents::new(), None); + editor.submitted = enter.get(); + Some(editor) + } } /// A sheet of `CELL_W` columns over `SheetLayout`, with the first column frozen. @@ -440,3 +473,72 @@ fn rows_in_view_stay_when_a_row_above_them_changes_height() { assert!(grown > idle, "the frame the row grew in ran the pass again at the anchored offset"); assert_eq!(next, idle, "an idle frame after it runs no extra pass"); } + +/// A field hosted in a row asks its scroll owner, the collection, to reveal row 25, out of view: the collection takes +/// the reveal in its next pass against that pass's rows, shows the row and scrolls once. Guards the reveal being +/// taken and dropped for want of a view. +#[trial] +fn a_reveal_from_a_hosted_field_scrolls_its_collection_in_the_same_pass() { + let (log, source) = (Log::new(), Count(30)); + let scroll = Cell::new(ScrollPos::default()); + let offsets = RefCell::new(Vec::new()); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + let mut held = scroll.get(); + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + let list = Probe::new(SelectMode::Single).scrolled(Bind::bound(&mut held)).id_salt("list"); + log.take(list.show_items(ui, &source, &mut |key, _| ProbeRow::new(*key, log))); + }); + scroll.set(held); + offsets.borrow_mut().push(held.y); + }; + frames.idle(3, &mut show); + let view = Rect::from_min_size(ORIGIN, VIEW); + let first = log.rect(0); + let row = Rect::from_min_size(first.min + Vec2::new(0.0, 25.0 * ROW_H), first.size()); + assert!(row.min.y >= view.max.y, "row 25 starts out of view"); + let before = scroll.get().y; + offsets.borrow_mut().clear(); + log.rects.borrow_mut().clear(); + craft_ui::testing::contract::queue_reveal(&frames.ctx, log.id(), row); + frames.frame(vec![], &mut show); + let shown = log.rect(25); + assert!(shown.min.y >= view.min.y - SAME && shown.max.y <= view.max.y + SAME, "row 25 lies in the view in the frame after the reveal: {shown:?}"); + frames.idle(2, &mut show); + let held: Vec = std::iter::once(before).chain(offsets.borrow().iter().copied()).collect(); + let changes = held.windows(2).filter(|pair| (pair[0] - pair[1]).abs() > f64::EPSILON).count(); + assert_eq!(changes, 1, "the collection scrolls once for the reveal: {held:?}"); +} + +/// Enter on a rename field nobody typed in commits the draft the collection proposed, and ends with no event when the +/// draft is the row's own text. +#[trial] +fn enter_on_an_untyped_rename_commits_only_a_proposed_draft() { + let renamed = |draft: &str| { + let (log, enter, words) = (Log::new(), Cell::new(false), Words::flat(&["a", "b", "c"])); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + let list = Probe::new(SelectMode::Single).id_salt("list").renaming(draft, &enter); + log.take(list.show_items(ui, &words, &mut |key, _| ProbeRow::new(*key, log))); + }); + }; + frames.idle(3, &mut show); + request_rename(&frames.ctx, log.id(), &1_usize); + frames.idle(3, &mut show); + enter.set(true); + frames.idle(2, &mut show); + let commits: Vec = log + .events + .borrow() + .iter() + .filter_map(|event| match event { + CollectionEvent::Rename(EditEvent::Commit { after, .. }) => Some(after.name.clone()), + _ => None, + }) + .collect(); + commits + }; + assert_eq!(renamed("proposed"), ["proposed"], "Enter accepts the proposed draft"); + assert!(renamed("b").is_empty(), "a draft equal to the row's text reports no commit"); +} diff --git a/crates/ui-contract/tests/it/collection/table.rs b/crates/ui-contract/tests/it/collection/table.rs index 8df428752..a47dd6818 100644 --- a/crates/ui-contract/tests/it/collection/table.rs +++ b/crates/ui-contract/tests/it/collection/table.rs @@ -1,29 +1,43 @@ -//! Collections with columns and reordering. +//! Collections with columns and reordering, and the trials of the header's sideways reveal and its bound layout. -use super::kit::{Dismissed, ROW_H, Row}; -use craft_behavior::{ItemSource, Selection, SpanLayout}; -use craft_ui::contract::{Collection, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, Role}; +use super::kit::{Count, Dismissed, ROW_H, Row}; +use craft_behavior::{ColumnKey, ColumnWidth, ItemSource, Selection, SpanLayout}; +use craft_ui::contract::{ + Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, ColumnEvent, ColumnLayout, ColumnSpec, Common, Component, + ContainerProps, Cx, Props as _, Role, ShowCollection as _, +}; use craft_ui::style::StyleCx; +use craft_ui::testing::layout::in_region; +use craft_ui::testing::{Frames, input, pointer, trial}; use craft_ui_test_kit::contract::PlainStyle; +use egui::{Key, Modifiers, Pos2, Rect, Ui, Vec2}; +use std::cell::RefCell; -/// A list of rows at `ROW_H` with the collection props the trial gives. +/// A list of rows at `ROW_H` with the collection props the trial gives, and the column layout it binds. #[derive(craft_ui::contract::Component)] #[component(collection)] -pub struct Table { +pub struct Table<'a> { #[common] common: Common, #[container] props: ContainerProps, items: CollectionProps, + column_layout: Option>, } -impl Table { +impl<'a> Table<'a> { pub fn new(items: CollectionProps) -> Self { - Table { common: Common::new(), props: ContainerProps::new().sizing(craft_ui::contract::Sizing::Fill), items } + Table { common: Common::new(), props: ContainerProps::new().sizing(craft_ui::contract::Sizing::Fill), items, column_layout: None } + } + + /// The column arrangement the trial owns. + pub fn column_layout(mut self, layout: Bind<'a, ColumnLayout>) -> Self { + self.column_layout = Some(layout); + self } } -impl Component for Table { +impl Component for Table<'_> { const ROLE: Role = Role::LIST; type Style = PlainStyle; type Output = CollectionResponse; @@ -37,7 +51,7 @@ impl Component for Table { } } -impl Collection for Table { +impl Collection for Table<'_> { type Key = usize; type ItemLayout = SpanLayout; type Selection = Selection; @@ -48,7 +62,163 @@ impl Collection for Table { &self.items } + fn column_layout(&mut self) -> Option> { + self.column_layout.as_mut().map(Bind::reborrow) + } + fn item_layout(&self, source: &dyn ItemSource, width: f32, _: &StyleCx<'_>) -> SpanLayout { SpanLayout::new(source, width, ROW_H) } } + +const ORIGIN: Pos2 = Pos2::new(10.0, 10.0); +const VIEW: Vec2 = Vec2::new(400.0, 240.0); +const COL: f32 = 100.0; +/// Places that differ by less are the same place: the rounding of the layout. +const SAME: f32 = 0.5; + +/// Where each row was last shown. +#[derive(Default)] +struct Rows(RefCell>); + +impl Rows { + fn note(&self, key: usize, rect: Rect) { + let mut rows = self.0.borrow_mut(); + rows.retain(|(held, _)| *held != key); + rows.push((key, rect)); + } + + fn row(&self, key: usize) -> Rect { + self.0.borrow().iter().find(|(held, _)| *held == key).map(|(_, rect)| *rect).expect("the row was shown") + } + + /// The height of the middle of the header row, above the first row. + fn header_y(&self) -> f32 { + (ORIGIN.y + self.row(0).min.y) / 2.0 + } +} + +fn sorts(events: &[CollectionEvent]) -> Vec { + events.iter().filter_map(|event| if let CollectionEvent::Column(ColumnEvent::Sort { key, .. }) = event { Some(key.clone()) } else { None }).collect() +} + +fn press(frames: &mut Frames, key: Key, mods: Modifiers, show: &mut impl FnMut(&mut Ui)) { + frames.frame(vec![input::key_press(key, mods)], &mut *show); + frames.frame(vec![craft_ui::testing::focus::key_release(key, mods)], &mut *show); +} + +/// Six columns wider together than the table: focus on the first header cell and Forward until the last holds focus +/// scrolls the header sideways to show the last cell whole, and the rows by the same offset, so a press where the +/// rows' offset puts the last cell lands on it. Guards keyboard reach to header cells out of view. +#[trial] +fn focus_on_an_out_of_view_header_cell_scrolls_it_in() { + const NAMES: [&str; 6] = ["a", "b", "c", "d", "e", "f"]; + let last = ColumnKey::new(NAMES[5]); + let columns = || { + let specs = NAMES + .iter() + .map(|name| { + let spec = ColumnSpec::new(ColumnKey::new(name), *name, ColumnWidth::Fixed(COL)); + if *name == NAMES[5] { spec.sortable() } else { spec } + }) + .collect(); + CollectionProps::new().columns(specs) + }; + let (rows, source) = (Rows::default(), Count(4)); + let events = RefCell::new(Vec::new()); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + let out = Table::new(columns()).id_salt("table").show_items(ui, &source, &mut |key, cx| { + rows.note(*key, cx.rect); + Row::new() + }); + events.borrow_mut().extend(out.events); + }); + }; + frames.idle(3, &mut show); + let header_y = rows.header_y(); + // Tab enters the rows; Shift+Tab goes back to the header row, on its first column (a press on a header cell takes + // no focus). + press(&mut frames, Key::Tab, Modifiers::NONE, &mut show); + press(&mut frames, Key::Tab, Modifiers::SHIFT, &mut show); + for _ in 1..NAMES.len() { + press(&mut frames, Key::ArrowRight, Modifiers::NONE, &mut show); + } + frames.idle(2, &mut show); + let scrolled = ORIGIN.x - rows.row(0).min.x; + let cell = (ORIGIN.x + COL * 5.0 - scrolled)..=(ORIGIN.x + COL * 6.0 - scrolled); + assert!( + *cell.start() >= ORIGIN.x - SAME && *cell.end() <= ORIGIN.x + VIEW.x + SAME, + "the last header cell lies whole in the header's view: {cell:?}, rows scrolled by {scrolled}" + ); + events.borrow_mut().clear(); + pointer::click(&mut frames, Pos2::new((cell.start() + cell.end()) / 2.0, header_y), &mut show); + assert_eq!(sorts(&events.borrow()), vec![last], "the header cell sits where the rows' sideways offset puts it"); +} + +/// A table bound to a layout that moves a column and hides another shows the bound order, and a resize by a header +/// edge drag writes the width into the binding in the pass that reports it. Guards restoring a saved layout. +#[trial] +fn a_bound_column_layout_is_restored_and_receives_changes() { + const NAME: ColumnKey = ColumnKey::new("name"); + const SIZE: ColumnKey = ColumnKey::new("size"); + const DATE: ColumnKey = ColumnKey::new("date"); + let columns = || { + CollectionProps::new().columns(vec![ + ColumnSpec::new(NAME, "Name", ColumnWidth::fill(1.0)).sortable().resizable().movable(), + ColumnSpec::new(SIZE, "Size", ColumnWidth::Fixed(COL)).sortable().movable(), + ColumnSpec::new(DATE, "Date", ColumnWidth::Fixed(COL)).sortable().hideable(), + ]) + }; + let saved = RefCell::new(ColumnLayout { order: vec![SIZE, NAME, DATE], widths: Vec::new(), hidden: vec![DATE] }); + let (rows, source) = (Rows::default(), Count(4)); + let events = RefCell::new(Vec::new()); + // Widths a pass reported whose binding did not hold them at the end of that pass. + let unsaved = RefCell::new(Vec::new()); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + let mut held = saved.borrow().clone(); + let mut got = Vec::new(); + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + got = Table::new(columns()) + .column_layout(Bind::bound(&mut held)) + .id_salt("table") + .show_items(ui, &source, &mut |key, cx| { + rows.note(*key, cx.rect); + Row::new() + }) + .events; + }); + for event in &got { + if let CollectionEvent::Column(ColumnEvent::Resized { key, width, .. }) = event + && !held.widths.contains(&(key.clone(), *width)) + { + unsaved.borrow_mut().push(*width); + } + } + *saved.borrow_mut() = held; + events.borrow_mut().extend(got); + }; + frames.idle(2, &mut show); + let header_y = rows.header_y(); + // Size first at its fixed width, Name filling the rest, Date hidden. + pointer::click(&mut frames, Pos2::new(ORIGIN.x + COL / 2.0, header_y), &mut show); + pointer::click(&mut frames, Pos2::new(ORIGIN.x + (COL + VIEW.x) / 2.0, header_y), &mut show); + assert_eq!(sorts(&events.borrow()), vec![SIZE, NAME], "the header shows the bound order without the hidden column"); + + events.borrow_mut().clear(); + let edge = Pos2::new(ORIGIN.x + VIEW.x - 1.0, header_y); + pointer::drag(&mut frames, edge, Vec2::new(-30.0, 0.0), &mut show); + let widths: Vec = events + .borrow() + .iter() + .filter_map(|event| if let CollectionEvent::Column(ColumnEvent::Resized { key, width, .. }) = event { (*key == NAME).then_some(*width) } else { None }) + .collect(); + let width = widths.last().copied().expect("the edge drag resizes the Name column"); + assert!(width < VIEW.x - COL, "the column narrowed: {width}"); + assert!(unsaved.borrow().is_empty(), "every reported width was in the binding in its own pass: {:?}", unsaved.borrow()); + let layout = saved.borrow().clone(); + assert_eq!(layout.widths, vec![(NAME, width)], "the binding holds the new width"); + assert_eq!((layout.order, layout.hidden), (vec![SIZE, NAME, DATE], vec![DATE]), "the resize keeps the bound order and hidden column"); +} diff --git a/crates/ui-widgets/src/list/view.rs b/crates/ui-widgets/src/list/view.rs index 1d59b27eb..b2a22580d 100644 --- a/crates/ui-widgets/src/list/view.rs +++ b/crates/ui-widgets/src/list/view.rs @@ -57,7 +57,7 @@ pub struct List<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { #[prop(func = "Fn(&K) -> bool")] can_rename: Option>, /// The text a row's rename field opens with, `None` for the row's text: an empty draft when several rows are picked - /// takes a name for all of them. + /// takes a name for all of them. Enter on a proposed draft nobody typed in commits it. #[prop(func = "Fn(&K) -> Option")] rename_draft: Option>, /// Which rows may be dragged.