Skip to main content

leptos_node_graph/
menu.rs

1use leptos::prelude::*;
2use leptos_use::use_event_listener;
3
4use crate::theme::NodeMenuStyle;
5use crate::types::*;
6
7/// A port definition on a menu item (type-erased for menu display/filtering).
8#[derive(Clone, Debug)]
9pub struct MenuPort {
10    /// Port identifier (used in the CreateNode event).
11    pub id: String,
12    /// Display label.
13    pub label: String,
14    /// Port direction.
15    pub direction: PortDirection,
16    /// Type identifier string for compatibility checking.
17    pub type_id: String,
18}
19
20/// Category with name and optional color.
21#[derive(Clone, Debug, Default)]
22pub struct Category {
23    pub name: String,
24    pub color: Option<String>,
25}
26
27impl Category {
28    pub fn new(name: impl Into<String>) -> Self {
29        Self {
30            name: name.into(),
31            color: None,
32        }
33    }
34
35    pub fn with_color(name: impl Into<String>, color: impl Into<String>) -> Self {
36        Self {
37            name: name.into(),
38            color: Some(color.into()),
39        }
40    }
41}
42
43/// A menu item representing a node type that can be created (type-erased).
44#[derive(Clone, Debug)]
45pub struct NodeMenuItem {
46    /// Unique identifier for this node type.
47    pub id: String,
48    /// Display label.
49    pub label: String,
50    /// Optional category for grouping and header display.
51    pub category: Option<Category>,
52    /// Optional description shown below the label.
53    pub description: Option<String>,
54    /// Ports this node type has.
55    pub ports: Vec<MenuPort>,
56}
57
58/// Typed port definition for use with the builder API.
59/// Converts to `MenuPort` automatically.
60#[derive(Clone, Debug)]
61pub struct TypedPort<T: PortType> {
62    pub id: String,
63    pub label: String,
64    pub direction: PortDirection,
65    pub port_type: T,
66}
67
68impl<T: PortType> TypedPort<T> {
69    pub fn input(id: impl Into<String>, label: impl Into<String>, port_type: T) -> Self {
70        Self {
71            id: id.into(),
72            label: label.into(),
73            direction: PortDirection::Input,
74            port_type,
75        }
76    }
77
78    pub fn output(id: impl Into<String>, label: impl Into<String>, port_type: T) -> Self {
79        Self {
80            id: id.into(),
81            label: label.into(),
82            direction: PortDirection::Output,
83            port_type,
84        }
85    }
86
87    /// Convert to a type-erased MenuPort for the menu UI.
88    pub fn to_menu_port(&self) -> MenuPort {
89        MenuPort {
90            id: self.id.clone(),
91            label: self.label.clone(),
92            direction: self.direction,
93            type_id: self.port_type.type_id(),
94        }
95    }
96}
97
98/// Typed node definition for use with the builder API.
99/// Converts to `NodeMenuItem` automatically.
100pub struct TypedNodeDef<T: PortType> {
101    pub id: String,
102    pub label: String,
103    pub category: Option<Category>,
104    pub description: Option<String>,
105    pub ports: Vec<TypedPort<T>>,
106}
107
108impl<T: PortType> TypedNodeDef<T> {
109    /// Convert to a type-erased NodeMenuItem for the menu UI.
110    pub fn to_menu_item(&self) -> NodeMenuItem {
111        NodeMenuItem {
112            id: self.id.clone(),
113            label: self.label.clone(),
114            category: self.category.clone(),
115            description: self.description.clone(),
116            ports: self.ports.iter().map(|p| p.to_menu_port()).collect(),
117        }
118    }
119}
120
121/// Events emitted by the node menu.
122#[derive(Clone, Debug)]
123pub enum NodeMenuEvent {
124    /// User selected a node type to create at this canvas position.
125    CreateNode {
126        item_id: String,
127        position: Position,
128        connect_to_port: Option<String>,
129    },
130    /// Menu was closed without selection.
131    Cancelled,
132}
133
134/// Context for controlling the node menu from outside.
135#[derive(Clone)]
136pub struct NodeMenuContext {
137    pub open_at: RwSignal<Option<Position>>,
138}
139
140/// Whether the menu was opened during a draft connection.
141#[derive(Clone)]
142pub struct DraftContext {
143    pub origin_direction: PortDirection,
144    /// Type ID of the draft source port (for compatibility filtering).
145    pub source_type_id: String,
146    /// Compatibility checker: given (output_type_id, input_type_id),
147    /// returns true if they can connect.
148    pub is_compatible: Callback<(String, String), bool>,
149}
150
151impl std::fmt::Debug for DraftContext {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("DraftContext")
154            .field("origin_direction", &self.origin_direction)
155            .field("source_type_id", &self.source_type_id)
156            .finish()
157    }
158}
159
160/// A searchable node creation menu.
161///
162/// When opened during a draft connection, compatible ports are shown inline.
163#[component]
164pub fn NodeMenu(
165    /// Reactive list of menu items.
166    items: Signal<Vec<NodeMenuItem>>,
167    /// Two-way search text signal.
168    search_text: RwSignal<String>,
169    /// Callback when item is selected or menu is cancelled.
170    on_event: Callback<NodeMenuEvent>,
171    /// Position to open the menu at (canvas coordinates). None = closed.
172    open_at: RwSignal<Option<Position>>,
173    /// Screen position for rendering the menu (fixed coordinates).
174    screen_pos: Signal<Option<Position>>,
175    /// If set, menu was opened during a draft connection.
176    #[prop(optional, into)]
177    draft_context: Signal<Option<DraftContext>>,
178) -> impl IntoView {
179    provide_context(NodeMenuContext { open_at });
180
181    let ms = use_context::<NodeMenuStyle>().unwrap_or_default();
182    let input_ref = NodeRef::<leptos::html::Input>::new();
183    let (selected_index, set_selected_index) = signal(0usize);
184
185    // Focus input when menu opens
186    Effect::new(move || {
187        if open_at.get().is_some() {
188            search_text.set(String::new());
189            set_selected_index.set(0);
190            request_animation_frame(move || {
191                if let Some(el) = input_ref.get_untracked() {
192                    let _ = el.focus();
193                }
194            });
195        }
196    });
197
198    // Close on Escape or click outside (native listener so it works reliably)
199    let on_event_close = on_event;
200    let _ = use_event_listener(
201        leptos::prelude::document(),
202        leptos::ev::pointerdown,
203        move |ev: web_sys::PointerEvent| {
204            if open_at.get_untracked().is_none() {
205                return;
206            }
207            if let Some(target) = ev.target() {
208                use leptos::wasm_bindgen::JsCast;
209                if let Some(el) = target.dyn_ref::<web_sys::Element>()
210                    && el.closest("[data-node-menu]").ok().flatten().is_some()
211                {
212                    return;
213                }
214            }
215            open_at.set(None);
216            on_event_close.run(NodeMenuEvent::Cancelled);
217        },
218    );
219
220    // The node types on screen: during a draft, only those with a port that
221    // could accept the connection.
222    //
223    // Derived HERE rather than inline in the view because keyboard nav, Enter,
224    // and rendering must agree. While the filter lived only in the view,
225    // arrowing walked the UNFILTERED count — the highlight ran off the end of
226    // the visible rows and stuck there — and Enter resolved that index against
227    // the unfiltered list, creating the wrong node.
228    let visible_items = Signal::derive(move || {
229        let all = items.get();
230        let Some(dc) = draft_context.get() else {
231            return all;
232        };
233        all.into_iter()
234            .filter(|item| !compatible_ports(item, &dc).is_empty())
235            .collect()
236    });
237
238    // What the selection actually walks. While a connection is in flight you are
239    // choosing a PIN, not a node — so a node offering two compatible ports
240    // contributes two entries and the arrows step pin by pin. With no draft (or
241    // a single compatible port, where the node row is unambiguous) it stays one
242    // entry per node.
243    let visible_entries = Signal::derive(move || {
244        let all = items.get();
245        let Some(dc) = draft_context.get() else {
246            return all
247                .into_iter()
248                .map(|item| (item, None))
249                .collect::<Vec<(NodeMenuItem, Option<String>)>>();
250        };
251        all.into_iter()
252            .flat_map(|item| {
253                let ports = compatible_ports(&item, &dc);
254                match ports.len() {
255                    0 => Vec::new(),
256                    1 => vec![(item, Some(ports[0].id.clone()))],
257                    _ => ports
258                        .iter()
259                        .map(|p| (item.clone(), Some(p.id.clone())))
260                        .collect(),
261                }
262            })
263            .collect()
264    });
265
266    // Helper: emit create event and close menu
267    let emit_create = {
268        move |item_id: String, port_id: Option<String>| {
269            if let Some(pos) = open_at.get_untracked() {
270                on_event.run(NodeMenuEvent::CreateNode {
271                    item_id,
272                    position: pos,
273                    connect_to_port: port_id,
274                });
275                open_at.set(None);
276            }
277        }
278    };
279
280    // Keyboard handler
281    let on_event_key = on_event;
282    let emit_create_key = emit_create;
283    let on_keydown = move |ev: web_sys::KeyboardEvent| {
284        // Stop all keyboard events from reaching the editor
285        ev.stop_propagation();
286        let item_count = visible_entries.with_untracked(|entries| entries.len());
287
288        match ev.key().as_str() {
289            "ArrowDown" => {
290                ev.prevent_default();
291                if item_count > 0 {
292                    set_selected_index.update(|i| *i = (*i + 1).min(item_count - 1));
293                }
294            }
295            "ArrowUp" => {
296                ev.prevent_default();
297                set_selected_index.update(|i| *i = i.saturating_sub(1));
298            }
299            "Enter" => {
300                ev.prevent_default();
301                let idx = selected_index.get_untracked();
302                // The entry already carries the exact pin that was selected —
303                // no re-deriving "first compatible port", which would ignore
304                // which pin the user actually arrowed to.
305                let entry = visible_entries.with_untracked(|entries| entries.get(idx).cloned());
306                if let Some((item, connect_port)) = entry {
307                    emit_create_key(item.id, connect_port);
308                }
309            }
310            "Escape" | "Tab" => {
311                ev.prevent_default();
312                open_at.set(None);
313                on_event_key.run(NodeMenuEvent::Cancelled);
314            }
315            _ => {}
316        }
317    };
318
319    // Keep the highlighted row visible while arrowing through the list. Effects
320    // run after the DOM patch, so the direct call is normally enough; the extra
321    // frame covers layout that settles later and is a no-op when it doesn't.
322    Effect::new(move || {
323        let _ = selected_index.get();
324        scroll_selected_into_view();
325        request_animation_frame(scroll_selected_into_view);
326    });
327
328    // Reset selected index when the entry list changes
329    Effect::new(move || {
330        let count = visible_entries.with(|entries| entries.len());
331        let current = selected_index.get_untracked();
332        if current >= count && count > 0 {
333            set_selected_index.set(count - 1);
334        }
335    });
336
337    move || {
338        let _canvas_pos = open_at.get()?;
339        let sp = screen_pos.get()?;
340
341        // Clamp the spawn point to the viewport so the menu never falls off the
342        // bottom/right edge (its box is up to min-width 220px × max-height 360px).
343        // `max(8)` keeps a small margin off the top/left too.
344        let (vw, vh) = web_sys::window()
345            .map(|w| {
346                (
347                    w.inner_width()
348                        .ok()
349                        .and_then(|v| v.as_f64())
350                        .unwrap_or(1920.0),
351                    w.inner_height()
352                        .ok()
353                        .and_then(|v| v.as_f64())
354                        .unwrap_or(1080.0),
355                )
356            })
357            .unwrap_or((1920.0, 1080.0));
358        const MENU_W: f64 = 240.0;
359        const MENU_H: f64 = 360.0;
360        let left = sp.x.min((vw - MENU_W - 8.0).max(8.0)).max(8.0);
361        let top = sp.y.min((vh - MENU_H - 8.0).max(8.0)).max(8.0);
362
363        let menu_style = format!(
364            "position: fixed; left: {}px; top: {}px; z-index: 10000;",
365            left, top,
366        );
367
368        let current_items = visible_items.get();
369        let selected = selected_index.get();
370        let dc = draft_context.get();
371
372        let panel_style = format!(
373            "background: {}; border: {}; border-radius: 8px; box-shadow: {}; \
374             min-width: 220px; max-height: 360px; display: flex; flex-direction: column; overflow: hidden;",
375            ms.background, ms.border, ms.shadow
376        );
377        let search_wrapper_style = format!("padding: 8px; border-bottom: {};", ms.divider);
378        let input_style = format!(
379            "width: 100%; background: {}; border: {}; border-radius: 4px; color: {}; \
380             font-size: 12px; padding: 6px 8px; outline: none; box-sizing: border-box;",
381            ms.input_background, ms.input_border, ms.input_color
382        );
383
384        Some(view! {
385            <div style=menu_style data-node-menu="">
386                <div style=panel_style>
387                    <div style=search_wrapper_style>
388                        <input
389                            node_ref=input_ref
390                            type="text"
391                            placeholder="Search nodes..."
392                            style=input_style
393                            prop:value=move || search_text.get()
394                            on:input=move |ev| {
395                                use leptos::wasm_bindgen::JsCast;
396                                let t = ev.target().unwrap()
397                                    .unchecked_into::<web_sys::HtmlInputElement>();
398                                search_text.set(t.value());
399                                set_selected_index.set(0);
400                            }
401                            on:keydown=on_keydown
402                        />
403                    </div>
404                    <div data-node-menu-list="" style="overflow-y: auto; padding: 4px 0;">
405                        {if current_items.is_empty() {
406                            view! {
407                                <div style=format!(
408                                    "padding: 12px 16px; color: {}; font-size: 12px; text-align: center;",
409                                    ms.empty_color
410                                )>
411                                    "No matching nodes"
412                                </div>
413                            }.into_any()
414                        } else {
415                            // Tag each node with the entry index its row (or its
416                            // first pin sub-row) corresponds to, so the rendered
417                            // highlight lands on exactly what the keyboard has
418                            // selected. Must consume entries in the same order
419                            // `visible_entries` produces them.
420                            let mut rows: Vec<(NodeMenuItem, Vec<MenuPort>, usize)> = Vec::new();
421                            let mut next_entry = 0usize;
422                            for item in current_items {
423                                let ports = dc
424                                    .as_ref()
425                                    .map(|dc| compatible_ports(&item, dc))
426                                    .unwrap_or_default();
427                                let consumed = if ports.len() > 1 { ports.len() } else { 1 };
428                                rows.push((item, ports, next_entry));
429                                next_entry += consumed;
430                            }
431
432                            let mut last_category: Option<String> = None; // track by name
433                            rows
434                                .into_iter()
435                                .map(|(item, compatible_ports, base_entry)| {
436                                    // A node offering several pins is never itself
437                                    // the selection — its pins are.
438                                    let has_multi_ports = compatible_ports.len() > 1;
439                                    let is_selected = !has_multi_ports && base_entry == selected;
440                                    let emit = emit_create;
441
442                                    // Category header
443                                    let cat_name = item.category.as_ref().map(|c| c.name.clone());
444                                    let cat_header = if cat_name != last_category {
445                                        last_category.clone_from(&cat_name);
446                                        item.category.clone().map(|cat| {
447                                            let color = cat.color.unwrap_or_else(|| ms.category_color.clone());
448                                            view! {
449                                                <div style=format!(
450                                                    "padding: 4px 12px 2px; font-size: 9px; font-weight: 600; \
451                                                     text-transform: uppercase; letter-spacing: 0.05em; color: {};",
452                                                    color
453                                                )>
454                                                    {cat.name}
455                                                </div>
456                                            }
457                                        })
458                                    } else {
459                                        None
460                                    };
461
462                                    let desc = item.description.clone();
463                                    let item_id = item.id.clone();
464
465                                    let item_bg = if is_selected {
466                                        format!("background: {};", ms.hover_background)
467                                    } else {
468                                        String::new()
469                                    };
470
471                                    let item_style = format!(
472                                        "padding: 6px 12px; cursor: pointer; font-size: 12px; \
473                                         color: {}; {item_bg}", ms.item_color
474                                    );
475
476                                    // Auto-connect port for single-port or no-draft cases
477                                    let auto_port = if compatible_ports.len() == 1 {
478                                        Some(compatible_ports[0].id.clone())
479                                    } else {
480                                        None
481                                    };
482
483                                    // Node item click handler
484                                    let emit_item = emit;
485                                    let item_id_click = item_id.clone();
486                                    let auto_port_click = auto_port.clone();
487
488                                    // Pin sub-rows, each its own selectable entry.
489                                    let port_views = if has_multi_ports {
490                                        let ports_html: Vec<_> = compatible_ports.into_iter().enumerate().map(|(j, port)| {
491                                            let emit_port = emit;
492                                            let iid = item_id.clone();
493                                            let pid = port.id.clone();
494                                            let dir_icon = match port.direction {
495                                                PortDirection::Input => "› ",
496                                                PortDirection::Output => "‹ ",
497                                            };
498                                            let pid_click = pid.clone();
499                                            let iid_click = iid.clone();
500                                            // Keyboard and mouse drive the SAME
501                                            // selection, so a pin highlights the
502                                            // same way however you reached it.
503                                            let entry_idx = base_entry + j;
504                                            let is_port_selected = entry_idx == selected;
505                                            let port_bg = if is_port_selected {
506                                                format!("background: {};", ms.hover_background)
507                                            } else {
508                                                String::new()
509                                            };
510                                            let port_style = format!(
511                                                "padding: 3px 4px 3px 20px; cursor: pointer; \
512                                                 font-size: 11px; color: {}; {port_bg}", ms.port_color
513                                            );
514                                            view! {
515                                                <div
516                                                    data-menu-item-selected=is_port_selected.then_some("")
517                                                    style=port_style
518                                                    on:pointerup=move |ev: web_sys::PointerEvent| {
519                                                        ev.stop_propagation();
520                                                        ev.prevent_default();
521                                                        emit_port(iid_click.clone(), Some(pid_click.clone()));
522                                                    }
523                                                    on:mouseenter=move |_| {
524                                                        set_selected_index.set(entry_idx);
525                                                    }
526                                                >
527                                                    {dir_icon}{port.label}
528                                                </div>
529                                            }
530                                        }).collect();
531                                        Some(ports_html.into_iter().collect_view())
532                                    } else {
533                                        None
534                                    };
535
536                                    view! {
537                                        {cat_header}
538                                        <div
539                                            data-menu-item-selected=is_selected.then_some("")
540                                            style=item_style
541                                            on:pointerup=move |ev: web_sys::PointerEvent| {
542                                                ev.stop_propagation();
543                                                if has_multi_ports { return; }
544                                                emit_item(item_id_click.clone(), auto_port_click.clone());
545                                            }
546                                            on:mouseenter=move |_| {
547                                                if !has_multi_ports {
548                                                    set_selected_index.set(base_entry);
549                                                }
550                                            }
551                                        >
552                                            {item.label}
553                                            {desc.map(|d| view! {
554                                                <div style=format!("font-size: 10px; color: {}; margin-top: 2px;", ms.description_color)>
555                                                    {d}
556                                                </div>
557                                            })}
558                                            {port_views}
559                                        </div>
560                                    }
561                                })
562                                .collect_view()
563                                .into_any()
564                        }}
565                    </div>
566                </div>
567            </div>
568        })
569    }
570}
571
572/// The ports on `item` that could accept the in-flight draft connection.
573///
574/// Single source of truth for "what is compatible": the visible node list, the
575/// pin entries the keyboard walks, and the rendered sub-rows all call this, so
576/// they cannot drift apart.
577fn compatible_ports(item: &NodeMenuItem, dc: &DraftContext) -> Vec<MenuPort> {
578    let target_dir = match dc.origin_direction {
579        PortDirection::Output => PortDirection::Input,
580        PortDirection::Input => PortDirection::Output,
581    };
582    item.ports
583        .iter()
584        .filter(|p| {
585            if p.direction != target_dir {
586                return false;
587            }
588            let (src, tgt) = if dc.origin_direction == PortDirection::Output {
589                (dc.source_type_id.clone(), p.type_id.clone())
590            } else {
591                (p.type_id.clone(), dc.source_type_id.clone())
592            };
593            dc.is_compatible.run((src, tgt))
594        })
595        .cloned()
596        .collect()
597}
598
599/// Scroll the highlighted row just far enough to be fully visible — the same
600/// behavior as `scrollIntoView({block: "nearest"})`, done with client rects so
601/// it needs neither a positioned `offsetParent` nor web-sys's
602/// `ScrollIntoViewOptions` feature. A row that's already visible doesn't move,
603/// which is what keeps mouse hover (which also sets the selection) from
604/// scrolling the list under the cursor.
605fn scroll_selected_into_view() {
606    let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
607        return;
608    };
609    let Ok(Some(list)) = doc.query_selector("[data-node-menu] [data-node-menu-list]") else {
610        return;
611    };
612    let Ok(Some(item)) =
613        doc.query_selector("[data-node-menu] [data-node-menu-list] [data-menu-item-selected]")
614    else {
615        return;
616    };
617
618    let lr = list.get_bounding_client_rect();
619    let ir = item.get_bounding_client_rect();
620    let delta = if ir.top() < lr.top() {
621        ir.top() - lr.top()
622    } else if ir.bottom() > lr.bottom() {
623        ir.bottom() - lr.bottom()
624    } else {
625        return;
626    };
627    list.set_scroll_top((list.scroll_top() as f64 + delta).round() as i32);
628}
629
630fn request_animation_frame(f: impl FnOnce() + 'static) {
631    use leptos::wasm_bindgen::prelude::*;
632    let cb = Closure::once_into_js(f);
633    let _ = web_sys::window()
634        .unwrap()
635        .request_animation_frame(cb.as_ref().unchecked_ref());
636}