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    pending_port_measurements: StoredValue<HashMap<P, (Position, Position)>>,
102    port_measurement_pending: StoredValue<bool>,
103    pub connections: RwSignal<HashMap<C, ConnectionEntry<P, C>>>,
104    pub selected_nodes: RwSignal<HashSet<N>>,
105    pub selected_connections: RwSignal<HashSet<C>>,
106    pub draft_connection: RwSignal<Option<DraftConnection<P, T>>>,
107    /// Stable gesture identity; pointer movement does not invalidate anchor styling.
108    pub draft_origin: Memo<Option<(P, PortDirection)>>,
109    pub viewport: RwSignal<ViewportTransform>,
110    /// A DEBOUNCED mirror of `viewport`, updated only after pan/zoom settles.
111    /// `NodeVisible` reads this (not the live `viewport`) so visibility — and thus
112    /// the create/dispose of off-screen node content — never churns mid-pan (the
113    /// live viewport still drives the smooth CSS transform every frame).
114    pub visibility_viewport: RwSignal<ViewportTransform>,
115    /// Measured pixel size of the editor container (screen space). Written by the
116    /// editor; read by nodes to compute their viewport visibility (`NodeVisible`).
117    pub container_size: RwSignal<Size>,
118    pub config: RwSignal<EditorConfig>,
119    pub on_event: StoredValue<Callback<GraphEvent<N, P, C>>>,
120    pub box_select: RwSignal<Option<BoxSelect>>,
121    /// Whether THIS editor instance is mid-pan. Set by the container's mousedown
122    /// (so it's scoped to the pressed graph) and checked by the document-level
123    /// mousemove — without it, a pan would move every open graph at once, since the
124    /// move listener is global.
125    pub is_panning: RwSignal<bool>,
126    /// Client-space pointer position from the previous pan frame.
127    ///
128    /// Pan deltas are measured against this rather than taken from
129    /// `MouseEvent.movementX/Y`: Chrome reports those in PHYSICAL device pixels
130    /// while `clientX/Y` are CSS pixels, so on a HiDPI screen (or with page
131    /// zoom) `movementX` overstates the cursor's travel by the device pixel
132    /// ratio and the canvas slides faster than the mouse.
133    pub pan_origin: RwSignal<Option<Position>>,
134    /// Whether the node-creation menu is open on this editor.
135    ///
136    /// Mirrored from the menu's own `open_at` signal so the interaction handlers
137    /// can see it: an open menu takes ownership of the in-flight draft, and a
138    /// mouseup that would otherwise cancel the draft has to leave it alone.
139    pub menu_open: RwSignal<bool>,
140    pub drag_state: RwSignal<Option<DragState<N>>>,
141    /// In-flight node width resize, if any.
142    pub resize_state: RwSignal<Option<ResizeState<N>>>,
143    /// Pending drag canvas position — written by mousemove, applied by RAF.
144    pub pending_drag_pos: RwSignal<Option<Position>>,
145    /// Whether a RAF callback is already scheduled for drag.
146    pub drag_raf_pending: RwSignal<bool>,
147}
148
149impl<N, P, C, T> EditorRegistry<N, P, C, T>
150where
151    N: NodeId,
152    P: PortId,
153    C: ConnectionId,
154    T: PortType,
155{
156    /// Create a new registry with the given configuration and event callback.
157    pub fn new(config: EditorConfig, on_event: Callback<GraphEvent<N, P, C>>) -> Self {
158        let draft_connection: RwSignal<Option<DraftConnection<P, T>>> = RwSignal::new(None);
159        let draft_origin = Memo::new(move |_| {
160            draft_connection.with(|draft| {
161                draft
162                    .as_ref()
163                    .map(|draft| (draft.source_port.clone(), draft.origin_direction))
164            })
165        });
166        Self {
167            nodes: RwSignal::new(HashMap::new()),
168            live_positions: RwSignal::new(HashMap::new()),
169            ports: RwSignal::new(HashMap::new()),
170            pending_port_measurements: StoredValue::new(HashMap::new()),
171            port_measurement_pending: StoredValue::new(false),
172            connections: RwSignal::new(HashMap::new()),
173            selected_nodes: RwSignal::new(HashSet::new()),
174            selected_connections: RwSignal::new(HashSet::new()),
175            draft_connection,
176            draft_origin,
177            viewport: RwSignal::new(ViewportTransform::default()),
178            visibility_viewport: RwSignal::new(ViewportTransform::default()),
179            container_size: RwSignal::new(Size::default()),
180            config: RwSignal::new(config),
181            on_event: StoredValue::new(on_event),
182            box_select: RwSignal::new(None),
183            is_panning: RwSignal::new(false),
184            pan_origin: RwSignal::new(None),
185            menu_open: RwSignal::new(false),
186            drag_state: RwSignal::new(None),
187            resize_state: RwSignal::new(None),
188            pending_drag_pos: RwSignal::new(None),
189            drag_raf_pending: RwSignal::new(false),
190        }
191    }
192
193    /// Emit an event through the on_event callback.
194    pub fn emit(&self, event: GraphEvent<N, P, C>) {
195        self.on_event.with_value(|cb| cb.run(event));
196    }
197
198    /// Register a node at the given position.
199    pub fn register_node(
200        &self,
201        id: N,
202        position: Position,
203        position_signal: Option<RwSignal<Position>>,
204    ) {
205        self.nodes.update(|nodes| {
206            nodes.insert(
207                id.clone(),
208                NodeEntry {
209                    id: id.clone(),
210                    position,
211                    size: Size::default(),
212                    position_signal,
213                },
214            );
215        });
216        self.live_positions.update(|positions| {
217            positions.insert(id, position);
218        });
219    }
220
221    /// Deregister a node, cascading removal of its ports and their connections.
222    pub fn deregister_node(&self, id: &N) {
223        // Collect ports belonging to this node.
224        let port_ids: Vec<P> = self.ports.with_untracked(|ports| {
225            ports
226                .values()
227                .filter(|entry| &entry.node_id == id)
228                .map(|entry| entry.id.clone())
229                .collect()
230        });
231
232        // Deregister each port (which also removes its connections).
233        for port_id in port_ids {
234            self.deregister_port(&port_id);
235        }
236
237        self.nodes.update(|nodes| {
238            nodes.remove(id);
239        });
240        self.live_positions.update(|positions| {
241            positions.remove(id);
242        });
243
244        self.selected_nodes.update(|sel| {
245            sel.remove(id);
246        });
247    }
248
249    /// Register a port. Invalidates cached offsets for all sibling ports on the same node
250    /// since the new port may shift their visual positions.
251    pub fn register_port(
252        &self,
253        id: P,
254        node_id: N,
255        direction: PortDirection,
256        port_type: T,
257        position: Position,
258    ) {
259        self.ports.update(|ports| {
260            // New port gets the next index for this node+direction
261            let next_idx = ports
262                .values()
263                .filter(|p| p.node_id == node_id && p.direction == direction)
264                .count();
265
266            // Invalidate offsets for existing sibling ports (positions may shift)
267            for entry in ports.values_mut() {
268                if entry.node_id == node_id {
269                    entry.offset = None;
270                }
271            }
272
273            ports.insert(
274                id.clone(),
275                PortEntry {
276                    id,
277                    node_id,
278                    direction,
279                    port_type,
280                    position,
281                    slot_index: next_idx,
282                    offset: None,
283                },
284            );
285        });
286    }
287
288    /// Deregister a port. Connections referencing this port are kept in the
289    /// consumer's data but not rendered (the connection renderer skips connections
290    /// with missing ports). This allows connections to restore if the port reappears.
291    pub fn deregister_port(&self, id: &P) {
292        self.pending_port_measurements.update_value(|updates| {
293            updates.remove(id);
294        });
295        // Get the node_id and direction before removing
296        let port_info = self
297            .ports
298            .with_untracked(|ports| ports.get(id).map(|p| (p.node_id.clone(), p.direction)));
299
300        self.ports.update(|ports| {
301            ports.remove(id);
302
303            // Reindex siblings preserving their original order
304            if let Some((node_id, direction)) = &port_info {
305                let mut siblings: Vec<(usize, P)> = ports
306                    .values()
307                    .filter(|p| &p.node_id == node_id && p.direction == *direction)
308                    .map(|p| (p.slot_index, p.id.clone()))
309                    .collect();
310                siblings.sort_by_key(|(idx, _)| *idx);
311
312                for (new_idx, (_, port_id)) in siblings.into_iter().enumerate() {
313                    if let Some(entry) = ports.get_mut(&port_id) {
314                        entry.slot_index = new_idx;
315                        entry.offset = None;
316                    }
317                }
318            }
319        });
320    }
321
322    /// Update a node's position.
323    pub fn set_node_position(&self, id: &N, position: Position) {
324        self.nodes.maybe_update(|nodes| {
325            let Some(entry) = nodes.get_mut(id) else {
326                return false;
327            };
328            if entry.position == position {
329                return false;
330            }
331            entry.position = position;
332            true
333        });
334        self.live_positions.update(|positions| {
335            positions.insert(id.clone(), position);
336        });
337    }
338
339    /// Update a node's position and its consumer signal. Used during drag for live feedback.
340    pub fn set_node_position_with_signal(&self, id: &N, position: Position) {
341        let mut signal = None;
342        self.nodes.maybe_update(|nodes| {
343            let Some(entry) = nodes.get_mut(id) else {
344                return false;
345            };
346            signal = entry.position_signal;
347            if entry.position == position {
348                return false;
349            }
350            entry.position = position;
351            true
352        });
353        if let Some(signal) = signal
354            && signal.get_untracked() != position
355        {
356            signal.set(position);
357        }
358        self.live_positions.update(|positions| {
359            positions.insert(id.clone(), position);
360        });
361    }
362
363    /// Batch-update positions for multiple nodes during drag.
364    /// Updates node entries, port positions (via cached offsets), and position signals.
365    /// Each map notifies at most once, and only when at least one value changed.
366    pub fn batch_set_positions(&self, updates: &[(N, Position)]) {
367        // 1. Update node entries and collect only consumer signals that changed.
368        let mut node_signals = Vec::new();
369        let mut node_moves = HashMap::new();
370        self.nodes.maybe_update(|nodes| {
371            let mut changed = false;
372            for (id, position) in updates {
373                let Some(entry) = nodes.get_mut(id) else {
374                    continue;
375                };
376                if entry.position == *position {
377                    if let Some(signal) = entry.position_signal
378                        && signal.get_untracked() != *position
379                    {
380                        node_signals.push((signal, *position));
381                    }
382                    continue;
383                }
384                let delta =
385                    Position::new(position.x - entry.position.x, position.y - entry.position.y);
386                entry.position = *position;
387                node_moves.insert(id.clone(), (*position, delta));
388                if let Some(signal) = entry.position_signal {
389                    node_signals.push((signal, *position));
390                }
391                changed = true;
392            }
393            changed
394        });
395        // 2. Batch-update port positions. Measured ports use their exact cached
396        // offset; dynamic siblings whose offset was invalidated still follow
397        // the node by translating their last known absolute position.
398        self.ports.maybe_update(|ports| {
399            let mut changed = false;
400            for entry in ports.values_mut() {
401                let Some((new_node_position, delta)) = node_moves.get(&entry.node_id) else {
402                    continue;
403                };
404                let position = match entry.offset {
405                    Some(offset) => Position::new(
406                        new_node_position.x + offset.x,
407                        new_node_position.y + offset.y,
408                    ),
409                    None => Position::new(entry.position.x + delta.x, entry.position.y + delta.y),
410                };
411                if entry.position != position {
412                    entry.position = position;
413                    changed = true;
414                }
415            }
416            changed
417        });
418
419        // 3. Set position signals (drives CSS node positioning via style=).
420        for (signal, position) in node_signals {
421            if signal.get_untracked() != position {
422                signal.set(position);
423            }
424        }
425        self.live_positions.update(|positions| {
426            for (id, position) in updates {
427                positions.insert(id.clone(), *position);
428            }
429        });
430    }
431
432    /// Update a node's size.
433    pub fn set_node_size(&self, id: &N, size: Size) {
434        self.nodes.maybe_update(|nodes| {
435            let Some(entry) = nodes.get_mut(id) else {
436                return false;
437            };
438            if entry.size == size {
439                return false;
440            }
441            entry.size = size;
442            true
443        });
444    }
445
446    /// Update a port's absolute canvas-space position.
447    pub fn set_port_position(&self, id: &P, position: Position) {
448        self.ports.maybe_update(|ports| {
449            let Some(entry) = ports.get_mut(id) else {
450                return false;
451            };
452            if entry.position == position {
453                return false;
454            }
455            entry.position = position;
456            true
457        });
458    }
459
460    /// Publish measured anchor geometry together, after all layout reads in this turn.
461    pub(crate) fn queue_port_measurement(&self, id: P, position: Position, offset: Position) {
462        self.pending_port_measurements.update_value(|updates| {
463            updates.insert(id, (position, offset));
464        });
465        if self.port_measurement_pending.get_value() {
466            return;
467        }
468        self.port_measurement_pending.set_value(true);
469        let registry = self.clone();
470        crate::raf::request_animation_frame(move || registry.flush_port_measurements());
471    }
472
473    fn flush_port_measurements(&self) {
474        let Some(updates) = self
475            .pending_port_measurements
476            .try_update_value(std::mem::take)
477        else {
478            return; // editor was disposed before the queued frame
479        };
480        self.port_measurement_pending
481            .try_update_value(|pending| *pending = false);
482        self.nodes.with_untracked(|nodes| {
483            self.ports.try_maybe_update(|ports| {
484                let mut changed = false;
485                for (id, (position, offset)) in updates {
486                    if let Some(port) = ports.get_mut(&id) {
487                        let position = nodes.get(&port.node_id).map_or(position, |node| {
488                            Position::new(node.position.x + offset.x, node.position.y + offset.y)
489                        });
490                        changed |= port.position != position;
491                        port.position = position;
492                        port.offset = Some(offset);
493                    }
494                }
495                (changed, ())
496            });
497        });
498    }
499
500    /// Set a port's cached offset from its node position.
501    pub fn set_port_offset(&self, id: &P, offset: Position) {
502        let mut guard = self.ports.write_untracked();
503        if let Some(entry) = guard.get_mut(id) {
504            entry.offset = Some(offset);
505        }
506    }
507
508    /// Replace the entire connections map (used by the consumer to sync state).
509    pub fn set_connections(&self, connections: HashMap<C, ConnectionEntry<P, C>>) {
510        self.connections.set(connections);
511    }
512
513    /// Get a port's position (untracked read).
514    pub fn port_position(&self, id: &P) -> Option<Position> {
515        self.ports
516            .with_untracked(|ports| ports.get(id).map(|e| e.position))
517    }
518
519    /// Get a clone of a port entry (untracked read).
520    pub fn get_port(&self, id: &P) -> Option<PortEntry<N, P, T>> {
521        self.ports.with_untracked(|ports| ports.get(id).cloned())
522    }
523
524    /// Check if a target port is compatible with the current draft connection.
525    ///
526    /// Requirements:
527    /// - Target must be an Input port.
528    /// - Target must not belong to the same node as the source.
529    /// - The port types must be compatible via `PortType::compatible`.
530    pub fn is_compatible_target(&self, target_id: &P) -> bool {
531        let draft = self.draft_connection.with_untracked(|d| d.clone());
532        let Some(draft) = draft else {
533            return false;
534        };
535
536        self.ports.with_untracked(|ports| {
537            let Some(target) = ports.get(target_id) else {
538                return false;
539            };
540
541            if target.direction != PortDirection::Input {
542                return false;
543            }
544
545            // Source port must exist and belong to a different node.
546            let Some(source) = ports.get(&draft.source_port) else {
547                return false;
548            };
549
550            if source.node_id == target.node_id {
551                return false;
552            }
553
554            T::compatible(&draft.port_type, &target.port_type)
555        })
556    }
557
558    /// Select a single node, clearing all other selections.
559    pub fn select_node(&self, id: N) {
560        self.selected_connections.update(|sel| sel.clear());
561        self.selected_nodes.update(|sel| {
562            sel.clear();
563            sel.insert(id);
564        });
565    }
566
567    /// Toggle a node's selection state (for shift+click).
568    pub fn toggle_node_selection(&self, id: N) {
569        self.selected_nodes.update(|sel| {
570            if !sel.remove(&id) {
571                sel.insert(id);
572            }
573        });
574    }
575
576    /// Select a single connection, clearing all other selections.
577    pub fn select_connection(&self, id: C) {
578        self.selected_nodes.update(|sel| sel.clear());
579        self.selected_connections.update(|sel| {
580            sel.clear();
581            sel.insert(id);
582        });
583    }
584
585    /// Clear all selections.
586    pub fn clear_selection(&self) {
587        self.selected_nodes.update(|sel| sel.clear());
588        self.selected_connections.update(|sel| sel.clear());
589    }
590
591    /// Select all nodes.
592    pub fn select_all(&self) {
593        let all_ids: HashSet<N> = self
594            .nodes
595            .with_untracked(|nodes| nodes.keys().cloned().collect());
596        self.selected_nodes.set(all_ids);
597    }
598
599    /// Emit deletion events for all selected items.
600    pub fn delete_selected(&self) {
601        let selected_node_ids: Vec<N> = self
602            .selected_nodes
603            .with_untracked(|sel| sel.iter().cloned().collect());
604
605        let selected_conn_ids: Vec<C> = self
606            .selected_connections
607            .with_untracked(|sel| sel.iter().cloned().collect());
608
609        // Emit connection removals first.
610        for conn_id in selected_conn_ids {
611            self.emit(GraphEvent::ConnectionRemoved { id: conn_id });
612        }
613
614        // Emit node deletions.
615        if !selected_node_ids.is_empty() {
616            self.emit(GraphEvent::NodesDeleted {
617                ids: selected_node_ids,
618            });
619        }
620    }
621
622    /// Return the set of node IDs whose bounding rectangles intersect the given rect.
623    /// The compatible port nearest `cursor` within `max_dist` (canvas units),
624    /// for the draft currently in flight.
625    ///
626    /// Applies exactly the rules a real connection would — opposite direction,
627    /// different node, type-compatible — so the wire can never snap to a port
628    /// that would refuse the connection on release.
629    pub fn snap_target_for_draft(&self, cursor: Position, max_dist: f64) -> Option<(P, Position)> {
630        let draft = self.draft_connection.with_untracked(|d| d.clone())?;
631        let source = self.get_port(&draft.source_port)?;
632
633        let mut best: Option<(P, Position, f64)> = None;
634        self.ports.with_untracked(|ports| {
635            for entry in ports.values() {
636                if entry.direction == draft.origin_direction || entry.node_id == source.node_id {
637                    continue;
638                }
639                // Reject distant ports before potentially expensive schema compatibility.
640                let dist = crate::utils::distance(cursor, entry.position);
641                if dist > max_dist || best.as_ref().is_some_and(|(_, _, b)| dist >= *b) {
642                    continue;
643                }
644                let (output_type, input_type) = if draft.origin_direction == PortDirection::Output {
645                    (&source.port_type, &entry.port_type)
646                } else {
647                    (&entry.port_type, &source.port_type)
648                };
649                if !T::compatible(output_type, input_type) {
650                    continue;
651                }
652                best = Some((entry.id.clone(), entry.position, dist));
653            }
654        });
655        best.map(|(id, pos, _)| (id, pos))
656    }
657
658    /// Bounding box of every registered node, in canvas space. `None` when the
659    /// graph is empty.
660    pub fn nodes_bounds(&self) -> Option<Rect> {
661        self.nodes.with_untracked(|nodes| {
662            let mut entries = nodes.values();
663            let first = entries.next()?;
664            let (mut min_x, mut min_y) = (first.position.x, first.position.y);
665            let mut max_x = first.position.x + first.size.width;
666            let mut max_y = first.position.y + first.size.height;
667            for entry in entries {
668                min_x = min_x.min(entry.position.x);
669                min_y = min_y.min(entry.position.y);
670                max_x = max_x.max(entry.position.x + entry.size.width);
671                max_y = max_y.max(entry.position.y + entry.size.height);
672            }
673            Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
674        })
675    }
676
677    /// Pan and zoom so `rect` (canvas space) is centered and fits the container,
678    /// inset by `padding` screen pixels. Zoom is clamped to the config's range,
679    /// and additionally to `max_zoom_override` when given — framing uses that to
680    /// avoid magnifying a small graph.
681    ///
682    /// No-op until the container has been measured.
683    pub fn fit_rect(&self, rect: &Rect, padding: f64, max_zoom_override: Option<f64>) {
684        let container = self.container_size.get_untracked();
685        if container.width <= 0.0 || container.height <= 0.0 {
686            return;
687        }
688
689        // A single zero-size node would otherwise divide by zero.
690        let width = rect.size.width.max(1.0);
691        let height = rect.size.height.max(1.0);
692        let avail_w = (container.width - 2.0 * padding).max(1.0);
693        let avail_h = (container.height - 2.0 * padding).max(1.0);
694
695        let (min_zoom, max_zoom) = self.config.with_untracked(|c| (c.min_zoom, c.max_zoom));
696        let ceiling = max_zoom_override.map_or(max_zoom, |m| m.min(max_zoom));
697        let zoom = (avail_w / width)
698            .min(avail_h / height)
699            .clamp(min_zoom, ceiling.max(min_zoom));
700
701        let center_x = rect.position.x + width / 2.0;
702        let center_y = rect.position.y + height / 2.0;
703        self.viewport.update(|vp| {
704            vp.zoom = zoom;
705            vp.pan_x = container.width / 2.0 - center_x * zoom;
706            vp.pan_y = container.height / 2.0 - center_y * zoom;
707        });
708    }
709
710    /// Frame the whole graph — the `F` hotkey. No-op on an empty graph.
711    pub fn fit_view(&self) {
712        let Some(bounds) = self.nodes_bounds() else {
713            return;
714        };
715        let (padding, fit_max_zoom) = self
716            .config
717            .with_untracked(|c| (c.fit_padding, c.fit_max_zoom));
718        self.fit_rect(&bounds, padding, Some(fit_max_zoom));
719    }
720
721    pub fn nodes_in_rect(&self, rect: &Rect) -> HashSet<N> {
722        self.nodes.with_untracked(|nodes| {
723            nodes
724                .values()
725                .filter(|entry| {
726                    let node_rect = Rect::new(
727                        entry.position.x,
728                        entry.position.y,
729                        entry.size.width,
730                        entry.size.height,
731                    );
732                    rect.intersects(&node_rect)
733                })
734                .map(|entry| entry.id.clone())
735                .collect()
736        })
737    }
738}
739
740#[cfg(test)]
741mod tests {
742    use std::sync::Arc;
743    use std::sync::atomic::{AtomicUsize, Ordering};
744
745    use super::*;
746
747    thread_local! { static COMPATIBILITY_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
748
749    #[derive(Clone, Debug, PartialEq)]
750    enum TestPortType {
751        Any,
752    }
753
754    impl PortType for TestPortType {
755        fn compatible(_: &Self, _: &Self) -> bool {
756            COMPATIBILITY_CHECKS.with(|count| count.set(count.get() + 1));
757            true
758        }
759
760        fn type_id(&self) -> String {
761            "any".into()
762        }
763
764        fn from_type_id(_: &str) -> Self {
765            Self::Any
766        }
767    }
768
769    #[test]
770    fn measured_ports_publish_once_and_use_the_latest_node_position() {
771        Owner::new().with(|| {
772            let registry = EditorRegistry::<String, String, String, TestPortType>::new(
773                EditorConfig::default(),
774                Callback::new(|_: GraphEvent<String, String, String>| {}),
775            );
776            registry.register_node("node".into(), Position::default(), None);
777            for i in 0..835 {
778                registry.register_port(
779                    i.to_string(),
780                    "node".into(),
781                    PortDirection::Input,
782                    TestPortType::Any,
783                    Position::default(),
784                );
785            }
786            let reads = Arc::new(AtomicUsize::new(0));
787            let count = reads.clone();
788            let ports = registry.ports;
789            let positions = Memo::new(move |_| {
790                count.fetch_add(1, Ordering::Relaxed);
791                ports.with(|ports| ports.values().map(|port| port.position.x).sum::<f64>())
792            });
793            assert_eq!(positions.get(), 0.0);
794            for i in 0..835 {
795                registry.pending_port_measurements.update_value(|updates| {
796                    updates.insert(
797                        i.to_string(),
798                        (Position::new(5.0, 0.0), Position::new(5.0, 0.0)),
799                    );
800                });
801                assert_eq!(positions.get(), 0.0);
802            }
803            assert_eq!(reads.load(Ordering::Relaxed), 1);
804            // A move between measurement and publication must not restore stale positions.
805            registry.set_node_position(&"node".into(), Position::new(10.0, 0.0));
806            let before = reads.load(Ordering::Relaxed);
807            registry.flush_port_measurements();
808            assert_eq!(positions.get(), 835.0 * 15.0);
809            assert_eq!(reads.load(Ordering::Relaxed), before + 1);
810            registry.flush_port_measurements();
811            assert_eq!(positions.get(), 835.0 * 15.0);
812            assert_eq!(reads.load(Ordering::Relaxed), before + 1);
813            assert!(registry.ports.with_untracked(|ports| {
814                ports
815                    .values()
816                    .all(|p| p.offset == Some(Position::new(5.0, 0.0)))
817            }));
818        });
819    }
820
821    #[test]
822    fn snapping_only_checks_types_within_the_pointer_radius() {
823        Owner::new().with(|| {
824            let registry = EditorRegistry::<String, String, String, TestPortType>::new(
825                EditorConfig::default(),
826                Callback::new(|_: GraphEvent<String, String, String>| {}),
827            );
828            registry.register_port(
829                "source".into(),
830                "origin".into(),
831                PortDirection::Output,
832                TestPortType::Any,
833                Position::default(),
834            );
835            for x in 0..1000 {
836                registry.register_port(
837                    format!("far-{x}"),
838                    "other".into(),
839                    PortDirection::Input,
840                    TestPortType::Any,
841                    Position::new(1000.0 + x as f64, 0.0),
842                );
843            }
844            registry.register_port(
845                "near".into(),
846                "other".into(),
847                PortDirection::Input,
848                TestPortType::Any,
849                Position::new(2.0, 0.0),
850            );
851            registry.draft_connection.set(Some(DraftConnection {
852                source_port: "source".into(),
853                source_position: Position::default(),
854                port_type: TestPortType::Any,
855                current_end: Position::default(),
856                origin_direction: PortDirection::Output,
857                snap_target: None,
858            }));
859            COMPATIBILITY_CHECKS.with(|count| count.set(0));
860            assert_eq!(
861                registry.snap_target_for_draft(Position::default(), 10.0),
862                Some(("near".into(), Position::new(2.0, 0.0)))
863            );
864            COMPATIBILITY_CHECKS.with(|count| assert_eq!(count.get(), 1));
865            COMPATIBILITY_CHECKS.with(|count| count.set(0));
866            assert_eq!(
867                registry.snap_target_for_draft(Position::new(-100.0, 0.0), 10.0),
868                None
869            );
870            COMPATIBILITY_CHECKS.with(|count| assert_eq!(count.get(), 0));
871        });
872    }
873
874    #[test]
875    fn pointer_moves_do_not_recompute_draft_consumers() {
876        Owner::new().with(|| {
877            let registry = EditorRegistry::<String, String, String, TestPortType>::new(
878                EditorConfig::default(),
879                Callback::new(|_: GraphEvent<String, String, String>| {}),
880            );
881            let reads = Arc::new(AtomicUsize::new(0));
882            let count = reads.clone();
883            let origin = registry.draft_origin;
884            let anchor = Memo::new(move |_| {
885                count.fetch_add(1, Ordering::Relaxed);
886                origin.get()
887            });
888            assert_eq!(anchor.get(), None);
889            registry.draft_connection.set(Some(DraftConnection {
890                source_port: "source".into(),
891                source_position: Position::default(),
892                port_type: TestPortType::Any,
893                current_end: Position::default(),
894                origin_direction: PortDirection::Output,
895                snap_target: None,
896            }));
897            assert!(anchor.get().is_some());
898            let baseline = reads.load(Ordering::Relaxed);
899            for x in 0..100 {
900                registry.draft_connection.update(|draft| {
901                    let draft = draft.as_mut().unwrap();
902                    draft.current_end = Position::new(x as f64, 0.0);
903                    draft.snap_target = Some(format!("target-{x}"));
904                });
905                assert!(anchor.get().is_some());
906            }
907            assert_eq!(reads.load(Ordering::Relaxed), baseline);
908            registry.draft_connection.set(None);
909            assert_eq!(anchor.get(), None);
910            assert_eq!(reads.load(Ordering::Relaxed), baseline + 1);
911        });
912    }
913
914    #[test]
915    fn geometry_writes_gate_noops_and_translate_offsetless_ports() {
916        Owner::new().with(|| {
917            let registry = EditorRegistry::<String, String, String, TestPortType>::new(
918                EditorConfig::default(),
919                Callback::new(|_: GraphEvent<String, String, String>| {}),
920            );
921            let position = Position::new(10.0, 20.0);
922            let position_signal = RwSignal::new(position);
923            let node_id = "node".to_string();
924            let port_id = "port".to_string();
925            let dynamic_port_id = "dynamic-port".to_string();
926            registry.register_node(node_id.clone(), position, Some(position_signal));
927            registry.register_port(
928                port_id.clone(),
929                node_id.clone(),
930                PortDirection::Output,
931                TestPortType::Any,
932                Position::new(30.0, 25.0),
933            );
934            registry.register_port(
935                dynamic_port_id.clone(),
936                node_id.clone(),
937                PortDirection::Output,
938                TestPortType::Any,
939                Position::new(50.0, 60.0),
940            );
941            registry.set_port_offset(&port_id, Position::new(20.0, 5.0));
942
943            let node_reads = Arc::new(AtomicUsize::new(0));
944            let node_reads_memo = Arc::clone(&node_reads);
945            let nodes = registry.nodes;
946            let node_geometry = Memo::new(move |_| {
947                node_reads_memo.fetch_add(1, Ordering::Relaxed);
948                nodes.with(|nodes| nodes.get("node").map(|node| (node.position, node.size)))
949            });
950
951            let port_reads = Arc::new(AtomicUsize::new(0));
952            let port_reads_memo = Arc::clone(&port_reads);
953            let ports = registry.ports;
954            let port_geometry = Memo::new(move |_| {
955                port_reads_memo.fetch_add(1, Ordering::Relaxed);
956                ports.with(|ports| {
957                    Some((
958                        ports.get("port")?.position,
959                        ports.get("dynamic-port")?.position,
960                    ))
961                })
962            });
963
964            assert!(node_geometry.get().is_some());
965            assert!(port_geometry.get().is_some());
966            registry.set_node_position(&node_id, position);
967            registry.set_node_position_with_signal(&node_id, position);
968            registry.set_node_size(&node_id, Size::default());
969            registry.set_port_position(&port_id, Position::new(30.0, 25.0));
970            registry.batch_set_positions(&[("node".into(), position)]);
971            assert!(node_geometry.get().is_some());
972            assert!(port_geometry.get().is_some());
973
974            assert_eq!(node_reads.load(Ordering::Relaxed), 1);
975            assert_eq!(port_reads.load(Ordering::Relaxed), 1);
976
977            let moved = Position::new(20.0, 30.0);
978            registry.batch_set_positions(&[(node_id.clone(), moved)]);
979            assert_eq!(node_geometry.get(), Some((moved, Size::default())));
980            assert_eq!(
981                port_geometry.get(),
982                Some((Position::new(40.0, 35.0), Position::new(60.0, 70.0)))
983            );
984            assert_eq!(position_signal.get_untracked(), moved);
985            assert_eq!(node_reads.load(Ordering::Relaxed), 2);
986            assert_eq!(port_reads.load(Ordering::Relaxed), 2);
987        });
988    }
989}