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
158    let container_ref = handle.map(|h| h.container).unwrap_or_default();
159
160    // Measure the container so each node can compute whether it's within the
161    // visible viewport (used to cull the expensive live content of off-screen
162    // nodes while keeping them mounted — their ports stay registered so wires
163    // are unaffected).
164    // Measured from the DOM on mount, with the observer driving later changes.
165    // The observer's first callback only arrives a frame after mount (and not at
166    // all while the tab is hidden and the browser throttles it), which would
167    // otherwise leave framing (`F`) and viewport culling working off a 0x0
168    // container until the first resize.
169    let UseElementSizeReturn {
170        width: cont_w,
171        height: cont_h,
172    } = use_element_size(container_ref);
173    let reg_cs = registry.clone();
174    Effect::new(move || {
175        let (obs_w, obs_h) = (cont_w.get(), cont_h.get());
176        if let Some(el) = container_ref.get() {
177            let (w, h) = (el.offset_width() as f64, el.offset_height() as f64);
178            if w > 0.0 || h > 0.0 {
179                reg_cs.container_size.set(Size::new(w, h));
180                return;
181            }
182        }
183        reg_cs.container_size.set(Size::new(obs_w, obs_h));
184    });
185
186    // Debounce viewport → visibility_viewport so node visibility (and thus the
187    // create/dispose of off-screen node content + its server queries) settles only
188    // AFTER a pan/zoom ends. The live `viewport` still drives the CSS transform
189    // every frame, so panning stays smooth; subscriptions never churn mid-pan.
190    let reg_settle = registry.clone();
191    let settle = use_debounce_fn(
192        move || {
193            let vp = reg_settle.viewport.get_untracked();
194            reg_settle.visibility_viewport.set(vp);
195        },
196        140.0,
197    );
198    let reg_track = registry.clone();
199    Effect::new(move || {
200        let _ = reg_track.viewport.get(); // track pan/zoom
201        settle();
202    });
203
204    // Menu state — owned by the editor
205    let menu_open_at: RwSignal<Option<Position>> = RwSignal::new(None);
206    let menu_screen_pos: RwSignal<Option<Position>> = RwSignal::new(None);
207    // Track last mouse position for Tab-to-open
208    let last_mouse: RwSignal<Position> = RwSignal::new(Position::new(400.0, 300.0));
209    let menu_search_signal = menu_search.unwrap_or_else(|| RwSignal::new(String::new()));
210    let has_menu = menu_items.is_some();
211
212    // Auto-focus the editor container on mount
213    Effect::new(move || {
214        if let Some(el) = container_ref.get() {
215            let _ = el.focus();
216        }
217    });
218
219    // Sync external connections into registry
220    let reg = registry.clone();
221    Effect::new(move || {
222        let conns = connections.get();
223        reg.set_connections(conns);
224    });
225
226    // Event handlers
227    let reg_md = registry.clone();
228    let ref_md = container_ref;
229    let on_mousedown = move |ev: web_sys::MouseEvent| {
230        interaction::handle_canvas_mousedown(&reg_md, ev, &ref_md);
231    };
232
233    let reg_mm = registry.clone();
234    let ref_mm = container_ref;
235    let _mousemove_cleanup = use_event_listener(
236        leptos::prelude::document(),
237        leptos::ev::mousemove,
238        move |ev: web_sys::MouseEvent| {
239            last_mouse.set(Position::new(ev.client_x() as f64, ev.client_y() as f64));
240            interaction::handle_canvas_mousemove(&reg_mm, ev, &ref_mm);
241        },
242    );
243
244    let reg_mu = registry.clone();
245    let ref_mu = container_ref;
246    let _mouseup_cleanup = use_event_listener(
247        leptos::prelude::document(),
248        leptos::ev::mouseup,
249        move |ev: web_sys::MouseEvent| {
250            interaction::handle_canvas_mouseup(&reg_mu, ev, &ref_mu);
251        },
252    );
253
254    let reg_wh = registry.clone();
255    let ref_wh = container_ref;
256    // Wheel must be attached directly and explicitly non-passive. A normal
257    // `on:wheel` is delegated by Leptos to `window`, where browsers default
258    // wheel listeners to passive and silently ignore `prevent_default()`. The
259    // page can then scroll while the graph zooms, moving the editor underneath
260    // the pointer and making the zoom anchor appear to drift until a refresh.
261    let _wheel_cleanup = use_event_listener_with_options(
262        container_ref,
263        leptos::ev::wheel,
264        move |ev: web_sys::WheelEvent| {
265            interaction::handle_wheel(&reg_wh, ev, &ref_wh);
266        },
267        UseEventListenerOptions::default().passive(false),
268    );
269
270    let reg_kd = registry.clone();
271    let ref_kd = container_ref;
272    let on_keydown = move |ev: web_sys::KeyboardEvent| {
273        // Tab opens the menu
274        if ev.key() == "Tab" && has_menu {
275            ev.prevent_default();
276            let mouse = last_mouse.get_untracked();
277            let (ox, oy) = ref_kd.with_untracked(|el| {
278                el.as_ref()
279                    .map(|e| {
280                        let r = e.get_bounding_client_rect();
281                        (r.left(), r.top())
282                    })
283                    .unwrap_or((0.0, 0.0))
284            });
285            let vp = reg_kd.viewport.get_untracked();
286            let canvas_pos = vp.screen_to_canvas(Position::new(mouse.x - ox, mouse.y - oy));
287            menu_open_at.set(Some(canvas_pos));
288            menu_screen_pos.set(Some(mouse));
289            return;
290        }
291        interaction::handle_keydown(&reg_kd, ev, &ref_kd);
292    };
293
294    // Double-click opens the menu
295    let reg_dbl = registry.clone();
296    let on_dblclick = move |ev: web_sys::MouseEvent| {
297        if !has_menu {
298            return;
299        }
300        // Not while a draft connection is in flight — completing/cancelling a
301        // connection can land a fast click pair on the canvas, and the draft menu
302        // is reached with Tab, not by clicking. Don't pop it from a connection
303        // gesture.
304        if reg_dbl.draft_connection.with_untracked(Option::is_some) {
305            return;
306        }
307        // Only on empty canvas
308        if let Some(target) = ev.target() {
309            use leptos::wasm_bindgen::JsCast;
310            if let Some(el) = target.dyn_ref::<web_sys::Element>() {
311                if el.closest("[data-node]").ok().flatten().is_some() {
312                    return;
313                }
314                if el.closest("[data-anchor]").ok().flatten().is_some() {
315                    return;
316                }
317            }
318        }
319        let vp = reg_dbl.viewport.get_untracked();
320        let container_rect =
321            container_ref.with_untracked(|el| el.as_ref().map(|e| e.get_bounding_client_rect()));
322        let (ox, oy) = container_rect
323            .as_ref()
324            .map(|r| (r.left(), r.top()))
325            .unwrap_or((0.0, 0.0));
326        let canvas_pos = vp.screen_to_canvas(Position::new(
327            ev.client_x() as f64 - ox,
328            ev.client_y() as f64 - oy,
329        ));
330        menu_open_at.set(Some(canvas_pos));
331        menu_screen_pos.set(Some(Position::new(
332            ev.client_x() as f64,
333            ev.client_y() as f64,
334        )));
335    };
336
337    // Menu event handler — emits GraphEvent::CreateNode and clears draft
338    let reg_menu = registry.clone();
339    let on_event_menu = on_event;
340    let on_menu_event = Callback::new(move |event: NodeMenuEvent| {
341        match event {
342            NodeMenuEvent::CreateNode {
343                item_id,
344                position,
345                connect_to_port,
346            } => {
347                // Capture draft info before clearing
348                let (connect_from, connect_dir) =
349                    reg_menu.draft_connection.with_untracked(|d| match d {
350                        Some(d) => (Some(d.source_port.clone()), Some(d.origin_direction)),
351                        None => (None, None),
352                    });
353
354                // Clear the draft
355                reg_menu.draft_connection.set(None);
356
357                // Emit to consumer
358                on_event_menu.run(GraphEvent::CreateNode {
359                    item_id,
360                    position,
361                    connect_from,
362                    connect_to: connect_to_port,
363                    connect_direction: connect_dir,
364                });
365            }
366            NodeMenuEvent::Cancelled => {
367                reg_menu.draft_connection.set(None);
368            }
369        }
370        // The menu stole keyboard focus to its search input; once it closes, focus
371        // lands on <body> and the editor's key handlers (Tab to reopen, delete, …)
372        // go dead until the user clicks the canvas. Return focus to the editor on
373        // the next frame (after the menu element is gone).
374        let refocus = container_ref;
375        request_animation_frame(move || {
376            if let Some(el) = refocus.get_untracked() {
377                let _ = el.focus();
378            }
379        });
380    });
381
382    // Mirror the menu's open state onto the registry so the interaction handlers
383    // can see it. `menu_open_at` stays the single source of truth; this is the
384    // read path for code that only has the registry (see `menu_open`).
385    let reg_menu_open = registry.clone();
386    Effect::new(move || {
387        reg_menu_open.menu_open.set(menu_open_at.get().is_some());
388    });
389
390    // Draft context for the menu (drives port sub-item visibility + type filtering)
391    let reg_draft = registry.clone();
392    let compat_cb = Callback::new(|(src, tgt): (String, String)| T::compatible_by_id(&src, &tgt));
393    let draft_context = Signal::derive(move || {
394        reg_draft.draft_connection.with(|d| {
395            d.as_ref().map(|d| {
396                let source_type_id = reg_draft.ports.with_untracked(|ports| {
397                    ports
398                        .get(&d.source_port)
399                        .map(|p| p.port_type.type_id())
400                        .unwrap_or_default()
401                });
402
403                DraftContext {
404                    origin_direction: d.origin_direction,
405                    source_type_id,
406                    is_compatible: compat_cb,
407                }
408            })
409        })
410    });
411
412    let reg_vp = registry.clone();
413    let canvas_transform = move || {
414        let vp = reg_vp.viewport.get();
415        format!(
416            "position: relative; transform: translate({}px, {}px) scale({}); transform-origin: 0 0;",
417            vp.pan_x, vp.pan_y, vp.zoom
418        )
419    };
420
421    // Mount point for node-anchored overlays (see overlay.rs).
422    let overlay_ref = NodeRef::<leptos::html::Div>::new();
423    provide_context(crate::overlay::NodeOverlayLayer {
424        mount: overlay_ref,
425        viewport: registry.viewport.into(),
426    });
427
428    // A fast drag or resize can outrun the node and leave the pointer over empty
429    // canvas — hold the gesture's cursor for its whole duration.
430    let reg_cursor = registry.clone();
431    let node_style_ctx = use_context::<crate::theme::NodeStyle>().unwrap_or_default();
432    let (cursor_dragging, cursor_resize) =
433        (node_style_ctx.cursor_dragging, node_style_ctx.cursor_resize);
434    let container_style = move || {
435        let base =
436            "position: relative; width: 100%; height: 100%; overflow: hidden; outline: none;";
437        if reg_cursor.resize_state.with(|rs| rs.is_some()) {
438            format!("{base} cursor: {cursor_resize};")
439        } else if reg_cursor.drag_state.with(|ds| ds.is_some()) {
440            format!("{base} cursor: {cursor_dragging};")
441        } else {
442            base.to_string()
443        }
444    };
445
446    // Menu items (use empty vec if not provided)
447    let menu_items_signal = menu_items.unwrap_or_else(|| Signal::derive(std::vec::Vec::new));
448
449    // Groups overlay
450    let groups_signal = groups.unwrap_or_else(|| Signal::derive(std::vec::Vec::new));
451    let groups_view = if let Some(cb) = on_group_event {
452        view! {
453            <GroupBoxOverlay<N, P, C, T>
454                groups=groups_signal
455                on_event=cb
456                on_ungroup=on_ungroup.unwrap_or_else(|| Callback::new(|_| {}))
457                on_select_all=on_select_all.unwrap_or_else(|| Callback::new(|_| {}))
458            />
459        }
460        .into_any()
461    } else {
462        view! {
463            <GroupBoxOverlay<N, P, C, T>
464                groups=groups_signal
465                on_ungroup=on_ungroup.unwrap_or_else(|| Callback::new(|_| {}))
466                on_select_all=on_select_all.unwrap_or_else(|| Callback::new(|_| {}))
467            />
468        }
469        .into_any()
470    };
471
472    let menu_screen_pos_signal = Signal::derive(move || menu_screen_pos.get());
473
474    view! {
475        <div
476            class="node-editor"
477            tabindex="0"
478            node_ref=container_ref
479            style=container_style
480            on:mousedown=on_mousedown
481            on:keydown=on_keydown
482            on:dblclick=on_dblclick
483        >
484            <div class="node-editor__canvas" style=canvas_transform>
485                <ConnectionRenderer<N, P, C, T> />
486                {groups_view}
487                {children()}
488            </div>
489            <SelectionBox<N, P, C, T> />
490            // Overlay layer: inside the pane but OUTSIDE the canvas transform,
491            // so node-anchored panels are unscaled and positioned in pane space,
492            // and are clipped by the graph rather than escaping to the document.
493            <div
494                class="node-editor__overlays"
495                node_ref=overlay_ref
496                style="position: absolute; inset: 0; overflow: hidden; \
497                       pointer-events: none; isolation: isolate;"
498            />
499        </div>
500        <NodeMenu
501            items=menu_items_signal
502            search_text=menu_search_signal
503            on_event=on_menu_event
504            open_at=menu_open_at
505            screen_pos=menu_screen_pos_signal
506            draft_context=draft_context
507        />
508    }
509}