Skip to main content

leptos_node_graph/
interaction.rs

1use leptos::prelude::*;
2use web_sys::{KeyboardEvent, MouseEvent, WheelEvent};
3
4use crate::registry::{BoxSelect, DragState, EditorRegistry};
5use crate::types::*;
6use crate::utils;
7
8/// Get canvas-space position from a mouse event relative to a container element.
9fn canvas_pos_from_event<N, P, C, T>(
10    registry: &EditorRegistry<N, P, C, T>,
11    ev: &MouseEvent,
12    container_ref: &NodeRef<leptos::html::Div>,
13) -> Position
14where
15    N: NodeId,
16    P: PortId,
17    C: ConnectionId,
18    T: PortType,
19{
20    let viewport = registry.viewport.get_untracked();
21    let (offset_x, offset_y) = container_ref.with_untracked(|el| {
22        if let Some(el) = el {
23            let rect = el.get_bounding_client_rect();
24            (rect.left(), rect.top())
25        } else {
26            (0.0, 0.0)
27        }
28    });
29    let screen = Position::new(
30        ev.client_x() as f64 - offset_x,
31        ev.client_y() as f64 - offset_y,
32    );
33    viewport.screen_to_canvas(screen)
34}
35
36pub fn handle_canvas_mousedown<N, P, C, T>(
37    registry: &EditorRegistry<N, P, C, T>,
38    ev: MouseEvent,
39    container_ref: &NodeRef<leptos::html::Div>,
40) where
41    N: NodeId,
42    P: PortId,
43    C: ConnectionId,
44    T: PortType,
45{
46    // Pan gesture start: middle button, or ctrl+left. This handler is on THIS
47    // container, so the flag scopes the pan to the pressed graph — the global
48    // mousemove listener checks it, so sibling graphs don't pan too. Cleared on
49    // mouseup.
50    if ev.button() == 1 || (ev.button() == 0 && ev.ctrl_key()) {
51        registry.is_panning.set(true);
52        registry.pan_origin.set(Some(Position::new(
53            ev.client_x() as f64,
54            ev.client_y() as f64,
55        )));
56        return;
57    }
58
59    // Only handle left click
60    if ev.button() != 0 {
61        return;
62    }
63
64    // Skip if click was on a node or anchor (those have their own handlers)
65    if let Some(target) = ev.target() {
66        use leptos::wasm_bindgen::JsCast;
67        if let Some(el) = target.dyn_ref::<web_sys::Element>() {
68            let on_node: bool = el.closest("[data-node]").ok().flatten().is_some();
69            let on_anchor: bool = el.closest("[data-anchor]").ok().flatten().is_some();
70            if on_node || on_anchor {
71                return;
72            }
73        }
74    }
75
76    // Cancel any draft connection
77    registry.draft_connection.set(None);
78
79    // Clear selection unless shift is held
80    if !ev.shift_key() {
81        registry.clear_selection();
82    }
83
84    // Start box select. Alt changes the same gesture into group creation on
85    // mouseup, which keeps the familiar selection rectangle as the preview.
86    let canvas_pos = canvas_pos_from_event(registry, &ev, container_ref);
87    registry.box_select.set(Some(BoxSelect {
88        start: canvas_pos,
89        current: canvas_pos,
90        create_group: ev.alt_key(),
91    }));
92}
93
94pub fn handle_canvas_mousemove<N, P, C, T>(
95    registry: &EditorRegistry<N, P, C, T>,
96    ev: MouseEvent,
97    container_ref: &NodeRef<leptos::html::Div>,
98) where
99    N: NodeId,
100    P: PortId,
101    C: ConnectionId,
102    T: PortType,
103{
104    // Node width resize. Written straight to the node's width signal rather than
105    // RAF-batched like a drag: one node, one style recompute per move, and the
106    // measured-size effect it triggers is already ResizeObserver-throttled.
107    let resize = registry.resize_state.with_untracked(|rs| rs.clone());
108    if let Some(rs) = resize {
109        let canvas_pos = canvas_pos_from_event(registry, &ev, container_ref);
110        let mut width = rs.start_width + (canvas_pos.x - rs.start_x);
111        width = width.max(rs.min_width);
112        if let Some(max) = rs.max_width {
113            width = width.min(max);
114        }
115        rs.width_signal.set(Some(width));
116        return;
117    }
118
119    // Panning — ONLY if this instance started the pan (see mousedown). The move
120    // listener is document-level, so this per-instance gate is what stops a drag
121    // from panning every open graph at once.
122    if registry.is_panning.get_untracked() {
123        // Delta measured from the last frame's CLIENT position — see
124        // `pan_origin`. `movementX/Y` would be in physical pixels here, which
125        // pans faster than the cursor on any display where the device pixel
126        // ratio isn't 1. Both are identical at ratio 1, so this costs nothing
127        // where the old path already behaved.
128        let now = Position::new(ev.client_x() as f64, ev.client_y() as f64);
129        let last = registry.pan_origin.get_untracked().unwrap_or(now);
130        registry.pan_origin.set(Some(now));
131        let (dx, dy) = (now.x - last.x, now.y - last.y);
132        registry.viewport.update(|vp| {
133            vp.pan_x += dx;
134            vp.pan_y += dy;
135        });
136        return;
137    }
138
139    // Alt can turn an ordinary drag into a group-transfer drag at any point in
140    // the gesture. Latch it before updating the position so GroupBoxOverlay
141    // observes the transition while the drag is still active.
142    if ev.alt_key()
143        && registry
144            .drag_state
145            .with_untracked(|drag| drag.as_ref().is_some_and(|drag| !drag.alt_key))
146    {
147        registry.drag_state.update(latch_group_transfer);
148    }
149
150    // Node dragging — store latest position and schedule RAF
151    let has_drag = registry.drag_state.with_untracked(|ds| ds.is_some());
152    if has_drag {
153        let canvas_pos = canvas_pos_from_event(registry, &ev, container_ref);
154        registry.pending_drag_pos.set(Some(canvas_pos));
155
156        if !registry.drag_raf_pending.get_untracked() {
157            registry.drag_raf_pending.set(true);
158            let reg = registry.clone();
159            crate::raf::request_animation_frame(move || {
160                reg.drag_raf_pending.set(false);
161                let canvas_pos = reg.pending_drag_pos.get_untracked();
162                if let Some(canvas_pos) = canvas_pos {
163                    reg.pending_drag_pos.set(None);
164                    let grid_size = reg.config.with_untracked(|c| c.grid_size);
165                    reg.drag_state.with_untracked(|ds| {
166                        if let Some(ds) = ds {
167                            let delta = Position::new(
168                                canvas_pos.x - ds.offset.x,
169                                canvas_pos.y - ds.offset.y,
170                            );
171                            let updates: Vec<(N, Position)> = ds
172                                .start_positions
173                                .iter()
174                                .map(|(node_id, start_pos)| {
175                                    let mut new_pos =
176                                        Position::new(start_pos.x + delta.x, start_pos.y + delta.y);
177                                    if let Some(grid) = grid_size {
178                                        new_pos = utils::snap_to_grid(new_pos, grid);
179                                    }
180                                    (node_id.clone(), new_pos)
181                                })
182                                .collect();
183                            reg.batch_set_positions(&updates);
184                        }
185                    });
186                }
187            });
188        }
189        return;
190    }
191
192    // Box select update
193    let has_box = registry.box_select.with_untracked(|bs| bs.is_some());
194    if has_box {
195        let canvas_pos = canvas_pos_from_event(registry, &ev, container_ref);
196        registry.box_select.update(|bs| {
197            if let Some(bs) = bs {
198                bs.current = canvas_pos;
199            }
200        });
201
202        // Select nodes in rect
203        let rect = registry
204            .box_select
205            .with_untracked(|bs| bs.as_ref().map(|bs| bs.to_rect()));
206        if let Some(rect) = rect {
207            let nodes_in = registry.nodes_in_rect(&rect);
208            registry.selected_nodes.set(nodes_in);
209        }
210        return;
211    }
212
213    // Draft connection: update end position, pulling to a nearby compatible port.
214    let has_draft = registry.draft_connection.with_untracked(|dc| dc.is_some());
215    if has_draft {
216        let canvas_pos = canvas_pos_from_event(registry, &ev, container_ref);
217
218        // The radius is configured in screen pixels and divided by zoom, so the
219        // pull feels identical whether you're zoomed in or out.
220        let snap_distance = registry.config.with_untracked(|c| c.snap_distance);
221        let snap = if snap_distance > 0.0 {
222            let zoom = registry.viewport.get_untracked().zoom;
223            let zoom = if zoom.abs() < 1e-6 { 1.0 } else { zoom };
224            registry.snap_target_for_draft(canvas_pos, snap_distance / zoom)
225        } else {
226            None
227        };
228
229        registry.draft_connection.update(|dc| {
230            if let Some(dc) = dc {
231                match &snap {
232                    Some((port_id, port_pos)) => {
233                        dc.current_end = *port_pos;
234                        dc.snap_target = Some(port_id.clone());
235                    }
236                    None => {
237                        dc.current_end = canvas_pos;
238                        dc.snap_target = None;
239                    }
240                }
241            }
242        });
243    }
244}
245
246/// Handle a document-level mouseup. Ends box-select and node-drag (emitting
247/// `NodesMoved`), then resolves an in-flight draft connection.
248///
249/// The draft is cancelled UNLESS the mouseup landed on an anchor or the node
250/// menu: a successful connection is completed by the target anchor's own
251/// handler, and an anchor mouseup that *didn't* complete (the initial click of a
252/// click-to-start/click-to-complete connection) must keep the draft alive so the
253/// follow-up click can finish it. Dropping on empty canvas cancels the draft —
254/// the creation menu is opened with Tab during a draft, not by dropping.
255pub fn handle_canvas_mouseup<N, P, C, T>(
256    registry: &EditorRegistry<N, P, C, T>,
257    ev: MouseEvent,
258    _container_ref: &NodeRef<leptos::html::Div>,
259) where
260    N: NodeId,
261    P: PortId,
262    C: ConnectionId,
263    T: PortType,
264{
265    // End pan (this instance) and box select.
266    let was_panning = registry.is_panning.get_untracked();
267    registry.is_panning.set(false);
268    if was_panning {
269        registry.pan_origin.set(None);
270    }
271    let box_select = registry.box_select.get_untracked();
272    registry.box_select.set(None);
273
274    if box_select.is_some_and(|bs| bs.create_group) {
275        let ids: Vec<N> = registry
276            .selected_nodes
277            .with_untracked(|selected| selected.iter().cloned().collect());
278        if ids.len() > 1 {
279            registry.emit(GraphEvent::GroupCreated { node_ids: ids });
280        }
281    }
282
283    // End a width resize. No event to emit here — the node's measured-size effect
284    // has been emitting `NodeResized` throughout the gesture.
285    if registry.resize_state.with_untracked(|rs| rs.is_some()) {
286        registry.resize_state.set(None);
287    }
288
289    // End node drag - emit one event containing every moved node. Consumers
290    // commonly persist graph edits as commands, so preserving the gesture
291    // boundary lets them apply a multi-selection move atomically.
292    let drag = registry.drag_state.with_untracked(|ds| ds.clone());
293    if let Some(drag) = drag {
294        registry.drag_state.set(None);
295
296        let nodes: Vec<_> = registry.nodes.with_untracked(|current| {
297            drag.start_positions
298                .keys()
299                .filter_map(|node_id| {
300                    current
301                        .get(node_id)
302                        .map(|node| (node_id.clone(), node.position))
303                })
304                .collect()
305        });
306        if !nodes.is_empty() {
307            registry.emit(GraphEvent::NodesMoved { nodes });
308        }
309    }
310
311    // Drafting is a LEFT-button gesture, so only a left release can end it.
312    // Releasing a pan (middle-drag, or ctrl+left-drag) must leave an in-flight
313    // connection alone — otherwise middle-clicking to pan mid-wiring silently
314    // drops the draft. Panning doesn't move the draft endpoint either: the pan
315    // shifts the canvas 1:1 with the cursor, so the canvas point under the
316    // pointer — which is what the endpoint stores — doesn't change.
317    if was_panning || ev.button() != 0 {
318        return;
319    }
320
321    // The node-creation menu owns the draft while it is open: it derives its
322    // compatible-port sub-items from it, and wires the created node to it. Tab
323    // is pressed mid-drag, so the release that follows is just the user letting
324    // go of the button they started the draft with — it must not end the
325    // gesture, or the menu loses its port list AND the node is created unwired.
326    // Both menu exits clear the draft themselves (`NodeMenuEvent::CreateNode`
327    // and `::Cancelled`), so nothing leaks by deferring to them.
328    if registry.menu_open.get_untracked() {
329        return;
330    }
331
332    // Released while snapped to a port: connect to it. The wire was already
333    // drawn attached to that port, so anything else would be a lie — and this is
334    // what makes the snap radius, rather than the dot itself, the drop target.
335    // (An anchor the pointer is literally over completes via its own mouseup,
336    // which runs first and clears the draft, so this can't double-fire.)
337    let snapped = registry
338        .draft_connection
339        .with_untracked(|dc| dc.as_ref().and_then(|d| d.snap_target.clone()));
340    if let Some(port_id) = snapped {
341        let direction = registry.get_port(&port_id).map(|p| p.direction);
342        if let Some(direction) = direction
343            && crate::anchor::try_complete_connection(registry, &port_id, direction)
344        {
345            return;
346        }
347    }
348
349    // Cancel draft connection only if mouseup was NOT on an anchor or the node menu.
350    if let Some(target) = ev.target() {
351        use leptos::wasm_bindgen::JsCast;
352        if let Some(el) = target.dyn_ref::<web_sys::Element>() {
353            let is_anchor = el.closest("[data-anchor]").ok().flatten().is_some();
354            let is_menu = el.closest("[data-node-menu]").ok().flatten().is_some();
355            if !is_anchor && !is_menu {
356                registry.draft_connection.set(None);
357            }
358        } else {
359            registry.draft_connection.set(None);
360        }
361    } else {
362        registry.draft_connection.set(None);
363    }
364}
365
366/// Regions the wheel always scrolls rather than zooming: the node creation menu,
367/// `NodeOverlay` panels (and their backdrop), and anything a consumer opts out
368/// with `data-graph-no-zoom` — the explicit override for content that should
369/// swallow the wheel even when it isn't (yet) overflowing.
370const NO_ZOOM_SELECTOR: &str =
371    "[data-node-menu],[data-node-overlay],[data-node-overlay-backdrop],[data-graph-no-zoom]";
372
373/// Whether this wheel belongs to scrollable content rather than to the canvas.
374///
375/// Anything overflowing under the pointer wins the wheel — a node body's list, a
376/// popup panel, an inspector — so consumers get correct behavior without tagging
377/// every scroller. Position within the scroller is deliberately NOT considered:
378/// hitting the end of a list mid-flick should stop, not start zooming.
379fn wheel_scrolls_content(ev: &WheelEvent, container: &web_sys::Element) -> bool {
380    use leptos::wasm_bindgen::JsCast;
381    let Some(target) = ev
382        .target()
383        .and_then(|t| t.dyn_ref::<web_sys::Element>().cloned())
384    else {
385        return false;
386    };
387
388    if target.closest(NO_ZOOM_SELECTOR).ok().flatten().is_some() {
389        return true;
390    }
391
392    // Walk target → container looking for an overflowing scroll box.
393    let win = leptos::prelude::window();
394    let mut node = Some(target);
395    while let Some(el) = node {
396        if el.is_same_node(Some(container)) {
397            return false;
398        }
399        let overflows = el.scroll_height() > el.client_height();
400        if overflows
401            && win
402                .get_computed_style(&el)
403                .ok()
404                .flatten()
405                .and_then(|s| s.get_property_value("overflow-y").ok())
406                .is_some_and(|o| o == "auto" || o == "scroll")
407        {
408            return true;
409        }
410        node = el.parent_element();
411    }
412    // Target outside the container (a portalled panel): treat it as content.
413    true
414}
415
416pub fn handle_wheel<N, P, C, T>(
417    registry: &EditorRegistry<N, P, C, T>,
418    ev: WheelEvent,
419    container_ref: &NodeRef<leptos::html::Div>,
420) where
421    N: NodeId,
422    P: PortId,
423    C: ConnectionId,
424    T: PortType,
425{
426    // A wheel over scrollable content belongs to that content, not to the canvas:
427    // zooming `prevent_default`s, so without this bail a popup list, node body or
428    // inspector can never be scrolled — the graph zooms instead. The overlay
429    // backdrop counts too: an open panel is placed once in pane space, so zooming
430    // behind it would leave it stranded away from its trigger.
431    let scrolls_content = container_ref.with_untracked(|el| {
432        el.as_ref()
433            .is_some_and(|el| wheel_scrolls_content(&ev, AsRef::<web_sys::Element>::as_ref(el)))
434    });
435    if scrolls_content {
436        return;
437    }
438
439    ev.prevent_default();
440
441    let (min_zoom, max_zoom) = registry.config.with_untracked(|c| (c.min_zoom, c.max_zoom));
442
443    let (offset_x, offset_y) = container_ref.with_untracked(|el| {
444        if let Some(el) = el {
445            let rect = el.get_bounding_client_rect();
446            (rect.left(), rect.top())
447        } else {
448            (0.0, 0.0)
449        }
450    });
451
452    let mouse_x = ev.client_x() as f64 - offset_x;
453    let mouse_y = ev.client_y() as f64 - offset_y;
454
455    // Geometric zoom by wheel DIRECTION only (not deltaY magnitude), matching
456    // `@panzoom/panzoom`'s `zoomWithWheel`: `scale * exp((isIn ? 1 : -1) * step)`
457    // with the default `step = 0.3` (~+35% in / −26% out per notch). Using the
458    // sign rather than the magnitude keeps the per-notch feel identical across
459    // mice/trackpads and `deltaMode`s (a magnitude-based factor zoomed at wildly
460    // different speeds depending on the device's deltaY).
461    const ZOOM_STEP: f64 = 0.3;
462    let dir = if ev.delta_y() < 0.0 { 1.0 } else { -1.0 };
463    let zoom_factor = (dir * ZOOM_STEP).exp();
464
465    registry.viewport.update(|vp| {
466        let old_zoom = vp.zoom;
467        let new_zoom = (old_zoom * zoom_factor).clamp(min_zoom, max_zoom);
468        let scale_change = new_zoom / old_zoom;
469
470        // Zoom toward mouse position
471        vp.pan_x = mouse_x - (mouse_x - vp.pan_x) * scale_change;
472        vp.pan_y = mouse_y - (mouse_y - vp.pan_y) * scale_change;
473        vp.zoom = new_zoom;
474    });
475}
476
477pub fn handle_keydown<N, P, C, T>(
478    registry: &EditorRegistry<N, P, C, T>,
479    ev: KeyboardEvent,
480    _container_ref: &NodeRef<leptos::html::Div>,
481) where
482    N: NodeId,
483    P: PortId,
484    C: ConnectionId,
485    T: PortType,
486{
487    // A modifier press does not necessarily move the pointer. Latch Alt from
488    // the keyboard event too, so group-transfer mode starts immediately even
489    // while the cursor is stationary.
490    if ev.key() == "Alt" {
491        registry.drag_state.update(latch_group_transfer);
492        return;
493    }
494
495    // Never hijack keys while the user is typing in a node's own controls: a
496    // bare "f" would re-frame the graph mid-word, and Delete would delete the
497    // selected nodes out from under them.
498    if let Some(target) = ev.target() {
499        use leptos::wasm_bindgen::JsCast;
500        if let Some(el) = target.dyn_ref::<web_sys::Element>() {
501            let tag = el.tag_name().to_uppercase();
502            let editable = matches!(tag.as_str(), "INPUT" | "TEXTAREA" | "SELECT")
503                || el.closest("[contenteditable]").ok().flatten().is_some();
504            if editable {
505                return;
506            }
507        }
508    }
509
510    let key = ev.key();
511    let ctrl = ev.ctrl_key() || ev.meta_key();
512    let shift = ev.shift_key();
513
514    match key.as_str() {
515        "Delete" | "Backspace" => {
516            ev.prevent_default();
517            registry.delete_selected();
518        }
519        "a" if ctrl => {
520            ev.prevent_default();
521            registry.select_all();
522        }
523        // Frame the whole graph.
524        "f" | "F" if !ctrl => {
525            ev.prevent_default();
526            registry.fit_view();
527        }
528        "c" if ctrl => {
529            ev.prevent_default();
530            let ids: Vec<N> = registry
531                .selected_nodes
532                .with_untracked(|sel| sel.iter().cloned().collect());
533            registry.emit(GraphEvent::NodesCopied { ids });
534        }
535        "v" if ctrl => {
536            ev.prevent_default();
537            registry.emit(GraphEvent::NodesPasted {
538                offset: Position::new(20.0, 20.0),
539            });
540        }
541        "z" if ctrl && shift => {
542            ev.prevent_default();
543            registry.emit(GraphEvent::Redo);
544        }
545        "z" if ctrl => {
546            ev.prevent_default();
547            registry.emit(GraphEvent::Undo);
548        }
549        "g" if ctrl => {
550            ev.prevent_default();
551            let ids: Vec<N> = registry
552                .selected_nodes
553                .with_untracked(|sel| sel.iter().cloned().collect());
554            registry.emit(GraphEvent::GroupCreated { node_ids: ids });
555        }
556        "Escape" => {
557            // Abort an in-flight resize back to the width it started at.
558            let resize = registry.resize_state.with_untracked(|rs| rs.clone());
559            if let Some(rs) = resize {
560                rs.width_signal.set(Some(rs.start_width));
561                registry.resize_state.set(None);
562            }
563            registry.draft_connection.set(None);
564            registry.clear_selection();
565        }
566        // Tab is handled by the editor directly (opens menu)
567        _ => {}
568    }
569}
570
571fn latch_group_transfer<N: NodeId>(drag: &mut Option<DragState<N>>) {
572    if let Some(drag) = drag {
573        drag.alt_key = true;
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use std::collections::HashMap;
580
581    use super::*;
582
583    #[test]
584    fn alt_can_activate_group_transfer_after_drag_start() {
585        let mut drag = Some(DragState {
586            node_id: "node".to_string(),
587            offset: Position::new(10.0, 20.0),
588            start_positions: HashMap::from([("node".to_string(), Position::new(0.0, 0.0))]),
589            alt_key: false,
590        });
591
592        latch_group_transfer(&mut drag);
593
594        assert!(drag.unwrap().alt_key);
595    }
596}