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