menus-w4: net change of 1 commits

- menus-w4: written from its sheet
This commit is contained in:
bflatastic committed 2026-11-21 21:26:06 +07:00
1 parent 3a990c45de
commit 652067832e
11 files changed
+464 -103

No files matched your search

+73 -28
View File
@@ -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<Action, ActionListError> {
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<String>) -> 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<String> = 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<Vec<Action>, ActionListError> {
let _ = set;
todo!("mn.M51")
if !self.sets().contains(&set) {
return Err(ActionListError::NoSuchSet(set.to_owned()));
}
let (removed, kept): (Vec<Action>, Vec<Action>) =
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<String, ActionListError> {
let mut order: Vec<String> = 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<usize> = (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)
+61
View File
@@ -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::<Vec<_>>(), ["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))));
}
+41 -13
View File
@@ -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<ActionsEvent>,
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<Option<ActionSelection>>,
/// 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<ActionSelection>, Vec<String>)>,
}
/// 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<ActionSelection>) -> (Option<ActionSelection>, Vec<String>) {
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<String> = 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.
+3 -3
View File
@@ -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() });
+17 -11
View File
@@ -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<usize>,
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::<ActionsWords>();
let list_words = env.words::<ListWords>();
@@ -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());
+20 -7
View File
@@ -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<ActionSelection> 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<ActionSelection> 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<ToggleState> {
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<ToggleCell> {
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<ToggleCell> {
)
.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)]),
}
}
+28 -1
View File
@@ -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();
+67 -4
View File
@@ -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)));
}
@@ -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<Label>) -> Self {
let _ = (self, detail);
todo!("mn.M53")
ReportNote { detail: Some(detail.into()), ..self }
}
/// Shows the text in the mono type role.
#[must_use]
pub fn code(self) -> Self {
let _ = self;
todo!("mn.M54")
ReportNote { code: true, ..self }
}
}
@@ -133,28 +133,33 @@ impl<'a> ReportDialog<'a> {
ReportDialog { title: title.into(), summary: summary.into(), notes, lines: Vec::new(), groups: Vec::new(), open: None }
}
/// The notes as the Copy button hands them back, one per line with the tone's word first; plain
/// [`lines`](ReportDialog::lines) one per line as they are.
/// The notes as the Copy button hands them back, one per line with the tone's word first (a note with a detail
/// ends with it in brackets); plain [`lines`](ReportDialog::lines) one per line as they are. Each group follows
/// with its heading line, then its notes.
pub fn as_text(&self, env: &Env) -> String {
let view = env.view();
if !self.lines.is_empty() {
return self.lines.iter().map(|line| view.resolve(line).as_str().to_owned()).collect::<Vec<_>>().join("\n");
}
let words = env.words::<ReportWords>();
self.notes
.iter()
.map(|note| {
let word = match note.tone {
Tone::Info => &words.info,
Tone::Warn => &words.warning,
Tone::Bad => &words.error,
Tone::Good => &words.success,
_ => &words.note,
};
words.line.fill(&[("tone", view.resolve(word).as_str()), ("text", view.resolve(&note.text).as_str())])
})
.collect::<Vec<_>>()
.join("\n")
let text = |label: &Label| view.resolve(label).as_str().to_owned();
let line = |note: &ReportNote| {
let word = match note.tone {
Tone::Info => &words.info,
Tone::Warn => &words.warning,
Tone::Bad => &words.error,
Tone::Good => &words.success,
_ => &words.note,
};
let (tone, body) = (text(word), text(&note.text));
match &note.detail {
Some(detail) => words.line_detail.fill(&[("tone", tone.as_str()), ("text", body.as_str()), ("detail", text(detail).as_str())]),
None => words.line.fill(&[("tone", tone.as_str()), ("text", body.as_str())]),
}
};
let mut out: Vec<String> = if self.lines.is_empty() { self.notes.iter().map(&line).collect() } else { self.lines.iter().map(&text).collect() };
for group in &self.groups {
out.push(text(&group.heading));
out.extend(group.notes.iter().map(&line));
}
out.join("\n")
}
/// Shows the report.
@@ -163,14 +168,15 @@ impl<'a> ReportDialog<'a> {
let words = env.words::<ReportWords>();
let common = env.words::<CommonWords>();
let text = self.as_text(&env);
let ReportDialog { title, summary, notes, lines, groups: _, open } = self;
let ReportDialog { title, summary, notes, lines, groups, open } = self;
let accept = FooterButton::new(common.ok.clone(), DialogRole::Accept);
let copy = FooterButton::new(words.copy.clone(), DialogRole::Other).stays_open(true);
let mut dialog = Dialog::new(title).buttons([accept, copy]);
if let Some(open) = open {
dialog = dialog.opened(open);
}
let shown_count = if lines.is_empty() { notes.len() } else { lines.len() };
let grouped: usize = groups.iter().map(|group| group.notes.len()).sum();
let shown_count = (if lines.is_empty() { notes.len() } else { lines.len() }) + grouped;
let count = (shown_count > 0).then(|| {
let n = shown_count as u64;
words.count.text(n, &env.format().integer(n))
@@ -183,9 +189,18 @@ impl<'a> ReportDialog<'a> {
if let Some(count) = &count {
Text::new(count.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
}
let mut at = 0;
if lines.is_empty() {
for (at, note) in notes.iter().enumerate() {
Notice::new(note.tone, note.text.clone()).layout(NoticeLayout::Inline).id_salt(at).show(ui);
for note in &notes {
show_note(ui, note, at);
at += 1;
}
}
for group in &groups {
Text::new(group.heading.clone()).role(TypeRole::Heading).show(ui);
for note in &group.notes {
show_note(ui, note, at);
at += 1;
}
}
for (at, line) in lines.iter().enumerate() {
@@ -198,13 +213,32 @@ impl<'a> ReportDialog<'a> {
}
}
/// A [`ReportDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns: a title, a summary and plain lines. The text
/// of the Copy button waits in [`take_copied`](HostedReport::take_copied) until the app puts it on the clipboard.
/// Shows `note`: a notice of its tone, with a detail as a line under the text. `at` tells the notes of one dialog apart.
fn show_note(ui: &mut Ui, note: &ReportNote, at: usize) {
if note.code {
// PLAN: Notice has no type-role slot, so a code note shows its text in the mono role without the tone icon.
Text::new(note.text.clone()).role(TypeRole::Mono).show(ui);
if let Some(detail) = &note.detail {
Text::new(detail.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
}
return;
}
let mut notice = Notice::new(note.tone, note.text.clone()).layout(NoticeLayout::Inline).id_salt(at);
if let Some(detail) = &note.detail {
notice = notice.lines([detail.clone()]);
}
notice.show(ui);
}
/// A [`ReportDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns: a title, a summary, plain lines and groups of
/// notes. The text of the Copy button waits in [`take_copied`](HostedReport::take_copied) until the app puts it on the
/// clipboard.
pub struct HostedReport {
id: crate::dialog::DialogId,
title: Label,
summary: Label,
lines: Vec<String>,
groups: Vec<ReportGroup>,
open: bool,
copied: Option<String>,
}
@@ -212,14 +246,22 @@ pub struct HostedReport {
impl HostedReport {
/// A report titled `title` with one `summary` line and the `lines`.
pub fn new(title: impl Into<Label>, summary: impl Into<Label>, lines: Vec<String>) -> Self {
HostedReport { id: crate::dialog::dialog_id("report"), title: title.into(), summary: summary.into(), lines, open: true, copied: None }
HostedReport {
id: crate::dialog::dialog_id("report"),
title: title.into(),
summary: summary.into(),
lines,
groups: Vec::new(),
open: true,
copied: None,
}
}
/// Shows and copies `groups` after the lines; `json_fields` lists their headings and note texts.
#[must_use]
pub fn groups(self, groups: Vec<ReportGroup>) -> Self {
let _ = (self, groups);
todo!("mn.M58")
pub fn groups(mut self, groups: Vec<ReportGroup>) -> Self {
self.groups = groups;
self
}
/// The text the Copy button copied since the last call, once. The app puts it on the clipboard.
@@ -242,7 +284,7 @@ impl crate::dialog::StackDialog for HostedReport {
summary: self.summary.clone(),
notes: Vec::new(),
lines,
groups: Vec::new(),
groups: self.groups.clone(),
open: Some(Bind::bound(&mut self.open)),
}
.show(ui);
@@ -257,7 +299,12 @@ impl crate::dialog::StackDialog for HostedReport {
}
fn json_fields(&self) -> Option<Value> {
Some(json!({ "lines": self.lines }))
let groups: Vec<Value> = self
.groups
.iter()
.map(|group| json!({ "heading": group.heading.as_str(), "notes": group.notes.iter().map(|note| note.text.as_str()).collect::<Vec<_>>() }))
.collect();
Some(json!({ "lines": self.lines, "groups": groups }))
}
}
@@ -1,6 +1,6 @@
//! Stories of `ReportDialog`.
use super::{ReportDialog, ReportNote};
use super::{ReportDialog, ReportGroup, ReportNote};
use crate::contract::Bind;
use crate::runtime::env::Label;
use crate::testing::{Drive, StoryData, StoryOutput, story};
@@ -24,3 +24,20 @@ fn report_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
}
dialog.opened(Bind::bound(data.value("open", true))).show(ui).into()
}
/// Two groups under headings: notes with a detail and a note in the mono role.
#[story(ReportDialog<'static>, covers = [], drive = Drive::Never)]
fn report_dialog_grouped(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let groups = vec![
ReportGroup::new(
"Fonts",
vec![ReportNote::new(Tone::Warn, "Arial was substituted").detail("page 2"), ReportNote::new(Tone::Info, "Inter Variable").code()],
),
ReportGroup::new("Images", vec![ReportNote::new(Tone::Bad, "hero.png could not be read").detail("3 uses")]),
];
ReportDialog::new("Check Script Report", "Checked 2 scripts.", Vec::new())
.groups(groups)
.opened(Bind::bound(data.value("open", true)))
.show(ui)
.into()
}
@@ -0,0 +1,54 @@
//! Trials of the report dialog.
#![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")]
use super::{HostedReport, ReportDialog, ReportGroup, ReportNote};
use crate::contract::Bind;
use crate::dialog::StackDialog as _;
use crate::runtime::env::Env;
use crate::testing::{Fixture, trial};
use craft_theme::variant::Tone;
use serde_json::json;
use std::cell::RefCell;
use std::rc::Rc;
fn groups() -> Vec<ReportGroup> {
vec![
ReportGroup::new(
"Fonts",
vec![ReportNote::new(Tone::Warn, "Missing Arial").detail("page 2"), ReportNote::new(Tone::Bad, "Cannot read Inter")],
),
ReportGroup::new("Images", vec![ReportNote::new(Tone::Good, "hero.png")]),
]
}
/// The copied text holds each group's heading before its notes, in order, with a detail after the text; the count line
/// counts every note; the hosted report lists the groups.
#[trial]
fn grouped_notes_copy_with_their_headings() {
let copied = Rc::new(RefCell::new(String::new()));
let sink = Rc::clone(&copied);
let mut open = true;
let mut fixture = Fixture::new(move |ui| {
let dialog = ReportDialog::new("Report", "Checked.", vec![ReportNote::new(Tone::Info, "Imported")]).groups(groups());
*sink.borrow_mut() = dialog.as_text(&Env::of(ui));
dialog.opened(Bind::bound(&mut open)).show(ui);
});
fixture.settle();
assert_eq!(
*copied.borrow(),
"Info: Imported\nFonts\nWarning: Missing Arial (page 2)\nError: Cannot read Inter\nImages\nSuccess: hero.png"
);
assert!(fixture.by_label("4 notes").is_some(), "the count counts the flat note and every grouped one");
let hosted = HostedReport::new("Report", "Checked.", Vec::new()).groups(groups());
assert_eq!(
hosted.json_fields(),
Some(json!({
"lines": [],
"groups": [
{ "heading": "Fonts", "notes": ["Missing Arial", "Cannot read Inter"] },
{ "heading": "Images", "notes": ["hero.png"] },
],
}))
);
}