Skip to main content

leptos_node_graph/
node.rs

1use std::collections::HashMap;
2use std::marker::PhantomData;
3
4use leptos::prelude::*;
5use leptos::wasm_bindgen::JsCast;
6use leptos_use::{
7    UseElementSizeReturn, UseMutationObserverOptions, use_element_size, use_event_listener,
8    use_mutation_observer_with_options,
9};
10
11use crate::registry::{DragState, EditorRegistry};
12// AnchorStyle is read by anchor.rs, not directly by node.rs
13use crate::types::*;
14
15/// Context provided by a Node to its children.
16#[derive(Clone)]
17pub struct NodeContext<N: NodeId> {
18    pub id: N,
19    pub position: RwSignal<Position>,
20    pub is_selected: Signal<bool>,
21    pub is_dragging: Signal<bool>,
22    /// Measured offset of the port rows, used to refresh anchor positions.
23    pub ports_y_offset: Signal<f64>,
24    /// Measured node width, used to refresh anchor positions.
25    pub node_width: Signal<f64>,
26    /// Changes when this node's port rows mount, unmount, or move.
27    pub ports_revision: RwSignal<u64>,
28}
29
30/// The enclosing node's root element. Deliberately non-generic, so widgets in a
31/// node body (e.g. `NodeOverlay`) can anchor to the node without naming the
32/// graph's id types.
33#[derive(Clone, Copy)]
34pub struct NodeElement(pub NodeRef<leptos::html::Div>);
35
36/// Per-node visibility flag: whether the node's rectangle intersects the visible
37/// viewport (plus an overscan margin). Provided (non-generically) in each node's
38/// context so consumers can gate expensive per-anchor content — e.g. live value
39/// subscriptions — on it. Off-screen nodes stay MOUNTED (their ports remain
40/// registered, so connection wires are unaffected); only their costly content is
41/// skipped. Until the canvas is measured, the flag is false so consumers can
42/// render placeholders without constructing every node’s live content first.
43#[derive(Clone, Copy)]
44pub struct NodeVisible(pub Signal<bool>);
45
46#[component]
47pub fn Node<N, P, C, T>(
48    id: N,
49    position: RwSignal<Position>,
50    #[prop(optional)] _marker: PhantomData<(P, C, T)>,
51    /// Header content (title bar). Library measures its height.
52    #[prop(optional)]
53    header: Option<Children>,
54    /// Body content (dropdowns, controls, etc.) between header and ports.
55    /// Library measures its height.
56    #[prop(optional)]
57    body: Option<Children>,
58    /// Input port anchors (left column). Use ViewFn for reactive/dynamic ports.
59    #[prop(optional, into)]
60    inputs: ViewFn,
61    /// Output port anchors (right column). Use ViewFn for reactive/dynamic ports.
62    #[prop(optional, into)]
63    outputs: ViewFn,
64    /// Per-node accent color (the top stripe). Reactive: accepts a `String`, a
65    /// `Signal<String>`, or a closure. `None`/empty = no accent bar. Reactive so
66    /// async-resolved colors (e.g. a node's category/service color) update the
67    /// stripe once they load.
68    #[prop(optional, into)]
69    accent_color: MaybeProp<String>,
70    /// Per-node header background override. When `Some`, overrides
71    /// `NodeStyle.header_background` for this node only (e.g. category colors).
72    #[prop(optional, into)]
73    header_color: Option<String>,
74    /// Explicit node width in pixels. `None` means "auto": the node sizes from
75    /// `NodeStyle.width`, or from its content above `NodeStyle.min_width`.
76    ///
77    /// Dragging the right-edge handle writes here, so pass a signal to own and
78    /// persist what the user drags to. Omit it and the node keeps its own, which
79    /// lives as long as the component does.
80    #[prop(optional)]
81    width: Option<RwSignal<Option<f64>>>,
82) -> impl IntoView
83where
84    N: NodeId,
85    P: PortId,
86    C: ConnectionId,
87    T: PortType,
88{
89    let registry = expect_context::<EditorRegistry<N, P, C, T>>();
90    let width = width.unwrap_or_else(|| RwSignal::new(None));
91    let node_ref = NodeRef::<leptos::html::Div>::new();
92    let header_ref = NodeRef::<leptos::html::Div>::new();
93    let body_ref = NodeRef::<leptos::html::Div>::new();
94
95    // Measure header + body heights
96    let UseElementSizeReturn {
97        width: obs_w,
98        height: obs_h,
99    } = use_element_size(node_ref);
100
101    // Node size, from the DOM directly plus the observer.
102    //
103    // `use_element_size` alone isn't enough here. Its first callback lands a
104    // frame after mount (and never, while the tab is hidden and the browser
105    // throttles ResizeObserver), so output ports — whose x is node.x + width -
106    // inset — would compute from a zero width until it arrives. Measuring here
107    // covers mount and every explicit width change deterministically; the
108    // observer below still covers size changes we can't see, i.e. content.
109    let measured = RwSignal::new(Size::default());
110    Effect::new(move || {
111        let _explicit_width = width.get();
112        if let Some(el) = node_ref.get() {
113            let (w, h) = (el.offset_width() as f64, el.offset_height() as f64);
114            if w > 0.0 || h > 0.0 {
115                measured.set(Size::new(w, h));
116            }
117        }
118    });
119    // The observer is used only as a "something changed" signal, not for its
120    // numbers: it reports the CONTENT box, while port geometry is relative to the
121    // node's left edge and so needs the BORDER box. Re-measure the same way the
122    // effect above does, or a bordered theme would get a width that flip-flops by
123    // the border width depending on which effect ran last.
124    Effect::new(move || {
125        let (w, h) = (obs_w.get(), obs_h.get());
126        if (w > 0.0 || h > 0.0)
127            && let Some(el) = node_ref.get_untracked()
128        {
129            measured.set(Size::new(
130                el.offset_width() as f64,
131                el.offset_height() as f64,
132            ));
133        }
134    });
135    let node_w = Signal::derive(move || measured.get().width);
136    let node_h = Signal::derive(move || measured.get().height);
137
138    let ports_ref = NodeRef::<leptos::html::Div>::new();
139    let ports_revision = RwSignal::new(0);
140    // Keyed ports can move within a column without mounting or changing node
141    // size. Only direct row-list mutations affect pin positions.
142    use_mutation_observer_with_options(
143        ports_ref,
144        move |mutations, _| {
145            if mutations.iter().any(|mutation| {
146                mutation
147                    .target()
148                    .as_ref()
149                    .and_then(|target| target.dyn_ref::<web_sys::Element>())
150                    .is_some_and(|target| {
151                        target.has_attribute("data-node-inputs")
152                            || target.has_attribute("data-node-outputs")
153                    })
154            }) {
155                ports_revision.update(|revision| *revision += 1);
156            }
157        },
158        UseMutationObserverOptions::default()
159            .child_list(true)
160            .subtree(true),
161    );
162
163    // Measure ports div offset from node top — exact, no padding math needed.
164    // Re-derives when node height changes (triggered by header/body resize).
165    let ports_y_offset = Signal::derive(move || {
166        let _nh = node_h.get(); // track node size changes to re-derive
167        ports_ref.with(|el| el.as_ref().map(|e| e.offset_top() as f64).unwrap_or(0.0))
168    });
169    let node_width = Signal::derive(move || node_w.get());
170
171    // Viewport visibility: does this node's rect intersect the visible canvas
172    // area (screen 0..container mapped to canvas space), padded by an overscan
173    // margin so nodes near the edge stay live and don't pop while panning?
174    // Until the container is measured, keep expensive content inactive.
175    // MUST be a Memo (value-deduped), NOT Signal::derive: the viewport changes
176    // every pan frame, so a non-deduped derived signal would re-fire — and thus
177    // rebuild every visible node's content + subscriptions — on EVERY frame. The
178    // Memo only notifies when the bool actually flips (a node crossing the edge),
179    // so panning is smooth. A generous overscan keeps edge nodes live so they
180    // don't pop/rebuild during a normal pan.
181    let reg_vis = registry.clone();
182    let in_viewport = Memo::new(move |_| {
183        // Use the settled viewport so live content is not rebuilt mid-pan.
184        node_in_viewport(
185            reg_vis.container_size.get(),
186            reg_vis.visibility_viewport.get(),
187            Rect {
188                position: position.get(),
189                size: Size::new(node_w.get().max(1.0), node_h.get().max(1.0)),
190            },
191        )
192    });
193
194    // Derived state signals
195    let id_sel = id.clone();
196    let reg_sel = registry.clone();
197    let is_selected =
198        Signal::derive(move || reg_sel.selected_nodes.with(|sel| sel.contains(&id_sel)));
199
200    let id_drag = id.clone();
201    let reg_drag = registry.clone();
202    let is_dragging = Signal::derive(move || {
203        reg_drag
204            .drag_state
205            .with(|ds| ds.as_ref().is_some_and(|d| d.node_id == id_drag))
206    });
207
208    // Any node dragging (not just this one) — a fast drag can outrun the node
209    // and put the pointer over a neighbor, which should still read "grabbing".
210    let reg_any_drag = registry.clone();
211    let any_dragging = Signal::derive(move || reg_any_drag.drag_state.with(|ds| ds.is_some()));
212
213    // Provide context with measurements
214    let ctx = NodeContext {
215        id: id.clone(),
216        position,
217        is_selected,
218        is_dragging,
219        ports_y_offset,
220        node_width,
221        ports_revision,
222    };
223    provide_context(ctx);
224    provide_context(NodeVisible(in_viewport.into()));
225    provide_context(NodeElement(node_ref));
226
227    // Register node
228    let initial_pos = position.get_untracked();
229    registry.register_node(id.clone(), initial_pos, Some(position));
230
231    // Deregister on cleanup
232    let reg_cleanup = registry.clone();
233    let id_cleanup = id.clone();
234    on_cleanup(move || {
235        reg_cleanup.deregister_node(&id_cleanup);
236    });
237
238    // Sync position signal -> registry (skip during drag to avoid cycles)
239    let reg_pos = registry.clone();
240    let id_pos = id.clone();
241    Effect::new(move || {
242        let pos = position.get();
243        let dragging = reg_pos.drag_state.with_untracked(|ds| ds.is_some());
244        if !dragging {
245            reg_pos.set_node_position(&id_pos, pos);
246        }
247    });
248
249    // Track node size
250    let reg_size = registry.clone();
251    let size_id = id.clone();
252    Effect::new(move || {
253        let w = node_w.get();
254        let h = node_h.get();
255        if w > 0.0 || h > 0.0 {
256            let size = Size::new(w, h);
257            reg_size.set_node_size(&size_id, size);
258            reg_size.emit(GraphEvent::NodeResized {
259                id: size_id.clone(),
260                size,
261            });
262        }
263    });
264
265    // Mouse down handler
266    let reg_md = registry.clone();
267    let id_md = id.clone();
268    let _ = use_event_listener(
269        node_ref,
270        leptos::ev::mousedown,
271        move |ev: web_sys::MouseEvent| {
272            if ev.button() != 0 {
273                return;
274            }
275
276            // Skip anchor dots and form elements
277            if let Some(target) = ev.target() {
278                use leptos::wasm_bindgen::JsCast;
279                if let Some(el) = target.dyn_ref::<web_sys::Element>() {
280                    if el.closest("[data-anchor-dot]").ok().flatten().is_some() {
281                        return;
282                    }
283                    let tag = el.tag_name().to_uppercase();
284                    if matches!(
285                        tag.as_str(),
286                        "INPUT" | "SELECT" | "TEXTAREA" | "BUTTON" | "OPTION"
287                    ) {
288                        return;
289                    }
290                }
291            }
292
293            ev.stop_propagation();
294
295            let node_id = id_md.clone();
296
297            if ev.shift_key() {
298                reg_md.toggle_node_selection(node_id);
299            } else {
300                let already_selected = reg_md
301                    .selected_nodes
302                    .with_untracked(|sel| sel.contains(&node_id));
303                if !already_selected {
304                    reg_md.select_node(node_id.clone());
305                }
306
307                let viewport = reg_md.viewport.get_untracked();
308                let container_rect = node_ref.with_untracked(|el| {
309                    el.as_ref().and_then(|el| {
310                        el.closest(".node-editor")
311                            .ok()
312                            .flatten()
313                            .map(|container| container.get_bounding_client_rect())
314                    })
315                });
316
317                let (offset_x, offset_y) = container_rect
318                    .map(|r| (r.left(), r.top()))
319                    .unwrap_or((0.0, 0.0));
320
321                let canvas_mouse = viewport.screen_to_canvas(Position::new(
322                    ev.client_x() as f64 - offset_x,
323                    ev.client_y() as f64 - offset_y,
324                ));
325
326                let start_positions: HashMap<N, Position> =
327                    reg_md.selected_nodes.with_untracked(|sel| {
328                        reg_md.nodes.with_untracked(|nodes| {
329                            sel.iter()
330                                .filter_map(|nid| {
331                                    nodes.get(nid).map(|entry| (nid.clone(), entry.position))
332                                })
333                                .collect()
334                        })
335                    });
336
337                reg_md.drag_state.set(Some(DragState {
338                    node_id: node_id.clone(),
339                    offset: canvas_mouse,
340                    start_positions,
341                    alt_key: ev.alt_key(),
342                }));
343            }
344        },
345    );
346
347    let ns = use_context::<crate::theme::NodeStyle>().unwrap_or_default();
348    let ns2 = ns.clone();
349
350    // --- Width resize -------------------------------------------------------
351    let resizable = ns.resizable;
352    // The stored width must not be able to go below what CSS will actually
353    // render, or dragging back out starts with a dead zone.
354    let resize_min = ns
355        .resize_min_width
356        .max(crate::utils::parse_px(&ns.min_width).unwrap_or(0.0));
357    let resize_max = ns.resize_max_width;
358    let handle_w = ns.resize_handle_width;
359    let handle_color = ns.resize_handle_color.clone();
360    let cursor_resize = ns.cursor_resize.clone();
361
362    let reg_any_resize = registry.clone();
363    let any_resizing = Signal::derive(move || reg_any_resize.resize_state.with(|rs| rs.is_some()));
364
365    let reg_is_resize = registry.clone();
366    let id_is_resize = id.clone();
367    let is_resizing = Signal::derive(move || {
368        reg_is_resize
369            .resize_state
370            .with(|rs| rs.as_ref().is_some_and(|r| r.node_id == id_is_resize))
371    });
372
373    let reg_rd = registry.clone();
374    let id_rd = id.clone();
375    let on_resize_down = move |ev: web_sys::MouseEvent| {
376        if ev.button() != 0 {
377            return;
378        }
379        // Keep this off the node-drag handler on the ancestor, and off the text
380        // selection the drag would otherwise start.
381        ev.stop_propagation();
382        ev.prevent_default();
383
384        let viewport = reg_rd.viewport.get_untracked();
385        let container_rect = node_ref.with_untracked(|el| {
386            el.as_ref().and_then(|el| {
387                el.closest(".node-editor")
388                    .ok()
389                    .flatten()
390                    .map(|container| container.get_bounding_client_rect())
391            })
392        });
393        let (offset_x, offset_y) = container_rect
394            .map(|r| (r.left(), r.top()))
395            .unwrap_or((0.0, 0.0));
396        let canvas_mouse = viewport.screen_to_canvas(Position::new(
397            ev.client_x() as f64 - offset_x,
398            ev.client_y() as f64 - offset_y,
399        ));
400
401        // An auto-width node has no width to start from — measure the DOM, so the
402        // first pixel of drag doesn't jump. `offset_width` is the untransformed
403        // layout width, which is exactly what a canvas-space delta adds to.
404        let start_width = width.get_untracked().unwrap_or_else(|| {
405            node_ref
406                .with_untracked(|el| el.as_ref().map(|e| e.offset_width() as f64))
407                .unwrap_or(0.0)
408        });
409
410        reg_rd.resize_state.set(Some(crate::registry::ResizeState {
411            node_id: id_rd.clone(),
412            start_x: canvas_mouse.x,
413            start_width,
414            width_signal: width,
415            min_width: resize_min,
416            max_width: resize_max,
417        }));
418    };
419
420    // Double-click the handle to drop back to auto width.
421    let on_resize_reset = move |ev: web_sys::MouseEvent| {
422        ev.stop_propagation();
423        width.set(None);
424    };
425
426    let handle_cursor = cursor_resize.clone();
427    let handle_style = move || {
428        let bg = if is_resizing.get() {
429            handle_color.as_str()
430        } else {
431            "transparent"
432        };
433        // Positioned, so it sits above the static anchor rows that span the full
434        // node width. The dots carry z-index 1 to stay above it in turn, for
435        // themes whose `dot_inset` brings them within the handle's reach.
436        format!(
437            "position: absolute; top: 0; right: 0; width: {handle_w}px; height: 100%; \
438             z-index: 0; cursor: {handle_cursor}; background: {bg};"
439        )
440    };
441
442    let node_style = move || {
443        let pos = position.get();
444        let selected = is_selected.get();
445        let dragging = is_dragging.get();
446
447        let outline = if selected {
448            format!("outline: {};", ns.outline_selected)
449        } else {
450            String::new()
451        };
452        let shadow = if selected {
453            &ns.shadow_selected
454        } else {
455            &ns.shadow
456        };
457        let opacity = if dragging { ns.opacity_dragging } else { 1.0 };
458        // Drag affordance: anchor dots and form controls inside the node set
459        // their own cursor, so this only shows over the parts that move it. A
460        // resize can outrun the handle, so it claims the whole node while it runs.
461        let cursor = if any_resizing.get() {
462            cursor_resize.as_str()
463        } else if any_dragging.get() {
464            ns.cursor_dragging.as_str()
465        } else {
466            ns.cursor.as_str()
467        };
468
469        // A dragged width wins; otherwise the theme's fixed width if it sets one
470        // (body content elides via the node's `overflow: hidden`); otherwise size
471        // to content above min-width.
472        let width = match width.get() {
473            Some(w) => format!("width: {w}px;"),
474            None if ns.width.is_empty() => String::new(),
475            None => format!("width: {};", ns.width),
476        };
477
478        format!(
479            "position: absolute; left: {}px; top: {}px; \
480             background: {}; border: {}; border-radius: {}; \
481             min-width: {}; {width} box-shadow: {shadow}; user-select: none; \
482             opacity: {opacity}; overflow: hidden; cursor: {cursor}; {outline}",
483            pos.x, pos.y, ns.background, ns.border, ns.border_radius, ns.min_width,
484        )
485    };
486
487    // Render header and body slots
488    let header_view = header.map(|h| h());
489    // ViewFn is Fn (not FnOnce) — wrapping in move || makes it reactive
490
491    let px = ns2.padding_x;
492    let header_bg = header_color.unwrap_or_else(|| ns2.header_background.clone());
493    let header_style = format!(
494        "padding: {}px {}px; border-bottom: {}; background: {}; \
495         font-size: {}; font-weight: 600; letter-spacing: 0.03em; \
496         text-transform: uppercase; color: {};",
497        ns2.header_padding_y,
498        px,
499        ns2.header_border_bottom,
500        header_bg,
501        ns2.header_font_size,
502        ns2.header_color,
503    );
504    let has_body = body.is_some();
505    let body_view = body.map(|b| b());
506    let body_style = if has_body {
507        format!(
508            "padding: {}px {}px; border-bottom: {};",
509            ns2.body_padding_y, px, ns2.body_border_bottom,
510        )
511    } else {
512        String::new()
513    };
514    // In Stacked layout the ports section is a single vertical column (inputs
515    // then outputs below); in Columns it's two side-by-side columns.
516    let stacked = ns2.anchor_layout == crate::theme::AnchorLayout::Stacked;
517    let ports_style = if stacked {
518        format!(
519            "display: flex; flex-direction: column; padding: {}px 0;",
520            ns2.ports_padding_y,
521        )
522    } else {
523        format!(
524            "display: flex; justify-content: space-between; padding: {}px 0;",
525            ns2.ports_padding_y,
526        )
527    };
528    // Stacked rows span the full node width (dot side comes from row-reverse on
529    // outputs); Columns hugs outputs to the right edge of their column.
530    let inputs_style = "display: flex; flex-direction: column;";
531    let outputs_style = if stacked {
532        "display: flex; flex-direction: column;"
533    } else {
534        "display: flex; flex-direction: column; align-items: flex-end;"
535    };
536
537    let resize_handle = resizable.then(|| {
538        view! {
539            <div
540                data-node-resize=""
541                style=handle_style
542                on:mousedown=on_resize_down
543                on:dblclick=on_resize_reset
544            />
545        }
546    });
547
548    let accent_h = ns2.header_accent_height;
549    let accent_view = move || {
550        accent_color.get().filter(|c| !c.is_empty()).map(|c| {
551            let accent_style = format!("height: {accent_h}px; background: {c}; flex-shrink: 0;");
552            view! { <div style=accent_style /> }
553        })
554    };
555
556    view! {
557        <div
558            style=node_style
559            node_ref=node_ref
560            data-node=""
561        >
562            {accent_view}
563            <div node_ref=header_ref data-node-header="" style=header_style>
564                {header_view}
565            </div>
566            <div node_ref=body_ref data-node-body="" style=body_style>
567                {body_view}
568            </div>
569            <div node_ref=ports_ref data-node-ports="" style=ports_style>
570                <div data-node-inputs="" style=inputs_style>
571                    {move || inputs.run()}
572                </div>
573                <div data-node-outputs="" style=outputs_style>
574                    {move || outputs.run()}
575                </div>
576            </div>
577            {resize_handle}
578        </div>
579    }
580}
581
582/// A labeled field row for use inside the node body slot.
583/// Renders label + children in a flex row, styled from `NodeStyle`.
584#[component]
585pub fn NodeField(#[prop(into)] label: String, children: Children) -> impl IntoView {
586    let ns = use_context::<crate::theme::NodeStyle>().unwrap_or_default();
587    let label_style = format!(
588        "font-size: {}; color: {}; text-transform: uppercase; \
589         letter-spacing: 0.04em; min-width: {};",
590        ns.field_label_font_size, ns.field_label_color, ns.field_label_min_width,
591    );
592    let row_style = format!("display: flex; align-items: center; gap: {};", ns.field_gap,);
593    view! {
594        <div style=row_style>
595            <label style=label_style>{label}</label>
596            {children()}
597        </div>
598    }
599}
600
601fn node_in_viewport(container: Size, viewport: ViewportTransform, node: Rect) -> bool {
602    if container.width <= 0.0 || container.height <= 0.0 {
603        return false;
604    }
605    let zoom = if viewport.zoom.abs() < 1e-6 {
606        1.0
607    } else {
608        viewport.zoom
609    };
610    let tl = viewport.screen_to_canvas(Position::new(0.0, 0.0));
611    let br = viewport.screen_to_canvas(Position::new(container.width, container.height));
612    let margin = 600.0 / zoom;
613    node.position.x <= br.x + margin
614        && node.position.x + node.size.width >= tl.x - margin
615        && node.position.y <= br.y + margin
616        && node.position.y + node.size.height >= tl.y - margin
617}
618
619#[cfg(test)]
620mod visibility_tests {
621    use super::*;
622
623    #[test]
624    fn content_waits_for_measurement_and_respects_canvas_bounds() {
625        let node = Rect {
626            position: Position::new(100.0, 100.0),
627            size: Size::new(200.0, 100.0),
628        };
629        let viewport = ViewportTransform::default();
630        assert!(!node_in_viewport(Size::default(), viewport, node));
631        assert!(!node_in_viewport(Size::new(800.0, 0.0), viewport, node));
632        assert!(node_in_viewport(Size::new(800.0, 600.0), viewport, node));
633        let remote = Rect {
634            position: Position::new(2000.0, 2000.0),
635            ..node
636        };
637        assert!(!node_in_viewport(Size::new(800.0, 600.0), viewport, remote));
638        let moved = ViewportTransform {
639            pan_x: -2000.0,
640            pan_y: -2000.0,
641            zoom: 1.0,
642        };
643        assert!(node_in_viewport(Size::new(800.0, 600.0), moved, remote));
644        let near = Rect {
645            position: Position::new(900.0, 600.0),
646            ..node
647        };
648        assert!(node_in_viewport(Size::new(800.0, 600.0), viewport, near));
649    }
650}