diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 0c9de875c..d6bdc7398 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -93,8 +93,36 @@ impl Workspace

{ /// and the revision stays. `MissingPanel` when `from` is in none of them, `DuplicatePanel` when `to` is /// already there. pub fn rename(&mut self, from: &P, to: P) -> Result<(), DockError> { - let _ = (from, to); - todo!("ch.K27") + if !self.holds(from) { + return Err(DockError::MissingPanel); + } + if self.holds(&to) { + return Err(DockError::DuplicatePanel); + } + let swap = |panel: &mut P| { + if *panel == *from { + *panel = to.clone(); + } + }; + let mut proposed = self.clone(); + if let Some(root) = proposed.layout.root.as_mut() { + rename_in_tree(root, &swap); + } + for window in &mut proposed.layout.floating { + rename_in_column(&mut window.column, &swap); + } + for (panel, location) in proposed.hidden.iter_mut().chain(&mut proposed.floated) { + swap(panel); + rename_in_location(location, &swap); + } + proposed.validate()?; + *self = proposed; + Ok(()) + } + + /// Whether `panel` is in the layout or is the key of a hidden or floated record. + fn holds(&self, panel: &P) -> bool { + self.layout.contains(panel) || self.hidden.iter().chain(&self.floated).any(|(held, _)| held == panel) } /// Check the version, the layout, that every hidden panel is hidden once and absent @@ -439,6 +467,37 @@ fn dock_columns_mut

(root: &mut Node

) -> Vec<&mut Column

> { out } +/// Applies `swap` to every panel of `root`, walking the tree with a stack: a loaded tree can be deeper than the call +/// stack. +fn rename_in_tree

(root: &mut Node

, swap: &impl Fn(&mut P)) { + let mut visit = vec![root]; + while let Some(node) = visit.pop() { + match node { + Node::Split { first, second, .. } => { + visit.push(second); + visit.push(first); + } + Node::Tabs { panels, .. } => panels.iter_mut().for_each(swap), + Node::Stack { entries } => entries.iter_mut().for_each(|entry| swap(&mut entry.panel)), + Node::Dock { columns, .. } => columns.iter_mut().for_each(|column| rename_in_column(column, swap)), + } + } +} + +/// Applies `swap` to every panel of the groups of `column`. +fn rename_in_column

(column: &mut Column

, swap: &impl Fn(&mut P)) { + column.groups.iter_mut().for_each(|group| group.panels.iter_mut().for_each(swap)); +} + +/// Applies `swap` to the panels a location names: its anchor, its siblings and the tab it goes before. +fn rename_in_location

(location: &mut Location

, swap: &impl Fn(&mut P)) { + location.anchor.iter_mut().for_each(swap); + location.sibling.iter_mut().for_each(swap); + if let DockPlacement::Tab { before: Some(panel) } = &mut location.placement { + swap(panel); + } +} + /// Whether `panel` is in a floating window of `layout`. fn floats(layout: &Layout

, panel: &P) -> bool { matches!(layout.place(panel), Some(PanelPlace::Floating { .. })) diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index 59d764ad3..9fe6c5cdb 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -400,6 +400,58 @@ fn a_panel_that_docks_only_in_columns_never_lands_in_a_frame() { assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]); } +/// A location whose anchor, sibling and tab-before name `anchor`. +fn recorded(layout: &Layout, anchor: u32) -> craft_behavior::dock::Location { + let mut location = layout.location(&5).unwrap(); + location.anchor = Some(anchor); + location.sibling = vec![anchor]; + location.placement = DockPlacement::tab(Some(anchor)); + location +} + +/// Every place of `workspace` that holds the panel `id`: the layout, the keys of the records and their locations. +fn mentions(workspace: &Workspace, id: u32) -> bool { + let records = workspace.hidden.iter().chain(&workspace.floated); + let named = records.clone().any(|(panel, location)| { + let before = matches!(&location.placement, DockPlacement::Tab { before: Some(p) } if *p == id); + *panel == id || location.anchor == Some(id) || location.sibling.contains(&id) || before + }); + named || workspace.layout.contains(&id) +} + +/// A rename keeps the panel's place wherever the id sits (tab group, dock column, floating window, records and the +/// anchors of other records), refuses a missing source and a taken name, and leaves the workspace as it was then. +#[test] +fn a_renamed_panel_keeps_its_place_and_a_taken_name_changes_nothing() { + for from in [11, 3, 7, 50, 51] { + let layout = docked(); + let mut base = Workspace::default(); + base.replace(Workspace::new(layout.clone())); + base.hidden = vec![(50, recorded(&layout, from)), (52, recorded(&layout, 5))]; + base.floated = vec![(51, recorded(&layout, from))]; + base.validate().unwrap(); + let swap = |panel: u32| if panel == from { 99 } else { panel }; + + let mut renamed = base.clone(); + renamed.rename(&from, 99).unwrap_or_else(|e| panic!("{from}: {e:?}")); + let panels = |workspace: &Workspace| workspace.layout.panels().into_iter().copied().collect::>(); + assert_eq!(panels(&renamed), panels(&base).into_iter().map(swap).collect::>(), "{from}: the panel keeps its position"); + let keys = |records: &[(u32, _)]| records.iter().map(|(panel, _)| *panel).collect::>(); + assert_eq!(keys(&renamed.hidden), keys(&base.hidden).into_iter().map(swap).collect::>(), "{from}: hidden keys"); + assert_eq!(keys(&renamed.floated), keys(&base.floated).into_iter().map(swap).collect::>(), "{from}: floated keys"); + assert!(!mentions(&renamed, from) && mentions(&renamed, 99), "{from}: no field holds the old id"); + renamed.validate().unwrap(); + assert_eq!(renamed.revision(), base.revision(), "{from}: a rename is an edit"); + + for (source, name, error) in [(40, 99, DockError::MissingPanel), (from, 4, DockError::DuplicatePanel), (from, 52, DockError::DuplicatePanel)] { + let mut refused = base.clone(); + assert_eq!(refused.rename(&source, name), Err(error), "{from}: {source} to {name}"); + assert_eq!(refused, base, "{from}: a refused rename changes nothing"); + assert_eq!(refused.revision(), base.revision()); + } + } +} + /// A stepped column (a toolbar's) keeps its step count docked, floating and through JSON, and its width moves only /// by steps. #[test] diff --git a/crates/ui-panels/src/rails/drawer.rs b/crates/ui-panels/src/rails/drawer.rs index 2720c1609..30cba433b 100644 --- a/crates/ui-panels/src/rails/drawer.rs +++ b/crates/ui-panels/src/rails/drawer.rs @@ -6,13 +6,13 @@ use super::words::RailWords; use crate::buttons::{Button, IconButton}; use crate::contract::overlay::{Anchor, Dismiss, Overlay, Place}; use crate::contract::{ - ActivateOn, Bind, CollectionEvent, Gap, ListDrag, NoValue, Outcome, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, - Sizing, clicked, + ActivateOn, Bind, CollectionEvent, Gap, ListDrag, NoValue, Outcome, PopupKind, Props as _, SelectMode, Show as _, ShowCollection as _, + ShowContainer as _, Sizing, Trigger, clicked, }; -use crate::display::{Shade, Text}; +use crate::display::{Shade, TargetMark, Text}; use crate::layout_components::{Row, Stack}; -use crate::list::{List, ListRow, RowInk}; -use crate::menu::PanelRow; +use crate::list::{List, ListRow, RowInk, RowRun}; +use crate::menu::{Menu, PanelMenu, PanelRow}; use crate::popover::Popover; use crate::primitives::IconSpec; use crate::runtime::commands::{self, ResolvedCommand}; @@ -49,8 +49,8 @@ impl DrawerGroup { /// A group headed `label` that lists the tools of `slots` one after another; each row carries its slot's run by /// position. pub fn slotted(label: impl Into

