Skip to content

Commit 045bc9a

Browse files
authored
Improve layer dragging ux (#5032)
* Keep a removed layer's offset on the layer replacing it * Move a layer's chain and stack when dragging with Ctrl * Follow the wire's route with its center line * Only write a node's layer flag when it changes
1 parent 9557c6a commit 045bc9a

15 files changed

Lines changed: 476 additions & 64 deletions

File tree

‎editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
9393
EditorDelta::NodeMetadata { network, node_id, change } => {
9494
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
9595
match change {
96-
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
96+
NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
9797
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
9898
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
9999
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),

‎editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,7 @@ impl NodeNetworkInterface {
475475
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
476476
let thick = vertical_end && vertical_start;
477477
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
478-
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
478+
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
479479

480480
let path_string = vector_wire.to_svg();
481481
let center_path_string = center_line.to_svg();
@@ -523,7 +523,7 @@ impl NodeNetworkInterface {
523523
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
524524
let thick = vertical_end && vertical_start;
525525
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
526-
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
526+
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style);
527527
Some((vector_wire, center_line, thick))
528528
}
529529

‎editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use super::{
22
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
33
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
44
};
5-
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
5+
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
66
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
77
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
88
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
@@ -4228,3 +4228,73 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
42284228
assert_eq!(overlapping_layers(&editor), Vec::new());
42294229
assert_invariants(&editor, "after grouping a group");
42304230
}
4231+
4232+
fn indent_below_parent(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Option<i32> {
4233+
let interface = &editor.active_document().network_interface;
4234+
let parent = layer.parent(interface.document_metadata())?;
4235+
Some(interface.position(&parent.to_node(), &[])?.x - interface.position(&layer.to_node(), &[])?.x)
4236+
}
4237+
4238+
#[tokio::test]
4239+
async fn reordering_the_layers_of_a_group_keeps_them_indented_below_it() {
4240+
let mut editor = EditorTestUtils::create();
4241+
editor.new_document().await;
4242+
editor.handle_message(new_artboard_message(NodeId::new())).await;
4243+
for x in [0., 50., 100.] {
4244+
editor.draw_rect(x, 0., x + 40., 40.).await;
4245+
}
4246+
4247+
let artboard = LayerNodeIdentifier::ROOT_PARENT
4248+
.children(editor.active_document().metadata())
4249+
.next()
4250+
.expect("the artboard should be a layer");
4251+
let top_two = artboard.children(editor.active_document().metadata()).take(2).map(LayerNodeIdentifier::to_node).collect();
4252+
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: top_two }).await;
4253+
group_selected_layers(&mut editor).await;
4254+
4255+
let group = artboard
4256+
.children(editor.active_document().metadata())
4257+
.next()
4258+
.expect("the group should be the top layer of the artboard");
4259+
for insert_index in [0, 2] {
4260+
let moved = group.children(editor.active_document().metadata()).nth(1 - insert_index / 2).expect("the group should hold two layers");
4261+
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![moved.to_node()] }).await;
4262+
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: group, insert_index }).await;
4263+
4264+
for layer in group.children(editor.active_document().metadata()).chain([group]) {
4265+
assert_eq!(indent_below_parent(&editor, layer), Some(LAYER_INDENT_OFFSET), "moving a layer to index {insert_index} of the group");
4266+
}
4267+
}
4268+
assert_eq!(overlapping_layers(&editor), Vec::new());
4269+
}
4270+
4271+
#[tokio::test]
4272+
async fn releasing_a_drag_of_a_layer_in_a_stack_leaves_every_layer_where_the_drag_drew_it() {
4273+
let mut editor = EditorTestUtils::create();
4274+
editor.new_document().await;
4275+
editor.handle_message(new_artboard_message(NodeId::new())).await;
4276+
for x in [0., 50., 100., 150.] {
4277+
editor.draw_rect(x, 0., x + 40., 40.).await;
4278+
}
4279+
let artboard = LayerNodeIdentifier::ROOT_PARENT
4280+
.children(editor.active_document().metadata())
4281+
.next()
4282+
.expect("the artboard should be a layer");
4283+
let third = artboard.children(editor.active_document().metadata()).nth(2).expect("the artboard should hold four layers");
4284+
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third.to_node()] }).await;
4285+
4286+
let interface = &mut editor.active_document_mut().network_interface;
4287+
let layers: Vec<NodeId> = interface.document_network().nodes.keys().copied().filter(|node_id| interface.is_layer(node_id, &[])).collect();
4288+
for keep_upstream in [false, true] {
4289+
for offset in [IVec2::new(0, 3), IVec2::new(0, -2), IVec2::new(5, 0)] {
4290+
let before = interface.positions(layers.iter().copied(), &[]);
4291+
interface.drag_selected_nodes(offset, keep_upstream, &[]);
4292+
let dragging = interface.positions(layers.iter().copied(), &[]);
4293+
interface.finish_drag(&[]);
4294+
4295+
assert_ne!(dragging, before, "dragging by {offset} keeping upstream: {keep_upstream} should move the layers");
4296+
4297+
assert_eq!(interface.positions(layers.iter().copied(), &[]), dragging, "dragging by {offset} keeping upstream: {keep_upstream}");
4298+
}
4299+
}
4300+
}

