mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 22:28:27 +00:00
panels-w6: review fixes (review-2)
This commit is contained in:
@@ -105,6 +105,27 @@ pub(super) fn has(groups: &[SwatchGroup], key: &SwatchKey) -> bool {
|
||||
group_of(groups, key).is_some()
|
||||
}
|
||||
|
||||
/// Whether the groups hold the most swatches a library may.
|
||||
pub(super) fn swatches_full(groups: &[SwatchGroup]) -> bool {
|
||||
groups.iter().map(|g| g.entries.len()).sum::<usize>() >= MAX_SWATCHES
|
||||
}
|
||||
|
||||
/// The name the swatch at `at` takes when renamed to `text`; `None` when `at` names nothing, the name is empty or
|
||||
/// another swatch has it.
|
||||
pub(super) fn swatch_rename(groups: &[SwatchGroup], at: SwatchAt, text: &str) -> Option<String> {
|
||||
let name = text.trim();
|
||||
groups.get(at.group)?.entries.get(at.index)?;
|
||||
(!name.is_empty() && find_swatch(groups, name).is_none_or(|other| other == at)).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// The name group `index` takes when renamed to `text`; `None` when there is no such group, the name is empty or
|
||||
/// another group has it.
|
||||
pub(super) fn group_rename(groups: &[SwatchGroup], index: usize, text: &str) -> Option<String> {
|
||||
let name = text.trim();
|
||||
groups.get(index)?;
|
||||
(!name.is_empty() && !groups.iter().enumerate().any(|(i, g)| i != index && g.name == name)).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// The flat rows of the browser: each group's header, then its swatches.
|
||||
fn flat<'a>(groups: impl IntoIterator<Item = &'a SwatchGroup>) -> Vec<SwatchKey> {
|
||||
let mut rows = Vec::new();
|
||||
@@ -142,8 +163,36 @@ fn group_slot(groups: &[SwatchGroup], names: &[&str], to: usize) -> usize {
|
||||
remaining[..to.min(remaining.len())].iter().filter(|k| matches!(k, SwatchKey::Group(_))).count()
|
||||
}
|
||||
|
||||
/// The edits a reorder of the browser makes, one per moved swatch or group in library order; the i-th gets the slot
|
||||
/// plus i, so the host keeps their order. Anything the library cannot do gives none.
|
||||
/// The `at` of each edit that moves `moved` (in library order) one by one within `order`, so that they end up together
|
||||
/// at `slot` among the names that stay. Edits run in turn, so each index treats the moved names still waiting in the
|
||||
/// list as absent: only the staying names and the ones already placed count.
|
||||
fn move_slots(order: &[&str], moved: &[&str], slot: usize) -> Vec<usize> {
|
||||
let mut list: Vec<&str> = order.to_vec();
|
||||
let mut slots = Vec::with_capacity(moved.len());
|
||||
for (i, name) in moved.iter().enumerate() {
|
||||
list.retain(|n| n != name);
|
||||
let anchors = slot + i;
|
||||
let mut at = if anchors == 0 { 0 } else { list.len() };
|
||||
let mut seen = 0;
|
||||
if anchors > 0 {
|
||||
for (index, n) in list.iter().enumerate() {
|
||||
if !moved[i + 1..].contains(n) {
|
||||
seen += 1;
|
||||
if seen == anchors {
|
||||
at = index + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
list.insert(at, *name);
|
||||
slots.push(at);
|
||||
}
|
||||
slots
|
||||
}
|
||||
|
||||
/// The edits a reorder of the browser makes, one per moved swatch or group in library order; each `at` counts the
|
||||
/// edits before it, so the host keeps their order. Anything the library cannot do gives none.
|
||||
pub(super) fn reorder_edits(groups: &[SwatchGroup], mv: &ReorderMove<SwatchKey>) -> Vec<SwatchEdit> {
|
||||
if mv.copy {
|
||||
return Vec::new();
|
||||
@@ -152,23 +201,20 @@ pub(super) fn reorder_edits(groups: &[SwatchGroup], mv: &ReorderMove<SwatchKey>)
|
||||
let group_names: Option<Vec<&str>> = mv.keys.iter().map(|k| if let SwatchKey::Group(n) = k { Some(n.as_str()) } else { None }).collect();
|
||||
if let Some(names) = swatches {
|
||||
let Some((group, slot)) = resolve_move(groups, &names, mv.to, mv.parent.as_ref()) else { return Vec::new() };
|
||||
let target = &groups[group].name;
|
||||
return groups
|
||||
.iter()
|
||||
.flat_map(|g| g.entries.iter())
|
||||
.filter(|e| names.contains(&e.name.as_str()))
|
||||
.enumerate()
|
||||
.map(|(i, e)| SwatchEdit::MoveTo { swatch: e.name.clone(), group: target.clone(), at: slot + i })
|
||||
let target = &groups[group];
|
||||
let order: Vec<&str> = target.entries.iter().map(|e| e.name.as_str()).collect();
|
||||
let moved: Vec<&str> = groups.iter().flat_map(|g| g.entries.iter()).map(|e| e.name.as_str()).filter(|n| names.contains(n)).collect();
|
||||
return move_slots(&order, &moved, slot)
|
||||
.into_iter()
|
||||
.zip(&moved)
|
||||
.map(|(at, name)| SwatchEdit::MoveTo { swatch: (*name).to_owned(), group: target.name.clone(), at })
|
||||
.collect();
|
||||
}
|
||||
let Some(names) = group_names else { return Vec::new() };
|
||||
let slot = group_slot(groups, &names, mv.to);
|
||||
groups
|
||||
.iter()
|
||||
.filter(|g| names.contains(&g.name.as_str()))
|
||||
.enumerate()
|
||||
.map(|(i, g)| SwatchEdit::MoveGroup { group: g.name.clone(), to: slot + i })
|
||||
.collect()
|
||||
let order: Vec<&str> = groups.iter().map(|g| g.name.as_str()).collect();
|
||||
let moved: Vec<&str> = order.iter().copied().filter(|n| names.contains(n)).collect();
|
||||
move_slots(&order, &moved, slot).into_iter().zip(&moved).map(|(to, name)| SwatchEdit::MoveGroup { group: (*name).to_owned(), to }).collect()
|
||||
}
|
||||
|
||||
impl SwatchLibrary {
|
||||
@@ -197,7 +243,7 @@ impl SwatchLibrary {
|
||||
/// where it went, or `None` when the library holds [`MAX_SWATCHES`].
|
||||
// pc: crates/engine/src/cmd/swatch_cmds.rs:150-171 (`swatches.add`: the cap, the name, group 0).
|
||||
pub fn add(&mut self, color: SwatchColor, name: Option<&str>, group: Option<usize>) -> Option<SwatchAt> {
|
||||
if self.total() >= MAX_SWATCHES {
|
||||
if swatches_full(&self.groups) {
|
||||
return None;
|
||||
}
|
||||
let name = name
|
||||
@@ -227,14 +273,8 @@ impl SwatchLibrary {
|
||||
|
||||
/// Renames a swatch; `false` when the name is empty or taken.
|
||||
pub fn rename(&mut self, at: SwatchAt, name: &str) -> bool {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || self.get(at).is_none() {
|
||||
return false;
|
||||
}
|
||||
if self.find(name).is_some_and(|other| other != at) {
|
||||
return false;
|
||||
}
|
||||
self.groups[at.group].entries[at.index].name = name.to_owned();
|
||||
let Some(name) = swatch_rename(&self.groups, at, name) else { return false };
|
||||
self.groups[at.group].entries[at.index].name = name;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -267,11 +307,8 @@ impl SwatchLibrary {
|
||||
|
||||
/// Renames a group; `false` when the name is empty or another group has it.
|
||||
fn rename_group(&mut self, group: usize, name: &str) -> bool {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || group >= self.groups.len() || self.groups.iter().enumerate().any(|(i, g)| i != group && g.name == name) {
|
||||
return false;
|
||||
}
|
||||
self.groups[group].name = name.to_owned();
|
||||
let Some(name) = group_rename(&self.groups, group, name) else { return false };
|
||||
self.groups[group].name = name;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -504,3 +541,34 @@ pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetR
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn group(name: &str, entries: &[&str]) -> SwatchGroup {
|
||||
SwatchGroup { name: name.to_owned(), entries: entries.iter().map(|n| SwatchEntry::new((*n).to_owned(), SwatchColor::Gray(0.5))).collect() }
|
||||
}
|
||||
|
||||
/// Edits that move several items down or up give the order the browser's own reorder gives.
|
||||
#[test]
|
||||
fn multi_item_moves_apply_as_the_reorder_does() {
|
||||
let library = SwatchLibrary::new(vec![group("G", &["A", "B", "C", "D"]), group("H", &["E"])]);
|
||||
let swatch = |n: &str| SwatchKey::Swatch(n.to_owned());
|
||||
let group_key = |n: &str| SwatchKey::Group(n.to_owned());
|
||||
let moves = [
|
||||
ReorderMove::new(swatch("A"), vec![swatch("A"), swatch("B")], 3, false),
|
||||
ReorderMove::new(swatch("C"), vec![swatch("C"), swatch("D")], 1, false),
|
||||
ReorderMove::new(group_key("G"), vec![group_key("G")], 2, false),
|
||||
];
|
||||
for mv in moves {
|
||||
let mut expected = library.clone();
|
||||
assert!(expected.apply_reorder(&mv));
|
||||
let mut applied = library.clone();
|
||||
for edit in reorder_edits(&library.groups, &mv) {
|
||||
assert!(applied.apply(&edit));
|
||||
}
|
||||
assert_eq!(applied, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ use craft_ui::menu::PanelRow;
|
||||
use craft_ui::patterns::presets::{PresetCommands, PresetEvent, PresetExport, PresetFileRequest, PresetFiles, PresetFooterEvent};
|
||||
use craft_ui::runtime::commands::{CommandRef, CommandState};
|
||||
|
||||
use super::library::{find_swatch, free_name, group_of, reorder_edits, unique_group_name};
|
||||
use super::{MAX_GROUPS, MAX_SWATCHES, SwatchEdit, SwatchKey, SwatchesState, SwatchesWords};
|
||||
use super::library::{find_swatch, free_name, group_of, group_rename, reorder_edits, swatch_rename, swatches_full, unique_group_name};
|
||||
use super::{MAX_GROUPS, SwatchEdit, SwatchKey, SwatchesState, SwatchesWords};
|
||||
use crate::palette::{SwatchColor, SwatchFormat, SwatchGroup, SwatchReport};
|
||||
|
||||
/// The purpose of the swatch file pickers: their folder is remembered under it.
|
||||
@@ -162,7 +162,7 @@ impl SwatchesMenu {
|
||||
/// The foreground colour into the selected swatch's group under the next free numbered name; the swatch is selected and
|
||||
/// its name opens for editing. `None` when the library is full.
|
||||
fn new_swatch_edit(groups: &[SwatchGroup], st: &mut SwatchesState, foreground: Srgba, words: &SwatchesWords) -> Option<SwatchEdit> {
|
||||
if groups.iter().map(|g| g.entries.len()).sum::<usize>() >= MAX_SWATCHES {
|
||||
if swatches_full(groups) {
|
||||
return None;
|
||||
}
|
||||
let group = st.selected.as_ref().and_then(|key| group_of(groups, key)).and_then(|index| groups.get(index)).map(|g| g.name.clone());
|
||||
@@ -210,21 +210,19 @@ pub(super) fn event_edits(
|
||||
Vec::new()
|
||||
}
|
||||
PresetEvent::Rename { key: SwatchKey::Swatch(old), text, .. } => {
|
||||
let name = text.trim();
|
||||
if find_swatch(groups, &old).is_none() || name.is_empty() || name == old || find_swatch(groups, name).is_some() {
|
||||
let Some(name) = find_swatch(groups, &old).and_then(|at| swatch_rename(groups, at, &text)).filter(|name| *name != old) else {
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
if st.selected == Some(SwatchKey::Swatch(old.clone())) {
|
||||
st.selected = Some(SwatchKey::Swatch(name.to_owned()));
|
||||
st.selected = Some(SwatchKey::Swatch(name.clone()));
|
||||
}
|
||||
vec![SwatchEdit::Rename { swatch: old, name: name.to_owned() }]
|
||||
vec![SwatchEdit::Rename { swatch: old, name }]
|
||||
}
|
||||
PresetEvent::Rename { key: SwatchKey::Group(old), text, .. } => {
|
||||
let name = text.trim();
|
||||
if !groups.iter().any(|g| g.name == old) || name.is_empty() || name == old || groups.iter().any(|g| g.name == name) {
|
||||
let Some(name) = groups.iter().position(|g| g.name == old).and_then(|i| group_rename(groups, i, &text)).filter(|name| *name != old) else {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![SwatchEdit::RenameGroup { group: old, name: name.to_owned() }]
|
||||
};
|
||||
vec![SwatchEdit::RenameGroup { group: old, name }]
|
||||
}
|
||||
PresetEvent::Delete(key) => delete_edit(groups, &key).into_iter().collect(),
|
||||
PresetEvent::MoveTo { key: SwatchKey::Swatch(name), group: SwatchKey::Group(to), .. } => {
|
||||
|
||||
@@ -6,9 +6,8 @@ use std::rc::Rc;
|
||||
|
||||
use craft_behavior::{EditEvent, Selection};
|
||||
use craft_color::palette::{SwatchColor, SwatchGroup};
|
||||
// PLAN: dialogs-w15 moves `SwatchTable` to `craft_ui::choice` (dl.K43); `craft_ui::choice` has no such item until then, so it is imported from `craft_color::ui`.
|
||||
use craft_color::ui::{
|
||||
ColorPanel, ColorPanelMode, ColorPanelState, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchPalette, SwatchTable, SwatchesCommand,
|
||||
ColorPanel, ColorPanelMode, ColorPanelState, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchTable, SwatchesCommand,
|
||||
SwatchesMenu, SwatchesPanel, SwatchesState,
|
||||
};
|
||||
use craft_theme::Srgba;
|
||||
@@ -257,14 +256,18 @@ fn swatches_rig(groups: Vec<SwatchGroup>) -> (Fixture, Rc<RefCell<Vec<SwatchEdit
|
||||
(fixture, edits)
|
||||
}
|
||||
|
||||
/// A swatch selected and deleted reports one `Delete` and leaves the groups it was shown as they were; New Swatch from
|
||||
/// the menu reports an `Add` in the selected swatch's group under the next free numbered name.
|
||||
/// Through the panel, a selected swatch deleted reports one `Delete`, and a swatch dragged onto another group's header
|
||||
/// reports one `MoveTo` the host can run; New Swatch from the menu reports an `Add` in the selected swatch's group under
|
||||
/// the next free numbered name. The slots of multi-swatch moves are checked in library.rs.
|
||||
#[trial]
|
||||
fn swatches_panel_reports_each_edit_and_leaves_the_library() {
|
||||
let red = SwatchColor::Rgb([1.0, 0.0, 0.0]);
|
||||
let blue = SwatchColor::Rgb([0.0, 0.0, 1.0]);
|
||||
let entry = |name: &str, color: SwatchColor| craft_color::palette::SwatchEntry::new(name.to_owned(), color);
|
||||
let groups = vec![SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red", red.clone()), entry("Color Swatch 1", blue)] }];
|
||||
let groups = vec![
|
||||
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red", red.clone()), entry("Color Swatch 1", blue.clone())] },
|
||||
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Blue", blue)] },
|
||||
];
|
||||
let (mut fixture, edits) = swatches_rig(groups.clone());
|
||||
let row = fixture.by_label("Red, #ff0000").expect("the Red swatch is named with its value");
|
||||
fixture.click(&row).settle();
|
||||
@@ -272,6 +275,17 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
|
||||
fixture.key(Key::Delete, Modifiers::NONE).settle();
|
||||
assert_eq!(*edits.borrow(), [SwatchEdit::Delete { swatch: "Red".to_owned() }], "one resolved edit, once");
|
||||
|
||||
let (mut fixture, edits) = swatches_rig(groups.clone());
|
||||
let row = fixture.by_label("Red, #ff0000").expect("the Red swatch");
|
||||
let header = fixture.by_label("Other").expect("the Other group's header").center();
|
||||
fixture.drag(&row, header - row.center()).settle();
|
||||
let reported = edits.borrow().clone();
|
||||
assert_eq!(reported.len(), 1, "one edit for one dragged swatch: {reported:?}");
|
||||
assert!(matches!(&reported[0], SwatchEdit::MoveTo { swatch, group, .. } if swatch == "Red" && group == "Other"), "{reported:?}");
|
||||
let mut library = SwatchLibrary::new(groups.clone());
|
||||
assert!(library.apply(&reported[0]), "the host can run it");
|
||||
assert!(library.find("Red").is_some_and(|at| library.groups[at.group].name == "Other"), "Red is in Other");
|
||||
|
||||
let mut state = SwatchesState::default();
|
||||
state.selected = Some(SwatchKey::Swatch("Red".to_owned()));
|
||||
let made = SwatchesMenu::run_command(&groups, &mut state, SwatchesCommand::NewSwatch, RED, &Default::default());
|
||||
|
||||
Reference in New Issue
Block a user