Skip to main content

leptos_node_graph/
connection.rs

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