Undo: a drag after a command replays on its own objects

When a command run during a tool drag deletes, hides or locks an object
that the drag's preview names in its ids, the preview applied again
leaves that object out, so the drag still edits the others. A preview
left naming no object records no step.

When the command changes the selection, the journal also records the
drag's own selection after the command (select.set, with its anchors,
segments, guides and key, or its slices, target, symbol part or Objects
on Path member), so replaying the journal moves the objects the drag
moved. A targeted object keeps its guides and key, and a path with
every anchor selected keeps them selected as anchors. The current layer
and the highlighted Layers panel rows are left as the drag left them.
This commit is contained in:
dotCooCoo committed 2026-11-24 09:52:58 -08:00
1 parent 828f43447d
commit 782715d467
2 files changed
+394 -1

No files matched your search

+136 -1
View File
@@ -383,10 +383,19 @@ impl Session {
}
return;
}
it.doc = st.doc.clone();
let began = std::mem::replace(&mut it.doc, st.doc.clone());
// The drag acts on the objects it began with: a selection the command made (a paste, a
// duplicate, Select All) does not change what the drag moves.
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
// The journal holds the selection the command left. The drag's own selection is journaled
// after it, so the drag and the commands after it replay on the objects they act on.
let reselect = (active && st.selection != *it.selection)
.then(|| selection_steps(&it.selection, &st.selection, &st.doc, st.active_layer, &st.highlighted_rows()));
// The objects the drag's preview names leave out those the command removed, hid or locked.
// A preview left naming none has nothing to apply, and the drag records no step.
if it.preview.as_mut().is_some_and(|(_, p)| !drag_targets(p, &began, &st.doc)) {
it.preview = None;
}
it.copies = None;
it.move_box = std::sync::OnceLock::new();
// With Real-time Drawing off the preview waits for the commit, as it did before the command.
@@ -398,6 +407,13 @@ impl Session {
st.revision += 1;
}
st.interaction = Some(it);
if let Some(steps) = reselect {
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
for step in steps {
self.journal.push(step);
}
self.journal_in_undo_groups(Some(uid), &grouped, from);
}
self.clear_deferred_overlay_cache();
if let Some((cmd, p)) = again {
match self.preview(&cmd, &p) {
@@ -686,3 +702,122 @@ fn drag_selection(began: &Selection, doc: &Document) -> Selection {
selection.remove_all(held);
selection
}
/// Take out of the `ids` of a drag's preview `params` the objects that a command run during the
/// drag removed from `doc`, or hid or locked there while they were editable in `began` → false
/// when the preview named objects and none of them is left.
fn drag_targets(params: &mut Value, began: &Document, doc: &Document) -> bool {
let Some(ids) = params.get_mut("ids").and_then(Value::as_array_mut) else { return true };
if ids.is_empty() {
return true;
}
let (was, now) = (began.editable(), doc.editable());
ids.retain(|v| v.as_u64().map(vectorcraft_doc::NodeId).is_none_or(|id| doc.node(id).is_some() && (now(id) || !was(id))));
!ids.is_empty()
}
/// The journal entries that select `selection` again in `doc` after `made`, the selection a
/// command left with `layer` current and `rows` highlighted in the Layers panel ([`object_steps`]).
/// When selecting the objects would make another layer current, `layer.setCurrent` makes `layer`
/// current again, as the drag leaves it, and `layer.highlight` gives back the highlighted rows.
fn selection_steps(
selection: &Selection,
made: &Selection,
doc: &Document,
layer: Option<vectorcraft_doc::NodeId>,
rows: &[vectorcraft_doc::NodeId],
) -> Vec<(String, Value)> {
let mut steps = object_steps(selection, doc);
// `layer.target` on a layer makes it current; any other change to the selected objects makes
// the layer of the last selected object current.
let targeted = steps.first().is_some_and(|(id, _)| id == "layer.target");
let selects = match selection.target.filter(|t| targeted && doc.node(*t).is_some_and(|n| n.is_layer())) {
Some(t) => Some(t),
None if selection.objects != made.objects => {
selection.objects.last().and_then(|id| doc.layer_containing(*id)).filter(|l| doc.is_editable(*l))
}
None => None,
};
if let Some(layer) = layer.filter(|l| selects.is_some_and(|s| s != *l)) {
steps.push(("layer.setCurrent".into(), serde_json::json!({ "id": layer.0 })));
// `layer.setCurrent` highlights the layer's row. `layer.highlight` sets the rows the command
// left instead; it keeps `layer` current while the last of them is on `layer`, or none is left.
if rows != [layer] && rows.last().is_none_or(|r| doc.layer_containing(*r) == Some(layer)) {
let ids: Vec<u64> = rows.iter().map(|r| r.0).collect();
steps.push(("layer.highlight".into(), serde_json::json!({ "ids": ids, "mode": "set" })));
}
}
steps
}
/// The journal entries that select `selection` in `doc`: the selections made on their own (its
/// slices with `object.slice.select`, its target with `layer.target`, its symbol part with
/// `symbol.instance.selectPart`, its Objects on Path member with
/// `object.objectsOnPath.selectMember`), or its objects in their order (`select.set`), the anchors
/// left out on paths that are not selected whole (`select.anchorsMany`), the anchors of paths with
/// every anchor selected (`select.anchors`) and its segments (`select.segments`); after its objects
/// or its target, its ruler guides (`guide.select`) and its key object, key guide or key anchor
/// (`select.key`).
fn object_steps(selection: &Selection, doc: &Document) -> Vec<(String, Value)> {
use serde_json::json;
if !selection.slices.is_empty() {
let slices: Vec<u64> = selection.slices.iter().map(|id| id.0).collect();
return vec![("object.slice.select".into(), json!({ "slices": slices }))];
}
// A target is selected again only while targeting it selects the same objects: when a command
// added art to a targeted layer, `select.set` selects the drag's objects.
let targets = |t: vectorcraft_doc::NodeId| match doc.node(t) {
Some(n) if n.is_layer() => n.layer_art(true) == selection.objects,
_ => selection.objects == [t],
};
let json_refs = |refs: &mut dyn Iterator<Item = &(usize, usize)>| Value::Array(refs.map(|&(a, b)| json!([a, b])).collect());
// A targeted object keeps the ruler guides and the key selected beside it.
let mut steps = if let Some(t) = selection.target.filter(|&t| targets(t)) {
vec![("layer.target".to_string(), json!({ "id": t.0 }))]
} else if let Some(part) = &selection.symbol_part {
return vec![("symbol.instance.selectPart".into(), json!({ "id": part.instance.0, "path": part.path }))];
} else if let Some(member) = selection.on_path_member {
return vec![("object.objectsOnPath.selectMember".into(), json!({ "member": member.0 }))];
} else {
let ids: Vec<u64> = selection.objects.iter().map(|id| id.0).collect();
let mut steps = vec![("select.set".to_string(), json!({ "ids": ids }))];
// `select.set` selects each path whole: subtracting the anchors that are not selected leaves
// the ones that are, and keeps the order of the objects. A path with every anchor selected
// as anchors gets them back with `select.anchors`, which keeps them all as anchors.
let mut every = Vec::new();
let partial: Vec<Value> = selection
.objects
.iter()
.filter_map(|id| {
let refs = selection.anchors.get(id)?;
let path = doc.node(*id)?.path_data()?;
let out: Vec<(usize, usize)> = path.anchors().map(|(s, i, _)| (s, i)).filter(|r| !refs.contains(r)).collect();
if out.is_empty() {
every.push(("select.anchors".to_string(), json!({ "id": id.0, "anchors": json_refs(&mut refs.iter()), "mode": "add" })));
return None;
}
Some(json!({ "id": id.0, "anchors": json_refs(&mut out.iter()) }))
})
.collect();
if !partial.is_empty() {
steps.push(("select.anchorsMany".into(), json!({ "items": partial, "mode": "subtract" })));
}
steps.extend(every);
for (id, refs) in &selection.segments {
steps.push(("select.segments".into(), json!({ "id": id.0, "segments": json_refs(&mut refs.iter()), "mode": "add" })));
}
steps
};
if !selection.guides.is_empty() {
let indexes = cmd::guide_indexes(doc, &selection.guides);
steps.push(("guide.select".into(), json!({ "indexes": indexes, "toggle": true })));
}
if let Some((id, (s, i))) = selection.key_anchor {
steps.push(("select.key".into(), json!({ "id": id.0, "anchor": [s, i] })));
} else if let Some(g) = selection.key_guide.and_then(|g| cmd::guide_indexes(doc, &[g]).first().copied()) {
steps.push(("select.key".into(), json!({ "guide": g })));
} else if let Some(key) = selection.key {
steps.push(("select.key".into(), json!({ "id": key.0 })));
}
steps
}
@@ -400,6 +400,264 @@ fn a_selection_made_during_a_move_drag_leaves_the_paints_of_the_drag_object() {
}
}
/// Replay the journal of `s` from `start` on `replayed`.
fn replay_from(s: &Session, start: usize, replayed: &mut Session) {
for (id, p) in s.journal.iter().skip(start) {
replayed.replay(id, p).unwrap();
}
}
/// The journal of a move drag with a selection command run during it replays as the drag went:
/// the drag moves its own object, not the one the command selected.
#[test]
fn a_move_drag_after_a_selection_command_replays_on_its_own_object() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, target, other) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let bounds = |s: &Session| {
let d = &s.doc().unwrap().doc;
(d.bounds_of(&[target], false), d.bounds_of(&[other], false))
};
assert_eq!(bounds(&s), (Some(Rect::new(150.0, 130.0, 190.0, 170.0)), Some(Rect::new(10.0, 10.0, 30.0, 30.0))), "{at}");
let (mut replayed, _, _) = two_squares(real_time);
replay_from(&s, start, &mut replayed);
assert_eq!(bounds(&replayed), bounds(&s), "{at}: {:?}", journaled(&s, start));
assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}");
assert_eq!(replayed.doc().unwrap().active_layer, s.doc().unwrap().active_layer, "{at}");
}
}
/// A square on a second layer selected with a ruler guide, and a square on the first layer →
/// the session (with Real-time Drawing `real_time`) and the square on the first layer.
fn square_and_guide(real_time: bool) -> (Session, NodeId) {
let mut s = Session::new();
s.prefs.real_time_drawing = real_time;
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let other = s.doc().unwrap().selection.objects[0];
s.execute("layer.new", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap();
let target = s.doc().unwrap().selection.objects[0];
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
(s, other)
}
/// The journal of a move drag of a square and a ruler guide, with a command during it that
/// selects an object on another layer, replays with the drag's selection, guide included, with
/// the layer the command made current and with the Layers panel rows the command left highlighted.
#[test]
fn a_move_drag_of_a_guide_after_a_selection_command_replays_its_selection_and_layer() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, other) = square_and_guide(real_time);
s.select_tool("selection", view()).unwrap();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let (mut replayed, _) = square_and_guide(real_time);
replay_from(&s, start, &mut replayed);
let state = |s: &mut Session| {
let d = s.doc().unwrap();
let state = (
d.selection.objects.clone(),
d.selection.guides.clone(),
d.active_layer,
d.highlighted_rows(),
d.doc.bounds_of(&d.selection.objects, false),
);
(state, s.execute("guide.list", &json!({})).unwrap())
};
assert_eq!(state(&mut replayed), state(&mut s), "{at}: {:?}", journaled(&s, start));
}
}
/// The journal of a move drag of a targeted square, with a command during it that selects another
/// square, replays with the square targeted, as the drag leaves it.
#[test]
fn a_move_drag_of_a_targeted_object_after_a_selection_command_replays_its_target() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let setup = || {
let (mut s, target, other) = two_squares(real_time);
s.execute("layer.target", &json!({"id": target.0})).unwrap();
s.select_tool("selection", view()).unwrap();
(s, other)
};
let (mut s, other) = setup();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let (mut replayed, _) = setup();
replay_from(&s, start, &mut replayed);
let state = |s: &Session| {
let d = s.doc().unwrap();
(d.selection.objects.clone(), d.selection.target, d.doc.bounds_of(&d.selection.objects, false))
};
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
}
}
/// The journal of a move drag of a targeted square and a ruler guide, with a command during it
/// that selects another square, replays with the square targeted and the guide selected.
#[test]
fn a_move_drag_of_a_targeted_object_and_a_guide_after_a_selection_command_replays_both() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let setup = || {
let (mut s, target, other) = two_squares(real_time);
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
s.execute("layer.target", &json!({"id": target.0})).unwrap();
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
s.select_tool("selection", view()).unwrap();
(s, target, other)
};
let (mut s, target, other) = setup();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let state = |s: &mut Session| {
let d = s.doc().unwrap();
let state = (d.selection.objects.clone(), d.selection.target, d.selection.guides.clone(), d.doc.bounds_of(&d.selection.objects, false));
(state, s.execute("guide.list", &json!({})).unwrap())
};
let live = state(&mut s);
assert_eq!((live.0.1, live.0.2.len()), (Some(target), 1), "{at}: the drag leaves the square targeted and the guide selected");
let (mut replayed, _, _) = setup();
replay_from(&s, start, &mut replayed);
assert_eq!(state(&mut replayed), live, "{at}: {:?}", journaled(&s, start));
}
}
/// The journal of a move drag of a path with every anchor selected as anchor points, with a
/// command during it that selects another square, replays with those anchors selected.
#[test]
fn a_move_drag_of_every_anchor_of_a_path_after_a_selection_command_replays_its_anchors() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let setup = || {
let (mut s, target, other) = two_squares(real_time);
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
s.execute("select.anchors", &json!({"id": target.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
s.select_tool("selection", view()).unwrap();
(s, target, other)
};
let (mut s, target, other) = setup();
let every = s.doc().unwrap().selection.anchors.get(&target).cloned();
assert!(every.as_ref().is_some_and(|a| a.len() > 1), "{at}: {every:?}");
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let state = |s: &Session| {
let d = s.doc().unwrap();
(d.selection.objects.clone(), d.selection.anchors.clone(), d.doc.bounds_of(&d.selection.objects, false))
};
assert_eq!(state(&s).1.get(&target), every.as_ref(), "{at}: the drag leaves every anchor selected as anchors");
let (mut replayed, _, _) = setup();
replay_from(&s, start, &mut replayed);
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
}
}
/// The journal of a move drag of a targeted layer's art, with a duplicate made on that layer
/// during it, replays with the drag moving its own objects, not the duplicates.
#[test]
fn a_move_drag_of_a_targeted_layer_after_a_duplicate_replays_its_objects() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let setup = || {
let (mut s, _, _) = two_squares(real_time);
let layer = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
s.select_tool("selection", view()).unwrap();
s
};
let mut s = setup();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("edit.duplicate", &json!({})).unwrap();
});
let mut replayed = setup();
replay_from(&s, start, &mut replayed);
let state = |s: &Session| {
let d = s.doc().unwrap();
(d.selection.objects.clone(), d.doc.bounds_of(&d.selection.objects, false), objects(s))
};
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
}
}
/// A selected user slice and a square → the session (with Real-time Drawing `real_time`), the
/// slice and the square.
fn slice_and_square(real_time: bool) -> (Session, NodeId, NodeId) {
let mut s = Session::new();
s.prefs.real_time_drawing = real_time;
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let other = s.doc().unwrap().selection.objects[0];
let slice = s.execute("object.slice.create", &json!({"x": 200, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("object.slice.select", &json!({"slices": [slice]})).unwrap();
(s, NodeId(slice), other)
}
/// The journal of a Slice Selection drag, with a command during it that selects an object,
/// replays with the slice selected, as the drag leaves it.
#[test]
fn a_slice_drag_after_a_selection_command_replays_its_slice_selection() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, slice, other) = slice_and_square(real_time);
s.select_tool("sliceSelection", view()).unwrap();
let start = s.journal.len();
drag_with(&mut s, &[(220.0, 220.0), (230.0, 230.0), (240.0, 240.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
assert_eq!(s.doc().unwrap().selection.slices, [slice], "{at}");
let (mut replayed, _, _) = slice_and_square(real_time);
replay_from(&s, start, &mut replayed);
let state = |s: &Session| {
let sel = &s.doc().unwrap().selection;
(sel.objects.clone(), sel.slices.clone())
};
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
}
}
/// A Warp stroke over two selected squares, with a command that deletes one of them during the
/// stroke: the release still warps the other square, and the stroke's journal entry names it.
#[test]
fn a_warp_stroke_over_an_object_a_command_deleted_still_warps_the_others() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, target, other) = two_squares(real_time);
s.execute("select.all", &json!({})).unwrap();
s.select_tool("warp", view()).unwrap();
let before = s.doc().unwrap().doc.node(target).cloned();
let steps = s.doc().unwrap().history.undo.len();
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
pointer(&mut s, PointerKind::Drag, 135.0, 125.0);
let r = s.execute("edit.clear", &json!({"ids": [other.0]})).unwrap();
assert!(r.get("warning").is_none(), "{at}: {r}");
pointer(&mut s, PointerKind::Up, 135.0, 125.0);
assert!(!s.in_interaction(), "{at}");
assert!(s.doc().unwrap().doc.node(other).is_none(), "{at}: the deletion stays");
assert_ne!(s.doc().unwrap().doc.node(target).cloned(), before, "{at}: the release warps the other square");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the deletion and the stroke are a step each");
let (id, p) = s.journal.last().unwrap();
assert_eq!((id.as_str(), &p["ids"]), ("object.liquify", &json!([target.0])), "{at}");
}
}
/// The Scale and Rotate tools and the Pen adding to a path, with a command that deletes the
/// object they act on during the drag: the drag ends without an edit of its own and the deletion
/// stays.