Skip to main content

leptos_node_graph/
node.rs

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