Skip to main content

leptos_node_graph/
menu.rs

1use leptos::{portal::Portal, 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 menu_ref = NodeRef::<leptos::html::Div>::new();
184    let (selected_index, set_selected_index) = signal(0usize);
185
186    // Focus input when menu opens
187    Effect::new(move || {
188        if open_at.get().is_some() {
189            search_text.set(String::new());
190            set_selected_index.set(0);
191            request_animation_frame(move || {
192                // The pane may have closed before this frame runs.
193                if open_at.try_get_untracked().flatten().is_none() {
194                    return;
195                }
196                if let Some(el) = input_ref.try_get_untracked().flatten() {
197                    let _ = el.focus();
198                }
199            });
200        }
201    });
202
203    // Close on Escape or click outside (native listener so it works reliably)
204    let on_event_close = on_event;
205    let _ = use_event_listener(
206        leptos::prelude::document(),
207        leptos::ev::pointerdown,
208        move |ev: web_sys::PointerEvent| {
209            if open_at.get_untracked().is_none() {
210                return;
211            }
212            if let Some(target) = ev.target() {
213                use leptos::wasm_bindgen::JsCast;
214                if let Some(target) = target.dyn_ref::<web_sys::Node>()
215                    && menu_ref
216                        .get_untracked()
217                        .is_some_and(|menu| menu.contains(Some(target)))
218                {
219                    return;
220                }
221            }
222            open_at.set(None);
223            on_event_close.run(NodeMenuEvent::Cancelled);
224        },
225    );
226
227    // The node types on screen: during a draft, only those with a port that
228    // could accept the connection.
229    //
230    // Derived HERE rather than inline in the view because keyboard nav, Enter,
231    // and rendering must agree. While the filter lived only in the view,
232    // arrowing walked the UNFILTERED count — the highlight ran off the end of
233    // the visible rows and stuck there — and Enter resolved that index against
234    // the unfiltered list, creating the wrong node.
235    let visible_items = Signal::derive(move || {
236        let all = items.get();
237        let Some(dc) = draft_context.get() else {
238            return all;
239        };
240        all.into_iter()
241            .filter(|item| !compatible_ports(item, &dc).is_empty())
242            .collect()
243    });
244
245    // What the selection actually walks. While a connection is in flight you are
246    // choosing a PIN, not a node — so a node offering two compatible ports
247    // contributes two entries and the arrows step pin by pin. With no draft (or
248    // a single compatible port, where the node row is unambiguous) it stays one
249    // entry per node.
250    let visible_entries = Signal::derive(move || {
251        let all = items.get();
252        let Some(dc) = draft_context.get() else {
253            return all
254                .into_iter()
255                .map(|item| (item, None))
256                .collect::<Vec<(NodeMenuItem, Option<String>)>>();
257        };
258        all.into_iter()
259            .flat_map(|item| {
260                let ports = compatible_ports(&item, &dc);
261                match ports.len() {
262                    0 => Vec::new(),
263                    1 => vec![(item, Some(ports[0].id.clone()))],
264                    _ => ports
265                        .iter()
266                        .map(|p| (item.clone(), Some(p.id.clone())))
267                        .collect(),
268                }
269            })
270            .collect()
271    });
272
273    // Helper: emit create event and close menu
274    let emit_create = {
275        move |item_id: String, port_id: Option<String>| {
276            if let Some(pos) = open_at.get_untracked() {
277                on_event.run(NodeMenuEvent::CreateNode {
278                    item_id,
279                    position: pos,
280                    connect_to_port: port_id,
281                });
282                open_at.set(None);
283            }
284        }
285    };
286
287    // Keyboard handler
288    let on_event_key = on_event;
289    let emit_create_key = emit_create;
290    let on_keydown = move |ev: web_sys::KeyboardEvent| {
291        // Stop all keyboard events from reaching the editor
292        ev.stop_propagation();
293        let item_count = visible_entries.with_untracked(|entries| entries.len());
294
295        match ev.key().as_str() {
296            "ArrowDown" => {
297                ev.prevent_default();
298                if item_count > 0 {
299                    set_selected_index.update(|i| *i = (*i + 1).min(item_count - 1));
300                }
301            }
302            "ArrowUp" => {
303                ev.prevent_default();
304                set_selected_index.update(|i| *i = i.saturating_sub(1));
305            }
306            "Enter" => {
307                ev.prevent_default();
308                let idx = selected_index.get_untracked();
309                // The entry already carries the exact pin that was selected —
310                // no re-deriving "first compatible port", which would ignore
311                // which pin the user actually arrowed to.
312                let entry = visible_entries.with_untracked(|entries| entries.get(idx).cloned());
313                if let Some((item, connect_port)) = entry {
314                    emit_create_key(item.id, connect_port);
315                }
316            }
317            "Escape" | "Tab" => {
318                ev.prevent_default();
319                open_at.set(None);
320                on_event_key.run(NodeMenuEvent::Cancelled);
321            }
322            _ => {}
323        }
324    };
325
326    // Keep the highlighted row visible while arrowing through the list. Effects
327    // run after the DOM patch, so the direct call is normally enough; the extra
328    // frame covers layout that settles later and is a no-op when it doesn't.
329    Effect::new(move || {
330        let _ = selected_index.get();
331        scroll_selected_into_view(menu_ref);
332        request_animation_frame(move || scroll_selected_into_view(menu_ref));
333    });
334
335    // Reset selected index when the entry list changes
336    Effect::new(move || {
337        let count = visible_entries.with(|entries| entries.len());
338        let current = selected_index.get_untracked();
339        if current >= count && count > 0 {
340            set_selected_index.set(count - 1);
341        }
342    });
343
344    let render_menu = move || {
345        let _canvas_pos = open_at.get()?;
346        let sp = screen_pos.get()?;
347
348        // Clamp the spawn point to the viewport so the menu never falls off the
349        // bottom/right edge (its box is up to min-width 220px × max-height 360px).
350        // `max(8)` keeps a small margin off the top/left too.
351        let (vw, vh) = web_sys::window()
352            .map(|w| {
353                (
354                    w.inner_width()
355                        .ok()
356                        .and_then(|v| v.as_f64())
357                        .unwrap_or(1920.0),
358                    w.inner_height()
359                        .ok()
360                        .and_then(|v| v.as_f64())
361                        .unwrap_or(1080.0),
362                )
363            })
364            .unwrap_or((1920.0, 1080.0));
365        const MENU_W: f64 = 240.0;
366        const MENU_H: f64 = 360.0;
367        let left = sp.x.min((vw - MENU_W - 8.0).max(8.0)).max(8.0);
368        let top = sp.y.min((vh - MENU_H - 8.0).max(8.0)).max(8.0);
369
370        let menu_style = format!(
371            "position: fixed; left: {}px; top: {}px; z-index: 10000; width: min(240px, calc(100vw - 16px));",
372            left, top,
373        );
374
375        let current_items = visible_items.get();
376        let selected = selected_index.get();
377        let dc = draft_context.get();
378
379        let panel_style = format!(
380            "background: {}; border: {}; border-radius: 8px; box-shadow: {}; \
381             box-sizing: border-box; max-height: min(360px, calc(100vh - 16px)); display: flex; flex-direction: column; overflow: hidden;",
382            ms.background, ms.border, ms.shadow
383        );
384        let search_wrapper_style = format!("padding: 8px; border-bottom: {};", ms.divider);
385        let input_style = format!(
386            "width: 100%; background: {}; border: {}; border-radius: 4px; color: {}; \
387             font-size: 12px; padding: 6px 8px; outline: none; box-sizing: border-box;",
388            ms.input_background, ms.input_border, ms.input_color
389        );
390
391        Some(view! {
392            <div node_ref=menu_ref style=menu_style data-node-menu="">
393                <div style=panel_style>
394                    <div style=search_wrapper_style>
395                        <input
396                            node_ref=input_ref
397                            type="text"
398                            placeholder="Search nodes..."
399                            style=input_style
400                            prop:value=move || search_text.get()
401                            on:input=move |ev| {
402                                use leptos::wasm_bindgen::JsCast;
403                                let t = ev.target().unwrap()
404                                    .unchecked_into::<web_sys::HtmlInputElement>();
405                                search_text.set(t.value());
406                                set_selected_index.set(0);
407                            }
408                            on:keydown=on_keydown
409                        />
410                    </div>
411                    <div data-node-menu-list="" style="overflow-y: auto; padding: 4px 0;">
412                        {if current_items.is_empty() {
413                            view! {
414                                <div style=format!(
415                                    "padding: 12px 16px; color: {}; font-size: 12px; text-align: center;",
416                                    ms.empty_color
417                                )>
418                                    "No matching nodes"
419                                </div>
420                            }.into_any()
421                        } else {
422                            // Tag each node with the entry index its row (or its
423                            // first pin sub-row) corresponds to, so the rendered
424                            // highlight lands on exactly what the keyboard has
425                            // selected. Must consume entries in the same order
426                            // `visible_entries` produces them.
427                            let mut rows: Vec<(NodeMenuItem, Vec<MenuPort>, usize)> = Vec::new();
428                            let mut next_entry = 0usize;
429                            for item in current_items {
430                                let ports = dc
431                                    .as_ref()
432                                    .map(|dc| compatible_ports(&item, dc))
433                                    .unwrap_or_default();
434                                let consumed = if ports.len() > 1 { ports.len() } else { 1 };
435                                rows.push((item, ports, next_entry));
436                                next_entry += consumed;
437                            }
438
439                            let mut last_category: Option<String> = None; // track by name
440                            rows
441                                .into_iter()
442                                .map(|(item, compatible_ports, base_entry)| {
443                                    // A node offering several pins is never itself
444                                    // the selection — its pins are.
445                                    let has_multi_ports = compatible_ports.len() > 1;
446                                    let is_selected = !has_multi_ports && base_entry == selected;
447                                    let emit = emit_create;
448
449                                    // Category header
450                                    let cat_name = item.category.as_ref().map(|c| c.name.clone());
451                                    let cat_header = if cat_name != last_category {
452                                        last_category.clone_from(&cat_name);
453                                        item.category.clone().map(|cat| {
454                                            let color = cat.color.unwrap_or_else(|| ms.category_color.clone());
455                                            view! {
456                                                <div style=format!(
457                                                    "padding: 4px 12px 2px; font-size: 9px; font-weight: 600; \
458                                                     text-transform: uppercase; letter-spacing: 0.05em; color: {};",
459                                                    color
460                                                )>
461                                                    {cat.name}
462                                                </div>
463                                            }
464                                        })
465                                    } else {
466                                        None
467                                    };
468
469                                    let desc = item.description.clone();
470                                    let item_id = item.id.clone();
471
472                                    let item_bg = if is_selected {
473                                        format!("background: {};", ms.hover_background)
474                                    } else {
475                                        String::new()
476                                    };
477
478                                    let item_style = format!(
479                                        "padding: 6px 12px; cursor: pointer; font-size: 12px; \
480                                         color: {}; {item_bg}", ms.item_color
481                                    );
482
483                                    // Auto-connect port for single-port or no-draft cases
484                                    let auto_port = if compatible_ports.len() == 1 {
485                                        Some(compatible_ports[0].id.clone())
486                                    } else {
487                                        None
488                                    };
489
490                                    // Node item click handler
491                                    let emit_item = emit;
492                                    let item_id_click = item_id.clone();
493                                    let auto_port_click = auto_port.clone();
494
495                                    // Pin sub-rows, each its own selectable entry.
496                                    let port_views = if has_multi_ports {
497                                        let ports_html: Vec<_> = compatible_ports.into_iter().enumerate().map(|(j, port)| {
498                                            let emit_port = emit;
499                                            let iid = item_id.clone();
500                                            let pid = port.id.clone();
501                                            let dir_icon = match port.direction {
502                                                PortDirection::Input => "› ",
503                                                PortDirection::Output => "‹ ",
504                                            };
505                                            let pid_click = pid.clone();
506                                            let iid_click = iid.clone();
507                                            // Keyboard and mouse drive the SAME
508                                            // selection, so a pin highlights the
509                                            // same way however you reached it.
510                                            let entry_idx = base_entry + j;
511                                            let is_port_selected = entry_idx == selected;
512                                            let port_bg = if is_port_selected {
513                                                format!("background: {};", ms.hover_background)
514                                            } else {
515                                                String::new()
516                                            };
517                                            let port_style = format!(
518                                                "padding: 3px 4px 3px 20px; cursor: pointer; \
519                                                 font-size: 11px; color: {}; {port_bg}", ms.port_color
520                                            );
521                                            view! {
522                                                <div
523                                                    data-menu-item-selected=is_port_selected.then_some("")
524                                                    style=port_style
525                                                    on:pointerup=move |ev: web_sys::PointerEvent| {
526                                                        ev.stop_propagation();
527                                                        ev.prevent_default();
528                                                        emit_port(iid_click.clone(), Some(pid_click.clone()));
529                                                    }
530                                                    on:mouseenter=move |_| {
531                                                        set_selected_index.set(entry_idx);
532                                                    }
533                                                >
534                                                    {dir_icon}{port.label}
535                                                </div>
536                                            }
537                                        }).collect();
538                                        Some(ports_html.into_iter().collect_view())
539                                    } else {
540                                        None
541                                    };
542
543                                    view! {
544                                        {cat_header}
545                                        <div
546                                            data-menu-item-selected=is_selected.then_some("")
547                                            style=item_style
548                                            on:pointerup=move |ev: web_sys::PointerEvent| {
549                                                ev.stop_propagation();
550                                                if has_multi_ports { return; }
551                                                emit_item(item_id_click.clone(), auto_port_click.clone());
552                                            }
553                                            on:mouseenter=move |_| {
554                                                if !has_multi_ports {
555                                                    set_selected_index.set(base_entry);
556                                                }
557                                            }
558                                        >
559                                            {item.label}
560                                            {desc.map(|d| view! {
561                                                <div style=format!("font-size: 10px; color: {}; margin-top: 2px;", ms.description_color)>
562                                                    {d}
563                                                </div>
564                                            })}
565                                            {port_views}
566                                        </div>
567                                    }
568                                })
569                                .collect_view()
570                                .into_any()
571                        }}
572                    </div>
573                </div>
574            </div>
575        })
576    };
577
578    // Keep the reactive owner and theme context, but leave pane stacking and
579    // clipping ancestors. Only the popup escapes; graph overlays stay pane-local.
580    view! { <Portal>{render_menu.clone()}</Portal> }
581}
582
583/// The ports on `item` that could accept the in-flight draft connection.
584///
585/// Single source of truth for "what is compatible": the visible node list, the
586/// pin entries the keyboard walks, and the rendered sub-rows all call this, so
587/// they cannot drift apart.
588fn compatible_ports(item: &NodeMenuItem, dc: &DraftContext) -> Vec<MenuPort> {
589    let target_dir = match dc.origin_direction {
590        PortDirection::Output => PortDirection::Input,
591        PortDirection::Input => PortDirection::Output,
592    };
593    item.ports
594        .iter()
595        .filter(|p| {
596            if p.direction != target_dir {
597                return false;
598            }
599            let (src, tgt) = if dc.origin_direction == PortDirection::Output {
600                (dc.source_type_id.clone(), p.type_id.clone())
601            } else {
602                (p.type_id.clone(), dc.source_type_id.clone())
603            };
604            dc.is_compatible.run((src, tgt))
605        })
606        .cloned()
607        .collect()
608}
609
610/// Scroll the highlighted row just far enough to be fully visible — the same
611/// behavior as `scrollIntoView({block: "nearest"})`, done with client rects so
612/// it needs neither a positioned `offsetParent` nor web-sys's
613/// `ScrollIntoViewOptions` feature. A row that's already visible doesn't move,
614/// which is what keeps mouse hover (which also sets the selection) from
615/// scrolling the list under the cursor.
616fn scroll_selected_into_view(menu_ref: NodeRef<leptos::html::Div>) {
617    let Some(menu) = menu_ref.try_get_untracked().flatten() else {
618        return;
619    };
620    let Ok(Some(list)) = menu.query_selector("[data-node-menu-list]") else {
621        return;
622    };
623    let Ok(Some(item)) = menu.query_selector("[data-node-menu-list] [data-menu-item-selected]")
624    else {
625        return;
626    };
627
628    let lr = list.get_bounding_client_rect();
629    let ir = item.get_bounding_client_rect();
630    let delta = if ir.top() < lr.top() {
631        ir.top() - lr.top()
632    } else if ir.bottom() > lr.bottom() {
633        ir.bottom() - lr.bottom()
634    } else {
635        return;
636    };
637    list.scroll_by_with_x_and_y(0.0, delta);
638}
639
640fn request_animation_frame(f: impl FnOnce() + 'static) {
641    use leptos::wasm_bindgen::prelude::*;
642    let cb = Closure::once_into_js(f);
643    let _ = web_sys::window()
644        .unwrap()
645        .request_animation_frame(cb.as_ref().unchecked_ref());
646}