Skip to main content

leptos_node_graph/
editor.rs

1use std::collections::HashMap;
2use std::marker::PhantomData;
3
4use leptos::prelude::*;
5use leptos_use::{
6    UseElementSizeReturn, UseEventListenerOptions, use_debounce_fn, use_element_size,
7    use_event_listener, use_event_listener_with_options,
8};
9
10use crate::connection::ConnectionRenderer;
11use crate::group::GroupBoxOverlay;
12use crate::interaction;
13use crate::menu::{DraftContext, NodeMenu, NodeMenuEvent, NodeMenuItem};
14use crate::registry::{ConnectionEntry, EditorRegistry};
15use crate::selection::SelectionBox;
16use crate::types::*;
17
18/// A consumer-side handle to a [`NodeEditor`] instance.
19///
20/// The editor provides its registry via context, which flows DOWN — so a handler
21/// mounted on an ancestor of the editor (an HTML5 drop target wrapping the graph,
22/// a toolbar, a sibling pane) has no way to reach the live pan/zoom transform.
23/// Construct a handle, pass it to [`NodeEditor`], and it works from anywhere:
24///
25/// ```ignore
26/// let handle = EditorHandle::new();
27/// view! {
28///     <div
29///         on:dragover=|ev: web_sys::DragEvent| ev.prevent_default()
30///         on:drop=move |ev: web_sys::DragEvent| {
31///             ev.prevent_default();
32///             if let Some(pos) = handle.client_to_canvas(ev.client_x() as f64, ev.client_y() as f64) {
33///                 // `pos` is in canvas space, correct under any pan/zoom.
34///             }
35///         }
36///     >
37///         <NodeEditor handle=handle ...>...</NodeEditor>
38///     </div>
39/// }
40/// ```
41///
42/// Prefer this over reading the canvas element's CSS transform: the class names
43/// and the transform's representation are internal and may change, whereas this
44/// is the supported surface.
45#[derive(Clone, Copy, Debug)]
46pub struct EditorHandle {
47    viewport: RwSignal<ViewportTransform>,
48    container: NodeRef<leptos::html::Div>,
49}
50
51impl Default for EditorHandle {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl EditorHandle {
58    pub fn new() -> Self {
59        Self {
60            viewport: RwSignal::new(ViewportTransform::default()),
61            container: NodeRef::new(),
62        }
63    }
64
65    /// The editor's live pan/zoom transform. Reading this in a reactive context
66    /// subscribes to it, so it also drives consumer-side minimaps, zoom readouts
67    /// and "frame the graph" controls.
68    ///
69    /// When this handle is passed to a [`NodeEditor`], the editor uses THIS
70    /// signal as its own — writing to it pans/zooms the graph.
71    pub fn viewport(&self) -> RwSignal<ViewportTransform> {
72        self.viewport
73    }
74
75    /// The editor's container element, once mounted.
76    pub fn container(&self) -> NodeRef<leptos::html::Div> {
77        self.container
78    }
79
80    /// Convert viewport client coordinates — `MouseEvent`/`DragEvent` `client_x`
81    /// and `client_y` — into canvas coordinates.
82    ///
83    /// This subtracts the container's own offset before applying the transform,
84    /// which is the step that's easy to miss: any padding, border or chrome
85    /// between the event's target and the editor's container shifts the result,
86    /// and the error only shows up once the layout gains that spacing.
87    ///
88    /// `None` before the editor has mounted. Reads are untracked, so this is safe
89    /// to call from event handlers without creating a subscription.
90    pub fn client_to_canvas(&self, client_x: f64, client_y: f64) -> Option<Position> {
91        let el = self.container.get_untracked()?;
92        let rect = el.get_bounding_client_rect();
93        Some(
94            self.viewport
95                .get_untracked()
96                .screen_to_canvas(Position::new(client_x - rect.left(), client_y - rect.top())),
97        )
98    }
99
100    /// Inverse of [`Self::client_to_canvas`]: canvas coordinates to viewport
101    /// client coordinates, for placing consumer-owned DOM over a graph position.
102    pub fn canvas_to_client(&self, canvas: Position) -> Option<Position> {
103        let el = self.container.get_untracked()?;
104        let rect = el.get_bounding_client_rect();
105        let s = self.viewport.get_untracked().canvas_to_screen(canvas);
106        Some(Position::new(s.x + rect.left(), s.y + rect.top()))
107    }
108}
109
110#[component]
111pub fn NodeEditor<N, P, C, T>(
112    #[prop(into)] config: EditorConfig,
113    #[prop(into)] connections: Signal<HashMap<C, ConnectionEntry<P, C>>>,
114    on_event: Callback<GraphEvent<N, P, C>>,
115    #[prop(optional)] _marker: PhantomData<T>,
116    /// Optional node catalog for the creation menu.
117    /// If provided, Tab/double-click opens a searchable menu.
118    /// Consumer filters this list reactively based on `menu_search`.
119    #[prop(optional, into)]
120    menu_items: Option<Signal<Vec<NodeMenuItem>>>,
121    /// Two-way search text for the menu. Consumer reads this to filter menu_items.
122    #[prop(optional)]
123    menu_search: Option<RwSignal<String>>,
124    /// Optional groups to render as visual overlays behind nodes.
125    #[prop(optional, into)]
126    groups: Option<Signal<Vec<crate::group::GroupBox<N>>>>,
127    /// Callback for group events (rename, add/remove node).
128    #[prop(optional, into)]
129    on_group_event: Option<Callback<crate::group::GroupEvent<N>>>,
130    /// Optional callback for the group header's ungroup action.
131    #[prop(optional, into)]
132    on_ungroup: Option<Callback<String>>,
133    /// Optional callback for the group header's select-all action.
134    #[prop(optional, into)]
135    on_select_all: Option<Callback<Vec<N>>>,
136    /// Optional consumer-owned handle. Gives code OUTSIDE the editor — a wrapping
137    /// drop target, a toolbar, a minimap — access to the live viewport and to
138    /// client/canvas coordinate conversion. See [`EditorHandle`].
139    #[prop(optional)]
140    handle: Option<EditorHandle>,
141    children: Children,
142) -> impl IntoView
143where
144    N: NodeId,
145    P: PortId,
146    C: ConnectionId,
147    T: PortType,
148{
149    // A handle owns the viewport signal and the container ref outright, rather
150    // than being kept in sync with internal copies — two-way mirroring of a
151    // signal that both sides write is a feedback loop waiting to happen.
152    let mut registry = EditorRegistry::<N, P, C, T>::new(config, on_event);
153    if let Some(h) = handle {
154        registry.viewport = h.viewport;
155    }
156    provide_context(registry.clone());
157    provide_context(crate::anchor::connected_ports(&registry));
158
159    let container_ref = handle.map(|h| h.container).unwrap_or_default();
160
161    // Measure the container so each node can compute whether it's within the
162    // visible viewport (used to cull the expensive live content of off-screen
163    // nodes while keeping them mounted — their ports stay registered so wires
164    // are unaffected).
165    // Measured from the DOM on mount, with the observer driving later changes.
166    // The observer's first callback only arrives a frame after mount (and not at
167    // all while the tab is hidden and the browser throttles it), which would
168    // otherwise leave framing (`F`) and viewport culling working off a 0x0
169    // container until the first resize.
170    let UseElementSizeReturn {
171        width: cont_w,
172        height: cont_h,
173    } = use_element_size(container_ref);
174    let reg_cs = registry.clone();
175    Effect::new(move || {
176        let (obs_w, obs_h) = (cont_w.get(), cont_h.get());
177        if let Some(el) = container_ref.get() {
178            let (w, h) = (el.offset_width() as f64, el.offset_height() as f64);
179            if w > 0.0 || h > 0.0 {
180                reg_cs.container_size.set(Size::new(w, h));
181                return;
182            }
183        }
184        reg_cs.container_size.set(Size::new(obs_w, obs_h));
185    });
186
187    // Debounce viewport → visibility_viewport so node visibility (and thus the
188    // create/dispose of off-screen node content + its server queries) settles only
189    // AFTER a pan/zoom ends. The live `viewport` still drives the CSS transform
190    // every frame, so panning stays smooth; subscriptions never churn mid-pan.
191    let reg_settle = registry.clone();
192    let settle = use_debounce_fn(
193        move || {
194            let vp = reg_settle.viewport.get_untracked();
195            reg_settle.visibility_viewport.set(vp);
196        },
197        140.0,
198    );
199    let reg_track = registry.clone();
200    Effect::new(move || {
201        let _ = reg_track.viewport.get(); // track pan/zoom
202        settle();
203    });
204
205    // Menu state — owned by the editor
206    let menu_open_at: RwSignal<Option<Position>> = RwSignal::new(None);
207    let menu_screen_pos: RwSignal<Option<Position>> = RwSignal::new(None);
208    // Track last mouse position for Tab-to-open
209    let last_mouse: RwSignal<Position> = RwSignal::new(Position::new(400.0, 300.0));
210    let menu_search_signal = menu_search.unwrap_or_else(|| RwSignal::new(String::new()));
211    let has_menu = menu_items.is_some();
212
213    // Auto-focus the editor container on mount
214    Effect::new(move || {
215        if let Some(el) = container_ref.get() {
216            let _ = el.focus();
217        }
218    });
219
220    // Sync external connections into registry
221    let reg = registry.clone();
222    Effect::new(move || {
223        let conns = connections.get();
224        reg.set_connections(conns);
225    });
226
227    // Event handlers
228    let reg_md = registry.clone();
229    let ref_md = container_ref;
230    let on_mousedown = move |ev: web_sys::MouseEvent| {
231        interaction::handle_canvas_mousedown(&reg_md, ev, &ref_md);
232    };
233
234    let reg_mm = registry.clone();
235    let ref_mm = container_ref;
236    let _mousemove_cleanup = use_event_listener(
237        leptos::prelude::document(),
238        leptos::ev::mousemove,
239        move |ev: web_sys::MouseEvent| {
240            last_mouse.set(Position::new(ev.client_x() as f64, ev.client_y() as f64));
241            interaction::handle_canvas_mousemove(&reg_mm, ev, &ref_mm);
242        },
243    );
244
245    let reg_mu = registry.clone();
246    let ref_mu = container_ref;
247    let _mouseup_cleanup = use_event_listener(
248        leptos::prelude::document(),
249        leptos::ev::mouseup,
250        move |ev: web_sys::MouseEvent| {
251            interaction::handle_canvas_mouseup(&reg_mu, ev, &ref_mu);
252        },
253    );
254
255    let reg_wh = registry.clone();
256    let ref_wh = container_ref;
257    // Wheel must be attached directly and explicitly non-passive. A normal
258    // `on:wheel` is delegated by Leptos to `window`, where browsers default
259    // wheel listeners to passive and silently ignore `prevent_default()`. The
260    // page can then scroll while the graph zooms, moving the editor underneath
261    // the pointer and making the zoom anchor appear to drift until a refresh.
262    let _wheel_cleanup = use_event_listener_with_options(
263        container_ref,
264        leptos::ev::wheel,
265        move |ev: web_sys::WheelEvent| {
266            interaction::handle_wheel(&reg_wh, ev, &ref_wh);
267        },
268        UseEventListenerOptions::default().passive(false),
269    );
270
271    let reg_kd = registry.clone();
272    let ref_kd = container_ref;
273    let on_keydown = move |ev: web_sys::KeyboardEvent| {
274        // Tab opens the menu
275        if ev.key() == "Tab" && has_menu {
276            ev.prevent_default();
277            let mouse = last_mouse.get_untracked();
278            let (ox, oy) = ref_kd.with_untracked(|el| {
279                el.as_ref()
280                    .map(|e| {
281                        let r = e.get_bounding_client_rect();
282                        (r.left(), r.top())
283                    })
284                    .unwrap_or((0.0, 0.0))
285            });
286            let vp = reg_kd.viewport.get_untracked();
287            let canvas_pos = vp.screen_to_canvas(Position::new(mouse.x - ox, mouse.y - oy));
288            menu_open_at.set(Some(canvas_pos));
289            menu_screen_pos.set(Some(mouse));
290            return;
291        }
292        interaction::handle_keydown(&reg_kd, ev, &ref_kd);
293    };
294
295    // Double-click opens the menu
296    let reg_dbl = registry.clone();
297    let on_dblclick = move |ev: web_sys::MouseEvent| {
298        if !has_menu {
299            return;
300        }
301        // Not while a draft connection is in flight — completing/cancelling a
302        // connection can land a fast click pair on the canvas, and the draft menu
303        // is reached with Tab, not by clicking. Don't pop it from a connection
304        // gesture.
305        if reg_dbl.draft_connection.with_untracked(Option::is_some) {
306            return;
307        }
308        // Only on empty canvas
309        if let Some(target) = ev.target() {
310            use leptos::wasm_bindgen::JsCast;
311            if let Some(el) = target.dyn_ref::<web_sys::Element>() {
312                if el.closest("[data-node]").ok().flatten().is_some() {
313                    return;
314                }
315                if el.closest("[data-anchor]").ok().flatten().is_some() {
316                    return;
317                }
318            }
319        }
320        let vp = reg_dbl.viewport.get_untracked();
321        let container_rect =
322            container_ref.with_untracked(|el| el.as_ref().map(|e| e.get_bounding_client_rect()));
323        let (ox, oy) = container_rect
324            .as_ref()
325            .map(|r| (r.left(), r.top()))
326            .unwrap_or((0.0, 0.0));
327        let canvas_pos = vp.screen_to_canvas(Position::new(
328            ev.client_x() as f64 - ox,
329            ev.client_y() as f64 - oy,
330        ));
331        menu_open_at.set(Some(canvas_pos));
332        menu_screen_pos.set(Some(Position::new(
333            ev.client_x() as f64,
334            ev.client_y() as f64,
335        )));
336    };
337
338    // Menu event handler — emits GraphEvent::CreateNode and clears draft
339    let reg_menu = registry.clone();
340    let on_event_menu = on_event;
341    let on_menu_event = Callback::new(move |event: NodeMenuEvent| {
342        match event {
343            NodeMenuEvent::CreateNode {
344                item_id,
345                position,
346                connect_to_port,
347            } => {
348                // Capture draft info before clearing
349                let (connect_from, connect_dir) =
350                    reg_menu.draft_connection.with_untracked(|d| match d {
351                        Some(d) => (Some(d.source_port.clone()), Some(d.origin_direction)),
352                        None => (None, None),
353                    });
354
355                // Clear the draft
356                reg_menu.draft_connection.set(None);
357
358                // Emit to consumer
359                on_event_menu.run(GraphEvent::CreateNode {
360                    item_id,
361                    position,
362                    connect_from,
363                    connect_to: connect_to_port,
364                    connect_direction: connect_dir,
365                });
366            }
367            NodeMenuEvent::Cancelled => {
368                reg_menu.draft_connection.set(None);
369            }
370        }
371        // The menu stole keyboard focus to its search input; once it closes, focus
372        // lands on <body> and the editor's key handlers (Tab to reopen, delete, …)
373        // go dead until the user clicks the canvas. Return focus to the editor on
374        // the next frame (after the menu element is gone).
375        let refocus = container_ref;
376        request_animation_frame(move || {
377            // A reopened menu or disposed pane invalidates this deferred work.
378            // Outside clicks may also have focused another pane's control.
379            if menu_open_at.try_get_untracked() != Some(None)
380                || document()
381                    .active_element()
382                    .is_some_and(|el| el.tag_name() != "BODY")
383            {
384                return;
385            }
386            if let Some(el) = refocus.try_get_untracked().flatten() {
387                let _ = el.focus();
388            }
389        });
390    });
391
392    // Mirror the menu's open state onto the registry so the interaction handlers
393    // can see it. `menu_open_at` stays the single source of truth; this is the
394    // read path for code that only has the registry (see `menu_open`).
395    let reg_menu_open = registry.clone();
396    Effect::new(move || {
397        reg_menu_open.menu_open.set(menu_open_at.get().is_some());
398    });
399
400    // Draft context for the menu (drives port sub-item visibility + type filtering)
401    let reg_draft = registry.clone();
402    let compat_cb = Callback::new(|(src, tgt): (String, String)| T::compatible_by_id(&src, &tgt));
403    let draft_context = Signal::derive(move || {
404        reg_draft.draft_connection.with(|d| {
405            d.as_ref().map(|d| {
406                let source_type_id = reg_draft.ports.with_untracked(|ports| {
407                    ports
408                        .get(&d.source_port)
409                        .map(|p| p.port_type.type_id())
410                        .unwrap_or_default()
411                });
412
413                DraftContext {
414                    origin_direction: d.origin_direction,
415                    source_type_id,
416                    is_compatible: compat_cb,
417                }
418            })
419        })
420    });
421
422    let reg_vp = registry.clone();
423    let canvas_transform = move || {
424        let vp = reg_vp.viewport.get();
425        format!(
426            "position: relative; transform: translate({}px, {}px) scale({}); transform-origin: 0 0;",
427            vp.pan_x, vp.pan_y, vp.zoom
428        )
429    };
430
431    // Mount point for node-anchored overlays (see overlay.rs).
432    let overlay_ref = NodeRef::<leptos::html::Div>::new();
433    provide_context(crate::overlay::NodeOverlayLayer {
434        mount: overlay_ref,
435        viewport: registry.viewport.into(),
436    });
437
438    // A fast drag or resize can outrun the node and leave the pointer over empty
439    // canvas — hold the gesture's cursor for its whole duration.
440    let reg_cursor = registry.clone();
441    let node_style_ctx = use_context::<crate::theme::NodeStyle>().unwrap_or_default();
442    let (cursor_dragging, cursor_resize) =
443        (node_style_ctx.cursor_dragging, node_style_ctx.cursor_resize);
444    let container_style = move || {
445        let base =
446            "position: relative; width: 100%; height: 100%; overflow: hidden; outline: none;";
447        if reg_cursor.resize_state.with(|rs| rs.is_some()) {
448            format!("{base} cursor: {cursor_resize};")
449        } else if reg_cursor.drag_state.with(|ds| ds.is_some()) {
450            format!("{base} cursor: {cursor_dragging};")
451        } else {
452            base.to_string()
453        }
454    };
455
456    // Menu items (use empty vec if not provided)
457    let menu_items_signal = menu_items.unwrap_or_else(|| Signal::derive(std::vec::Vec::new));
458
459    // Groups overlay
460    let groups_signal = groups.unwrap_or_else(|| Signal::derive(std::vec::Vec::new));
461    let groups_view = if let Some(cb) = on_group_event {
462        view! {
463            <GroupBoxOverlay<N, P, C, T>
464                groups=groups_signal
465                on_event=cb
466                on_ungroup=on_ungroup.unwrap_or_else(|| Callback::new(|_| {}))
467                on_select_all=on_select_all.unwrap_or_else(|| Callback::new(|_| {}))
468            />
469        }
470        .into_any()
471    } else {
472        view! {
473            <GroupBoxOverlay<N, P, C, T>
474                groups=groups_signal
475                on_ungroup=on_ungroup.unwrap_or_else(|| Callback::new(|_| {}))
476                on_select_all=on_select_all.unwrap_or_else(|| Callback::new(|_| {}))
477            />
478        }
479        .into_any()
480    };
481
482    let menu_screen_pos_signal = Signal::derive(move || menu_screen_pos.get());
483
484    view! {
485        <div
486            class="node-editor"
487            tabindex="0"
488            node_ref=container_ref
489            style=container_style
490            on:mousedown=on_mousedown
491            on:keydown=on_keydown
492            on:dblclick=on_dblclick
493        >
494            <div class="node-editor__canvas" style=canvas_transform>
495                <ConnectionRenderer<N, P, C, T> />
496                {groups_view}
497                {children()}
498            </div>
499            <SelectionBox<N, P, C, T> />
500            // Overlay layer: inside the pane but OUTSIDE the canvas transform,
501            // so node-anchored panels are unscaled and positioned in pane space,
502            // and are clipped by the graph rather than escaping to the document.
503            <div
504                class="node-editor__overlays"
505                node_ref=overlay_ref
506                style="position: absolute; inset: 0; overflow: hidden; \
507                       pointer-events: none; isolation: isolate;"
508            />
509        </div>
510        <NodeMenu
511            items=menu_items_signal
512            search_text=menu_search_signal
513            on_event=on_menu_event
514            open_at=menu_open_at
515            screen_pos=menu_screen_pos_signal
516            draft_context=draft_context
517        />
518    }
519}