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