From 652067832ed42226374eb6d54eb7ee31ff117cd6 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 21:26:06 +0700 Subject: [PATCH] menus-w4: net change of 1 commits - menus-w4: written from its sheet --- crates/automation/src/actions/list.rs | 101 ++++++++++----- crates/automation/src/actions/tests.rs | 61 +++++++++ crates/automation/src/ui/actions/body.rs | 54 ++++++-- crates/automation/src/ui/actions/menu.rs | 6 +- crates/automation/src/ui/actions/panel.rs | 28 +++-- crates/automation/src/ui/actions/rows.rs | 27 ++-- crates/automation/src/ui/actions/stories.rs | 29 ++++- crates/automation/tests/it/actions.rs | 71 ++++++++++- .../src/patterns/form_dialogs/report.rs | 117 ++++++++++++------ .../patterns/form_dialogs/report/stories.rs | 19 ++- .../patterns/form_dialogs/report/trials.rs | 54 ++++++++ 11 files changed, 464 insertions(+), 103 deletions(-) create mode 100644 crates/ui-patterns/src/patterns/form_dialogs/report/trials.rs diff --git a/crates/automation/src/actions/list.rs b/crates/automation/src/actions/list.rs index 5241e69262..5ca18f8b03 100644 --- a/crates/automation/src/actions/list.rs +++ b/crates/automation/src/actions/list.rs @@ -83,9 +83,9 @@ struct LibrarySnapshot { } /// The recorded actions: one flat list (PhotoCraft's engine, journal and file are flat), each -/// action with an optional set name, plus the names of sets that hold no action yet, so New Set -/// works before anything is recorded into it (VectorCraft's nested sets map onto -/// it). +/// action with an optional set name, plus the order of every set, with or without actions, so New +/// Set works before anything is recorded into it and a set keeps its place as it fills and empties +/// (VectorCraft's nested sets map onto it). /// /// The list is app data shared by the panel, the app's commands, the CLI and the control channel: /// the panel only reads it and reports events, and the app applies each event with these calls @@ -123,12 +123,11 @@ impl ActionList { self.actions.get(index) } - /// Every set name in display order: sets of actions in order of first appearance, then the - /// empty sets in the order they were made. + /// Every set name in display order: the order sets were made or loaded, with or without actions. + /// A set an action names that the order lacks follows, by first appearance. pub fn sets(&self) -> Vec<&str> { - let mut sets: Vec<&str> = Vec::new(); - let named = self.actions.iter().filter_map(|action| action.set.as_deref()); - for set in named.chain(self.sets.iter().map(String::as_str)) { + let mut sets: Vec<&str> = self.sets.iter().map(String::as_str).collect(); + for set in self.actions.iter().filter_map(|action| action.set.as_deref()) { if !sets.contains(&set) { sets.push(set); } @@ -183,6 +182,9 @@ impl ActionList { if self.name_in_use(name) { return Err(ActionListError::NameTaken(name.to_owned())); } + if let Some(set) = &set { + self.record_set(set); + } self.actions.push(Action { set, ..Action::new(name, Vec::new()) }); self.touch(); Ok(self.actions.len() - 1) @@ -227,7 +229,7 @@ impl ActionList { Ok(()) } - /// Removes and returns the action at `index`. + /// Removes and returns the action at `index`; the set it leaves empty stays, in its place. pub fn delete_action(&mut self, index: usize) -> Result { if index >= self.actions.len() { return Err(ActionListError::NoSuchAction(index)); @@ -270,22 +272,29 @@ impl ActionList { } /// Puts the action at `index` into `set` (`None`: out of any set), as a drop into or out of a - /// set folder does. + /// set folder does. A new set goes at the end of the order; the set the action leaves stays, in + /// its place, even when it is now empty. pub fn assign_set(&mut self, index: usize, set: Option) -> Result<(), ActionListError> { - let target = self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?; + if index >= self.actions.len() { + return Err(ActionListError::NoSuchAction(index)); + } let set = match set { None => None, Some(set) if set.trim().is_empty() => return Err(ActionListError::EmptyName), Some(set) => Some(set.trim().to_owned()), }; - target.set = set; + if let Some(set) = &set { + self.record_set(set); + } + self.actions[index].set = set; self.touch(); Ok(()) } /// Moves step `step` of action `from` to position `to` of action `into` (the same action or /// another). Within one action `disabled` and `dialogs` follow [`moved_index`]; between - /// actions the step takes its include and dialog flags along. + /// actions the step takes its include and dialog flags along. A set never changes: one whose last + /// step moves away keeps its place. pub fn move_step(&mut self, from: usize, step: usize, into: usize, to: usize) -> Result<(), ActionListError> { let source = self.actions.get(from).ok_or(ActionListError::NoSuchAction(from))?; if step >= source.steps.len() { @@ -408,6 +417,9 @@ impl ActionList { if self.name_in_use(&action.name) { return Err(ActionListError::NameTaken(action.name)); } + if let Some(set) = &action.set { + self.record_set(set); + } self.actions.push(action); self.touch(); Ok(self.actions.len() - 1) @@ -461,28 +473,53 @@ impl ActionList { /// for an empty name, [`ActionListError::NameTaken`] for a name another set has, [`ActionListError::NoSuchSet`] for an /// unknown set. The same name succeeds and changes nothing. pub fn rename_set(&mut self, set: &str, name: &str) -> Result<(), ActionListError> { - let _ = (set, name); - todo!("mn.M50") + let name = name.trim(); + if name.is_empty() { + return Err(ActionListError::EmptyName); + } + let order: Vec = self.sets().into_iter().map(str::to_owned).collect(); + let at = order.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; + if name == set { + return Ok(()); + } + if order.iter().any(|each| each == name) { + return Err(ActionListError::NameTaken(name.to_owned())); + } + self.sets = order; + self.sets[at] = name.to_owned(); + for action in self.actions.iter_mut().filter(|action| action.set.as_deref() == Some(set)) { + action.set = Some(name.to_owned()); + } + self.touch(); + Ok(()) } /// Removes the set `set` from the order and its actions from the list, and returns the actions in list order: /// [`ActionListError::NoSuchSet`] for an unknown set. pub fn delete_set(&mut self, set: &str) -> Result, ActionListError> { - let _ = set; - todo!("mn.M51") + if !self.sets().contains(&set) { + return Err(ActionListError::NoSuchSet(set.to_owned())); + } + let (removed, kept): (Vec, Vec) = + std::mem::take(&mut self.actions).into_iter().partition(|action| action.set.as_deref() == Some(set)); + self.actions = kept; + self.sets.retain(|each| each != set); + self.touch(); + Ok(removed) } /// Duplicates the set `set` under a unique name and returns that name; `shift` is as for - /// [`duplicate_action`](Self::duplicate_action). The copies of its actions go after its last - /// action; a set with none becomes an empty set after it. + /// [`duplicate_action`](Self::duplicate_action). The new set goes right after `set` in the order; + /// the copies of its actions go after its last action, and a set with none gives an empty set. pub fn duplicate_set(&mut self, set: &str, mut shift: impl FnMut(&mut ActionStep, usize, usize)) -> Result { + let mut order: Vec = self.sets().into_iter().map(str::to_owned).collect(); + let position = order.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; + let name = Names::new(order.iter().cloned()).claim(&format!("{set} copy")); + order.insert(position + 1, name.clone()); + self.sets = order; let members: Vec = (0..self.actions.len()).filter(|&i| self.actions[i].set.as_deref() == Some(set)).collect(); - let name = Names::new(self.sets().into_iter().map(str::to_owned)).claim(&format!("{set} copy")); - if members.is_empty() { - let position = self.sets.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; - self.sets.insert(position + 1, name.clone()); - } else { - let at = members[members.len() - 1] + 1; + if let Some(&last) = members.last() { + let at = last + 1; // Each copy's name is claimed before the next, so the copies never repeat one. let mut names = Names::of(&self.actions); for (offset, &source) in members.iter().enumerate() { @@ -558,6 +595,9 @@ impl ActionList { merged.ids.push((id.clone(), name.clone())); } action.name = name; + if let Some(set) = &action.set { + self.record_set(set); + } self.actions.push(action); merged.added.push(self.actions.len() - 1); } @@ -567,9 +607,7 @@ impl ActionList { } } for set in empty_sets { - if !self.sets().contains(&set.as_str()) { - self.sets.push(set); - } + self.record_set(&set); } self.touch(); merged @@ -714,6 +752,13 @@ impl ActionList { ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()) } + /// Puts `set` at the end of the set order when the order lacks it. + fn record_set(&mut self, set: &str) { + if !self.sets.iter().any(|each| each == set) { + self.sets.push(set.to_owned()); + } + } + /// Whether an action has `name`. fn name_in_use(&self, name: &str) -> bool { self.actions.iter().any(|action| action.name == name) diff --git a/crates/automation/src/actions/tests.rs b/crates/automation/src/actions/tests.rs index 9e5bfc1e90..a3ec1840c6 100644 --- a/crates/automation/src/actions/tests.rs +++ b/crates/automation/src/actions/tests.rs @@ -271,3 +271,64 @@ fn action_player_charges_a_shared_budget_and_detects_loops() { } assert_eq!(deep.enter("more"), Err(PlaybackRefusal::TooDeep)); } + +// A set keeps its place as it gets its first action and loses its last; a duplicate goes right after its source; +// rename keeps the place and moves the members and refuses empty, taken and unknown names; delete returns the members +// in list order. +#[trial] +fn sets_keep_their_place_as_they_fill_empty_rename_and_go() { + let mut list = ActionList::new(); + for set in ["A", "B", "C"] { + list.new_set(set).unwrap(); + } + list.new_action("x", Some("B".into())).unwrap(); + assert_eq!(list.sets(), ["A", "B", "C"], "B keeps its place when it gets its first action"); + list.delete_action(0).unwrap(); + assert_eq!(list.sets(), ["A", "B", "C"], "B keeps its place when it loses its last"); + + assert_eq!(list.duplicate_set("A", |_, _, _| {}).unwrap(), "A copy"); + list.new_action("y", Some("B".into())).unwrap(); + assert_eq!(list.duplicate_set("B", |_, _, _| {}).unwrap(), "B copy"); + list.new_action("z", Some("B".into())).unwrap(); + assert_eq!(list.sets(), ["A", "A copy", "B", "B copy", "C"], "a copy follows its source, with or without actions"); + + let revision = list.revision(); + list.rename_set("B", "B").unwrap(); + assert_eq!(list.revision(), revision, "the same name changes nothing"); + assert_eq!(list.rename_set("B", " "), Err(ActionListError::EmptyName)); + assert_eq!(list.rename_set("B", "C"), Err(ActionListError::NameTaken("C".into()))); + assert_eq!(list.rename_set("Nope", "Z"), Err(ActionListError::NoSuchSet("Nope".into()))); + assert_eq!(list.revision(), revision, "a refused rename changes nothing"); + list.rename_set("B", " Beta ").unwrap(); + assert_eq!(list.sets(), ["A", "A copy", "Beta", "B copy", "C"]); + let members = list.actions().iter().filter(|action| action.set.as_deref() == Some("Beta")).count(); + assert_eq!(members, 2, "the members follow the rename"); + + let gone = list.delete_set("Beta").unwrap(); + assert_eq!(gone.iter().map(|action| action.name.as_str()).collect::>(), ["y", "z"]); + assert_eq!(list.sets(), ["A", "A copy", "B copy", "C"]); + assert_eq!(list.actions().len(), 1); + assert_eq!(list.delete_set("Beta"), Err(ActionListError::NoSuchSet("Beta".into()))); +} + +// An option of an action stays with it through a duplicate, a set duplicate, a step move, the file and a merge. +#[trial] +fn app_options_ride_with_an_action_through_edits_and_files() { + let mut base = action("A", &["a", "b"]); + base.set = Some("S".into()); + base.options.insert("key".into(), json!(3)); + let mut list = list_of(vec![base]); + list.duplicate_action(0, |_, _, _| {}).unwrap(); + list.duplicate_set("S", |_, _, _| {}).unwrap(); + list.move_step(0, 0, 0, 1).unwrap(); + assert_eq!(list.actions().len(), 4); + assert!(list.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); + + let text = list.to_file().to_json().unwrap(); + assert!(text.contains("\"options\"")); + let loaded = ActionList::from_file(ActionsFile::from_json(&text).unwrap()); + assert!(loaded.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); + let mut merged = ActionList::new(); + merged.merge_file(ActionsFile::from_json(&text).unwrap(), false, |_, _| {}); + assert!(merged.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); +} diff --git a/crates/automation/src/ui/actions/body.rs b/crates/automation/src/ui/actions/body.rs index 19dcfca8a7..a38f637be5 100644 --- a/crates/automation/src/ui/actions/body.rs +++ b/crates/automation/src/ui/actions/body.rs @@ -17,7 +17,7 @@ use craft_ui::runtime::env::{Env, Label}; use egui::{Id, Response, Ui}; use super::menu::OpenMenu; -use super::panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanelState, Session}; +use super::panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanelState, Session, StepCells}; use super::rows::{ActionRows, DIALOG_COLUMN, INCLUDE_COLUMN, NAME_COLUMN, build_row, cells}; use super::words::ActionsWords; use crate::actions::{ActionList, moved_index}; @@ -32,6 +32,8 @@ pub(super) struct Body<'a> { pub(super) env: &'a Env, /// The id the tree's list shows under, which its drags carry as `ListDrag::list`. pub(super) list_id: Id, + /// Which step cells the rows show. + pub(super) step_cells: StepCells, } /// Where a moved row goes. @@ -82,8 +84,9 @@ pub struct ActionMove { pub(super) struct BodyOutput { pub(super) events: Vec, pub(super) response: Response, - /// The selection the list ended on, for the caller to store after the container; `None` when the body did not show the tree. - pub(super) selected: Option>, + /// The selected row and the range of sets the list ended on, for the caller to store after the container; `None` + /// when the body did not show the tree. + pub(super) selected: Option<(Option, Vec)>, } /// The part of the panel above the footer: the empty notice, Button Mode's buttons or the tree. @@ -149,19 +152,24 @@ fn show_tree(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState, sessio let recording = host.and_then(|host| host.recording()); let rows = ActionRows::build(list, state, host); let order = rows.keys(); - let mut selection = Selection::new(state.selected.iter().cloned().collect(), state.selected.clone(), state.selected.clone()); + let items = if state.selected_sets.is_empty() { + state.selected.iter().cloned().collect() + } else { + state.selected_sets.iter().cloned().map(ActionSelection::Set).collect() + }; + let mut selection = Selection::new(items, state.selected.clone(), state.selected.clone()); if let Some(index) = rename.filter(|_| editable) { request_rename(ui.ctx(), list_id, &ActionSelection::Action(index)); } - let columns = vec![ - ColumnSpec::toggle(INCLUDE_COLUMN, Label::Empty, ToggleColumn::sweepable()), - ColumnSpec::toggle(DIALOG_COLUMN, Label::Empty, ToggleColumn::sweepable()).icon(IconId::new("note")), - ColumnSpec::new(NAME_COLUMN, Label::Empty, ColumnWidth::fill(1.0)), - ]; + let mut columns = vec![ColumnSpec::toggle(INCLUDE_COLUMN, Label::Empty, ToggleColumn::sweepable())]; + if body.step_cells == StepCells::IncludeAndDialog { + columns.push(ColumnSpec::toggle(DIALOG_COLUMN, Label::Empty, ToggleColumn::sweepable()).icon(IconId::new("note"))); + } + columns.push(ColumnSpec::new(NAME_COLUMN, Label::Empty, ColumnWidth::fill(1.0))); let mut widget = List::new(words.name.clone()) .id(list_id) .tree(true) - .select(SelectMode::Single) + .select(SelectMode::Multi) .allow_empty(true) .space(SpaceAction::ToggleCell) .deletable(true) @@ -224,17 +232,37 @@ fn show_tree(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState, sessio } } CollectionEvent::Delete(keys) if editable => { - events.extend(keys.first().and_then(|key| delete_event(key, recording.is_some()))); + if state.selected_sets.is_empty() { + events.extend(keys.first().and_then(|key| delete_event(key, recording.is_some()))); + } else if recording.is_none() { + events.push(ActionsEvent::DeleteSets(state.selected_sets.clone())); + } } CollectionEvent::ContextMenu(request) => session.menu = OpenMenu::opened(request, list, host), _ => {} } } - let mut selected = selection.items.first().cloned(); + let (mut selected, sets) = kept(list, &selection); for (source, to) in &moves { selected = selected.map(|selected| remapped(selected, source, to)); } - BodyOutput { events, response: out.response, selected: Some(selected) } + BodyOutput { events, response: out.response, selected: Some((selected, sets)) } +} + +/// The selection the panel keeps after the list applied this pass's input: the lead row, and the range of sets in list +/// order when the lead and the range's other end (the anchor) are both set rows. The list's range runs over the shown +/// rows, so one across an expanded set holds that set's action rows too; only the set rows are kept. A lead that is an +/// action or step, or a set reached from one of those, is the whole selection. A range of fewer than two sets is none. +fn kept(list: &ActionList, selection: &Selection) -> (Option, Vec) { + let lead = selection.lead.clone().filter(|lead| selection.items.contains(lead)); + let range = matches!((&lead, &selection.anchor), (Some(ActionSelection::Set(_)), Some(ActionSelection::Set(_)))); + let sets: Vec = if range { + let chosen = |set: &str| selection.items.iter().any(|key| matches!(key, ActionSelection::Set(name) if name == set)); + list.sets().into_iter().filter(|set| chosen(set)).map(str::to_owned).collect() + } else { + Vec::new() + }; + (lead, if sets.len() > 1 { sets } else { Vec::new() }) } /// The `Delete` event for `selected`: a step always; a set or an action not while recording. diff --git a/crates/automation/src/ui/actions/menu.rs b/crates/automation/src/ui/actions/menu.rs index ed1e728371..21f6007ba4 100644 --- a/crates/automation/src/ui/actions/menu.rs +++ b/crates/automation/src/ui/actions/menu.rs @@ -276,7 +276,7 @@ pub fn panel_rows(facts: ActionsMenuFacts, offered: &dyn Fn(ActionsPanelCommands /// The shortcut as the context menu has made it so far. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct PendingShortcut { - /// 0 for none, else 1..=12. + /// 0 for none, else 1..=15. key: u8, shift: bool, command: bool, @@ -319,7 +319,7 @@ impl OpenMenu { /// Shows the menu the last request chose, hanging from `opener` (the list), and reports what its /// rows ran: -/// - On an action: Keyboard Shortcuts (a caption), None and F1 to F12 as radio rows, then Shift and +/// - On an action: Keyboard Shortcuts (a caption), None and F1 to F15 as radio rows, then Shift and /// Command (Ctrl off macOS) check rows, enabled only with a key; the check rows keep the menu /// open so both can be ticked, and each tick is reported as it is made with the shortcut as it /// stands. A separator, then Color: a submenu of None, Red, Orange, Yellow, Green, Blue, Violet @@ -345,7 +345,7 @@ pub(super) fn show_menu(ui: &mut Ui, body: &Body<'_>, opener: &Response, session shortcut.key = 0; events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); } - for key in 1..=12u8 { + for key in 1..=15u8 { if MenuItem::new(format!("F{key}")).radio_mark(shortcut.key == key).show(ui).ran { shortcut.key = key; events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs index 5807ca44a0..7fa36dc813 100644 --- a/crates/automation/src/ui/actions/panel.rs +++ b/crates/automation/src/ui/actions/panel.rs @@ -118,7 +118,7 @@ pub enum StepCells { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ShortcutChoice { - /// F1 to F12: 1..=12. + /// F1 to F15: 1..=15. pub key: u8, /// Shift is part of the shortcut. pub shift: bool, @@ -127,7 +127,7 @@ pub struct ShortcutChoice { } impl ShortcutChoice { - /// Function key `key` (1 to 12) with the given modifiers. + /// Function key `key` (1 to 15) with the given modifiers. pub const fn new(key: u8, shift: bool, command: bool) -> Self { Self { key, shift, command } } @@ -138,7 +138,7 @@ impl ShortcutChoice { self.chord().display(Platform::current()) } - /// The shortcut as a keymap chord; a key above 12 is taken as F12. + /// The shortcut as a keymap chord; a key outside 1..=15 is taken as F12. fn chord(&self) -> Chord { let key = match self.key { 1 => Key::F1, @@ -152,6 +152,9 @@ impl ShortcutChoice { 9 => Key::F9, 10 => Key::F10, 11 => Key::F11, + 13 => Key::F13, + 14 => Key::F14, + 15 => Key::F15, _ => Key::F12, }; Chord::new(Mods { cmd: self.command, shift: self.shift, ..Mods::NONE }, key) @@ -390,12 +393,13 @@ pub struct ActionsPanel<'a> { host: Option<&'a dyn ActionsHost>, rename: Option, enabled: bool, + step_cells: StepCells, } impl<'a> ActionsPanel<'a> { /// A panel over `list` with `state`. pub fn new(state: &'a mut ActionsPanelState, list: &'a ActionList) -> Self { - Self { state, list, host: None, rename: None, enabled: true } + Self { state, list, host: None, rename: None, enabled: true, step_cells: StepCells::default() } } /// The app's side; without one, steps show their command ids and nothing records or plays. @@ -413,9 +417,9 @@ impl<'a> ActionsPanel<'a> { /// Which step cells the rows show. #[must_use] - pub fn step_cells(self, cells: StepCells) -> Self { - let _ = cells; - todo!("mn.M40") + pub fn step_cells(mut self, cells: StepCells) -> Self { + self.step_cells = cells; + self } /// Whether the panel takes input (default true). @@ -427,7 +431,7 @@ impl<'a> ActionsPanel<'a> { /// Draws the tree (or the buttons) and the footer, and reports this pass's events in order: /// the list's, the cells', the context menu's, the footer's. pub fn show(self, ui: &mut Ui) -> ActionsPanelOutput { - let ActionsPanel { state, list, host, rename, enabled } = self; + let ActionsPanel { state, list, host, rename, enabled, step_cells } = self; let env = Env::of(ui); let words = env.words::(); let list_words = env.words::(); @@ -435,7 +439,7 @@ impl<'a> ActionsPanel<'a> { let settings_before = state.settings.clone(); let events = RefCell::new(Vec::new()); let state = RefCell::new(state); - let body = Body { list, host, words: &words, list_words: &list_words, env: &env, list_id }; + let body = Body { list, host, words: &words, list_words: &list_words, env: &env, list_id, step_cells }; let shown = Stack::new() .fill() @@ -457,8 +461,10 @@ impl<'a> ActionsPanel<'a> { let mut reported = Vec::new(); if let Some((body_events, selected)) = shown.inner { reported = body_events; - if let Some(selected) = selected { - state.borrow_mut().selected = selected; + if let Some((row, sets)) = selected { + let mut state = state.borrow_mut(); + state.selected = row; + state.selected_sets = sets; } } reported.extend(events.into_inner()); diff --git a/crates/automation/src/ui/actions/rows.rs b/crates/automation/src/ui/actions/rows.rs index 2319e3021d..cc9907c4be 100644 --- a/crates/automation/src/ui/actions/rows.rs +++ b/crates/automation/src/ui/actions/rows.rs @@ -11,7 +11,7 @@ use craft_ui::primitives::IconSpec; use craft_ui::runtime::env::Label; use super::body::Body; -use super::panel::{ActionSelection, ActionsHost, ActionsPanelState}; +use super::panel::{ActionSelection, ActionsHost, ActionsPanelState, StepCells}; use crate::actions::{ActionInclude, ActionList}; /// The include column: a toggle on action rows (every step) and step rows. @@ -145,6 +145,7 @@ impl ItemSource for ActionRows<'_> { (ActionSelection::Action(index), column) if *column == INCLUDE_COLUMN => { self.list.action(*index).is_some_and(|action| action.include() == ActionInclude::All) } + (ActionSelection::Set(name), column) if *column == INCLUDE_COLUMN => matches!(set_include(self.list, name), Some(ToggleState::On)), _ => match self.recorded_step(at) { Some((action, step)) if *column == INCLUDE_COLUMN => self.list.action(action).is_some_and(|held| held.step_enabled(step)), Some((action, step)) if *column == DIALOG_COLUMN => self.list.action(action).is_some_and(|held| held.dialogs.contains(&step)), @@ -158,11 +159,19 @@ impl ItemSource for ActionRows<'_> { match &row.key { ActionSelection::Action(index) => *column == INCLUDE_COLUMN && self.list.action(*index).is_some_and(|action| !action.steps.is_empty()), ActionSelection::Step(..) => self.recorded_step(at).is_some(), - ActionSelection::Set(_) => false, + ActionSelection::Set(name) => *column == INCLUDE_COLUMN && set_include(self.list, name).is_some(), } } } +/// The include mark of the set `name` over its actions that have steps: on when every one is fully included, off when +/// none is, mixed otherwise; `None` when no action of the set has a step. +fn set_include(list: &ActionList, name: &str) -> Option { + let mut marks = list.actions().iter().filter(|action| action.set.as_deref() == Some(name) && !action.steps.is_empty()).map(|action| action.include()); + let first = marks.next()?; + Some(if marks.all(|mark| mark == first) { include_state(first) } else { ToggleState::Mixed }) +} + fn include_state(include: ActionInclude) -> ToggleState { match include { ActionInclude::All => ToggleState::On, @@ -224,10 +233,10 @@ pub(super) fn build_row(body: &Body<'_>, state: &ActionsPanelState, key: &Action } } -/// The toggle cells of a row: the include cell of an action with steps and of a recorded step, the -/// dialog cell of a recorded step. +/// The toggle cells of a row: the include cell of an action or set with steps and of a recorded step, the +/// dialog cell of a recorded step unless the panel leaves the dialog column out. pub(super) fn cells(body: &Body<'_>, key: &ActionSelection) -> Vec { - let Body { list, words, .. } = *body; + let Body { list, words, step_cells, .. } = *body; let include = |state: ToggleState| ToggleCell::check(INCLUDE_COLUMN, state, words.include.clone()).tooltip(words.include_tooltip.clone()); match key { ActionSelection::Action(index) => match list.action(*index) { @@ -245,10 +254,14 @@ pub(super) fn cells(body: &Body<'_>, key: &ActionSelection) -> Vec { ) .tooltip(words.dialog_tooltip.clone()); dialog.check_box = true; - vec![include(ToggleState::of(action.step_enabled(*step))), dialog] + let mut cells = vec![include(ToggleState::of(action.step_enabled(*step)))]; + if step_cells == StepCells::IncludeAndDialog { + cells.push(dialog); + } + cells } _ => Vec::new(), }, - ActionSelection::Set(_) => Vec::new(), + ActionSelection::Set(name) => set_include(list, name).map_or_else(Vec::new, |state| vec![include(state)]), } } diff --git a/crates/automation/src/ui/actions/stories.rs b/crates/automation/src/ui/actions/stories.rs index e2b754c6b0..b5f7ebd939 100644 --- a/crates/automation/src/ui/actions/stories.rs +++ b/crates/automation/src/ui/actions/stories.rs @@ -5,7 +5,7 @@ use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use super::mock::{FakeActionsHost, action, list_of, sample_list, step}; -use super::{ActionSelection, ActionsPanel, ActionsPanelState, ShortcutChoice}; +use super::{ActionSelection, ActionsPanel, ActionsPanelState, ShortcutChoice, StepCells}; use crate::actions::{ActionColor, ActionList}; /// The sample list with Sharpen open and selected, one step off, and a shortcut on it. @@ -43,6 +43,33 @@ fn actions_panel_button_mode(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).show(ui).into() } +/// The include variant: step rows without the dialog cell, and set rows with an include cell, one of them mixed. +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_include_cells(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let mut blur = action("Blur", Some("Effects"), &["blur", "mask"]); + blur.disabled.insert(1); + let list = list_of(vec![blur, action("Glow", Some("Effects"), &["glow"]), action("Levels", Some("Basics"), &["levels", "curves"])]); + let mut state = ActionsPanelState::default(); + state.expanded.insert("Blur".to_owned()); + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).step_cells(StepCells::Include).show(ui).into() +} + +/// A range of three sets selected, as a Shift-click from the first to the last leaves it. +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_set_range(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let list = list_of(vec![ + action("Blur", Some("Effects"), &["blur"]), + action("Levels", Some("Basics"), &["levels"]), + action("Glow", Some("Finish"), &["glow"]), + ]); + let mut state = ActionsPanelState { + selected: Some(ActionSelection::Set("Finish".to_owned())), + selected_sets: ["Effects", "Basics", "Finish"].map(str::to_owned).to_vec(), + ..ActionsPanelState::default() + }; + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).show(ui).into() +} + #[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] fn actions_panel_empty(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { let mut state = ActionsPanelState::default(); diff --git a/crates/automation/tests/it/actions.rs b/crates/automation/tests/it/actions.rs index f017fd4f9a..6d33a3b627 100644 --- a/crates/automation/tests/it/actions.rs +++ b/crates/automation/tests/it/actions.rs @@ -5,7 +5,7 @@ use std::rc::Rc; use craft_automation::actions::ActionList; use craft_automation::ui::actions::mock::{FakeActionsHost, action, list_of}; -use craft_automation::ui::actions::{ActionMove, ActionPlace, ActionSelection, ActionsEvent, ActionsPanel, ActionsPanelState, INCLUDE_COLUMN}; +use craft_automation::ui::actions::{ActionMove, ActionPlace, ActionSelection, ActionsEvent, ActionsPanel, ActionsPanelState, INCLUDE_COLUMN, StepCells}; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Key, Modifiers, Pos2, Ui, Vec2}; @@ -29,16 +29,20 @@ fn app(list: ActionList) -> App { App { state: ActionsPanelState::default(), list, host: FakeActionsHost::prefixed("Run "), events: Vec::new() } } -fn show(ui: &mut Ui, app: &mut App) { +fn show(ui: &mut Ui, app: &mut App, cells: StepCells) { let App { state, list, host, events } = app; - let out = ActionsPanel::new(state, list).host(&*host).show(ui); + let out = ActionsPanel::new(state, list).host(&*host).step_cells(cells).show(ui); events.extend(out.events); } fn rig(app: App) -> (Fixture, Shared) { + rig_cells(app, StepCells::default()) +} + +fn rig_cells(app: App, cells: StepCells) -> (Fixture, Shared) { let shared = Rc::new(RefCell::new(app)); let shown = Rc::clone(&shared); - let mut fixture = Fixture::new(move |ui| show(ui, &mut shown.borrow_mut())); + let mut fixture = Fixture::new(move |ui| show(ui, &mut shown.borrow_mut(), cells)); fixture.room(PANEL); fixture.settle(); (fixture, shared) @@ -248,3 +252,62 @@ fn actions_panel_menu_offers_the_library_commands() { let events: Vec<_> = [C::ClearAll, C::Reset, C::Replace].into_iter().map(|c| c.run(&mut panel, &list, idle)).collect(); assert_eq!(events, [ActionsEvent::ClearAll, ActionsEvent::Reset, ActionsEvent::Replace].map(|event| Some(ActionsMenuAction::Event(event)))); } + +/// A step row has an include and a dialog cell, or with `StepCells::Include` the include cell only; a set row with steps +/// has an include cell whose press reports a toggle of the set, and a set without steps has none. +#[trial] +fn a_set_row_has_an_include_cell_and_the_include_variant_has_no_dialog_column() { + let mut shown = app(two_sets()); + shown.state.expanded.insert("First".into()); + let (fixture, _) = rig(shown); + assert!(fixture.by_label("Include in playback: Run b").is_some(), "a step row has its include cell"); + assert!(fixture.by_label("Show dialog during playback: Run b").is_some(), "and its dialog cell"); + + let mut list = two_sets(); + list.new_set("Hollow").unwrap(); + let mut shown = app(list); + shown.state.expanded.insert("First".into()); + let (mut fixture, shared) = rig_cells(shown, StepCells::Include); + assert!(fixture.by_label("Include in playback: Run b").is_some(), "the include cell stays"); + assert!(fixture.by_label("Show dialog during playback: Run b").is_none(), "the dialog cell is left out"); + assert!(fixture.by_label("Include in playback: Hollow").is_none(), "a set with no steps has no include cell"); + + let cell = node(&fixture, "Include in playback: Alpha"); + click(&mut fixture, cell.center()); + let toggled = take(&shared).into_iter().any(|event| { + matches!(event, ActionsEvent::Toggle(craft_ui::contract::SweepStep::Flip(edit)) + if edit.key == ActionSelection::Set("Alpha".into()) && edit.column == INCLUDE_COLUMN) + }); + assert!(toggled, "a press on a set's include cell reports a toggle of the set"); +} + +/// Shift on a later set row selects the sets between, across an expanded set's action rows; Delete reports the range in +/// one event; a click on an action clears the range. +#[trial] +fn shift_clicking_a_set_selects_the_range_and_delete_reports_it_once() { + let list = list_of(vec![ + action("Loose", None, &["a"]), + action("First", Some("Alpha"), &["b"]), + action("Second", Some("Beta"), &["c"]), + action("Third", Some("Gamma"), &["d"]), + ]); + let (mut fixture, shared) = rig(app(list)); + let (first, last) = (node(&fixture, "Alpha").center(), node(&fixture, "Gamma").center()); + click(&mut fixture, first); + fixture.hold(Modifiers::SHIFT); + click(&mut fixture, last); + fixture.hold(Modifiers::NONE); + let names = ["Alpha", "Beta", "Gamma"].map(str::to_owned).to_vec(); + assert_eq!(shared.borrow().state.selected_sets, names, "the sets between, in list order, not the actions among them"); + + take(&shared); + fixture.key(Key::Delete, Modifiers::NONE).idle(2); + let events = take(&shared); + let deletes: Vec<_> = events.iter().filter(|event| matches!(event, ActionsEvent::Delete(_) | ActionsEvent::DeleteSets(_))).collect(); + assert_eq!(deletes, [&ActionsEvent::DeleteSets(names)], "one event for the range"); + + let row = node(&fixture, "First").center(); + click(&mut fixture, row); + assert!(shared.borrow().state.selected_sets.is_empty(), "a click on an action ends the range"); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Action(1))); +} diff --git a/crates/ui-patterns/src/patterns/form_dialogs/report.rs b/crates/ui-patterns/src/patterns/form_dialogs/report.rs index f7bc310c1f..b55fffab39 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/report.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/report.rs @@ -18,6 +18,8 @@ use serde_json::{Value, json}; #[cfg(feature = "testing")] mod stories; +#[cfg(feature = "testing")] +mod trials; craft_ui::words! { /// The words of the report dialog beside the common OK. @@ -58,15 +60,13 @@ impl ReportNote { /// A muted second part after the text. #[must_use] pub fn detail(self, detail: impl Into