Skip to main content

leptos_node_graph/
connection.rs

1use std::collections::{HashMap, HashSet};
2use std::marker::PhantomData;
3
4use leptos::prelude::*;
5
6use crate::registry::{ConnectionEntry, EditorRegistry, NodeEntry, PortEntry};
7use crate::subway::{self, SubwayConnection, SubwayOptions, SubwayRect, SubwayRoutingStats};
8use crate::types::*;
9use crate::utils;
10
11/// Visual endpoints for ports hidden inside collapsed compound rows.
12/// Connections retain their original port ids for selection, deletion and editing.
13#[derive(Clone)]
14pub struct PortDisplayAliases<P: PortId>(pub Signal<HashMap<P, P>>);
15
16fn display_ports<N: NodeId, P: PortId, T: PortType>(
17    mut ports: HashMap<P, PortEntry<N, P, T>>,
18    aliases: &HashMap<P, P>,
19) -> HashMap<P, PortEntry<N, P, T>> {
20    for (port, parent) in aliases {
21        if let Some(mut parent) = ports.get(parent).cloned() {
22            parent.id = port.clone();
23            ports.insert(port.clone(), parent);
24        }
25    }
26    ports
27}
28
29/// Corner rounding applied to routed polylines when drawing them.
30const SUBWAY_CORNER_RADIUS: f64 = 6.0;
31/// Frozen routes within this distance of a changed node are included in its incremental solve.
32const SUBWAY_INCREMENTAL_PROXIMITY_PAD: f64 = 48.0;
33
34/// How connections are routed between ports.
35///
36/// Provided reactively by the consumer as an `RwSignal<RoutingMode>` in
37/// context. When no context is present the renderer falls back to
38/// [`RoutingMode::Orthogonal`] so existing embeds are unchanged.
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum RoutingMode {
41    /// Right-angle "subway map" wiring (default).
42    #[default]
43    Orthogonal,
44    /// Classic bezier curves.
45    Bezier,
46}
47
48impl RoutingMode {
49    /// Build the SVG path `d` string for this routing mode.
50    fn path(self, start: Position, end: Position) -> String {
51        match self {
52            RoutingMode::Bezier => utils::bezier_path(start, end),
53            RoutingMode::Orthogonal => utils::orthogonal_path(start, end),
54        }
55    }
56}
57
58/// The deterministic, pure input to one subway solve.
59///
60/// Keeping this value separately from the result lets reactive notifications
61/// which did not change world geometry skip the router entirely.
62#[derive(Clone, Debug, PartialEq)]
63struct SubwayBatch<N, C> {
64    rect_ids: Vec<N>,
65    rects: Vec<SubwayRect>,
66    connections: Vec<SubwayBatchConnection<N, C>>,
67}
68
69#[derive(Clone, Debug, PartialEq)]
70struct SubwayBatchConnection<N, C> {
71    id: C,
72    start_node: N,
73    end_node: N,
74    input: SubwayConnection,
75}
76
77impl<N, C> SubwayBatch<N, C>
78where
79    N: NodeId,
80    C: ConnectionId,
81{
82    fn subset(&self, ids: &HashSet<C>) -> Self {
83        Self {
84            rect_ids: self.rect_ids.clone(),
85            rects: self.rects.clone(),
86            connections: self
87                .connections
88                .iter()
89                .filter(|connection| ids.contains(&connection.id))
90                .cloned()
91                .collect(),
92        }
93    }
94
95    /// Return the nodes responsible for a geometry-only change. Node/connection
96    /// population and endpoint ownership changes are structural and require a
97    /// full solve; positions and rects can be handled incrementally.
98    fn changed_nodes_since(&self, previous: &Self) -> Option<HashSet<N>> {
99        if self.rect_ids != previous.rect_ids
100            || self.connections.len() != previous.connections.len()
101        {
102            return None;
103        }
104
105        let mut changed = HashSet::new();
106        for ((id, current), old) in self.rect_ids.iter().zip(&self.rects).zip(&previous.rects) {
107            if current != old {
108                changed.insert(id.clone());
109            }
110        }
111
112        for (current, old) in self.connections.iter().zip(&previous.connections) {
113            if current.id != old.id
114                || current.start_node != old.start_node
115                || current.end_node != old.end_node
116                || current.input.start_rect != old.input.start_rect
117                || current.input.end_rect != old.input.end_rect
118            {
119                return None;
120            }
121            if current.input.start != old.input.start {
122                changed.insert(current.start_node.clone());
123            }
124            if current.input.end != old.input.end {
125                changed.insert(current.end_node.clone());
126            }
127        }
128
129        Some(changed)
130    }
131}
132
133/// Collect routing geometry in stable debug-id order. Stable node order is as
134/// important as stable connection order because endpoint rects are indices.
135fn subway_batch<N, P, C, T>(
136    conns: &HashMap<C, ConnectionEntry<P, C>>,
137    ports: &HashMap<P, PortEntry<N, P, T>>,
138    nodes: &HashMap<N, NodeEntry<N>>,
139) -> SubwayBatch<N, C>
140where
141    N: NodeId,
142    P: PortId,
143    C: ConnectionId,
144    T: PortType,
145{
146    let mut ordered_nodes: Vec<(&N, &NodeEntry<N>)> = nodes.iter().collect();
147    ordered_nodes.sort_by_cached_key(|(id, _)| format!("{id:?}"));
148
149    let mut rect_ids = Vec::with_capacity(ordered_nodes.len());
150    let mut rects = Vec::with_capacity(ordered_nodes.len());
151    let mut rect_of: HashMap<&N, usize> = HashMap::with_capacity(ordered_nodes.len());
152    for (id, node) in ordered_nodes {
153        rect_of.insert(id, rects.len());
154        rect_ids.push(id.clone());
155        rects.push(SubwayRect {
156            x: node.position.x,
157            y: node.position.y,
158            w: node.size.width,
159            h: node.size.height,
160        });
161    }
162
163    let mut ordered: Vec<(&C, &ConnectionEntry<P, C>)> = conns.iter().collect();
164    ordered.sort_by_cached_key(|(id, _)| format!("{id:?}"));
165
166    let mut connections = Vec::with_capacity(ordered.len());
167    for (id, conn) in ordered {
168        let (Some(src), Some(tgt)) = (ports.get(&conn.source), ports.get(&conn.target)) else {
169            continue;
170        };
171        connections.push(SubwayBatchConnection {
172            id: id.clone(),
173            start_node: src.node_id.clone(),
174            end_node: tgt.node_id.clone(),
175            input: SubwayConnection {
176                start: src.position,
177                end: tgt.position,
178                start_rect: rect_of.get(&src.node_id).copied(),
179                end_rect: rect_of.get(&tgt.node_id).copied(),
180            },
181        });
182    }
183
184    SubwayBatch {
185        rect_ids,
186        rects,
187        connections,
188    }
189}
190
191fn solve_subway_batch<N, C>(
192    batch: &SubwayBatch<N, C>,
193) -> (HashMap<C, Vec<Position>>, SubwayRoutingStats)
194where
195    N: NodeId,
196    C: ConnectionId,
197{
198    let inputs: Vec<_> = batch
199        .connections
200        .iter()
201        .map(|connection| connection.input)
202        .collect();
203    let (routes, stats) =
204        subway::compute_subway_routes_with_stats(&batch.rects, &inputs, &SubwayOptions::default());
205    let routes = batch
206        .connections
207        .iter()
208        .map(|connection| connection.id.clone())
209        .zip(routes)
210        .collect();
211    (routes, stats)
212}
213
214/// Choose the small batch needed for a node geometry change: every incident
215/// wire plus any frozen route close enough that the moving obstacle affects it.
216fn incremental_route_ids<N, C>(
217    batch: &SubwayBatch<N, C>,
218    previous: &SubwayBatch<N, C>,
219    changed_nodes: &HashSet<N>,
220    cached_routes: &HashMap<C, Vec<Position>>,
221) -> HashSet<C>
222where
223    N: NodeId,
224    C: ConnectionId,
225{
226    // A frozen route may be close only to where an obstacle used to be. Test
227    // both sides of the move so large jumps also straighten old detours.
228    let affected_rects: Vec<_> = batch
229        .rect_ids
230        .iter()
231        .zip(&batch.rects)
232        .chain(previous.rect_ids.iter().zip(&previous.rects))
233        .filter_map(|(id, rect)| changed_nodes.contains(id).then_some(*rect))
234        .collect();
235
236    batch
237        .connections
238        .iter()
239        .filter(|connection| {
240            changed_nodes.contains(&connection.start_node)
241                || changed_nodes.contains(&connection.end_node)
242                || cached_routes.get(&connection.id).is_some_and(|route| {
243                    affected_rects.iter().any(|rect| {
244                        subway::route_intersects_rect(
245                            route,
246                            *rect,
247                            SUBWAY_INCREMENTAL_PROXIMITY_PAD,
248                        )
249                    })
250                })
251        })
252        .map(|connection| connection.id.clone())
253        .collect()
254}
255
256#[derive(Debug, PartialEq)]
257enum SubwaySolve<C: ConnectionId> {
258    Cached,
259    Full,
260    Partial(HashSet<C>),
261}
262
263fn plan_subway_solve<N, C>(
264    batch: &SubwayBatch<N, C>,
265    previous: Option<&SubwayBatch<N, C>>,
266    cached_routes: &HashMap<C, Vec<Position>>,
267) -> SubwaySolve<C>
268where
269    N: NodeId,
270    C: ConnectionId,
271{
272    let Some(previous) = previous else {
273        return SubwaySolve::Full;
274    };
275    if batch == previous {
276        return SubwaySolve::Cached;
277    }
278    match batch.changed_nodes_since(previous) {
279        Some(changed_nodes) => SubwaySolve::Partial(incremental_route_ids(
280            batch,
281            previous,
282            &changed_nodes,
283            cached_routes,
284        )),
285        None => SubwaySolve::Full,
286    }
287}
288
289#[derive(Clone, Copy, Debug, Default, PartialEq)]
290struct ConnectionEndpoints {
291    source: Option<Position>,
292    target: Option<Position>,
293}
294
295#[derive(Clone)]
296struct ConnectionSignals {
297    endpoints: ArcRwSignal<ConnectionEndpoints>,
298    route: ArcRwSignal<Option<Vec<Position>>>,
299}
300
301struct SubwayCache<N, C> {
302    geometry: Option<SubwayBatch<N, C>>,
303    routes: HashMap<C, Vec<Position>>,
304}
305
306impl<N, C> Default for SubwayCache<N, C> {
307    fn default() -> Self {
308        Self {
309            geometry: None,
310            routes: HashMap::new(),
311        }
312    }
313}
314
315/// Style configuration for connections. Consumer provides this to customize appearance.
316#[derive(Clone, Debug)]
317pub struct ConnectionStyle {
318    pub stroke: String,
319    pub stroke_selected: String,
320    pub stroke_draft: String,
321    pub stroke_width: f64,
322    pub stroke_width_selected: f64,
323}
324
325impl Default for ConnectionStyle {
326    fn default() -> Self {
327        Self {
328            stroke: "#71717a".into(),
329            stroke_selected: "#ef4444".into(),
330            stroke_draft: "#22d3ee".into(),
331            stroke_width: 2.0,
332            stroke_width_selected: 3.0,
333        }
334    }
335}
336
337#[component]
338pub fn ConnectionRenderer<N, P, C, T>(
339    #[prop(optional)] _marker: PhantomData<(N, P, C, T)>,
340) -> impl IntoView
341where
342    N: NodeId,
343    P: PortId,
344    C: ConnectionId,
345    T: PortType,
346{
347    let registry = expect_context::<EditorRegistry<N, P, C, T>>();
348    let style_config = use_context::<ConnectionStyle>().unwrap_or_default();
349    let aliases = use_context::<PortDisplayAliases<P>>();
350    let port_registry = registry.clone();
351    let rendered_ports = Signal::derive(move || {
352        display_ports(
353            port_registry.ports.get(),
354            &aliases
355                .as_ref()
356                .map(|aliases| aliases.0.get())
357                .unwrap_or_default(),
358        )
359    });
360    // Reactive routing mode; absent context defaults to Orthogonal (subway).
361    let routing_mode = use_context::<RwSignal<RoutingMode>>();
362    let connection_signals = StoredValue::new(HashMap::<C, ConnectionSignals>::new());
363    let subway_cache = StoredValue::new(SubwayCache::<N, C>::default());
364    let last_subway_stats = StoredValue::new(None::<(SubwayRoutingStats, usize, usize)>);
365
366    // Collapse the coarse registry maps into per-connection signals. A port map
367    // update still costs one cheap walk, but only paths whose endpoints really
368    // changed receive a reactive notification.
369    {
370        let reg = registry.clone();
371        Effect::new(move |_| {
372            let conns = reg.connections.get();
373            let ports = rendered_ports.get();
374            connection_signals.update_value(|signals| {
375                signals.retain(|id, _| conns.contains_key(id));
376                for (id, connection) in &conns {
377                    let endpoints = ConnectionEndpoints {
378                        source: ports.get(&connection.source).map(|port| port.position),
379                        target: ports.get(&connection.target).map(|port| port.position),
380                    };
381                    let signals = signals
382                        .entry(id.clone())
383                        .or_insert_with(|| ConnectionSignals {
384                            endpoints: ArcRwSignal::new(endpoints),
385                            route: ArcRwSignal::new(
386                                subway_cache.with_value(|cache| cache.routes.get(id).cloned()),
387                            ),
388                        });
389                    if signals.endpoints.get_untracked() != endpoints {
390                        signals.endpoints.set(endpoints);
391                    }
392                }
393            });
394        });
395    }
396
397    // Solve routes separately from rendering. The cache filters identical
398    // geometry, and node-only changes merge a small partial solve into frozen routes.
399    {
400        let reg = registry.clone();
401        Effect::new(move |_| {
402            let mode = routing_mode.map(|mode| mode.get()).unwrap_or_default();
403            let conns = reg.connections.get();
404            let ports = rendered_ports.get();
405            let nodes = reg.nodes.get();
406            let ports_at_node_origin = ports
407                .values()
408                .filter(|port| {
409                    nodes
410                        .get(&port.node_id)
411                        .is_some_and(|node| utils::distance(port.position, node.position) < 0.01)
412                })
413                .count();
414
415            if mode == RoutingMode::Bezier {
416                subway_cache.update_value(|cache| *cache = SubwayCache::default());
417                connection_signals.with_value(|signals| {
418                    for signals in signals.values() {
419                        if signals.route.get_untracked().is_some() {
420                            signals.route.set(None);
421                        }
422                    }
423                });
424                log_subway_stats(
425                    &last_subway_stats,
426                    SubwayRoutingStats::default(),
427                    conns.len(),
428                    ports_at_node_origin,
429                    ports.len(),
430                );
431                return;
432            }
433
434            let batch = subway_batch(&conns, &ports, &nodes);
435            let solve = subway_cache.with_value(|cache| {
436                plan_subway_solve(&batch, cache.geometry.as_ref(), &cache.routes)
437            });
438
439            let stats = match solve {
440                SubwaySolve::Cached => return,
441                SubwaySolve::Full => {
442                    let (routes, stats) = solve_subway_batch(&batch);
443                    subway_cache.update_value(|cache| {
444                        cache.geometry = Some(batch.clone());
445                        cache.routes = routes.clone();
446                    });
447                    connection_signals.with_value(|signals| {
448                        for (id, signals) in signals {
449                            let route = routes.get(id).cloned();
450                            if signals.route.get_untracked() != route {
451                                signals.route.set(route);
452                            }
453                        }
454                    });
455                    stats
456                }
457                SubwaySolve::Partial(ids) => {
458                    if ids.is_empty() {
459                        subway_cache.update_value(|cache| {
460                            cache.geometry = Some(batch);
461                        });
462                        return;
463                    }
464                    let partial_batch = batch.subset(&ids);
465                    let (routes, stats) = solve_subway_batch(&partial_batch);
466                    subway_cache.update_value(|cache| {
467                        cache.geometry = Some(batch);
468                        cache.routes.extend(routes.clone());
469                    });
470                    connection_signals.with_value(|signals| {
471                        for (id, route) in routes {
472                            if let Some(signals) = signals.get(&id)
473                                && signals.route.get_untracked().as_ref() != Some(&route)
474                            {
475                                signals.route.set(Some(route));
476                            }
477                        }
478                    });
479                    stats
480                }
481            };
482
483            log_subway_stats(
484                &last_subway_stats,
485                stats,
486                conns.len(),
487                ports_at_node_origin,
488                ports.len(),
489            );
490        });
491    }
492
493    let reg_for_each = registry.clone();
494    let reg_for_children = registry.clone();
495    let sc_for_each = style_config.clone();
496    let connections_view = view! {
497        <For
498            each=move || {
499                let conns = reg_for_each.connections.get();
500                let ports = rendered_ports.get_untracked();
501                let mut ids: Vec<_> = conns.keys().cloned().collect();
502                ids.sort_by_cached_key(|id| format!("{id:?}"));
503                let mut items = Vec::with_capacity(ids.len());
504                connection_signals.update_value(|signals| {
505                    for id in ids {
506                        let endpoints = conns.get(&id).map_or_else(
507                            ConnectionEndpoints::default,
508                            |connection| ConnectionEndpoints {
509                                source: ports.get(&connection.source).map(|port| port.position),
510                                target: ports.get(&connection.target).map(|port| port.position),
511                            },
512                        );
513                        let signals = signals
514                            .entry(id.clone())
515                            .or_insert_with(|| ConnectionSignals {
516                                endpoints: ArcRwSignal::new(endpoints),
517                                route: ArcRwSignal::new(
518                                    subway_cache.with_value(|cache| cache.routes.get(&id).cloned()),
519                                ),
520                            })
521                            .clone();
522                        items.push((id, signals));
523                    }
524                });
525                items
526            }
527            key=|(id, _)| id.clone()
528            children=move |(conn_id, signals)| {
529                let endpoints_d = signals.endpoints.clone();
530                let route_d = signals.route.clone();
531                let normal_d = move || {
532                    let endpoints = endpoints_d.get();
533                    match (endpoints.source, endpoints.target) {
534                        (Some(source), Some(target)) => {
535                            let mode = routing_mode.map(|mode| mode.get()).unwrap_or_default();
536                            match route_d.get() {
537                                Some(route) if mode == RoutingMode::Orthogonal && route.len() >= 2 => {
538                                    utils::rounded_polyline_path(&route, SUBWAY_CORNER_RADIUS)
539                                }
540                                _ => mode.path(source, target),
541                            }
542                        }
543                        _ => String::new(),
544                    }
545                };
546
547                let endpoints_normal_style = signals.endpoints.clone();
548                let reg_normal_style = reg_for_children.clone();
549                let normal_style_id = conn_id.clone();
550                let normal_sc = sc_for_each.clone();
551                let normal_style = move || {
552                    let selected = reg_normal_style
553                        .selected_connections
554                        .with(|selected| selected.contains(&normal_style_id));
555                    let (stroke, width) = if selected {
556                        (&normal_sc.stroke_selected, normal_sc.stroke_width_selected)
557                    } else {
558                        (&normal_sc.stroke, normal_sc.stroke_width)
559                    };
560                    let display = if matches!(
561                        endpoints_normal_style.get(),
562                        ConnectionEndpoints { source: Some(_), target: Some(_) }
563                    ) {
564                        ""
565                    } else {
566                        "display: none;"
567                    };
568                    format!(
569                        "{display} pointer-events: stroke; cursor: pointer; stroke: {stroke}; stroke-width: {width};"
570                    )
571                };
572
573                let endpoints_data = signals.endpoints.clone();
574                let reg_click = reg_for_children.clone();
575                let click_id = conn_id.clone();
576
577                let endpoints_stub_d = signals.endpoints.clone();
578                let stub_d = move || dangling_geometry(endpoints_stub_d.get()).map_or_else(
579                    String::new,
580                    |(start, finish, _, _, _)| {
581                        routing_mode
582                            .map(|mode| mode.get())
583                            .unwrap_or_default()
584                            .path(start, finish)
585                    },
586                );
587                let endpoints_stub_style = signals.endpoints.clone();
588                let reg_stub_style = reg_for_children.clone();
589                let stub_style_id = conn_id.clone();
590                let stub_sc = sc_for_each.clone();
591                let stub_style = move || {
592                    let selected = reg_stub_style
593                        .selected_connections
594                        .with(|selected| selected.contains(&stub_style_id));
595                    let (stroke, width) = if selected {
596                        (&stub_sc.stroke_selected, stub_sc.stroke_width_selected)
597                    } else {
598                        (&stub_sc.stroke, stub_sc.stroke_width)
599                    };
600                    let display = if dangling_geometry(endpoints_stub_style.get()).is_some() {
601                        ""
602                    } else {
603                        "display: none;"
604                    };
605                    format!(
606                        "{display} pointer-events: none; stroke: {stroke}; stroke-width: {width}; stroke-dasharray: 4 3; opacity: 0.5;"
607                    )
608                };
609
610                let endpoints_q_x = signals.endpoints.clone();
611                let endpoints_q_y = signals.endpoints.clone();
612                let endpoints_anchor = signals.endpoints.clone();
613                let endpoints_text_style = signals.endpoints.clone();
614                let reg_text_style = reg_for_children.clone();
615                let text_style_id = conn_id.clone();
616                let text_sc = sc_for_each.clone();
617
618                view! {
619                    <path
620                        d=normal_d
621                        fill="none"
622                        style=normal_style
623                        data-connection=move || matches!(
624                            endpoints_data.get(),
625                            ConnectionEndpoints { source: Some(_), target: Some(_) }
626                        ).then_some("")
627                        on:mousedown=move |ev: web_sys::MouseEvent| {
628                            ev.stop_propagation();
629                            if ev.shift_key() {
630                                reg_click.selected_connections.update(|selected| {
631                                    if !selected.remove(&click_id) {
632                                        selected.insert(click_id.clone());
633                                    }
634                                });
635                            } else {
636                                reg_click.select_connection(click_id.clone());
637                            }
638                        }
639                    />
640                    <path
641                        d=stub_d
642                        fill="none"
643                        style=stub_style
644                        data-connection-dangling=move || {
645                            dangling_geometry(signals.endpoints.get()).is_some().then_some("")
646                        }
647                    />
648                    <text
649                        x=move || dangling_geometry(endpoints_q_x.get()).map_or(0.0, |(_, _, x, _, _)| x)
650                        y=move || dangling_geometry(endpoints_q_y.get()).map_or(0.0, |(_, _, _, y, _)| y)
651                        style=move || {
652                            let selected = reg_text_style
653                                .selected_connections
654                                .with(|selected| selected.contains(&text_style_id));
655                            let stroke = if selected {
656                                &text_sc.stroke_selected
657                            } else {
658                                &text_sc.stroke
659                            };
660                            let display = if dangling_geometry(endpoints_text_style.get()).is_some() {
661                                ""
662                            } else {
663                                "display: none;"
664                            };
665                            let anchor = dangling_geometry(endpoints_anchor.get())
666                                .map_or("start", |(_, _, _, _, anchor)| anchor);
667                            format!(
668                                "{display} font-size: 10px; fill: {stroke}; opacity: 0.5; font-weight: 600; pointer-events: none; text-anchor: {anchor};"
669                            )
670                        }
671                    >
672                        "?"
673                    </text>
674                }
675            }
676        />
677    };
678
679    let reg_draft = registry.clone();
680    let draft_sc = style_config.clone();
681    let draft_view = move || {
682        let mode = routing_mode.map(|mode| mode.get()).unwrap_or_default();
683        let draft = reg_draft.draft_connection.get();
684        let sc = draft_sc.clone();
685        draft.map(|draft| {
686            // When dragging from an input, swap so the curve flows left→right
687            let (start, end) = if draft.origin_direction == PortDirection::Input {
688                (draft.current_end, draft.source_position)
689            } else {
690                (draft.source_position, draft.current_end)
691            };
692            let path_d = mode.path(start, end);
693            let style = format!(
694                "pointer-events: none; stroke: {}; stroke-width: {}; stroke-dasharray: 6 4;",
695                sc.stroke_draft, sc.stroke_width
696            );
697            view! {
698                <path
699                    d=path_d
700                    fill="none"
701                    style=style
702                    data-connection-draft=""
703                />
704            }
705        })
706    };
707
708    view! {
709        <svg style="position: absolute; top: 0; left: 0; width: 10000px; height: 10000px; pointer-events: none; overflow: visible;">
710            {connections_view}
711            {draft_view}
712        </svg>
713    }
714}
715
716fn dangling_geometry(
717    endpoints: ConnectionEndpoints,
718) -> Option<(Position, Position, f64, f64, &'static str)> {
719    let (position, source_present) = match (endpoints.source, endpoints.target) {
720        (Some(position), None) => (position, true),
721        (None, Some(position)) => (position, false),
722        _ => return None,
723    };
724    let end_x = position.x + if source_present { 30.0 } else { -30.0 };
725    let end = Position::new(end_x, position.y);
726    let (start, finish) = if source_present {
727        (position, end)
728    } else {
729        (end, position)
730    };
731    Some((
732        start,
733        finish,
734        end_x + if source_present { 6.0 } else { -6.0 },
735        position.y + 4.0,
736        if source_present { "start" } else { "end" },
737    ))
738}
739
740fn log_subway_stats(
741    last_subway_stats: &StoredValue<Option<(SubwayRoutingStats, usize, usize)>>,
742    stats: SubwayRoutingStats,
743    connection_count: usize,
744    ports_at_node_origin: usize,
745    port_count: usize,
746) {
747    let signature = (stats, ports_at_node_origin, port_count);
748    let changed = last_subway_stats.with_value(|previous| *previous != Some(signature));
749    if changed {
750        last_subway_stats.set_value(Some(signature));
751        leptos::logging::log!(
752            "[subway] connections={} ports_at_node_origin={}/{} grid={}x{} ({} cells) expansions={} routed={} fallbacks={} (grid={} budget={} no_path={})",
753            connection_count,
754            ports_at_node_origin,
755            port_count,
756            stats.grid_width,
757            stats.grid_height,
758            stats.grid_cells,
759            stats.expansions,
760            stats.routed,
761            stats.fallbacks(),
762            stats.grid_fallbacks,
763            stats.budget_fallbacks,
764            stats.no_path_fallbacks,
765        );
766    }
767}
768
769#[cfg(test)]
770mod tests {
771    use super::*;
772    #[derive(Clone, Debug, PartialEq)]
773    struct TestPort;
774    impl PortType for TestPort {
775        fn compatible(_: &Self, _: &Self) -> bool {
776            true
777        }
778        fn type_id(&self) -> String {
779            "any".into()
780        }
781        fn from_type_id(_: &str) -> Self {
782            Self
783        }
784    }
785
786    #[test]
787    fn collapsed_alias_changes_display_geometry_without_changing_registry_or_connection() {
788        let parent = PortEntry {
789            id: "radius".to_owned(),
790            node_id: "node".to_owned(),
791            direction: PortDirection::Input,
792            port_type: TestPort,
793            position: Position::new(120.0, 40.0),
794            slot_index: 0,
795            offset: None,
796        };
797        let ports = HashMap::from([("radius".to_owned(), parent)]);
798        let connection = ConnectionEntry {
799            id: "wire".to_owned(),
800            source: "wave".to_owned(),
801            target: "radius.y".to_owned(),
802        };
803        let collapsed = display_ports(
804            ports.clone(),
805            &HashMap::from([("radius.y".to_owned(), "radius".to_owned())]),
806        );
807        assert_eq!(
808            collapsed.get(&connection.target).map(|port| port.position),
809            Some(Position::new(120.0, 40.0))
810        );
811        assert!(!ports.contains_key(&connection.target));
812        assert_eq!(connection.target, "radius.y");
813        let expanded = display_ports(ports, &HashMap::new());
814        assert!(!expanded.contains_key(&connection.target));
815    }
816
817    fn batch() -> SubwayBatch<String, String> {
818        SubwayBatch {
819            rect_ids: vec!["moving".into(), "fixed".into(), "other".into()],
820            rects: vec![
821                SubwayRect {
822                    x: 0.0,
823                    y: 0.0,
824                    w: 20.0,
825                    h: 20.0,
826                },
827                SubwayRect {
828                    x: 100.0,
829                    y: 0.0,
830                    w: 20.0,
831                    h: 20.0,
832                },
833                SubwayRect {
834                    x: 200.0,
835                    y: 0.0,
836                    w: 20.0,
837                    h: 20.0,
838                },
839            ],
840            connections: vec![
841                SubwayBatchConnection {
842                    id: "incident".into(),
843                    start_node: "moving".into(),
844                    end_node: "fixed".into(),
845                    input: SubwayConnection {
846                        start: Position::new(20.0, 10.0),
847                        end: Position::new(100.0, 10.0),
848                        start_rect: Some(0),
849                        end_rect: Some(1),
850                    },
851                },
852                SubwayBatchConnection {
853                    id: "nearby".into(),
854                    start_node: "fixed".into(),
855                    end_node: "other".into(),
856                    input: SubwayConnection {
857                        start: Position::new(120.0, 10.0),
858                        end: Position::new(200.0, 10.0),
859                        start_rect: Some(1),
860                        end_rect: Some(2),
861                    },
862                },
863            ],
864        }
865    }
866
867    fn cached_routes() -> HashMap<String, Vec<Position>> {
868        HashMap::from([
869            (
870                "incident".to_string(),
871                vec![Position::new(20.0, 10.0), Position::new(100.0, 10.0)],
872            ),
873            (
874                "nearby".to_string(),
875                vec![Position::new(-50.0, 30.0), Position::new(50.0, 30.0)],
876            ),
877        ])
878    }
879
880    #[test]
881    fn programmatic_single_node_move_plans_incident_and_nearby_routes() {
882        let previous = batch();
883        let mut current = previous.clone();
884        current.rects[0].x += 5.0;
885        current.connections[0].input.start.x += 5.0;
886
887        assert_eq!(
888            plan_subway_solve(&current, Some(&previous), &cached_routes()),
889            SubwaySolve::Partial(HashSet::from([
890                "incident".to_string(),
891                "nearby".to_string(),
892            ]))
893        );
894    }
895
896    #[test]
897    fn incremental_plan_includes_routes_near_only_the_previous_rect() {
898        let previous = batch();
899        let mut current = previous.clone();
900        current.rects[0].x += 500.0;
901        current.connections[0].input.start.x += 500.0;
902        let routes = cached_routes();
903        let nearby = routes.get("nearby").unwrap();
904
905        assert!(subway::route_intersects_rect(
906            nearby,
907            previous.rects[0],
908            SUBWAY_INCREMENTAL_PROXIMITY_PAD,
909        ));
910        assert!(!subway::route_intersects_rect(
911            nearby,
912            current.rects[0],
913            SUBWAY_INCREMENTAL_PROXIMITY_PAD,
914        ));
915        assert_eq!(
916            plan_subway_solve(&current, Some(&previous), &routes),
917            SubwaySolve::Partial(HashSet::from([
918                "incident".to_string(),
919                "nearby".to_string(),
920            ]))
921        );
922    }
923
924    #[test]
925    fn endpoint_diffs_are_mapped_back_to_their_nodes() {
926        let previous = batch();
927        let mut current = previous.clone();
928        current.connections[1].input.end.y += 2.0;
929
930        assert_eq!(
931            current.changed_nodes_since(&previous),
932            Some(HashSet::from(["other".to_string()]))
933        );
934    }
935
936    #[test]
937    fn final_drop_with_identical_geometry_is_a_cache_hit() {
938        let geometry = batch();
939        assert_eq!(
940            plan_subway_solve(&geometry, Some(&geometry), &cached_routes()),
941            SubwaySolve::Cached
942        );
943    }
944
945    #[test]
946    fn structural_changes_still_request_a_full_solve() {
947        let previous = batch();
948        let mut current = previous.clone();
949        current.connections.pop();
950
951        assert_eq!(
952            plan_subway_solve(&current, Some(&previous), &cached_routes()),
953            SubwaySolve::Full
954        );
955    }
956}