diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 8ef48a619..91013d35e 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -90,7 +90,7 @@ pub use label_column::{LabelColumn, LabelPlacement}; pub use layout_memory::SizeTween; pub use monitor::{Monitor, MonitorKey}; pub use motion::{MotionKind, MotionMode, Playback}; -pub use nav::{Arrows, Letters, NavOutline, NavShape, NavState, NavStep, Roving, TypeAhead, wheel_step}; +pub use nav::{Arrows, Letters, NavOutline, NavShape, NavState, NavStep, Roving, TypeAhead, lead_step, wheel_step}; pub use part::{PartKey, PartRef}; pub use pixel_size::PixelSize; diff --git a/crates/behavior/src/nav/roving.rs b/crates/behavior/src/nav/roving.rs index 8c0e645a7..4274d271e 100644 --- a/crates/behavior/src/nav/roving.rs +++ b/crates/behavior/src/nav/roving.rs @@ -1,6 +1,6 @@ //! Roving focus groups and type-ahead matching. -use crate::intent::{MoveMods, NavMove}; +use crate::intent::{Granularity, MoveMods, NavMove}; use super::*; @@ -40,6 +40,9 @@ pub struct Roving { /// Whether the focused member is no lead, so the next move is a first move: forward moves land on the first /// enabled member, backward moves on the last. pub no_lead: bool, + /// Whether Left and Right with the lead modifier (Ctrl, Cmd on macOS; `lead_step`) reach the focused member instead + /// of moving the focus: a table header moves its column with them. + pub keeps_lead_moves: bool, } /// Which arrow keys a roving group moves its lead with. @@ -70,6 +73,7 @@ impl Roving { first_column: None, hands_back: false, no_lead: false, + keeps_lead_moves: false, } } @@ -116,6 +120,12 @@ impl Roving { self } + /// Left and Right with the lead modifier reach the focused member. + pub const fn keeps_lead_moves(mut self) -> Self { + self.keeps_lead_moves = true; + self + } + /// Whether the focused member is no lead: the next move starts at an end, as from a group with no lead. pub const fn no_lead(mut self, on: bool) -> Self { self.no_lead = on; @@ -133,9 +143,11 @@ impl Roving { } /// Whether the group handles `mv` with `mods`: Page moves only with a page size and without `lead` (on a document - /// canvas that scrolls sideways), Start and End only with Home and End. + /// canvas that scrolls sideways), Start and End only with Home and End, and no `lead_step` in a group that + /// `keeps_lead_moves`. pub const fn takes(&self, mv: NavMove, mods: MoveMods) -> bool { match mv { + _ if self.keeps_lead_moves && lead_step(mv, mods).is_some() => false, NavMove::PageUp | NavMove::PageDown => self.page.is_some() && !mods.lead, NavMove::Start | NavMove::End => self.home_end, NavMove::Back | NavMove::Forward => matches!(self.arrows, Arrows::All | Arrows::Horizontal), @@ -144,6 +156,21 @@ impl Roving { } } +/// The step Left or Right with the lead modifier makes, physical as the arrows are: Ctrl+Left and Ctrl+Right (Back +/// and Forward with the lead), and Cmd+Left and Cmd+Right on macOS, which the key table makes a move to the start or +/// end of the line. +pub const fn lead_step(mv: NavMove, mods: MoveMods) -> Option { + if !mods.lead { + return None; + } + match mv { + NavMove::Back | NavMove::Forward => Some(mv), + NavMove::Start if matches!(mods.by, Granularity::Line) => Some(NavMove::Back), + NavMove::End if matches!(mods.by, Granularity::Line) => Some(NavMove::Forward), + _ => None, + } +} + /// Typed letters of the last second as one prefix. #[derive(Clone, Debug, Default)] pub struct TypeAhead { diff --git a/crates/ui-contract/src/contract/collection.rs b/crates/ui-contract/src/contract/collection.rs index 58115a404..ac4861d7f 100644 --- a/crates/ui-contract/src/contract/collection.rs +++ b/crates/ui-contract/src/contract/collection.rs @@ -8,7 +8,9 @@ mod response; pub use columns::{ColumnAlign, ColumnKind, ColumnSort, ColumnSpec, ToggleColumn}; pub use drops::{DropAt, DropKind, DropPayload, DropPlace}; -pub use events::{CollectionEvent, ColumnEvent, ContextMenuRequest, HeaderMenuRequest, ListDrag, OpenChange, Rename, ReorderMove, ToggleEdit}; +pub use events::{ + CollectionEvent, ColumnEvent, ColumnRequest, ContextMenuRequest, HeaderMenuRequest, ListDrag, OpenChange, Rename, ReorderMove, ToggleEdit, +}; pub use props::{ ActivateOn, CollectionProps, DragPayload, ItemKeys, LeadOnOpen, LeadSource, ReorderRule, RowPressed, RowState, SelectMode, SpaceAction, }; diff --git a/crates/ui-contract/src/contract/collection/columns.rs b/crates/ui-contract/src/contract/collection/columns.rs index 553125246..f93710b76 100644 --- a/crates/ui-contract/src/contract/collection/columns.rs +++ b/crates/ui-contract/src/contract/collection/columns.rs @@ -80,6 +80,8 @@ pub struct ColumnSpec { /// The most of the collection's width a `Content` column takes, as a share: a name column as wide as its widest /// name, at most a third of the table. pub max_share: Option, + /// The header menu has a check for the column, so the user can hide it. A column that can't be hidden always shows. + pub hideable: bool, } /// Where a column's content sits. @@ -110,6 +112,7 @@ impl ColumnSpec { icon: None, tip: None, max_share: None, + hideable: false, } } @@ -163,6 +166,13 @@ impl ColumnSpec { self } + /// The user can hide the column from the header menu. + #[must_use] + pub fn hideable(mut self) -> Self { + self.hideable = true; + self + } + /// A `Content` column takes at most `share` of the collection's width. #[must_use] pub fn at_most(mut self, share: f32) -> Self { diff --git a/crates/ui-contract/src/contract/collection/events.rs b/crates/ui-contract/src/contract/collection/events.rs index f3095fd17..8c7605bc3 100644 --- a/crates/ui-contract/src/contract/collection/events.rs +++ b/crates/ui-contract/src/contract/collection/events.rs @@ -63,16 +63,29 @@ impl ListDrag { } } -/// A request for the context menu of a column header: the app lists `ColumnCommands` in it. +/// A request for the header menu: a secondary click on a header cell or on the empty header after the last one, or the +/// Menu key on a focused header. The collection that shows the menu reads it with `Cx::header_menu`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct HeaderMenuRequest { - /// The column whose header was pressed or focused. - pub column: ColumnKey, + /// The column whose header was pressed or focused; `None` for the empty header. + pub column: Option, /// Where the menu opens. pub at: Pos2, } +/// What a pick in the header menu asks of the header, given back with `Cx::column_request`. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ColumnRequest { + /// Show or hide a hideable column. + Shown(ColumnKey, bool), + /// Put back the app's order, show every column and drop the user's widths; the sort stays. + Reset, + /// Run a header command on the menu's column. + Command(crate::contract::ColumnCommands), +} + /// A toggle column's cell flipped. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -154,6 +167,17 @@ pub enum ColumnEvent { /// Its new position. to: usize, }, + /// The user showed or hid the column from the header menu. + Shown { + /// The column. + key: ColumnKey, + /// Whether it shows now. + shown: bool, + }, + /// The user hid the sorted column: the rows have no sort, and the app puts them in their natural order. + Unsorted, + /// The user reset the columns: the app's order, every column shown, the app's widths. The sort stays. + Reset, } /// What a collection reports, in drawing order. @@ -221,8 +245,6 @@ pub enum CollectionEvent { Toggle(EditEvent>), /// A column changed. Column(ColumnEvent), - /// The user asked for the context menu of a column header. - HeaderMenu(HeaderMenuRequest), /// An item reported an event. Item(K, E), } diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 793fb7529..db3944fb4 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -154,6 +154,10 @@ pub struct CxCore<'a> { /// The events and visible range the item step left for `collection_response`. pub(crate) collection_events: Option>, pub(crate) visible_rows: Range, + /// The header row's facts the item step leaves for the collection's `update` and `overlay` (`Cx::header_menu`). + pub(crate) header: crate::contract::items::HeaderFacts, + /// The header menu's picks, which the item step applies at the end of the pass (`Cx::column_request`). + pub(crate) column_requests: Vec, /// What the collection's props allow, for `collection_response`. pub(crate) gestures: crate::contract::collection::Gestures, /// The text part's result of this pass, from step 8b. diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index 10f6f7a9d..5bd774d7b 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -18,6 +18,7 @@ mod request; pub use drag::{SweepApply, SweepStep}; pub use header::ColumnCommands; +pub(crate) use header::HeaderFacts; #[doc(hidden)] pub use header::put_toggle_names; pub use press::item_part_open; diff --git a/crates/ui-contract/src/contract/items/header.rs b/crates/ui-contract/src/contract/items/header.rs index c639299b7..73e7cba6b 100644 --- a/crates/ui-contract/src/contract/items/header.rs +++ b/crates/ui-contract/src/contract/items/header.rs @@ -1,9 +1,9 @@ -//! The header row (17.1, 17.3 I0): column widths and order, sort presses, resize grips, column moves and the -//! header commands, in one roving group of focusable parts. +//! The header row (17.1, 17.3 I0): column widths, order and hidden columns, sort presses, resize grips, column moves, +//! the header commands and the header menu's request, in one roving group of focusable parts. use super::ItemsHooks; use crate::contract::collection::{ - CollectionEvent, CollectionProps, ColumnEvent, ColumnKind, ColumnSort, ColumnSpec, HeaderMenuRequest, ToggleColumn, + CollectionEvent, CollectionProps, ColumnEvent, ColumnKind, ColumnRequest, ColumnSort, ColumnSpec, HeaderMenuRequest, ToggleColumn, }; use crate::contract::reorder::{self, Gap}; use crate::contract::{ @@ -31,11 +31,13 @@ use egui::{Align, Context, Id, Pos2, Rect, Response, Ui, UiBuilder, Vec2}; const HEADER_ROLE: TypeRole = TypeRole::Label; const HEADER: PartKey = PartKey::new("header"); const GRIP: PartKey = PartKey::new("header_grip"); +/// The empty header after the last column: a secondary click on it asks for the header menu. +const ROOM: PartKey = PartKey::new("header_room"); /// The narrowest a resized column gets, in control heights. const MIN_COLUMN: f32 = 2.0; -/// The commands of a column header (17.1): resize and move work from the keyboard through them. The app lists -/// them in the menu it opens for `CollectionEvent::HeaderMenu`, and `commands::fire` routes them to the collection. +/// The commands of a column header (17.1): resize works from the keyboard through them, and the header menu lists +/// them for the column it was opened from. `commands::fire` routes them to the collection. #[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::CommandSet)] #[command(prefix = "column", scope = "column")] #[non_exhaustive] @@ -105,6 +107,19 @@ pub(super) fn content_id(id: Id, key: &ColumnKey) -> Id { sub(id, ("column_content", hash_of(key))) } +/// The header row's facts for the collection that shows the header menu. +#[derive(Clone, Debug, Default)] +pub(crate) struct HeaderFacts { + /// The menu was asked for in this pass. + pub(crate) asked: bool, + /// The header menu asked for, while it may be open. + pub(crate) menu: Option, + /// The columns the user hid. + pub(crate) hidden: Vec, + /// The header commands that can act on the menu's column. + pub(crate) enabled: Vec, +} + /// What the header keeps in session memory under the collection's id. #[derive(Clone, Debug, Default)] pub(super) struct HeaderMemory { @@ -112,9 +127,11 @@ pub(super) struct HeaderMemory { order: Vec, /// User widths of `Content` and `Fill` columns. widths: Vec<(ColumnKey, f32)>, - /// The column a context menu or command acts on when no header part holds focus, and the frame the menu was - /// requested in. The menu is gone once no layer that takes keys is open a frame after its request. - menu: Option<(ColumnKey, u64)>, + /// Columns the user hid from the header menu. + hidden: Vec, + /// 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)>, /// The column the keyboard resize command works on. resizing: Option, grab: Option, @@ -145,7 +162,12 @@ pub(super) struct Header { unit: f32, cells: Vec, events: Vec, - menus: Vec, + /// A header menu asked for in this pass. + asked: bool, + /// The hideable columns, shown or hidden. + hideable: Vec, + /// The empty header after the last column. + room: Option, /// The narrowest a resized column gets, and the keyboard resize step. min: f32, step: f32, @@ -162,7 +184,9 @@ impl Header { self.memory = stage.session::(sub(id, "columns")).clone(); self.sort = props.sort.clone(); self.on = props.header; - let mut specs = props.columns.to_vec(); + self.hideable = props.columns.iter().filter(|spec| spec.hideable).map(|spec| spec.key.clone()).collect(); + let hidden = &self.memory.hidden; + let mut specs: Vec = props.columns.iter().filter(|spec| !(spec.hideable && hidden.contains(&spec.key))).cloned().collect(); let order = &self.memory.order; specs.sort_by_key(|spec| order.iter().position(|key| *key == spec.key).unwrap_or(usize::MAX)); self.content = vec![0.0; specs.len()]; @@ -357,9 +381,18 @@ impl Header { } self.cells.push(Cell { spec: at, rect, hash }); } - // A keyboard resize reads Forward and Back itself, so the cells do not rove while it lasts. + let room = flow.rect(); + self.room = (room.width() > 0.0).then_some(room); + if let Some(room) = self.room { + pcx.part(ROOM, room) + .sense(Sense::CLICK) + .priority(HitPriority::new(HitLevel::Body, 0)) + .pointer_only("the Menu key on a header opens the header menu"); + } + // A keyboard resize reads Forward and Back itself, so the cells do not rove while it lasts. Ctrl or Cmd with + // Left or Right reaches the header, which moves the focused column. if self.memory.resizing.is_none() { - pcx.roving(Roving::new(NavShape::Flat)); + pcx.roving(Roving::new(NavShape::Flat).keeps_lead_moves()); } } @@ -463,8 +496,7 @@ impl Header { self.sort(&key); } if cx.part(HEADER.at(hash)).hovered && crate::runtime::pointer::frame(&ctx).release == Some(PointerButton::Secondary) { - self.memory.menu = Some((key.clone(), crate::runtime::egui::pass::root_frame_nr(&ctx))); - self.menus.push(HeaderMenuRequest { column: key.clone(), at: rect.left_bottom() }); + self.ask_menu(&ctx, Some(key.clone()), ctx.pointer_latest_pos().unwrap_or(rect.left_bottom())); } if movable && primary && matches!(phase, PressPhase::DragStart { .. }) { cx.start_drag(ColumnDrag { table: id, key: key.clone() }, DragPreview::None); @@ -501,9 +533,17 @@ impl Header { } } if active == Some(at) && cx.core.intents.take(Intent::ContextMenu) { - self.memory.menu = Some((key.clone(), crate::runtime::egui::pass::root_frame_nr(&ctx))); - self.menus.push(HeaderMenuRequest { column: key, at: rect.left_bottom() }); + self.ask_menu(&ctx, Some(key.clone()), rect.left_bottom()); } + if active == Some(at) { + self.lead_moves(cx, at, rtl); + } + } + if let Some(room) = self.room + && cx.part(ROOM).hovered + && crate::runtime::pointer::frame(&ctx).release == Some(PointerButton::Secondary) + { + self.ask_menu(&ctx, None, ctx.pointer_latest_pos().unwrap_or(room.left_bottom())); } self.column_drop(cx, id, rtl); self.keyboard_resize(cx); @@ -511,6 +551,85 @@ impl Header { active.is_some() || self.memory.resizing.is_some() } + /// Asks for the header menu at `at`, for `column` or for the empty header. + fn ask_menu(&mut self, ctx: &Context, column: Option, at: Pos2) { + self.memory.menu = Some((HeaderMenuRequest { column, at }, crate::runtime::egui::pass::root_frame_nr(ctx))); + self.asked = true; + } + + /// Ctrl or Cmd with Left or Right on the focused header at `at` moves its column one place that way, as the move + /// commands do. + fn lead_moves(&mut self, cx: &mut Cx<'_, C>, at: usize, rtl: bool) { + while let Some((mv, mods)) = cx.core.intents.take_move_where(|mv, mods| craft_behavior::lead_step(mv, mods).is_some()) { + let command = + if craft_behavior::lead_step(mv, mods) == Some(NavMove::Back) { ColumnCommands::MoveLeft } else { ColumnCommands::MoveRight }; + if self.allowed(command, at, rtl) { + self.run(command, at, rtl); + } + } + } + + /// Runs `command` on the column at display position `at`, which `allowed` let it act on. + fn run(&mut self, command: ColumnCommands, at: usize, rtl: bool) { + let key = self.specs[self.cells[at].spec].key.clone(); + match command { + ColumnCommands::Resize => self.memory.resizing = Some(key), + ColumnCommands::MoveLeft => self.move_to(&key, if rtl { at + 1 } else { at - 1 }), + ColumnCommands::MoveRight => self.move_to(&key, if rtl { at - 1 } else { at + 1 }), + } + } + + /// The column the open header menu acts on, by display position. + fn menu_target(&self) -> Option { + self.memory.menu.as_ref().and_then(|(menu, _)| menu.column.as_ref()).and_then(|key| self.cell_at(key)) + } + + /// Applies the header menu's picks at the end of the pass: a column shown or hidden, the columns reset, a command + /// run on the menu's column. + pub(super) fn apply_requests(&mut self, ctx: &Context, requests: Vec, rtl: bool) { + for request in requests { + match request { + ColumnRequest::Shown(key, shown) => { + if !self.hideable.contains(&key) || shown != self.memory.hidden.contains(&key) { + continue; + } + if shown { + self.memory.hidden.retain(|held| *held != key); + } else { + self.memory.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 }); + if unsorted { + self.events.push(ColumnEvent::Unsorted); + } + } + ColumnRequest::Reset => { + let menu = self.memory.menu.take(); + self.memory = HeaderMemory { menu, ..HeaderMemory::default() }; + self.events.push(ColumnEvent::Reset); + } + ColumnRequest::Command(command) => { + if let Some(at) = self.menu_target().filter(|&at| self.allowed(command, at, rtl)) { + self.run(command, at, rtl); + } + } + } + crate::runtime::egui::repaint::request_of(ctx, crate::runtime::egui::pass::current_viewport(ctx)); + } + } + + /// What the collection's `update` and `overlay` read of the header this pass (`Cx::header_menu`). + pub(super) fn facts(&self, rtl: bool) -> HeaderFacts { + let target = self.menu_target(); + HeaderFacts { + asked: self.asked, + menu: self.memory.menu.as_ref().map(|(menu, _)| menu.clone()), + hidden: self.memory.hidden.clone(), + enabled: ColumnCommands::ALL.into_iter().filter(|&command| target.is_some_and(|at| self.allowed(command, at, rtl))).collect(), + } + } + /// The keyboard resize the `Resize` command starts: Forward widens, Back narrows, Enter or Escape ends it. /// The drop target of this collection's own header drag: the gap mark while the drag is over the header, the move /// on release. @@ -551,7 +670,7 @@ impl Header { { self.memory.menu = None; } - let target = active.or_else(|| self.memory.menu.as_ref().and_then(|(key, _)| self.cell_at(key))); + let target = active.or_else(|| self.menu_target()); let chain = cx.core.env.command_chain().pushed(ColumnCommands::SCOPE, id); for command in ColumnCommands::ALL { let enabled = target.is_some_and(|at| self.allowed(command, at, rtl)); @@ -560,12 +679,7 @@ impl Header { while let Some((command, _)) = commands::take_for_instance(&ctx, Some(id), false, ColumnCommands::from_ref) { let Some(at) = target.filter(|&at| self.allowed(command, at, rtl)) else { continue }; self.memory.menu = None; - let key = self.specs[self.cells[at].spec].key.clone(); - match command { - ColumnCommands::Resize => self.memory.resizing = Some(key), - ColumnCommands::MoveLeft => self.move_to(&key, if rtl { at + 1 } else { at - 1 }), - ColumnCommands::MoveRight => self.move_to(&key, if rtl { at - 1 } else { at + 1 }), - } + self.run(command, at, rtl); } } @@ -625,11 +739,10 @@ impl ItemsHooks<'_, '_, C> { /// Step 9 for the header: its events join the collection's, in drawing order. pub(super) fn header_step(&mut self, cx: &mut Cx<'_, C>) -> bool { let (id, rtl) = (cx.core.id, cx.core.flow.is_rtl()); + self.header.asked = false; let held = self.header.update(cx, id, rtl); self.take_column_events(); - for menu in self.header.menus.drain(..) { - self.events.push(CollectionEvent::HeaderMenu(menu)); - } + cx.core.header = self.header.facts(rtl); held } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index f55b0f8e1..347d56c19 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -754,6 +754,11 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { } *cx.core.memory.session::>(sub(id, "lead")) = self.lead.clone(); cx.core.memory.session::>(sub(id, "item_layout")).0 = self.layout.clone(); + let requests = std::mem::take(&mut cx.core.column_requests); + if !requests.is_empty() { + self.header.apply_requests(&cx.core.ctx, requests, cx.core.flow.is_rtl()); + self.take_column_events(); + } *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); diff --git a/crates/ui-contract/src/contract/items/output.rs b/crates/ui-contract/src/contract/items/output.rs index 1680bc416..b53da95c3 100644 --- a/crates/ui-contract/src/contract/items/output.rs +++ b/crates/ui-contract/src/contract/items/output.rs @@ -1,7 +1,8 @@ //! What a collection's caller reads from `Cx` after the item step: its selection and response. -use crate::contract::collection::{CollectionResponse, ItemsOut}; -use crate::contract::{Collection, Cx}; +use crate::contract::collection::{CollectionResponse, ColumnRequest, HeaderMenuRequest, ItemsOut}; +use crate::contract::{Collection, ColumnCommands, Cx}; +use craft_behavior::ColumnKey; impl Cx<'_, C> { /// The selection the item step holds this pass: the app's binding when it has one, else the one the item step @@ -11,6 +12,29 @@ impl Cx<'_, C> { self.core.collection_selection.as_ref().and_then(|held| held.downcast_ref::()) } + /// The header menu, from the item step's header: the request while the menu may be open (a secondary click on a + /// header cell or the empty header, the Menu key on a focused header) and whether it was made in this pass. The + /// collection that shows the menu opens its popup on a fresh request and gives the picks back with + /// `column_request`. + pub fn header_menu(&self) -> Option<(&HeaderMenuRequest, bool)> { + self.core.header.menu.as_ref().map(|menu| (menu, self.core.header.asked)) + } + + /// The columns the user hid from the header menu; the header leaves them out. + pub fn hidden_columns(&self) -> &[ColumnKey] { + &self.core.header.hidden + } + + /// Whether the header command `command` can act on the header menu's column. + pub fn column_command_enabled(&self, command: ColumnCommands) -> bool { + self.core.header.enabled.contains(&command) + } + + /// Gives a header menu pick back to the header, which applies it at the end of this pass and reports what changed. + pub fn column_request(&mut self, request: ColumnRequest) { + self.core.column_requests.push(request); + } + /// The output of a collection: its response, every event in drawing order and the positions it showed. pub fn collection_response(&mut self) -> CollectionResponse { let events = self diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 74f668309..2c29462d4 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -49,7 +49,7 @@ pub use body::REORDER_BAND; #[doc(hidden)] pub use body::pad_of; pub use collection::{ - ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnSort, ColumnSpec, + ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnRequest, ColumnSort, ColumnSpec, ContextMenuRequest, DragPayload, DropAt, DropKind, DropPayload, DropPlace, HeaderMenuRequest, ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowPressed, RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, }; diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 0bdc67ff9..fc3bcb8eb 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -368,6 +368,8 @@ fn blank_core<'a>( roving_lead: None, collection_events: None, visible_rows: 0..0, + header: Default::default(), + column_requests: Vec::new(), gestures: Default::default(), texts: None, selections: Vec::new(), diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index 2cf968086..778f9103e 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -444,8 +444,6 @@ pub enum CollectionKind { Toggle(EditKind), /// A column changed. Column, - /// A column header's context menu was asked for. - HeaderMenu, /// An item reported an event. Item, } @@ -470,7 +468,6 @@ impl CollectionKind { CollectionEvent::Rename(edit) => CollectionKind::Rename(EditKind::of(edit)?), CollectionEvent::Toggle(edit) => CollectionKind::Toggle(EditKind::of(edit)?), CollectionEvent::Column(_) => CollectionKind::Column, - CollectionEvent::HeaderMenu(_) => CollectionKind::HeaderMenu, CollectionEvent::Item(..) => CollectionKind::Item, }) } diff --git a/crates/ui-widgets/src/table/stories.rs b/crates/ui-widgets/src/table/stories.rs index 6f0b3e004..a2b6de825 100644 --- a/crates/ui-widgets/src/table/stories.rs +++ b/crates/ui-widgets/src/table/stories.rs @@ -69,7 +69,7 @@ fn columns(keep: bool, widths: &Widths) -> Vec { let mut columns = vec![ ColumnSpec::new(NAME, "File name", ColumnWidth::fill(2.0)).sortable().resizable().movable(), ColumnSpec::new(PAGES, "Pages", width_of(widths, &PAGES, ColumnWidth::Controls(3.0))).numeric().sortable().resizable(), - ColumnSpec::new(SIZE, "Size (KB)", width_of(widths, &SIZE, ColumnWidth::Controls(4.0))).numeric().sortable().resizable(), + ColumnSpec::new(SIZE, "Size (KB)", width_of(widths, &SIZE, ColumnWidth::Controls(4.0))).numeric().sortable().resizable().hideable(), ]; if keep { columns.insert(0, ColumnSpec::new(KEEP, "Keep", ColumnWidth::Controls(1.5)).kind(ColumnKind::Toggle(ToggleColumn::sweepable()))); diff --git a/crates/ui-widgets/src/table/view.rs b/crates/ui-widgets/src/table/view.rs index 4988431c3..deb06daae 100644 --- a/crates/ui-widgets/src/table/view.rs +++ b/crates/ui-widgets/src/table/view.rs @@ -1,19 +1,25 @@ //! `Table`: a `List` with columns. The contract's header row draws the headers and reports sort presses, widths, -//! resizes and moves; the item step lays each row's cells out along the columns; the rows are `ListRow`s that draw a -//! value in each cell. The table keeps no sort order and no hidden columns: the app owns both and passes the columns -//! it shows. +//! resizes, moves and hidden columns; the item step lays each row's cells out along the columns; the rows are +//! `ListRow`s that draw a value in each cell. The table shows the header menu. The app owns the sort order. +use super::words::TableWords; +use crate::contract::overlay::Anchor; use crate::contract::{ - Bind, BindMut, Collection, CollectionProps, CollectionResponse, ColumnSpec, Common, Component, ContainerProps, Cx, DropKind, EditResponse, - ListDrag, Props as _, Role, SelectMode, Sizing, + Bind, BindMut, Collection, CollectionProps, CollectionResponse, ColumnCommands, ColumnRequest, ColumnSpec, Common, Component, ContainerProps, Cx, + DropKind, EditResponse, ListDrag, OverlayUi, Overlays as _, Props as _, Role, SelectMode, Show as _, ShowContainer as _, Sizing, WordSetCx as _, }; +use crate::display::Divider; use crate::list::{DropTest, ListRow, RowEvent, RowTest, RowText}; +use crate::menu::{Menu, MenuItem}; use crate::runtime::env::Label; use crate::style::{ComponentStyle, StyleCx}; use craft_behavior::{ItemSource, Metrics, Selection, SpanLayout}; use egui::{Rect, Ui}; use std::hash::Hash; +/// The header menu's popup. +const HEADER_MENU: &str = "header_menu"; + /// The style of the table: it has no look of its own beyond its container's surface. #[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] #[non_exhaustive] @@ -27,7 +33,12 @@ pub struct TableStyle { /// menus. /// /// The app sorts its rows and tells the table the order it used (`sort`); a press on a sortable header reports -/// `ColumnEvent::Sort` with the next order. A table of groups and their children is a tree: the label column is +/// `ColumnEvent::Sort` with the next order. A secondary click on a header, or on the empty header after the last +/// one, or the Menu key on a focused header, opens the header menu: "Columns" over a check per hideable column, which +/// shows or hides it and leaves the menu open, then Reset Columns (the app's order, every column shown, the app's +/// widths; the sort stays), and for a header the column commands (Resize Column…, Move Column Left and Right). Ctrl or +/// Cmd with Left or Right on a focused header moves its column. What the user changes is reported as `ColumnEvent`s +/// for the app to save. A table of groups and their children is a tree: the label column is /// indented by depth and groups open and close as in a `List`. #[derive(crate::contract::Component, crate::contract::Props)] #[component(collection, probe(Table<'static, usize>))] @@ -102,6 +113,61 @@ impl Component for Table<'_, K> { TableStyle::default() } + fn update(&mut self, cx: &mut Cx<'_, Self>) { + cx.popup(HEADER_MENU); + } + + /// The header menu: the item step's header asks for it after `update`, so it opens here. + fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { + let popup = cx.popup(HEADER_MENU); + let Some((_, asked)) = cx.header_menu() else { return }; + if asked { + popup.open(cx); + } + let Some((menu, _)) = cx.header_menu() else { return }; + let (at, for_column) = (menu.at, menu.column.is_some()); + let hidden = cx.hidden_columns().to_vec(); + let hideable: Vec<_> = self.items.columns.iter().filter(|spec| spec.hideable).map(|spec| (spec.key.clone(), spec.header.clone())).collect(); + let commands: Vec<(ColumnCommands, bool)> = if for_column { + ColumnCommands::ALL.into_iter().map(|command| (command, cx.column_command_enabled(command))).collect() + } else { + Vec::new() + }; + let ctx = cx.core.ctx.clone(); + let words = cx.words::(); + let mut picks = Vec::new(); + let layer = crate::menu::layer(false).anchor(Anchor::Point(at)); + ui.show(popup, layer, |ui, _| { + Menu::inline(words.columns.clone()).show(ui, |ui, _| { + if !hideable.is_empty() { + MenuItem::new(words.columns.clone()).enabled(false).show(ui); + for (key, header) in &hideable { + let shown = !hidden.contains(key); + if MenuItem::new(header.clone()).check(shown).keep_open(true).show(ui).ran { + picks.push(ColumnRequest::Shown(key.clone(), !shown)); + } + } + Divider::horizontal().show(ui); + } + if MenuItem::new(words.reset_columns.clone()).show(ui).ran { + picks.push(ColumnRequest::Reset); + } + if !commands.is_empty() { + Divider::horizontal().show(ui); + } + for (command, enabled) in &commands { + let label = crate::runtime::commands::resolve(&ctx, *command).label; + if MenuItem::new(label.to_string()).enabled(*enabled).show(ui).ran { + picks.push(ColumnRequest::Command(*command)); + } + } + }); + }); + for pick in picks { + cx.column_request(pick); + } + } + fn finish(self, mut cx: Cx<'_, Self>) -> Self::Output { cx.collection_response() } diff --git a/crates/ui-widgets/src/table/words.rs b/crates/ui-widgets/src/table/words.rs index 5d7c7e5ef..e3245ba47 100644 --- a/crates/ui-widgets/src/table/words.rs +++ b/crates/ui-widgets/src/table/words.rs @@ -1,5 +1,15 @@ //! Built-in words of the table family. +craft_ui::words! { + /// The words of the table's header menu. + pub struct TableWords { + /// The label over the checks that show and hide columns. + columns: "table.columns" = "Columns"; + /// Puts back the app's columns. + reset_columns: "table.resetColumns" = "Reset Columns"; + } +} + craft_ui::words! { /// The words of the metadata table. pub struct MetadataWords { diff --git a/crates/ui-widgets/tests/it/table.rs b/crates/ui-widgets/tests/it/table.rs index 04620744c..60d3a8a04 100644 --- a/crates/ui-widgets/tests/it/table.rs +++ b/crates/ui-widgets/tests/it/table.rs @@ -1,17 +1,20 @@ //! The table's header row and column widths: a double click on a column's edge fits the column to its widest cell in -//! view, and the metadata table's name column follows its widest name up to a third of the table. +//! view, the header menu hides, shows and resets columns, Ctrl or Cmd with an arrow moves the focused column, and the +//! metadata table's name column follows its widest name up to a third of the table. use craft_behavior::{ColumnKey, ColumnWidth, keyed}; -use craft_ui::contract::{CollectionEvent, ColumnEvent, ColumnSpec, ShowCollection as _}; +use craft_host::target::Os; +use craft_ui::contract::{CollectionEvent, ColumnEvent, ColumnSort, ColumnSpec, Role, ShowCollection as _}; use craft_ui::list::ListRow; use craft_ui::table::{MetadataGroup, MetadataRow, MetadataTable, Table}; -use craft_ui::testing::{Fixture, Room, trial}; -use egui::{Pos2, Rect}; +use craft_ui::testing::{Fixture, Room, pointer, trial}; +use egui::{Key, Modifiers, Pos2, Rect}; use std::cell::{Cell, RefCell}; use std::rc::Rc; const NAME: ColumnKey = ColumnKey::new("name"); const SIZE: ColumnKey = ColumnKey::new("size"); +const DATE: ColumnKey = ColumnKey::new("date"); const LONG: &str = "A file name far longer than the column it starts in"; /// A table of `names` whose name column starts `controls` control heights wide; the app applies the widths the @@ -117,3 +120,95 @@ fn the_metadata_name_column_fits_its_widest_name_up_to_a_third_of_the_table() { assert!(long_value > short_value, "a longer name widens the name column"); assert!(long_value - table.left() <= table.width() / 3.0 + padding, "the name column stops at a third of the table"); } + +/// A table sorted by its hideable Size column, with movable Name and Date columns; the app drops its sort on +/// `Unsorted`. Returns the fixture and the column events seen. +fn sorted_files() -> (Fixture, Rc>>) { + let events = Rc::new(RefCell::new(Vec::new())); + let sort = Rc::new(RefCell::new(Some(ColumnSort::ascending(SIZE)))); + let seen = events.clone(); + let mut fixture = Fixture::new(move |ui| { + let columns = vec![ + ColumnSpec::new(NAME, "Name", ColumnWidth::Controls(6.0)).movable(), + ColumnSpec::new(SIZE, "Size", ColumnWidth::Controls(4.0)).sortable().hideable(), + ColumnSpec::new(DATE, "Date", ColumnWidth::Controls(4.0)).movable(), + ]; + let keys = [0_usize, 1, 2]; + let source = keyed(&keys, |key: &usize| *key); + let shown = sort.borrow().clone(); + let out = + Table::new("Files", columns).sort(shown).show_items(ui, &source, &mut |key, icx| ListRow::new(format!("File {key}")).cells(icx.cells())); + for event in out.events { + if let CollectionEvent::Column(column) = event { + if column == ColumnEvent::Unsorted { + *sort.borrow_mut() = None; + } + seen.borrow_mut().push(column); + } + } + }); + fixture.in_room(Room::Dialog).settle(); + (fixture, events) +} + +fn headers(fixture: &Fixture) -> Vec { + fixture.by_role(Role::COLUMN_HEADER).iter().filter_map(|target| fixture.tree().name_of(target.node).map(str::to_owned)).collect() +} + +fn secondary_click(fixture: &mut Fixture, at: Pos2) { + fixture.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fixture.frame(vec![pointer::secondary(at, false)]).settle(); +} + +/// The menu row named `label` of `role`. +fn menu_row(fixture: &Fixture, role: Role, label: &str) -> Option { + fixture.by_role(role).into_iter().find(|target| fixture.tree().name_of(target.node) == Some(label)) +} + +/// A secondary click on a header opens the header menu; unchecking a hideable column hides it, reports it and, as it +/// was the sorted one, reports the rows unsorted, and the menu stays open; Reset Columns brings it back. A secondary +/// click on the empty header after the last column opens the menu without the column commands. +#[trial] +fn the_header_menu_hides_shows_and_resets_columns() { + let (mut fixture, events) = sorted_files(); + assert_eq!(headers(&fixture), ["Name", "Size", "Date"]); + let name = fixture.by_label("Name").expect("the header cell").center(); + secondary_click(&mut fixture, name); + let size = menu_row(&fixture, Role::MENU_ITEM_CHECK_BOX, "Size").expect("the menu lists the hideable column"); + assert!(menu_row(&fixture, Role::MENU_ITEM_CHECK_BOX, "Name").is_none(), "a column that can't be hidden has no check"); + assert!(menu_row(&fixture, Role::MENU_ITEM, "Move Column Right").is_some(), "the menu of a header lists the column commands"); + fixture.click(&size).settle(); + assert_eq!(headers(&fixture), ["Name", "Date"], "the hidden column leaves the header"); + assert!(events.borrow().contains(&ColumnEvent::Shown { key: SIZE, shown: false }), "the hide is reported"); + assert!(events.borrow().contains(&ColumnEvent::Unsorted), "hiding the sorted column drops the sort"); + let reset = menu_row(&fixture, Role::MENU_ITEM, "Reset Columns").expect("the menu stays open after a check"); + fixture.click(&reset).settle(); + assert_eq!(headers(&fixture), ["Name", "Size", "Date"], "Reset Columns shows every column again"); + assert!(events.borrow().contains(&ColumnEvent::Reset), "the reset is reported"); + + let date = fixture.by_label("Date").expect("the header cell").rect; + let table = fixture.shown(); + let room = Pos2::new((date.right() + table.right()) / 2.0, date.center().y); + secondary_click(&mut fixture, room); + assert!(menu_row(&fixture, Role::MENU_ITEM, "Reset Columns").is_some(), "the empty header opens the header menu"); + assert!(menu_row(&fixture, Role::MENU_ITEM, "Move Column Right").is_none(), "with no column there are no column commands"); +} + +/// Ctrl or Cmd with Right on a focused movable header moves its column one place on; Right alone moves the focus. +/// macOS makes Cmd+Right a move to the line's end, which the header reads the same. +#[trial] +fn ctrl_or_cmd_with_an_arrow_moves_the_focused_column() { + for os in [Os::Linux, Os::Mac] { + let (mut fixture, events) = sorted_files(); + fixture.os(os); + // Tab enters the rows; Shift+Tab goes back to the header row, on its first column. + fixture.key(Key::Tab, Modifiers::NONE).key(Key::Tab, Modifiers::SHIFT).settle(); + fixture.key(Key::ArrowRight, Modifiers::COMMAND).settle(); + let moves: Vec = events.borrow().iter().filter(|event| matches!(event, ColumnEvent::Moved { .. })).cloned().collect(); + assert_eq!(moves.len(), 1, "{os:?}: one move: {moves:?}"); + assert!(matches!(&moves[0], ColumnEvent::Moved { key, to, .. } if *key == NAME && *to == 1)); + assert_eq!(headers(&fixture), ["Size", "Name", "Date"]); + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + assert_eq!(events.borrow().iter().filter(|event| matches!(event, ColumnEvent::Moved { .. })).count(), 1, "a plain arrow moves no column"); + } +}