Skip to main content

leptos_node_graph/
registry.rs

1use std::collections::{HashMap, HashSet};
2
3use leptos::prelude::*;
4
5use crate::types::*;
6
7/// Entry for a registered node.
8#[derive(Clone)]
9pub struct NodeEntry<N: NodeId> {
10    pub id: N,
11    pub position: Position,
12    pub size: Size,
13    /// The consumer's position signal — updated during drag for live visual feedback.
14    pub position_signal: Option<RwSignal<Position>>,
15}
16
17/// Entry for a registered port.
18#[derive(Clone, Debug)]
19pub struct PortEntry<N: NodeId, P: PortId, T: PortType> {
20    pub id: P,
21    pub node_id: N,
22    pub direction: PortDirection,
23    pub port_type: T,
24    pub position: Position,
25    /// Index of this port among its node's ports of the same direction.
26    pub slot_index: usize,
27    /// Cached offset from node position. Set by the anchor's first DOM measurement.
28    pub offset: Option<Position>,
29}
30
31/// A connection between two ports.
32#[derive(Clone, Debug)]
33pub struct ConnectionEntry<P: PortId, C: ConnectionId> {
34    pub id: C,
35    pub source: P,
36    pub target: P,
37}
38
39/// Box select state.
40#[derive(Clone, Debug)]
41pub struct BoxSelect {
42    pub start: Position,
43    pub current: Position,
44    /// Alt-dragging an empty canvas creates a group from the enclosed nodes.
45    pub create_group: bool,
46}
47
48impl BoxSelect {
49    /// Compute the axis-aligned bounding rectangle from start and current positions.
50    pub fn to_rect(&self) -> Rect {
51        let min_x = self.start.x.min(self.current.x);
52        let min_y = self.start.y.min(self.current.y);
53        let max_x = self.start.x.max(self.current.x);
54        let max_y = self.start.y.max(self.current.y);
55        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
56    }
57}
58
59/// Drag state for node dragging.
60#[derive(Clone, Debug)]
61pub struct DragState<N: NodeId> {
62    pub node_id: N,
63    pub offset: Position,
64    pub start_positions: HashMap<N, Position>,
65    /// Whether Alt has activated group transfer for this drag.
66    ///
67    /// This is latched once Alt is pressed, including after pointer-down, so
68    /// releasing the modifier before mouse-up does not cancel the transfer.
69    pub alt_key: bool,
70}
71
72/// Width-resize state for one node. Started by that node's right-edge handle,
73/// driven by the document-level mousemove, cleared on mouseup.
74#[derive(Clone)]
75pub struct ResizeState<N: NodeId> {
76    pub node_id: N,
77    /// Canvas-space x where the gesture started.
78    pub start_x: f64,
79    /// The node's rendered width when the gesture started.
80    pub start_width: f64,
81    /// The node's width signal — written live so the node re-renders as it drags.
82    pub width_signal: RwSignal<Option<f64>>,
83    /// Clamp bounds, resolved from the theme when the gesture started.
84    pub min_width: f64,
85    pub max_width: Option<f64>,
86}
87
88/// The central reactive state store.
89#[derive(Clone)]
90pub struct EditorRegistry<N, P, C, T>
91where
92    N: NodeId,
93    P: PortId,
94    C: ConnectionId,
95    T: PortType,
96{
97    pub nodes: RwSignal<HashMap<N, NodeEntry<N>>>,
98    /// Live positions written by the drag RAF, independent of persisted state.
99    pub live_positions: RwSignal<HashMap<N, Position>>,
100    pub ports: RwSignal<HashMap<P, PortEntry<N, P, T>>>,
101    pub connections: RwSignal<HashMap<C, ConnectionEntry<P, C>>>,
102    pub selected_nodes: RwSignal<HashSet<N>>,
103    pub selected_connections: RwSignal<HashSet<C>>,
104    pub draft_connection: RwSignal<Option<DraftConnection<P, T>>>,
105    pub viewport: RwSignal<ViewportTransform>,
106    /// A DEBOUNCED mirror of `viewport`, updated only after pan/zoom settles.
107    /// `NodeVisible` reads this (not the live `viewport`) so visibility — and thus
108    /// the create/dispose of off-screen node content — never churns mid-pan (the
109    /// live viewport still drives the smooth CSS transform every frame).
110    pub visibility_viewport: RwSignal<ViewportTransform>,
111    /// Measured pixel size of the editor container (screen space). Written by the
112    /// editor; read by nodes to compute their viewport visibility (`NodeVisible`).
113    pub container_size: RwSignal<Size>,
114    pub config: RwSignal<EditorConfig>,
115    pub on_event: StoredValue<Callback<GraphEvent<N, P, C>>>,
116    pub box_select: RwSignal<Option<BoxSelect>>,
117    /// Whether THIS editor instance is mid-pan. Set by the container's mousedown
118    /// (so it's scoped to the pressed graph) and checked by the document-level
119    /// mousemove — without it, a pan would move every open graph at once, since the
120    /// move listener is global.
121    pub is_panning: RwSignal<bool>,
122    /// Client-space pointer position from the previous pan frame.
123    ///
124    /// Pan deltas are measured against this rather than taken from
125    /// `MouseEvent.movementX/Y`: Chrome reports those in PHYSICAL device pixels
126    /// while `clientX/Y` are CSS pixels, so on a HiDPI screen (or with page
127    /// zoom) `movementX` overstates the cursor's travel by the device pixel
128    /// ratio and the canvas slides faster than the mouse.
129    pub pan_origin: RwSignal<Option<Position>>,
130    /// Whether the node-creation menu is open on this editor.
131    ///
132    /// Mirrored from the menu's own `open_at` signal so the interaction handlers
133    /// can see it: an open menu takes ownership of the in-flight draft, and a
134    /// mouseup that would otherwise cancel the draft has to leave it alone.
135    pub menu_open: RwSignal<bool>,
136    pub drag_state: RwSignal<Option<DragState<N>>>,
137    /// In-flight node width resize, if any.
138    pub resize_state: RwSignal<Option<ResizeState<N>>>,
139    /// Pending drag canvas position — written by mousemove, applied by RAF.
140    pub pending_drag_pos: RwSignal<Option<Position>>,
141    /// Whether a RAF callback is already scheduled for drag.
142    pub drag_raf_pending: RwSignal<bool>,
143}
144
145impl<N, P, C, T> EditorRegistry<N, P, C, T>
146where
147    N: NodeId,
148    P: PortId,
149    C: ConnectionId,
150    T: PortType,
151{
152    /// Create a new registry with the given configuration and event callback.
153    pub fn new(config: EditorConfig, on_event: Callback<GraphEvent<N, P, C>>) -> Self {
154        Self {
155            nodes: RwSignal::new(HashMap::new()),
156            live_positions: RwSignal::new(HashMap::new()),
157            ports: RwSignal::new(HashMap::new()),
158            connections: RwSignal::new(HashMap::new()),
159            selected_nodes: RwSignal::new(HashSet::new()),
160            selected_connections: RwSignal::new(HashSet::new()),
161            draft_connection: RwSignal::new(None),
162            viewport: RwSignal::new(ViewportTransform::default()),
163            visibility_viewport: RwSignal::new(ViewportTransform::default()),
164            container_size: RwSignal::new(Size::default()),
165            config: RwSignal::new(config),
166            on_event: StoredValue::new(on_event),
167            box_select: RwSignal::new(None),
168            is_panning: RwSignal::new(false),
169            pan_origin: RwSignal::new(None),
170            menu_open: RwSignal::new(false),
171            drag_state: RwSignal::new(None),
172            resize_state: RwSignal::new(None),
173            pending_drag_pos: RwSignal::new(None),
174            drag_raf_pending: RwSignal::new(false),
175        }
176    }
177
178    /// Emit an event through the on_event callback.
179    pub fn emit(&self, event: GraphEvent<N, P, C>) {
180        self.on_event.with_value(|cb| cb.run(event));
181    }
182
183    /// Register a node at the given position.
184    pub fn register_node(
185        &self,
186        id: N,
187        position: Position,
188        position_signal: Option<RwSignal<Position>>,
189    ) {
190        self.nodes.update(|nodes| {
191            nodes.insert(
192                id.clone(),
193                NodeEntry {
194                    id: id.clone(),
195                    position,
196                    size: Size::default(),
197                    position_signal,
198                },
199            );
200        });
201        self.live_positions.update(|positions| {
202            positions.insert(id, position);
203        });
204    }
205
206    /// Deregister a node, cascading removal of its ports and their connections.
207    pub fn deregister_node(&self, id: &N) {
208        // Collect ports belonging to this node.
209        let port_ids: Vec<P> = self.ports.with_untracked(|ports| {
210            ports
211                .values()
212                .filter(|entry| &entry.node_id == id)
213                .map(|entry| entry.id.clone())
214                .collect()
215        });
216
217        // Deregister each port (which also removes its connections).
218        for port_id in port_ids {
219            self.deregister_port(&port_id);
220        }
221
222        self.nodes.update(|nodes| {
223            nodes.remove(id);
224        });
225        self.live_positions.update(|positions| {
226            positions.remove(id);
227        });
228
229        self.selected_nodes.update(|sel| {
230            sel.remove(id);
231        });
232    }
233
234    /// Register a port. Invalidates cached offsets for all sibling ports on the same node
235    /// since the new port may shift their visual positions.
236    pub fn register_port(
237        &self,
238        id: P,
239        node_id: N,
240        direction: PortDirection,
241        port_type: T,
242        position: Position,
243    ) {
244        self.ports.update(|ports| {
245            // New port gets the next index for this node+direction
246            let next_idx = ports
247                .values()
248                .filter(|p| p.node_id == node_id && p.direction == direction)
249                .count();
250
251            // Invalidate offsets for existing sibling ports (positions may shift)
252            for entry in ports.values_mut() {
253                if entry.node_id == node_id {
254                    entry.offset = None;
255                }
256            }
257
258            ports.insert(
259                id.clone(),
260                PortEntry {
261                    id,
262                    node_id,
263                    direction,
264                    port_type,
265                    position,
266                    slot_index: next_idx,
267                    offset: None,
268                },
269            );
270        });
271    }
272
273    /// Deregister a port. Connections referencing this port are kept in the
274    /// consumer's data but not rendered (the connection renderer skips connections
275    /// with missing ports). This allows connections to restore if the port reappears.
276    pub fn deregister_port(&self, id: &P) {
277        // Get the node_id and direction before removing
278        let port_info = self
279            .ports
280            .with_untracked(|ports| ports.get(id).map(|p| (p.node_id.clone(), p.direction)));
281
282        self.ports.update(|ports| {
283            ports.remove(id);
284
285            // Reindex siblings preserving their original order
286            if let Some((node_id, direction)) = &port_info {
287                let mut siblings: Vec<(usize, P)> = ports
288                    .values()
289                    .filter(|p| &p.node_id == node_id && p.direction == *direction)
290                    .map(|p| (p.slot_index, p.id.clone()))
291                    .collect();
292                siblings.sort_by_key(|(idx, _)| *idx);
293
294                for (new_idx, (_, port_id)) in siblings.into_iter().enumerate() {
295                    if let Some(entry) = ports.get_mut(&port_id) {
296                        entry.slot_index = new_idx;
297                        entry.offset = None;
298                    }
299                }
300            }
301        });
302    }
303
304    /// Update a node's position.
305    pub fn set_node_position(&self, id: &N, position: Position) {
306        self.nodes.maybe_update(|nodes| {
307            let Some(entry) = nodes.get_mut(id) else {
308                return false;
309            };
310            if entry.position == position {
311                return false;
312            }
313            entry.position = position;
314            true
315        });
316        self.live_positions.update(|positions| {
317            positions.insert(id.clone(), position);
318        });
319    }
320
321    /// Update a node's position and its consumer signal. Used during drag for live feedback.
322    pub fn set_node_position_with_signal(&self, id: &N, position: Position) {
323        let mut signal = None;
324        self.nodes.maybe_update(|nodes| {
325            let Some(entry) = nodes.get_mut(id) else {
326                return false;
327            };
328            signal = entry.position_signal;
329            if entry.position == position {
330                return false;
331            }
332            entry.position = position;
333            true
334        });
335        if let Some(signal) = signal
336            && signal.get_untracked() != position
337        {
338            signal.set(position);
339        }
340        self.live_positions.update(|positions| {
341            positions.insert(id.clone(), position);
342        });
343    }
344
345    /// Batch-update positions for multiple nodes during drag.
346    /// Updates node entries, port positions (via cached offsets), and position signals.
347    /// Each map notifies at most once, and only when at least one value changed.
348    pub fn batch_set_positions(&self, updates: &[(N, Position)]) {
349        // 1. Update node entries and collect only consumer signals that changed.
350        let mut node_signals = Vec::new();
351        let mut node_moves = HashMap::new();
352        self.nodes.maybe_update(|nodes| {
353            let mut changed = false;
354            for (id, position) in updates {
355                let Some(entry) = nodes.get_mut(id) else {
356                    continue;
357                };
358                if entry.position == *position {
359                    if let Some(signal) = entry.position_signal
360                        && signal.get_untracked() != *position
361                    {
362                        node_signals.push((signal, *position));
363                    }
364                    continue;
365                }
366                let delta =
367                    Position::new(position.x - entry.position.x, position.y - entry.position.y);
368                entry.position = *position;
369                node_moves.insert(id.clone(), (*position, delta));
370                if let Some(signal) = entry.position_signal {
371                    node_signals.push((signal, *position));
372                }
373                changed = true;
374            }
375            changed
376        });
377        // 2. Batch-update port positions. Measured ports use their exact cached
378        // offset; dynamic siblings whose offset was invalidated still follow
379        // the node by translating their last known absolute position.
380        self.ports.maybe_update(|ports| {
381            let mut changed = false;
382            for entry in ports.values_mut() {
383                let Some((new_node_position, delta)) = node_moves.get(&entry.node_id) else {
384                    continue;
385                };
386                let position = match entry.offset {
387                    Some(offset) => Position::new(
388                        new_node_position.x + offset.x,
389                        new_node_position.y + offset.y,
390                    ),
391                    None => Position::new(entry.position.x + delta.x, entry.position.y + delta.y),
392                };
393                if entry.position != position {
394                    entry.position = position;
395                    changed = true;
396                }
397            }
398            changed
399        });
400
401        // 3. Set position signals (drives CSS node positioning via style=).
402        for (signal, position) in node_signals {
403            if signal.get_untracked() != position {
404                signal.set(position);
405            }
406        }
407        self.live_positions.update(|positions| {
408            for (id, position) in updates {
409                positions.insert(id.clone(), *position);
410            }
411        });
412    }
413
414    /// Update a node's size.
415    pub fn set_node_size(&self, id: &N, size: Size) {
416        self.nodes.maybe_update(|nodes| {
417            let Some(entry) = nodes.get_mut(id) else {
418                return false;
419            };
420            if entry.size == size {
421                return false;
422            }
423            entry.size = size;
424            true
425        });
426    }
427
428    /// Update a port's absolute canvas-space position.
429    pub fn set_port_position(&self, id: &P, position: Position) {
430        self.ports.maybe_update(|ports| {
431            let Some(entry) = ports.get_mut(id) else {
432                return false;
433            };
434            if entry.position == position {
435                return false;
436            }
437            entry.position = position;
438            true
439        });
440    }
441
442    /// Set a port's cached offset from its node position.
443    pub fn set_port_offset(&self, id: &P, offset: Position) {
444        let mut guard = self.ports.write_untracked();
445        if let Some(entry) = guard.get_mut(id) {
446            entry.offset = Some(offset);
447        }
448    }
449
450    /// Replace the entire connections map (used by the consumer to sync state).
451    pub fn set_connections(&self, connections: HashMap<C, ConnectionEntry<P, C>>) {
452        self.connections.set(connections);
453    }
454
455    /// Get a port's position (untracked read).
456    pub fn port_position(&self, id: &P) -> Option<Position> {
457        self.ports
458            .with_untracked(|ports| ports.get(id).map(|e| e.position))
459    }
460
461    /// Get a clone of a port entry (untracked read).
462    pub fn get_port(&self, id: &P) -> Option<PortEntry<N, P, T>> {
463        self.ports.with_untracked(|ports| ports.get(id).cloned())
464    }
465
466    /// Check if a target port is compatible with the current draft connection.
467    ///
468    /// Requirements:
469    /// - Target must be an Input port.
470    /// - Target must not belong to the same node as the source.
471    /// - The port types must be compatible via `PortType::compatible`.
472    pub fn is_compatible_target(&self, target_id: &P) -> bool {
473        let draft = self.draft_connection.with_untracked(|d| d.clone());
474        let Some(draft) = draft else {
475            return false;
476        };
477
478        self.ports.with_untracked(|ports| {
479            let Some(target) = ports.get(target_id) else {
480                return false;
481            };
482
483            if target.direction != PortDirection::Input {
484                return false;
485            }
486
487            // Source port must exist and belong to a different node.
488            let Some(source) = ports.get(&draft.source_port) else {
489                return false;
490            };
491
492            if source.node_id == target.node_id {
493                return false;
494            }
495
496            T::compatible(&draft.port_type, &target.port_type)
497        })
498    }
499
500    /// Select a single node, clearing all other selections.
501    pub fn select_node(&self, id: N) {
502        self.selected_connections.update(|sel| sel.clear());
503        self.selected_nodes.update(|sel| {
504            sel.clear();
505            sel.insert(id);
506        });
507    }
508
509    /// Toggle a node's selection state (for shift+click).
510    pub fn toggle_node_selection(&self, id: N) {
511        self.selected_nodes.update(|sel| {
512            if !sel.remove(&id) {
513                sel.insert(id);
514            }
515        });
516    }
517
518    /// Select a single connection, clearing all other selections.
519    pub fn select_connection(&self, id: C) {
520        self.selected_nodes.update(|sel| sel.clear());
521        self.selected_connections.update(|sel| {
522            sel.clear();
523            sel.insert(id);
524        });
525    }
526
527    /// Clear all selections.
528    pub fn clear_selection(&self) {
529        self.selected_nodes.update(|sel| sel.clear());
530        self.selected_connections.update(|sel| sel.clear());
531    }
532
533    /// Select all nodes.
534    pub fn select_all(&self) {
535        let all_ids: HashSet<N> = self
536            .nodes
537            .with_untracked(|nodes| nodes.keys().cloned().collect());
538        self.selected_nodes.set(all_ids);
539    }
540
541    /// Emit deletion events for all selected items.
542    pub fn delete_selected(&self) {
543        let selected_node_ids: Vec<N> = self
544            .selected_nodes
545            .with_untracked(|sel| sel.iter().cloned().collect());
546
547        let selected_conn_ids: Vec<C> = self
548            .selected_connections
549            .with_untracked(|sel| sel.iter().cloned().collect());
550
551        // Emit connection removals first.
552        for conn_id in selected_conn_ids {
553            self.emit(GraphEvent::ConnectionRemoved { id: conn_id });
554        }
555
556        // Emit node deletions.
557        if !selected_node_ids.is_empty() {
558            self.emit(GraphEvent::NodesDeleted {
559                ids: selected_node_ids,
560            });
561        }
562    }
563
564    /// Return the set of node IDs whose bounding rectangles intersect the given rect.
565    /// The compatible port nearest `cursor` within `max_dist` (canvas units),
566    /// for the draft currently in flight.
567    ///
568    /// Applies exactly the rules a real connection would — opposite direction,
569    /// different node, type-compatible — so the wire can never snap to a port
570    /// that would refuse the connection on release.
571    pub fn snap_target_for_draft(&self, cursor: Position, max_dist: f64) -> Option<(P, Position)> {
572        let draft = self.draft_connection.with_untracked(|d| d.clone())?;
573        let source = self.get_port(&draft.source_port)?;
574
575        let mut best: Option<(P, Position, f64)> = None;
576        self.ports.with_untracked(|ports| {
577            for entry in ports.values() {
578                if entry.direction == draft.origin_direction || entry.node_id == source.node_id {
579                    continue;
580                }
581                let (output_type, input_type) = if draft.origin_direction == PortDirection::Output {
582                    (&source.port_type, &entry.port_type)
583                } else {
584                    (&entry.port_type, &source.port_type)
585                };
586                if !T::compatible(output_type, input_type) {
587                    continue;
588                }
589                let dist = crate::utils::distance(cursor, entry.position);
590                if dist <= max_dist && best.as_ref().is_none_or(|(_, _, b)| dist < *b) {
591                    best = Some((entry.id.clone(), entry.position, dist));
592                }
593            }
594        });
595        best.map(|(id, pos, _)| (id, pos))
596    }
597
598    /// Bounding box of every registered node, in canvas space. `None` when the
599    /// graph is empty.
600    pub fn nodes_bounds(&self) -> Option<Rect> {
601        self.nodes.with_untracked(|nodes| {
602            let mut entries = nodes.values();
603            let first = entries.next()?;
604            let (mut min_x, mut min_y) = (first.position.x, first.position.y);
605            let mut max_x = first.position.x + first.size.width;
606            let mut max_y = first.position.y + first.size.height;
607            for entry in entries {
608                min_x = min_x.min(entry.position.x);
609                min_y = min_y.min(entry.position.y);
610                max_x = max_x.max(entry.position.x + entry.size.width);
611                max_y = max_y.max(entry.position.y + entry.size.height);
612            }
613            Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
614        })
615    }
616
617    /// Pan and zoom so `rect` (canvas space) is centered and fits the container,
618    /// inset by `padding` screen pixels. Zoom is clamped to the config's range,
619    /// and additionally to `max_zoom_override` when given — framing uses that to
620    /// avoid magnifying a small graph.
621    ///
622    /// No-op until the container has been measured.
623    pub fn fit_rect(&self, rect: &Rect, padding: f64, max_zoom_override: Option<f64>) {
624        let container = self.container_size.get_untracked();
625        if container.width <= 0.0 || container.height <= 0.0 {
626            return;
627        }
628
629        // A single zero-size node would otherwise divide by zero.
630        let width = rect.size.width.max(1.0);
631        let height = rect.size.height.max(1.0);
632        let avail_w = (container.width - 2.0 * padding).max(1.0);
633        let avail_h = (container.height - 2.0 * padding).max(1.0);
634
635        let (min_zoom, max_zoom) = self.config.with_untracked(|c| (c.min_zoom, c.max_zoom));
636        let ceiling = max_zoom_override.map_or(max_zoom, |m| m.min(max_zoom));
637        let zoom = (avail_w / width)
638            .min(avail_h / height)
639            .clamp(min_zoom, ceiling.max(min_zoom));
640
641        let center_x = rect.position.x + width / 2.0;
642        let center_y = rect.position.y + height / 2.0;
643        self.viewport.update(|vp| {
644            vp.zoom = zoom;
645            vp.pan_x = container.width / 2.0 - center_x * zoom;
646            vp.pan_y = container.height / 2.0 - center_y * zoom;
647        });
648    }
649
650    /// Frame the whole graph — the `F` hotkey. No-op on an empty graph.
651    pub fn fit_view(&self) {
652        let Some(bounds) = self.nodes_bounds() else {
653            return;
654        };
655        let (padding, fit_max_zoom) = self
656            .config
657            .with_untracked(|c| (c.fit_padding, c.fit_max_zoom));
658        self.fit_rect(&bounds, padding, Some(fit_max_zoom));
659    }
660
661    pub fn nodes_in_rect(&self, rect: &Rect) -> HashSet<N> {
662        self.nodes.with_untracked(|nodes| {
663            nodes
664                .values()
665                .filter(|entry| {
666                    let node_rect = Rect::new(
667                        entry.position.x,
668                        entry.position.y,
669                        entry.size.width,
670                        entry.size.height,
671                    );
672                    rect.intersects(&node_rect)
673                })
674                .map(|entry| entry.id.clone())
675                .collect()
676        })
677    }
678}
679
680#[cfg(test)]
681mod tests {
682    use std::sync::Arc;
683    use std::sync::atomic::{AtomicUsize, Ordering};
684
685    use super::*;
686
687    #[derive(Clone, Debug, PartialEq)]
688    enum TestPortType {
689        Any,
690    }
691
692    impl PortType for TestPortType {
693        fn compatible(_: &Self, _: &Self) -> bool {
694            true
695        }
696
697        fn type_id(&self) -> String {
698            "any".into()
699        }
700
701        fn from_type_id(_: &str) -> Self {
702            Self::Any
703        }
704    }
705
706    #[test]
707    fn geometry_writes_gate_noops_and_translate_offsetless_ports() {
708        Owner::new().with(|| {
709            let registry = EditorRegistry::<String, String, String, TestPortType>::new(
710                EditorConfig::default(),
711                Callback::new(|_: GraphEvent<String, String, String>| {}),
712            );
713            let position = Position::new(10.0, 20.0);
714            let position_signal = RwSignal::new(position);
715            let node_id = "node".to_string();
716            let port_id = "port".to_string();
717            let dynamic_port_id = "dynamic-port".to_string();
718            registry.register_node(node_id.clone(), position, Some(position_signal));
719            registry.register_port(
720                port_id.clone(),
721                node_id.clone(),
722                PortDirection::Output,
723                TestPortType::Any,
724                Position::new(30.0, 25.0),
725            );
726            registry.register_port(
727                dynamic_port_id.clone(),
728                node_id.clone(),
729                PortDirection::Output,
730                TestPortType::Any,
731                Position::new(50.0, 60.0),
732            );
733            registry.set_port_offset(&port_id, Position::new(20.0, 5.0));
734
735            let node_reads = Arc::new(AtomicUsize::new(0));
736            let node_reads_memo = Arc::clone(&node_reads);
737            let nodes = registry.nodes;
738            let node_geometry = Memo::new(move |_| {
739                node_reads_memo.fetch_add(1, Ordering::Relaxed);
740                nodes.with(|nodes| nodes.get("node").map(|node| (node.position, node.size)))
741            });
742
743            let port_reads = Arc::new(AtomicUsize::new(0));
744            let port_reads_memo = Arc::clone(&port_reads);
745            let ports = registry.ports;
746            let port_geometry = Memo::new(move |_| {
747                port_reads_memo.fetch_add(1, Ordering::Relaxed);
748                ports.with(|ports| {
749                    Some((
750                        ports.get("port")?.position,
751                        ports.get("dynamic-port")?.position,
752                    ))
753                })
754            });
755
756            assert!(node_geometry.get().is_some());
757            assert!(port_geometry.get().is_some());
758            registry.set_node_position(&node_id, position);
759            registry.set_node_position_with_signal(&node_id, position);
760            registry.set_node_size(&node_id, Size::default());
761            registry.set_port_position(&port_id, Position::new(30.0, 25.0));
762            registry.batch_set_positions(&[("node".into(), position)]);
763            assert!(node_geometry.get().is_some());
764            assert!(port_geometry.get().is_some());
765
766            assert_eq!(node_reads.load(Ordering::Relaxed), 1);
767            assert_eq!(port_reads.load(Ordering::Relaxed), 1);
768
769            let moved = Position::new(20.0, 30.0);
770            registry.batch_set_positions(&[(node_id.clone(), moved)]);
771            assert_eq!(node_geometry.get(), Some((moved, Size::default())));
772            assert_eq!(
773                port_geometry.get(),
774                Some((Position::new(40.0, 35.0), Position::new(60.0, 70.0)))
775            );
776            assert_eq!(position_signal.get_untracked(), moved);
777            assert_eq!(node_reads.load(Ordering::Relaxed), 2);
778            assert_eq!(port_reads.load(Ordering::Relaxed), 2);
779        });
780    }
781}