‎editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,21 @@ pub enum NodeMetadataChange {
6262
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
6363
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
6464
NodeType(NodeTypePersistentMetadata),
65+
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
66+
Position(NodeTypePersistentMetadata),
6567
DisplayName(String),
6668
Locked(bool),
6769
Pinned(bool),
6870
}
6971

72+
impl NodeMetadataChange {
73+
/// The change from `before` to `after`, writing whether the node is a layer only when that changes.
74+
pub fn placement(before: &NodeTypePersistentMetadata, after: NodeTypePersistentMetadata) -> Self {
75+
let is_layer = |node_type: &NodeTypePersistentMetadata| matches!(node_type, NodeTypePersistentMetadata::Layer(_));
76+
if is_layer(before) == is_layer(&after) { Self::Position(after) } else { Self::NodeType(after) }
77+
}
78+
}
79+
7080
/// One field of a network's persistent metadata. The navigation transform and width are absent
7181
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
7282
#[derive(Debug, Clone, PartialEq)]
@@ -319,6 +329,10 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
319329
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
320330
]
321331
}
332+
NodeMetadataChange::Position(node_type) => vec![node_attribute(
333+
node_attr::ui::POSITION,
334+
Some(serialize_attribute(node_attr::ui::POSITION, &position_from_runtime(node_type))?),
335+
)],
322336
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
323337
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
324338
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],

‎editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
33
use super::storage_metadata::StorageMetadataView;
44
use super::{InputConnector, NodeTemplate};
55
use crate::test_utils::test_prelude::*;
6+
use document_graph_storage::attr::node as node_attr;
67
use document_graph_storage::delta::compute_deltas;
78
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
89
use graph_craft::document::value::TaggedValue;
@@ -184,7 +185,7 @@ async fn per_field_metadata_edits_match_the_diff() {
184185
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
185186
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
186187
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
187-
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
188+
metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
188189
EditorDelta::Graph(RuntimeDelta::SetVisibility {
189190
network: None,
190191
node_id: node,
@@ -283,6 +284,32 @@ async fn unchanged_writes_emit_nothing() {
283284
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
284285
}
285286

287+
#[tokio::test]
288+
async fn moving_a_layer_writes_only_its_position() {
289+
let mut editor = EditorTestUtils::create();
290+
editor.new_document().await;
291+
editor.draw_rect(0., 0., 40., 40.).await;
292+
let layer = LayerNodeIdentifier::ROOT_PARENT
293+
.children(editor.active_document().metadata())
294+
.next()
295+
.expect("the rectangle should be a layer")
296+
.to_node();
297+
298+
let working = convert(&editor);
299+
editor.active_document_mut().network_interface.discard_deltas();
300+
editor.active_document_mut().network_interface.shift_node(&layer, glam::IVec2::new(3, 5), &[]);
301+
302+
let emitted = committed_deltas(&mut editor);
303+
let written: Vec<String> = construct(&editor, &emitted, &working)
304+
.into_iter()
305+
.filter_map(|op| match op {
306+
RegistryDelta::ChangeNodeAttribute { delta, .. } => Some(delta.key),
307+
_ => None,
308+
})
309+
.collect();
310+
assert_eq!(written, [node_attr::ui::POSITION]);
311+
}
312+
286313
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
287314
/// without the caller saying anything about it.
288315
#[tokio::test]

‎editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,10 +1126,10 @@ impl NodeNetworkInterface {
11261126
}
11271127
}
11281128

1129-
let reconnected_offset = reconnect_to_input
1130-
.as_ref()
1131-
.and_then(NodeInput::as_node)
1132-
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?)));
1129+
let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
1130+
let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
1131+
Some((reconnected, offset))
1132+
});
11331133