{ id: DialogId, set: WorkspaceSet

, @@ -256,9 +257,9 @@ impl HostedNewWorkspace

{ /// The name and captures the dialog opens with; without it, `NewWorkspace::default()`. #[must_use] - pub fn value(self, value: NewWorkspace) -> Self { - let _ = (self, value); - todo!("ch.K26") + pub fn value(mut self, value: NewWorkspace) -> Self { + self.value = value; + self } } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/list_manager.rs b/crates/ui-patterns/src/patterns/form_dialogs/list_manager.rs index 8f4125980..bfaa67673 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/list_manager.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/list_manager.rs @@ -14,7 +14,7 @@ use crate::runtime::words::CommonWords; use crate::sections::{DialogRole, FooterButton}; use crate::style::TypeRole; use crate::text::TextField; -use craft_behavior::{DisplayOrder, ItemSource, Selection}; +use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed, Selection}; use craft_i18n::Folder; use egui::{Response, Ui}; use std::borrow::Cow; @@ -187,13 +187,12 @@ pub struct ListManagerChoice { } impl ListManagerChoice { - /// The action id of an in-place rename ([`ListManager::renames`]). + /// The action id of an in-place rename ([`ListManager::renames`]). An app's own action must not use this id. pub const RENAME: &'static str = "rename"; /// Whether the choice is an in-place rename. pub fn is_rename(&self) -> bool { - let _ = self; - todo!("ch.K25") + self.action == Self::RENAME } } @@ -320,6 +319,8 @@ fn is_enabled(action: &ListManagerAction, entries: &[ListManagerEntry], folder: /// it is enabled, Delete in the list runs the `delete` action, Escape cancels. /// - Actions are the buttons in a column beside the list: the first action, Cancel, then the other actions in the /// given order. The app replaces `entries` between passes; the name box keeps its text. +/// - Rename: with `renames`, F2 on an entry of that kind edits its name in the row. A commit reports a choice whose +/// action is [`ListManagerChoice::RENAME`] and leaves the dialog open; Escape reports nothing. #[must_use = "show the dialog with `show`"] #[derive(crate::contract::Pattern, crate::contract::Props)] pub struct ListManager<'a> { @@ -342,6 +343,10 @@ pub struct ListManager<'a> { /// Binds the open state to `open`. #[prop(name = "opened")] open: Option>, + /// Entries of this kind rename in place: a commit reports a [`ListManagerChoice`] with the `RENAME` action, the + /// entry's id and the trimmed name, and the dialog stays open. + #[prop] + renames: Option, } impl<'a> ListManager<'a> { @@ -362,20 +367,13 @@ impl<'a> ListManager<'a> { searchable: false, name: None, open: None, + renames: None, } } - /// Entries of `kind` rename in place: a commit reports a [`ListManagerChoice`] with the `RENAME` action, the - /// entry's id and the trimmed name, and the dialog stays open. - #[must_use] - pub fn renames(self, kind: u32) -> Self { - let _ = (self, kind); - todo!("ch.K25") - } - /// Shows the dialog. pub fn show(self, ui: &mut Ui) -> ListManagerOutput { - let ListManager { title, name_label, entries, actions, empty, note, searchable, name, open } = self; + let ListManager { title, name_label, entries, actions, empty, note, searchable, name, open, renames } = self; let env = Env::of(ui); let words = env.words::(); let common = env.words::(); @@ -416,6 +414,7 @@ impl<'a> ListManager<'a> { let folder = env.folder(); let activated = Cell::new(None::); let typed = RefCell::new(String::new()); + let renamed = RefCell::new(None::<(usize, String)>); let shown = dialog.show(ui, |ui, cx| { let mut session = cx.memory::().clone(); if cx.appeared() @@ -458,6 +457,9 @@ impl<'a> ListManager<'a> { if searchable { list = list.filter(&session.name, |at| Label::from(entries[*at].name.clone())); } + if let Some(kind) = renames { + list = list.rename(true).can_rename(move |at| entries[*at].kind == kind); + } let events = list .show_items(ui, &source, &mut |at, _| { let entry = &entries[*at]; @@ -488,6 +490,13 @@ impl<'a> ListManager<'a> { let delete = actions.iter().position(|action| action.id == DELETE); activated.set(delete.filter(|at| is_enabled(&actions[*at], entries, &folder, &session.name))); } + CollectionEvent::Rename(EditEvent::Commit { after: Mixed::Same(rename), .. }) => { + let name = rename.name.trim(); + if !name.is_empty() { + session.name = name.to_owned(); + *renamed.borrow_mut() = Some((rename.key, session.name.clone())); + } + } _ => {} } } @@ -509,6 +518,9 @@ impl<'a> ListManager<'a> { let entry = entries.iter().find(|entry| is_named(entry, &folder, &typed) && accepts(&actions[at], entry)); ListManagerChoice { action: actions[at].id.clone(), entry: entry.map(|entry| entry.id.clone()), name: typed.trim().to_owned() } }); - ListManagerOutput { response, closed, choice } + let rename = renamed.take().and_then(|(at, name)| { + entries.get(at).map(|entry| ListManagerChoice { action: ListManagerChoice::RENAME.to_owned(), entry: Some(entry.id.clone()), name }) + }); + ListManagerOutput { response, closed, choice: choice.or(rename) } } } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/list_manager/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/list_manager/stories.rs index 959848e96..66bda3cc3 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/list_manager/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/list_manager/stories.rs @@ -28,6 +28,15 @@ fn list_manager(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { .into() } +/// Entries of kind 1 rename in place: F2 on a row edits its name there. +#[story(ListManager<'static>, covers = [], drive = Drive::Never)] +fn list_manager_renames(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let words = Env::of(ui).words::(); + let actions = vec![ListManagerAction::run(&words), ListManagerAction::delete(&words)]; + let entries: Vec = entries().into_iter().enumerate().map(|(at, entry)| if at == 1 { entry } else { entry.kind(1) }).collect(); + ListManager::new("Macros", "Macro name:", entries, actions).renames(1).opened(Bind::bound(data.value("open", true))).show(ui).into() +} + #[story(ListManager<'static>, covers = [], drive = Drive::Never)] fn list_manager_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let words = Env::of(ui).words::(); diff --git a/crates/ui-patterns/tests/it/form_dialogs/list_manager.rs b/crates/ui-patterns/tests/it/form_dialogs/list_manager.rs new file mode 100644 index 000000000..d1e037947 --- /dev/null +++ b/crates/ui-patterns/tests/it/form_dialogs/list_manager.rs @@ -0,0 +1,67 @@ +//! `ListManager`'s in-place rename: a commit is a choice, Escape and an entry of another kind are not. + +use craft_ui::contract::Bind; +use craft_ui::patterns::form_dialogs::{ActionEnabled, ListManager, ListManagerAction, ListManagerChoice, ListManagerEntry}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers, Vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +#[trial] +fn a_committed_rename_reports_entry_and_name_and_escape_keeps_it() { + let rows = Rc::new(RefCell::new(vec![ + ListManagerEntry::new("a", "Alpha").kind(1), + ListManagerEntry::new("b", "Bravo"), + ListManagerEntry::new("c", "Gamma").kind(1), + ])); + let choices = Rc::new(RefCell::new(Vec::::new())); + let closed = Rc::new(Cell::new(false)); + let (held, seen, ended) = (Rc::clone(&rows), Rc::clone(&choices), Rc::clone(&closed)); + let mut fixture = Fixture::new(move |ui| { + let entries = held.borrow().clone(); + let actions = vec![ListManagerAction::new("run", "Run", ActionEnabled::OnEntry { kind: None })]; + let out = ListManager::new("Macros", "Macro name:", entries, actions).renames(1).opened(Bind::given(true)).show(ui); + ended.set(ended.get() || out.closed.is_some()); + if let Some(choice) = out.choice { + if choice.is_rename() { + for entry in held.borrow_mut().iter_mut().filter(|entry| Some(&entry.id) == choice.entry.as_ref()) { + entry.name.clone_from(&choice.name); + } + } + seen.borrow_mut().push(choice); + } + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + let renames = || choices.borrow().iter().filter(|choice| choice.is_rename()).count(); + + let alpha = fixture.by_label("Alpha").expect("the list shows Alpha"); + fixture.click(&alpha).idle(4); + fixture.key(Key::F2, Modifiers::NONE).idle(4); + fixture.key(Key::A, Modifiers::COMMAND).idle(2); + fixture.type_text(" Zed ").idle(2); + fixture.key(Key::Enter, Modifiers::NONE).idle(6); + { + let seen = choices.borrow(); + let [choice] = seen.as_slice() else { panic!("one choice for the commit, got {seen:?}") }; + assert!(choice.is_rename(), "the commit is a rename"); + assert_eq!(choice.entry.as_deref(), Some("a"), "it names the renamed entry"); + assert_eq!(choice.name, "Zed", "it carries the trimmed name"); + } + assert!(!closed.get(), "the dialog stays open"); + + let zed = fixture.by_label("Zed").expect("the row shows the new name"); + fixture.click(&zed).idle(4); + fixture.key(Key::F2, Modifiers::NONE).idle(4); + fixture.type_text("Q").idle(2); + fixture.key(Key::Escape, Modifiers::NONE).idle(6); + assert_eq!(renames(), 1, "Escape reports no rename"); + assert!(!closed.get(), "Escape ends the editor and keeps the dialog"); + assert_eq!(rows.borrow()[0].name, "Zed", "the entry keeps its name"); + + let bravo = fixture.by_label("Bravo").expect("the list shows Bravo"); + fixture.click(&bravo).idle(4); + fixture.key(Key::F2, Modifiers::NONE).idle(4); + fixture.type_text("X").idle(2); + fixture.key(Key::Enter, Modifiers::NONE).idle(6); + assert_eq!(renames(), 1, "an entry of another kind does not rename"); +}