LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Engine: album.reorder and album.sort
Nathaniel Ledford2c5cb708bb50
diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rsindex 4ff64eb3a..11f665898 100644--- a/crates/engine/src/cmd/library.rs+++ b/crates/engine/src/cmd/library.rs@@ -119,6 +119,14 @@ fn album_param(p: &Value, key: &str, c: &str) -> Result<AlbumId> {p.get(key).and_then(Value::as_u64).map(AlbumId).ok_or_else(|| bad(c, format!("missing album `{key}`")))}+/// An optional album id: absent or `null` is `None`, anything but a number is an error.+fn opt_album_param(p: &Value, key: &str, c: &str) -> Result<Option<AlbumId>> {+ match p.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(v) => v.as_u64().map(|n| Some(AlbumId(n))).ok_or_else(|| bad(c, format!("`{key}` must be an album id or null"))),+ }+}+fn strs(p: &Value, key: &str) -> Vec<String> {p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default()}@@ -880,6 +888,76 @@ pub fn specs() -> Vec<CommandSpec> {s.commit("Move Album", Op::MoveAlbum { id, parent })?;ok()}),+ cmd!(+ "album.reorder",+ "Reorder Album",+ [],+ None,+ "{id, parent?: folderId|null, before?: albumId|null} — places the album (or folder) in `parent` (default: where it is; null: the top level) before the sibling `before` of the same kind, or last of its kind; the folder is then ordered by hand. One undo step. → {changed}",+ always,+ |s, p| {+ let id = album_param(p, "id", "album.reorder")?;+ let me = s.catalog.album(id).ok_or_else(|| bad("album.reorder", "no such album"))?;+ let parent = if p.get("parent").is_some() { opt_album_param(p, "parent", "album.reorder")? } else { me.parent };+ let before = opt_album_param(p, "before", "album.reorder")?;+ let mut order: Vec<AlbumId> = s.catalog.album_children(parent).into_iter().filter(|a| a.id != id).map(|a| a.id).collect();+ let at = match before {+ Some(b) => {+ let at = order.iter().position(|x| *x == b).ok_or_else(|| bad("album.reorder", "`before` is not inside that folder"))?;+ if s.catalog.album(b).is_none_or(|x| x.folder != me.folder) {+ return Err(bad("album.reorder", "folders are placed among folders and albums among albums"));+ }+ at+ }+ None if me.folder => order.iter().take_while(|x| s.catalog.album(**x).is_some_and(|a| a.folder)).count(),+ None => order.len(),+ };+ order.insert(at.min(order.len()), id);+ let moved = me.parent != parent;+ let mut ops = Vec::new();+ if moved {+ ops.push(Op::MoveAlbum { id, parent });+ }+ for (i, aid) in order.iter().enumerate() {+ let want = u32::try_from(i).ok();+ // a moved album starts without a place in its new folder+ let have = if moved && *aid == id { None } else { s.catalog.album(*aid).and_then(|a| a.order) };+ if have != want {+ ops.push(Op::SetAlbumOrder { id: *aid, order: want });+ }+ }+ if ops.is_empty() {+ return Ok(json!({"changed": 0}));+ }+ let changed = ops.len();+ s.commit("Reorder Album", Op::Batch { ops })?;+ Ok(json!({"changed": changed}))+ }+ ),+ cmd!(+ "album.sort",+ "Sort Albums by Name",+ [],+ None,+ "{parent?: folderId|null} — drops the hand order of the albums inside the folder (default: the top level), so they are listed by name → {changed}",+ always,+ |s, p| {+ let parent = opt_album_param(p, "parent", "album.sort")?;+ let ops: Vec<Op> = s+ .catalog+ .album_children(parent)+ .into_iter()+ .filter(|a| a.order.is_some())+ .map(|a| Op::SetAlbumOrder { id: a.id, order: None })+ .collect();+ if ops.is_empty() {+ return Ok(json!({"changed": 0}));+ }+ let changed = ops.len();+ s.commit("Sort Albums by Name", Op::Batch { ops })?;+ Ok(json!({"changed": changed}))+ }+ ),cmd!("album.addPhotos", "Add to Album", ["Photo"], None, "{id: albumId, ids?: [photoIds]} (default: selection)", has_selection, |s, p| {let id = album_param(p, "id", "album.addPhotos")?;let targets = ids_param(p).unwrap_or_else(|| s.targets(&Value::Null));diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex f26b4ca7a..0ecc431e4 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -781,6 +781,8 @@ pub fn json_delta(old: &Value, new: &Value) -> Option<Value> {#[cfg(test)]mod tests;#[cfg(test)]+mod tests_album_order;+#[cfg(test)]mod tests_color;#[cfg(test)]mod tests_export;diff --git a/crates/engine/src/tests_album_order.rs b/crates/engine/src/tests_album_order.rsnew file mode 100644index 000000000..324c0db5c--- /dev/null+++ b/crates/engine/src/tests_album_order.rs@@ -0,0 +1,132 @@+//! Ordering albums by hand: `album.reorder` puts an album (or folder) before a sibling, or last of+//! its kind, in one undo step, also when it changes folder; `album.sort` goes back to by name.++use lightcraft_catalog::AlbumId;+use serde_json::{Value, json};++use crate::Session;++fn make(s: &mut Session, name: &str, parent: Option<u64>, folder: bool) -> u64 {+ let mut p = json!({"name": name, "folder": folder});+ if let Some(parent) = parent {+ p["parent"] = json!(parent);+ }+ s.execute("album.create", &p).unwrap()["id"].as_u64().unwrap()+}++fn names(s: &Session, parent: Option<u64>) -> Vec<String> {+ s.catalog.album_children(parent.map(AlbumId)).iter().map(|a| a.name.clone()).collect()+}++fn reorder(s: &mut Session, id: u64, params: Value) -> Result<Value, String> {+ let mut p = params;+ p["id"] = json!(id);+ s.execute("album.reorder", &p).map_err(|e| e.to_string())+}++/// Given three albums listed by name, when one is placed before another, then the list follows;+/// "no sibling" puts it last (among albums).+#[test]+fn an_album_is_placed_before_a_sibling_or_last() {+ let mut s = Session::new();+ let (a, b, c) = (make(&mut s, "A", None, false), make(&mut s, "B", None, false), make(&mut s, "C", None, false));+ reorder(&mut s, c, json!({"before": a})).unwrap();+ assert_eq!(names(&s, None), ["C", "A", "B"]);+ assert!(s.catalog.album_children_are_ordered(None));+ reorder(&mut s, c, json!({"before": null})).unwrap();+ assert_eq!(names(&s, None), ["A", "B", "C"]);+ reorder(&mut s, a, json!({})).unwrap();+ assert_eq!(names(&s, None), ["B", "C", "A"], "no `before`: last");+ reorder(&mut s, b, json!({"before": b})).expect_err("not before itself");+ let _ = (a, b);+}++/// Folders stay ahead of albums: a folder is placed among folders, an album among albums.+#[test]+fn folders_and_albums_keep_to_their_own_group() {+ let mut s = Session::new();+ let (f1, f2) = (make(&mut s, "F1", None, true), make(&mut s, "F2", None, true));+ let (a1, a2) = (make(&mut s, "A1", None, false), make(&mut s, "A2", None, false));+ reorder(&mut s, f2, json!({"before": f1})).unwrap();+ reorder(&mut s, a2, json!({"before": a1})).unwrap();+ assert_eq!(names(&s, None), ["F2", "F1", "A2", "A1"]);+ reorder(&mut s, f1, json!({"before": a1})).expect_err("a folder is not placed among albums");+ reorder(&mut s, a1, json!({"before": f1})).expect_err("an album is not placed among folders");+ reorder(&mut s, f2, json!({"before": null})).unwrap();+ assert_eq!(names(&s, None), ["F1", "F2", "A2", "A1"], "last of the folders");+}++/// Placing an album in another folder moves it there, and one undo undoes both.+#[test]+fn placing_across_folders_moves_it_and_undoes_in_one_step() {+ let mut s = Session::new();+ let folder = make(&mut s, "Trips", None, true);+ let (x, y) = (make(&mut s, "X", Some(folder), false), make(&mut s, "Y", Some(folder), false));+ let loose = make(&mut s, "Loose", None, false);+ reorder(&mut s, y, json!({"before": x})).unwrap();+ assert_eq!(names(&s, Some(folder)), ["Y", "X"]);+ reorder(&mut s, loose, json!({"parent": folder, "before": x})).unwrap();+ assert_eq!(names(&s, Some(folder)), ["Y", "Loose", "X"]);+ assert_eq!(s.catalog.album(AlbumId(loose)).unwrap().parent, Some(AlbumId(folder)));+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(names(&s, Some(folder)), ["Y", "X"]);+ assert_eq!(s.catalog.album(AlbumId(loose)).unwrap().parent, None);+ assert_eq!(s.catalog.album(AlbumId(loose)).unwrap().order, None);+}++/// Bad requests change nothing: a `before` that is not in the target folder, a target that is not+/// a folder or lies inside the album, an unknown album.+#[test]+fn bad_placements_are_refused_and_change_nothing() {+ let mut s = Session::new();+ let f = make(&mut s, "F", None, true);+ let inner = make(&mut s, "Inner", Some(f), true);+ let (a, b) = (make(&mut s, "A", None, false), make(&mut s, "B", Some(f), false));+ let before = s.catalog.to_snapshot();+ reorder(&mut s, a, json!({"before": b})).expect_err("B is in F, not at the top level");+ reorder(&mut s, a, json!({"parent": b})).expect_err("a plain album is no folder");+ reorder(&mut s, f, json!({"parent": inner})).expect_err("a folder into itself");+ reorder(&mut s, 987_654, json!({})).expect_err("no such album");+ reorder(&mut s, a, json!({"before": 987_654})).expect_err("no such sibling");+ assert_eq!(s.catalog.to_snapshot(), before, "nothing changed");+}++/// `album.sort` drops the hand order of one folder (and only that one): by name again.+#[test]+fn sorting_goes_back_to_by_name_for_one_folder() {+ let mut s = Session::new();+ let f = make(&mut s, "F", None, true);+ let (x, y) = (make(&mut s, "X", Some(f), false), make(&mut s, "Y", Some(f), false));+ let (a, b) = (make(&mut s, "A", None, false), make(&mut s, "B", None, false));+ reorder(&mut s, y, json!({"before": x})).unwrap();+ reorder(&mut s, b, json!({"before": a})).unwrap();+ assert_eq!(names(&s, Some(f)), ["Y", "X"]);+ assert_eq!(names(&s, None), ["F", "B", "A"]);+ let r = s.execute("album.sort", &json!({"parent": f})).unwrap();+ assert_eq!(r["changed"], 2);+ assert_eq!(names(&s, Some(f)), ["X", "Y"]);+ assert_eq!(names(&s, None), ["F", "B", "A"], "the top level keeps its order");+ assert!(!s.catalog.album_children_are_ordered(Some(AlbumId(f))));+ // nothing to do: no undo step is made+ let r = s.execute("album.sort", &json!({"parent": f})).unwrap();+ assert_eq!(r["changed"], 0);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(names(&s, Some(f)), ["Y", "X"], "the one undo step was the sort");+ let r = s.execute("album.sort", &json!({})).unwrap();+ assert_eq!(r["changed"], 3, "every child of the top level had a place: F, B and A");+ assert_eq!(names(&s, None), ["F", "A", "B"]);+}++/// Moving an album with `album.move` out of an ordered folder leaves the old neighbours' order.+#[test]+fn moving_out_of_an_ordered_folder_keeps_the_others_in_place() {+ let mut s = Session::new();+ let f = make(&mut s, "F", None, true);+ let (x, y, z) = (make(&mut s, "X", Some(f), false), make(&mut s, "Y", Some(f), false), make(&mut s, "Z", Some(f), false));+ reorder(&mut s, z, json!({"before": x})).unwrap();+ assert_eq!(names(&s, Some(f)), ["Z", "X", "Y"]);+ s.execute("album.move", &json!({"id": x, "parent": null})).unwrap();+ assert_eq!(names(&s, Some(f)), ["Z", "Y"]);+ assert_eq!(names(&s, None), ["F", "X"]);+ let _ = y;+}