11341134
let mut exports_fed_by_import = Vec::new();
11351135

‎editor/src/messages/portfolio/document/utility_types/network_interface/reconcile.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,10 @@ fn field_deltas(
328328
}
329329

330330
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
331-
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
331+
deltas.push(metadata(NodeMetadataChange::placement(
332+
&current_metadata.node_type_metadata,
333+
target_metadata.node_type_metadata.clone(),
334+
)));
332335
}
333336
if current_metadata.display_name != target_metadata.display_name {
334337
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));

‎editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -229,13 +229,14 @@ impl NodeMut<'_> {
229229

230230
/// Whether the node is displayed as a layer or a node, together with its position.
231231
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
232-
let changed = self.metadata.node_type_metadata != node_type;
233-
self.metadata.node_type_metadata = node_type;
234-
if changed {
235-
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
236-
self.deltas.metadata(change);
232+
if self.metadata.node_type_metadata == node_type {
233+
return false;
237234
}
238-
changed
235+
236+
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
237+
self.metadata.node_type_metadata = node_type;
238+
self.deltas.metadata(change);
239+
true
239240
}
240241

241242
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.

‎editor/src/messages/portfolio/document/utility_types/wires.rs‎

Lines changed: 43 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
22
use glam::{DVec2, IVec2};
33
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
4-
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape};
4+
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
55

66
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
77
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -125,23 +125,27 @@ fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -
125125
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
126126
}
127127

128-
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output
129-
/// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
130-
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath {
128+
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
129+
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
130+
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
131131
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
132132
return BezPath::new();
133133
}
134134

135-
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
136-
let sign = (input_position.y - output_position.y).signum();
137-
let output_trim = 1.5;
138-
let input_trim = 1.;
139-
let start = output_position + DVec2::new(0., output_trim * sign);
140-
let end = input_position - DVec2::new(0., input_trim * sign);
135+
let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style);
136+
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
137+
return BezPath::new();
138+
};
141139

140+
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
141+
let sign = (input_position.y - output_position.y).signum();
142142
let mut center_line = BezPath::new();
143-
center_line.move_to(dvec2_to_point(start));
144-
center_line.line_to(dvec2_to_point(end));
143+
center_line.move_to(start - Vec2::new(0., 1.5 * sign));
144+
center_line.line_to(start);
145+
for element in wire.elements().iter().skip(1) {
146+
center_line.push(*element);
147+
}
148+
center_line.line_to(end + Vec2::new(0., 2. * sign));
145149
center_line
146150
}
147151

@@ -580,7 +584,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
580584
#[cfg(test)]
581585
mod tests {
582586
use super::*;
583-
use kurbo::{Affine, Vec2};
587+
use kurbo::{Affine, ParamCurveNearest};
584588

585589
#[test]
586590
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
@@ -603,4 +607,30 @@ mod tests {
603607
}
604608
}
605609
}
610+
611+
#[test]
612+
fn the_center_line_of_a_stack_wire_runs_inside_it() {
613+
let ends = [
614+
(DVec2::new(48., 12.), DVec2::new(48., 84.)),
615+
(DVec2::new(240., 12.), DVec2::new(48., 132.)),
616+
(DVec2::new(48., 0.), DVec2::new(0., 27.)),
617+
];
618+
let half_wire_width = 4.;
619+
620+
for (output, input) in ends {
621+
for style in [GraphWireStyle::Direct, GraphWireStyle::GridAligned] {
622+
let wire = build_vector_wire(output, input, true, true, style);
623+
let center_line = build_thick_wire_center_line(output, input, true, true, style);
624+
625+
let samples = center_line.segments().flat_map(|segment| (0..=10).map(move |step| segment.eval(f64::from(step) / 10.)));
626+
for sample in samples {
627+
let distance = wire
628+
.segments()
629+
.map(|segment| segment.nearest(sample, DEFAULT_ACCURACY).distance_sq.sqrt())
630+
.fold(f64::INFINITY, f64::min);
631+
assert!(distance <= half_wire_width, "the center line from {output} to {input} drawn {style:?} leaves its wire at {sample:?}");
632+
}
633+
}
634+
}
635+
}
606636
}

0 commit comments

Comments
 (0)