ratatui-flow 0.1.1

Node graph / flow diagram widgets for ratatui
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
use ratatui::buffer::Buffer;
use ratatui::layout::Position;
use ratatui::widgets::Widget;

use super::*;
use crate::id::{NodeId, PortId};

const MARGIN: u16 = 5;

/// Error returned by [`NodeGraph::add_node_with_id`] when the requested
/// [`NodeId`] already exists in the graph.
///
/// Note: this is **not** pushed into [`NodeGraph::diagnostics`] (which is
/// cleared on every [`calculate`][NodeGraph::calculate]); it is returned as a
/// `Result` so the caller can react immediately.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AddNodeError {
	/// The given [`NodeId`] is already in use by an existing node.
	ConflictingId,
}

impl std::fmt::Display for AddNodeError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			AddNodeError::ConflictingId => write!(f, "node id already in use"),
		}
	}
}

impl std::error::Error for AddNodeError {}

#[derive(Debug, Clone)]
pub struct NodeGraph<'a> {
	/// Nodes in render order, each tagged with its stable [`NodeId`].
	///
	/// This is a `Vec` of `(id, layout)` pairs (not indexed by id) so that
	/// [`add_node_with_id`] can accept non-contiguous ids. Lookups happen by
	/// scanning (node counts are in the low hundreds); the old "`NodeId(i)` is
	/// the vector index" convention is preserved only for graphs built via
	/// [`new`][Self::new], which assigns `NodeId(0..n)`.
	nodes: Vec<(NodeId, NodeLayout<'a>)>,
	connections: Vec<Connection<'a>>,
	placements: Map<NodeId, Rect>,
	conn_layout: ConnectionsLayout<'a>,
	width: usize,
	height: usize,
	/// Which way the graph flows (root edge + child growth axis). Defaults to
	/// [`FlowDirection::Rtl`], which is byte-for-byte identical to the
	/// pre-parameterization hard-coded layout.
	direction: FlowDirection,
	/// Auto-incrementing counter for ids handed out by [`add_node`][Self::add_node].
	/// `add_node_with_id` may push ids beyond this counter without bumping it.
	next_id: u32,
	/// True whenever a mutator changed the graph since the last
	/// [`calculate`][Self::calculate]. Mutators do **not** re-run layout
	/// automatically — callers must invoke `calculate` before reading
	/// [`positions`][Self::positions] / [`split`][Self::split] / etc., or the
	/// values will be stale.
	dirty: bool,
	/// Off-screen canvas holding the full graph's borders/ports/connections
	/// (no node *content*) after [`calculate`][Self::calculate]. Used by
	/// [`NodeGraphView`] to blit the visible window onto the screen.
	canvas: Buffer,
	/// Non-fatal problems detected during the last [`calculate`][Self::calculate]
	/// (unreachable nodes, ignored bad connections, unrouted connections).
	/// Cleared at the start of each `calculate`.
	diagnostics: Vec<Diagnostic>,
	/// Style applied to the selected node's border during stateful render (the
	/// hover node gets this style with a `DIM` modifier added). Defaults to bold
	/// yellow fg.
	highlight_style: Style,
	/// When `true`, the `to` (in) port of each connection is drawn as a direction
	/// arrow ([`arrow_symbol`][crate] — ◄/►/▼/…) pointing in the flow direction,
	/// instead of the in-port connection glyph (`┤`/`┴` family). The `from` (out)
	/// port always keeps its `├`/`┬` glyph. **Off by default**; enable with
	/// [`show_arrows`][Self::show_arrows].
	show_arrows: bool,
}

impl<'a> NodeGraph<'a> {
	pub fn new(
		nodes: Vec<NodeLayout<'a>>,
		connections: Vec<Connection<'a>>,
		width: usize,
		height: usize,
	) -> Self {
		let mut graph = Self::empty(width, height);
		// Assign NodeId(0..n) to the incoming nodes so the legacy
		// `rects[i]` / `NodeId(i)` semantics stay intact. We bump `next_id`
		// to `n` so a subsequent `add_node` keeps handing out fresh ids.
		for (i, node) in nodes.into_iter().enumerate() {
			// ids 0..n are guaranteed unique here (graph is empty).
			let _ = graph.add_node_with_id(NodeId(i as u32), node);
		}
		// Same for the supplied connections.
		for conn in connections {
			graph.add_connection(conn);
		}
		graph
	}

	/// Build an empty graph with the given canvas size. Single construction
	/// path shared by [`new`][Self::new] and incremental callers.
	fn empty(width: usize, height: usize) -> Self {
		let canvas = Buffer::empty(Rect {
			x: 0,
			y: 0,
			width: width as u16,
			height: height as u16,
		});
		Self {
			nodes: Vec::new(),
			connections: Vec::new(),
			conn_layout: ConnectionsLayout::new(width, height),
			placements: Default::default(),
			width,
			height,
			direction: FlowDirection::default(),
			next_id: 0,
			dirty: true,
			canvas,
			diagnostics: Vec::new(),
			highlight_style: Style::default()
				.add_modifier(Modifier::BOLD)
				.fg(Color::Yellow),
			show_arrows: false,
		}
	}

	// ----- configuration --------------------------------------------------

	/// Set the graph's [`FlowDirection`] (which edge the root anchors to and
	/// which way children flow). The graph is marked dirty; call
	/// [`calculate`][Self::calculate] before reading positions.
	///
	/// Defaults to [`FlowDirection::Rtl`] (the original hard-coded behavior).
	#[must_use]
	pub fn with_direction(mut self, direction: FlowDirection) -> Self {
		self.direction = direction;
		self.dirty = true;
		self
	}

	/// The graph's configured [`FlowDirection`].
	pub fn direction(&self) -> FlowDirection {
		self.direction
	}

	/// Set the highlight [`Style`] applied to the **selected** node's border
	/// during stateful render (see [`FlowState::selection`]). The **hover**
	/// node's border gets this style with an added [`Modifier::DIM`] so the two
	/// states stay visually distinct. Defaults to bold yellow foreground.
	///
	/// Only the border is recolored (the port glyphs on the border keep their
	/// symbols and pick up the highlight's fg/modifier); node content is never
	/// touched.
	#[must_use]
	pub fn highlight_style(self, style: Style) -> Self {
		let mut this = self;
		this.highlight_style = style;
		this
	}

	/// Toggle drawing a **direction arrow** on each connection's `to` (in) port,
	/// pointing in the flow direction (e.g. `◄` for `Rtl`, `▶` for `Ltr`, `▼`
	/// for `Ttb`). **Off by default** — pass `true` to replace the in-port
	/// connection glyph (`┤`/`┴` family) with an arrow so the flow direction
	/// reads at a glance. The `from` (out) port always keeps its `├`/`┬` glyph.
	#[must_use]
	pub fn show_arrows(mut self, on: bool) -> Self {
		self.show_arrows = on;
		self
	}

	// ----- mutators -------------------------------------------------------

	/// Append a node, assigning it the next fresh [`NodeId`] (and bumping the
	/// internal counter). The graph is marked dirty; you must call
	/// [`calculate`][Self::calculate] before reading positions.
	///
	/// `node.title`/content strings should outlive the graph; using a
	/// `&'static str` is the common case.
	pub fn add_node(&mut self, node: NodeLayout<'a>) -> NodeId {
		let id = NodeId(self.next_id);
		self.next_id += 1;
		// next_id is monotonically increasing, so the id is guaranteed unique.
		let _ = self.add_node_with_id(id, node);
		id
	}

	/// Append a node with a caller-chosen [`NodeId`]. Returns
	/// [`AddNodeError::ConflictingId`] if `id` is already in use; otherwise the
	/// node is inserted (preserving render order) and the graph is marked dirty.
	///
	/// The id need not be contiguous — this is the path used to support
	/// non-contiguous node ids. The auto-increment counter is bumped past `id`
	/// only if `id` would otherwise collide with a future `add_node` result.
	pub fn add_node_with_id(
		&mut self,
		id: NodeId,
		node: NodeLayout<'a>,
	) -> Result<(), AddNodeError> {
		if self.has_node(id) {
			return Err(AddNodeError::ConflictingId);
		}
		// keep next_id strictly greater than any id ever inserted so a later
		// add_node() can't hand out an id that add_node_with_id already took.
		if id.0 >= self.next_id {
			self.next_id = id.0 + 1;
		}
		self.nodes.push((id, node));
		self.dirty = true;
		Ok(())
	}

	/// Append a [`Connection`]. The graph is marked dirty.
	pub fn add_connection(&mut self, conn: Connection<'a>) {
		self.connections.push(conn);
		self.dirty = true;
	}

	/// Remove the node with the given [`NodeId`] and cascade-delete every
	/// [`Connection`] that references it (on either endpoint). No-op (returns
	/// `false`) if `id` is not in the graph. The graph is marked dirty.
	///
	/// Returns `true` if a node was actually removed.
	pub fn remove_node(&mut self, id: NodeId) -> bool {
		let before = self.nodes.len();
		self.nodes.retain(|(nid, _)| *nid != id);
		let removed = self.nodes.len() != before;
		if removed {
			// cascade: drop any connection touching the removed node.
			self.connections.retain(|c| c.from_node != id && c.to_node != id);
			self.dirty = true;
		}
		removed
	}

	/// Remove the first [`Connection`] matching the given endpoints. No-op
	/// (returns `false`) if no such connection exists. The graph is marked dirty.
	///
	/// Returns `true` if a connection was removed.
	pub fn remove_connection(
		&mut self,
		from: NodeId,
		from_port: PortId,
		to: NodeId,
		to_port: PortId,
	) -> bool {
		let before = self.connections.len();
		if let Some(pos) = self.connections.iter().position(|c| {
			c.from_node == from
				&& c.from_port == from_port
				&& c.to_node == to
				&& c.to_port == to_port
		}) {
			self.connections.remove(pos);
		}
		let removed = self.connections.len() != before;
		if removed {
			self.dirty = true;
		}
		removed
	}

	// ----- queries / getters ---------------------------------------------

	/// `true` if a node with the given [`NodeId`] exists in the graph.
	pub fn has_node(&self, id: NodeId) -> bool {
		self.nodes.iter().any(|(nid, _)| *nid == id)
	}

	/// `true` if the graph changed since the last [`calculate`][Self::calculate]
	/// (any node/connection added or removed). Mutators do not re-run layout
	/// automatically, so a dirty graph means [`positions`] / [`split`] may be
	/// stale until you call `calculate`.
	///
	/// [`positions`]: Self::positions
	/// [`split`]: Self::split
	pub fn is_dirty(&self) -> bool {
		self.dirty
	}

	/// All node placements from the last [`calculate`][Self::calculate], keyed
	/// by [`NodeId`]. Each [`Rect`] is the node's **full frame** (border
	/// included) in **canvas coordinates** (origin top-left of the off-screen
	/// canvas, x growing leftwards — see [`split`] for the mirroring).
	///
	/// [`split`]: Self::split
	pub fn positions(&self) -> &Map<NodeId, Rect> {
		&self.placements
	}

	/// The full-frame [`Rect`] (border included, canvas coordinates) of a
	/// single node, or `None` if the node was not placed (unreachable / unknown
	/// / never calculated).
	pub fn node_rect(&self, id: NodeId) -> Option<Rect> {
		self.placements.get(&id).copied()
	}

	/// Internal helper: borrow the [`NodeLayout`] for a node id, if present.
	fn node_layout(&self, id: NodeId) -> Option<&NodeLayout<'a>> {
		self.nodes.iter().find_map(|(nid, n)| (*nid == id).then_some(n))
	}

	/// The full-graph canvas (borders/ports/connections only, no content)
	/// rendered during [`calculate`][Self::calculate]. Width/height match the
	/// values passed to [`new`][Self::new].
	///
	/// Exposed so [`NodeGraphView`] can blit a scrolled window from it.
	pub(crate) fn canvas(&self) -> &Buffer {
		&self.canvas
	}

	pub fn calculate(&mut self) {
		self.placements.clear();
		self.diagnostics.clear();
		self.dirty = false;

		// Build the set of known node ids up front so the connection filter
		// below doesn't need to re-borrow `self` (which would conflict with
		// the `&mut self.diagnostics` push for invalid refs).
		let known_ids: Set<NodeId> = self.nodes.iter().map(|(id, _)| *id).collect();

		// filter out connections that reference unknown node ids. these
		// would otherwise panic on indexing later. we keep `self.connections`
		// untouched and only work off this local slice for the rest of
		// calculate().
		let mut bad_refs: Vec<Diagnostic> = Vec::new();
		let valid_conns: Vec<Connection<'a>> = self
			.connections
			.iter()
			.copied()
			.filter(|ea| {
				if !known_ids.contains(&ea.from_node) || !known_ids.contains(&ea.to_node)
				{
					log::warn!(
						"skipping connection: node id not present \
						 (from_node={}, to_node={})",
						ea.from_node,
						ea.to_node,
					);
					bad_refs.push(Diagnostic::InvalidConnectionRef {
						from_node: ea.from_node,
						to_node: ea.to_node,
					});
					false
				} else {
					true
				}
			})
			.collect();
		self.diagnostics.append(&mut bad_refs);

		// find root nodes: every node id that is never a `from_node`.
		let mut roots: Set<_> = self.nodes.iter().map(|(id, _)| *id).collect();
		for ea_connection in valid_conns.iter() {
			roots.remove(&ea_connection.from_node);
		}

		// place them and their children (recursively)
		let mut main_chain = Vec::new();
		let mut visited = Set::new();
		for ea_root in roots {
			self.place_node(ea_root, 0, 0, &mut main_chain, &mut visited, &valid_conns);
			assert!(main_chain.is_empty());
		}

		// calculate connections (eventually, this should be done during node
		// placement, but thats really complicated and i dont wanna deal with that
		// right now. essentially, adding non-trivial connections nudges nodes,
		// and nudging nodes nudges existing connections.)
		let mut conn_map = Map::<(NodeId, PortId), usize>::new();
		let mut next_idx = 1;
		for ea_conn in valid_conns.iter() {
			// a connection may reference a node that never got placed (e.g. one
			// that was only reachable through a cycle that broke placement).
			// skip those defensively instead of indexing into placements.
			let (Some(&a_pos), Some(&b_pos)) = (
				self.placements.get(&ea_conn.from_node),
				self.placements.get(&ea_conn.to_node),
			) else {
				log::warn!(
					"skipping connection layout: endpoint not placed \
					 (from_node={}, to_node={})",
					ea_conn.from_node,
					ea_conn.to_node
				);
				continue;
			};
			// NOTE: canvas main axis is mirrored relative to layout coords for
			// Rtl/Btt (see FlowDirection). Compute each port's canvas point from
			// its layout rect + port index, parameterized by the flow direction.
			//
			// Horizontal (Ltr/Rtl): the main axis is x. The `from` (child) port
			// sits at the node's main-axis leading edge (layout x), the `to`
			// (parent) port one cell outside the trailing edge (layout right);
			// the cross axis (y) is top + port + 1.
			//
			// Vertical (Ttb/Btt): the main axis is y, cross axis is x. Ports run
			// along the node's width instead of its height, and the main-axis
			// mirror (if any) is applied to y.
			let dir = self.direction;
			let (a_point, b_point) = if dir.is_horizontal() {
				// defensively clamp port offsets to the node's inner height.
				let from_port = clamp_port(ea_conn.from_port.0 as usize, a_pos.height);
				let to_port = clamp_port(ea_conn.to_port.0 as usize, b_pos.height);
				let mw = self.width;
				// `from` (child) port at the node's main-axis leading edge
				// (layout left); `to` (parent) port one cell outside the
				// trailing edge (layout right). mirror_axis maps layout→canvas.
				let ax = mirror_axis(mw, a_pos.left() as usize, dir);
				let bx = mirror_axis(mw, b_pos.right() as usize, dir).saturating_sub(1);
				let a = (ax, a_pos.top() as usize + from_port + 1);
				let b = (bx, b_pos.top() as usize + to_port + 1);
				(a, b)
			} else {
				// vertical: ports index along the node's width (cross axis = x).
				// `from` (child) port at the node's top edge (layout top), `to`
				// (parent) port one cell outside the bottom edge (layout bottom).
				let from_port = clamp_port(ea_conn.from_port.0 as usize, a_pos.width);
				let to_port = clamp_port(ea_conn.to_port.0 as usize, b_pos.width);
				let mh = self.height;
				let ay = mirror_axis(mh, a_pos.top() as usize, dir);
				let by = mirror_axis(mh, b_pos.bottom() as usize, dir);
				let a = (a_pos.left() as usize + from_port + 1, ay);
				let b = (b_pos.left() as usize + to_port + 1, by);
				(a, b)
			};
			self.conn_layout.insert_port(
				false,
				ea_conn.from_node,
				ea_conn.from_port,
				a_point,
			);
			self.conn_layout.insert_port(true, ea_conn.to_node, ea_conn.to_port, b_point);
			let key = (ea_conn.from_node, ea_conn.from_port);
			conn_map.entry(key).or_insert_with(|| {
				let idx = next_idx;
				next_idx += 1;
				idx
			});
			self.conn_layout.push_connection((*ea_conn, conn_map[&key]));
			let vertical = !dir.is_horizontal();
			self.conn_layout.block_port(a_point, vertical);
			self.conn_layout.block_port(b_point, vertical);
		}
		for mut ea_placement in self.placements.values().cloned() {
			if self.direction.is_horizontal() && self.direction.mirror_main_axis() {
				ea_placement.x = (self.width as u16)
					.saturating_sub(ea_placement.x + ea_placement.width);
			} else if !self.direction.is_horizontal() && self.direction.mirror_main_axis()
			{
				ea_placement.y = (self.height as u16)
					.saturating_sub(ea_placement.y + ea_placement.height);
			}
			self.conn_layout.block_zone(ea_placement);
		}
		self.conn_layout.calculate(self.direction);

		// pull routing failures (RoutingFailed) up from the connection layout
		// into the graph-level diagnostics. `append` moves conn_layout's buffer
		// in wholesale and leaves it empty, which is fine — conn_layout's
		// diagnostics aren't read again after this point and are repopulated
		// on the next calculate().
		self.diagnostics.append(&mut self.conn_layout.diagnostics);

		// any node that never got a placement is unreachable (not on any root's
		// upstream chain — e.g. a pure cycle or an isolated node). record it.
		for (node_id, _) in &self.nodes {
			if !self.placements.contains_key(node_id) {
				log::warn!("unreachable node not placed (node={})", node_id);
				self.diagnostics.push(Diagnostic::UnplacedNode { node: *node_id });
			}
		}

		// Re-render the whole graph's borders/ports/connections (no node
		// *content*) into the off-screen canvas. This runs once per layout; the
		// viewport widget then just blits a scrolled window from it each frame
		// instead of re-laying-out.
		//
		// Render into a fresh local buffer first, then assign: `render_to` borrows
		// `&self` (for nodes/placements/connections), so we can't hand it
		// `&mut self.canvas` at the same time.
		let canvas_rect = Rect {
			x: 0,
			y: 0,
			width: self.width as u16,
			height: self.height as u16,
		};
		let mut canvas = Buffer::empty(canvas_rect);
		self.render_to(canvas_rect, &mut canvas);
		self.canvas = canvas;
	}

	/// Non-fatal problems detected during the most recent
	/// [`calculate`][Self::calculate]: unreachable (unplaced) nodes, ignored
	/// out-of-bounds connections, and connections that couldn't be routed.
	///
	/// The slice is cleared at the start of each `calculate`, so it always
	/// reflects the latest run. Each entry is also emitted via `log::warn!`.
	pub fn diagnostics(&self) -> &[Diagnostic] {
		&self.diagnostics
	}

	/// Place a node and recurse into its children.
	///
	/// `x` is the **main-axis** coordinate (the flow direction — children
	/// advance along it away from the root); `y` is the **cross-axis**
	/// coordinate (siblings stack along it). For horizontal flows (`Ltr`/`Rtl`)
	/// the main axis is x and the cross axis is y; for vertical flows it is
	/// reversed. The direction is read from `self.direction`.
	fn place_node(
		&mut self,
		idx_node: NodeId,
		x: u16,
		y: u16,
		main_chain: &mut Vec<NodeId>,
		visited: &mut Set<NodeId>,
		conns: &[Connection<'a>],
	) {
		// cycle guard: if this node was already placed (reachable again through
		// a cycle), don't re-place or recurse. this is what prevents stack
		// overflows on root-reachable cycles.
		if self.placements.contains_key(&idx_node) || !visited.insert(idx_node) {
			return;
		}

		// place the node
		let Some(node_layout) = self.node_layout(idx_node) else {
			// node id not present (defensive; calculate() already filtered).
			return;
		};
		let size_me = node_layout.size;
		let mut rect_me = Rect { x, y, width: size_me.0, height: size_me.1 };
		let horiz = self.direction.is_horizontal();

		// nudge placement. if a node intersects with another node, its entire
		// main chain (largest subset of nodes including this one where every
		// node is the first child of its parent) should be moved along the cross
		// axis to not intersect.
		//
		// Repeat the for loop until it runs all the way through without any
		// intersections. Surely there's a more efficient way to do this.
		'outer: loop {
			for (_, ea_them) in self.placements.iter() {
				if rect_me.intersects(*ea_them) {
					if horiz {
						rect_me.y = rect_me.y.max(ea_them.bottom());
					} else {
						rect_me.x = rect_me.x.max(ea_them.right());
					}
					continue 'outer;
				}
			}
			break;
		}
		for ea_node in main_chain.iter() {
			if horiz {
				let y = self.placements[ea_node].y.max(rect_me.y);
				self.placements.get_mut(ea_node).unwrap().y = y;
			} else {
				let x = self.placements[ea_node].x.max(rect_me.x);
				self.placements.get_mut(ea_node).unwrap().x = x;
			}
		}
		self.placements.insert(idx_node, rect_me);

		// find children and order them.
		// Siblings stack along the cross axis; initialize the cross-axis cursor
		// from this node's own cross-axis coordinate (NOT from a function param,
		// since the param mapping to main/cross flips with direction).
		let mut cross = if horiz { rect_me.y } else { rect_me.x };
		let cur_main = if horiz { rect_me.x } else { rect_me.y };
		let main_extent = if horiz { rect_me.width } else { rect_me.height };
		main_chain.push(idx_node);
		for ea_child in get_upstream(conns, idx_node) {
			if self.placements.contains_key(&ea_child.from_node) {
				// nudge it (if necessary). a fresh in_progress set per top-level
				// nudge tracks the recursion stack to break cycles without
				// blocking legitimate re-nudges. pass the new main-axis coordinate.
				let mut in_progress = Set::new();
				let new_main = cur_main + main_extent + MARGIN;
				self.nudge(ea_child.from_node, new_main, &mut in_progress, conns);
			} else {
				// place it. child advances along the main axis; siblings stack
				// along the cross axis. place_node takes (x, y) where for
				// horizontal x=main,y=cross and for vertical x=cross,y=main.
				let child_main = cur_main + main_extent + MARGIN;
				let (px, py) =
					if horiz { (child_main, cross) } else { (cross, child_main) };
				self.place_node(ea_child.from_node, px, py, main_chain, visited, conns);
				main_chain.clear();
				// child may not have been placed (e.g. it's part of a cycle);
				// only advance the cross axis if it actually got a rect.
				if let Some(child_rect) = self.placements.get(&ea_child.from_node) {
					if horiz {
						cross += child_rect.height;
					} else {
						cross += child_rect.width;
					}
				}
			}
		}
		main_chain.pop();
	}

	/// Push a node (and its subtree) further along the main axis if its
	/// current main-axis coordinate is less than `main`. `main` is the
	/// main-axis coordinate (x for horizontal, y for vertical).
	fn nudge(
		&mut self,
		idx_node: NodeId,
		main: u16,
		in_progress: &mut Set<NodeId>,
		conns: &[Connection<'a>],
	) {
		// cycle guard: break only if this node is already on the current
		// recursion stack (i.e. we're inside a cycle). a node legitimately
		// nudged twice through different paths must still be processed, so we
		// use a per-recursion-stack set, not a global visited set.
		if !in_progress.insert(idx_node) {
			return;
		}
		let rect_me = self.placements[&idx_node];
		let horiz = self.direction.is_horizontal();
		let cur_main = if horiz { rect_me.x } else { rect_me.y };
		let my_extent = if horiz { rect_me.width } else { rect_me.height };
		if cur_main < main {
			if horiz {
				self.placements.get_mut(&idx_node).unwrap().x = main;
			} else {
				self.placements.get_mut(&idx_node).unwrap().y = main;
			}
			for ea_child in get_upstream(conns, idx_node) {
				// the child must already be placed for nudging to make sense;
				// skip defensively if not.
				if self.placements.contains_key(&ea_child.from_node) {
					self.nudge(
						ea_child.from_node,
						main + my_extent + MARGIN,
						in_progress,
						conns,
					);
				}
			}
		}
		in_progress.remove(&idx_node);
	}

	pub fn split(&self, area: Rect) -> Vec<Rect> {
		self.split_named(area).into_iter().map(|(_, r)| r).collect()
	}

	/// Like [`split`][Self::split], but each entry is tagged with its [`NodeId`].
	/// The order matches [`split`] (nodes in render order) and the rects are the
	/// same content rects (border removed, mirrored to screen coordinates within
	/// `area`).
	///
	/// Useful when you need to map a placed rect back to the node it belongs to
	/// (e.g. hit testing).
	pub fn split_named(&self, area: Rect) -> Vec<(NodeId, Rect)> {
		self.nodes
			.iter()
			.map(|(id, _)| {
				let r = self
					.placements
					.get(id)
					.map(|pos| {
						if pos.right() > area.width || pos.bottom() > area.height {
							return Rect { x: 0, y: 0, width: 0, height: 0 };
						}
						let mut pos = *pos;
						if self.direction.is_horizontal() {
							if self.direction.mirror_main_axis() {
								pos.x = area.width - pos.right() + area.x;
							} else {
								pos.x += area.x;
							}
							pos.y += area.y;
						} else {
							pos.x += area.x;
							if self.direction.mirror_main_axis() {
								pos.y = area.height - pos.bottom() + area.y;
							} else {
								pos.y += area.y;
							}
						}
						pos.inner(Margin { horizontal: 1, vertical: 1 })
					})
					.unwrap_or_default();
				(*id, r)
			})
			.collect()
	}

	/// Hit-test a **screen** coordinate against the placed nodes and return the
	/// [`NodeId`] of the node whose full frame (border included) contains
	/// `(x, y)`, or `None` if the point falls in empty space or on a node that
	/// was never placed.
	///
	/// `(x, y)` is interpreted relative to `area`'s top-left corner (i.e. they
	/// are screen coordinates within `area`), exactly like the rects returned by
	/// [`split`][Self::split] / [`split_named`][Self::split_named]. The hit area
	/// is each node's **bordered** rect (a point on the border counts as a hit),
	/// matching the granularity used by the off-screen canvas — so the inner
	/// content rects from `split_named` are strictly contained in the hit rects.
	///
	/// Must be called **after** [`calculate`][Self::calculate]; before that,
	/// [`positions`][Self::positions] is empty and `hit_test` always returns
	/// `None`. The transformation honors [`direction`][Self::direction] (the same
	/// canvas→screen mirror as `split_named`), so hit testing is correct for
	/// `Ltr`/`Rtl`/`Ttb`/`Btt`.
	///
	/// Nodes never overlap in canvas space, so at most one node can contain a
	/// given point; the first match (in render order) is returned. Viewport
	/// offset is **not** applied here — for a scrolled graph use the upcoming
	/// `hit_test_viewport` (Step 6), or pre-translate `(x, y)` by the offset.
	pub fn hit_test(&self, area: Rect, x: u16, y: u16) -> Option<NodeId> {
		for (id, canvas_rect) in self.placements.iter() {
			// A 0×0 placement means the node never fit / was never placed —
			// it has no on-screen extent to hit.
			if canvas_rect.width == 0 || canvas_rect.height == 0 {
				continue;
			}
			// Same bounds + canvas→screen transform as `split_named`, but kept
			// WITHOUT `.inner(Margin{1,1})` so the border is part of the hit
			// rect. Mirroring uses `self.direction` so Ltr/Btt/Ttb stay aligned.
			if canvas_rect.right() > area.width || canvas_rect.bottom() > area.height {
				continue;
			}
			let mut pos = *canvas_rect;
			if self.direction.is_horizontal() {
				if self.direction.mirror_main_axis() {
					pos.x = area.width - pos.right() + area.x;
				} else {
					pos.x += area.x;
				}
				pos.y += area.y;
			} else {
				pos.x += area.x;
				if self.direction.mirror_main_axis() {
					pos.y = area.height - pos.bottom() + area.y;
				} else {
					pos.y += area.y;
				}
			}
			if pos.contains(Position { x, y }) {
				return Some(*id);
			}
		}
		None
	}

	/// Like [`split`][Self::split], but returns each node's content rect in
	/// **screen** coordinates for a scrolled viewport.
	///
	/// Each rect is the node's canvas-rect (mirrored, inner border removed),
	/// translated by `-viewport.offset + area.origin`, then clipped to `area`.
	/// A node fully scrolled off-screen yields a 0×0 rect (render it only when
	/// `width > 0 && height > 0`).
	///
	/// Typical per-frame usage:
	/// ```ignore
	/// let zones = graph.split_viewport(view_area, &viewport);
	/// for (i, z) in zones.iter().enumerate() {
	///     if z.width > 0 && z.height > 0 {
	///         f.render_widget(my_content[i], *z);
	///     }
	/// }
	/// f.render_widget(NodeGraphView::new(&graph).viewport(viewport), view_area);
	/// ```
	#[deprecated(
		since = "0.1.0",
		note = "use `split_stateful(area, &FlowState)` with a FlowState whose `view_offset` is set"
	)]
	#[allow(deprecated)]
	pub fn split_viewport(&self, area: Rect, viewport: &Viewport) -> Vec<Rect> {
		let canvas_rect = Rect {
			x: 0,
			y: 0,
			width: self.width as u16,
			height: self.height as u16,
		};
		let (ox, oy) = viewport.offset;
		self.split(canvas_rect)
			.into_iter()
			.map(|z| {
				// A node whose entire rect sits above/left of the viewport
				// (canvas right edge <= offset.x, or bottom edge <= offset.y) is
				// fully scrolled off and must become 0×0. `saturating_sub` alone
				// would clamp it to the screen's top-left edge and keep its size,
				// wrongly painting a partial node in the corner — so detect that
				// case first.
				if z.right() <= ox || z.bottom() <= oy {
					return Rect::default();
				}
				let mut z = z;
				// translate canvas-coord rect to screen coordinates: subtract the
				// viewport offset, then add the screen area's origin.
				z.x = z.x.saturating_sub(ox).saturating_add(area.x);
				z.y = z.y.saturating_sub(oy).saturating_add(area.y);
				// clip to the visible area; `intersection` returns a 0×0 rect when
				// the node is fully off the far edge.
				z.intersection(area)
			})
			.collect()
	}

	/// Like [`split_named`][Self::split_named], but each content rect is
	/// translated by `state.view_offset` and clipped to `area` — i.e. it returns
	/// the screen-coordinate content rects for a scrolled/panned view driven by
	/// a [`FlowState`].
	///
	/// This is the stateful-path counterpart of
	/// [`split_viewport`][Self::split_viewport]: it yields `(NodeId, Rect)`
	/// pairs (so the caller can route content to the right node), and the rect
	/// math is identical — each node's canvas-rect (mirrored, inner border
	/// removed) is shifted by `-view_offset + area.origin` and clipped to `area`.
	/// A node fully scrolled off-screen yields a 0×0 rect (render it only when
	/// `width > 0 && height > 0`).
	///
	/// Typical per-frame usage with the stateful render path:
	/// ```ignore
	/// let zones = graph.split_stateful(view_area, &flow_state);
	/// for (id, z) in &zones {
	///     if z.width > 0 && z.height > 0 {
	///         f.render_widget(my_content_for(id), *z);
	///     }
	/// }
	/// f.render_stateful_widget(graph, view_area, &mut flow_state);
	/// ```
	pub fn split_stateful(
		&self,
		area: Rect,
		state: &crate::FlowState,
	) -> Vec<(NodeId, Rect)> {
		let canvas_rect = Rect {
			x: 0,
			y: 0,
			width: self.width as u16,
			height: self.height as u16,
		};
		let (ox, oy) = state.view_offset;
		self.split_named(canvas_rect)
			.into_iter()
			.map(|(id, z)| {
				// A node whose entire rect sits above/left of the viewport is
				// fully scrolled off and must become 0×0 (see split_viewport).
				if z.right() <= ox || z.bottom() <= oy {
					return (id, Rect::default());
				}
				let mut z = z;
				z.x = z.x.saturating_sub(ox).saturating_add(area.x);
				z.y = z.y.saturating_sub(oy).saturating_add(area.y);
				(id, z.intersection(area))
			})
			.collect()
	}

	/// Translate a node's canvas-rect (border included) into screen coordinates
	/// under a panned view: apply the canvas→screen mirror (per `self.direction`)
	/// and the `view_offset` pan, then return the (possibly clipped) rect. Used
	/// by the stateful highlight overlay to find where a node's border lives on
	/// screen. Returns `None` if the node isn't placed or its rect is 0×0.
	fn node_screen_rect(
		&self,
		id: NodeId,
		area: Rect,
		view_offset: (u16, u16),
	) -> Option<Rect> {
		let canvas_rect = self.placements.get(&id).copied()?;
		if canvas_rect.width == 0 || canvas_rect.height == 0 {
			return None;
		}
		let (ox, oy) = view_offset;
		// canvas-coord bordered rect -> screen: subtract the pan offset, add the
		// area origin. No mirror here — the canvas already holds the mirrored
		// rendering (render_to ran with the mirror during calculate), so the
		// canvas cell at (cx, cy) corresponds to screen (cx - ox + area.x, ...).
		let mut pos = canvas_rect;
		// fully scrolled off the top/left edge -> not visible.
		if pos.right() <= ox || pos.bottom() <= oy {
			return None;
		}
		pos.x = pos.x.saturating_sub(ox).saturating_add(area.x);
		pos.y = pos.y.saturating_sub(oy).saturating_add(area.y);
		// clip to area; if no overlap, not visible.
		let clipped = pos.intersection(area);
		if clipped.width == 0 || clipped.height == 0 {
			return None;
		}
		Some(clipped)
	}

	/// Recolor the **border** cells of a node's on-screen rect with `style`'s
	/// foreground/add-modifier, preserving each cell's existing symbol (so the
	/// port glyphs ├/┬/etc. that the canvas blit already placed on the border
	/// survive — only their color changes). Only the perimeter cells are
	/// touched; the node's inner content is left untouched.
	///
	/// This is the highlight mechanism used by the stateful render path: after
	/// the (possibly scrolled) canvas is blitted, the selection/hover node's
	/// border is recolored in place without re-running `Block::render` (which
	/// would clobber the port symbols).
	fn highlight_border(&self, buf: &mut Buffer, screen_rect: Rect, style: Style) {
		let r = screen_rect;
		// perimeter: top row, bottom row, left col, right col — clamped to the
		// rect itself (a 1-wide/1-tall rect degenerates to a single row/col,
		// which is correct: its only cells are border cells).
		for x in r.left()..r.right() {
			if let Some(cell) = buf.cell_mut(Position::new(x, r.top())) {
				merge_style(cell, style);
			}
			if r.height > 1
				&& let Some(cell) = buf.cell_mut(Position::new(x, r.bottom() - 1))
			{
				merge_style(cell, style);
			}
		}
		for y in r.top()..r.bottom() {
			if let Some(cell) = buf.cell_mut(Position::new(r.left(), y)) {
				merge_style(cell, style);
			}
			if r.width > 1
				&& let Some(cell) = buf.cell_mut(Position::new(r.right() - 1, y))
			{
				merge_style(cell, style);
			}
		}
	}
}

/// Overlay `style` onto an existing cell without changing the cell's symbol.
/// Used by the stateful highlight to recolor a node's border while preserving
/// the port glyphs already on it.
///
/// `Style::patch` merges fg/bg with `or` and modifiers with `insert` (set
/// union), which is exactly the "keep existing, add new" semantics we want.
fn merge_style(cell: &mut ratatui::buffer::Cell, style: Style) {
	let merged = cell.style().patch(style);
	cell.set_style(merged);
}

/// Scroll position into a [`NodeGraph`]'s canvas.
///
/// `offset` is the (x, y) coordinate of the viewport's top-left corner within
/// the off-screen canvas. (0, 0) shows the top-left of the graph; increasing x
/// scrolls right, increasing y scrolls down.
///
/// Pass it to [`NodeGraph::split_viewport`] (for node content rects) and
/// [`NodeGraphView`] (for borders/connections).
#[deprecated(
	since = "0.1.0",
	note = "use `FlowState` (its `view_offset` field replaces `Viewport.offset`)"
)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Viewport {
	/// Top-left corner of the viewport in canvas coordinates.
	pub offset: (u16, u16),
}

#[allow(deprecated)]
impl Viewport {
	/// Create a viewport at offset (0, 0) (top-left of the canvas).
	pub fn new() -> Self {
		Self::default()
	}

	/// Set the viewport's top-left offset in canvas coordinates.
	#[must_use]
	pub fn offset(mut self, x: u16, y: u16) -> Self {
		self.offset = (x, y);
		self
	}
}

#[allow(deprecated)]
impl std::fmt::Display for Viewport {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "Viewport({}, {})", self.offset.0, self.offset.1)
	}
}

/// A read-only [`Widget`] that renders a scrolled window of a [`NodeGraph`]'s
/// borders/ports/connections (no node *content*).
///
/// The full graph is rendered once into an off-screen canvas during
/// [`NodeGraph::calculate`]; this widget blits the visible window (determined
/// by its [`Viewport`]) onto the frame each draw. Render your own node content
/// into the rects from [`NodeGraph::split_viewport`] separately.
///
/// ```ignore
/// f.render_widget(NodeGraphView::new(&graph).offset(x, y), area);
/// ```
#[deprecated(
	since = "0.1.0",
	note = "use `NodeGraph`'s `StatefulWidget` impl with `FlowState` (set `view_offset` for panning)"
)]
pub struct NodeGraphView<'a> {
	graph: &'a NodeGraph<'a>,
	#[allow(deprecated)]
	viewport: Viewport,
}

#[allow(deprecated)]
impl<'a> NodeGraphView<'a> {
	/// Create a view over `graph` at offset (0, 0).
	pub fn new(graph: &'a NodeGraph<'a>) -> Self {
		Self { graph, viewport: Viewport::default() }
	}

	/// Set the viewport (offset into the canvas).
	#[must_use]
	pub fn viewport(mut self, viewport: Viewport) -> Self {
		self.viewport = viewport;
		self
	}

	/// Convenience: set the viewport offset directly (x, y).
	#[must_use]
	pub fn offset(mut self, x: u16, y: u16) -> Self {
		self.viewport.offset = (x, y);
		self
	}
}

#[allow(deprecated)]
impl Widget for NodeGraphView<'_> {
	fn render(self, area: Rect, buf: &mut Buffer) {
		let canvas = self.graph.canvas();
		let (ox, oy) = self.viewport.offset;
		blit_canvas(canvas, area, buf, (ox, oy));
	}
}

/// Blit the visible window of `canvas` onto `area` of `buf`, cell by cell.
///
/// `offset` is the top-left corner of the visible window inside `canvas`. For
/// each screen cell `(vx, vy)` in `area`, the canvas cell at
/// `(offset.x + vx, offset.y + vy)` is looked up; if it's non-blank, its symbol
/// and style are copied into the matching `buf` cell. Blank canvas cells (node
/// content / background) are left untouched so caller-rendered content shows
/// through.
///
/// Shared between [`NodeGraphView::render`] (the legacy stateless viewport
/// widget) and [`NodeGraph`]'s stateful render path so both blit identically.
pub(crate) fn blit_canvas(
	canvas: &Buffer,
	area: Rect,
	buf: &mut Buffer,
	offset: (u16, u16),
) {
	let (ox, oy) = offset;
	for vy in 0..area.height {
		for vx in 0..area.width {
			let sx = ox.saturating_add(vx);
			let sy = oy.saturating_add(vy);
			let src = match canvas.cell(Position::new(sx, sy)) {
				Some(c) => c,
				None => continue,
			};
			// Blank canvas cells are node content areas / background — leave
			// them untouched so content the caller rendered into the
			// `split_viewport` rects shows through. Only copy cells the canvas
			// actually drew (borders / ports / connections).
			if src.symbol() == " " {
				continue;
			}
			if let Some(dst) = buf.cell_mut(Position::new(area.x + vx, area.y + vy)) {
				dst.set_symbol(src.symbol());
				dst.set_style(src.style());
			}
		}
	}
}

fn get_upstream<'a>(conns: &[Connection<'a>], idx_node: NodeId) -> Vec<Connection<'a>> {
	// find children and order them
	let mut upstream: Vec<_> =
		conns.iter().filter(|ea| ea.to_node == idx_node).copied().collect();
	upstream.sort_by_key(|a| a.to_port);
	upstream
}

fn get_downstream<'a>(conns: &[Connection<'a>], idx_node: NodeId) -> Vec<Connection<'a>> {
	// find parents and order them
	let mut downstream: Vec<_> =
		conns.iter().filter(|ea| ea.from_node == idx_node).copied().collect();
	downstream.sort_by_key(|a| a.from_port);
	downstream
}

/// Clamp a port index into the valid range of inner rows for a node of the
/// given height. Ports are used as a y-offset into the node's frame; an
/// out-of-range value would draw outside the frame (or past the buffer). The
/// usable inner rows are `0..=height-2` (height includes the top/bottom
/// borders), so the largest valid offset is `height-2`.
fn clamp_port(port: usize, node_height: u16) -> usize {
	let max = (node_height as usize).saturating_sub(2);
	port.min(max)
}

/// Direction a port name grows from its anchor cell (Step 9).
enum PortNameDir {
	/// First char at the anchor cell, subsequent chars to the right (used for
	/// **in** ports on the left/top edge, so the name grows toward the node
	/// interior).
	Right,
	/// First char at the anchor cell, subsequent chars to the left (used for
	/// **out** ports on the right/bottom edge, so the name grows toward the node
	/// interior). The anchor cell is thus the inner-most cell and holds the
	/// name's first character.
	Left,
}

/// Draw a port's display name horizontally, anchored at `(x, y)` (one cell
/// *inside* the node from its port symbol) and growing in `dir`. The name is
/// truncated so it never leaves the node's inner content area (`pos` is the
/// node's full frame, so the inner row is `pos.left()+1 ..= pos.right()-2`):
/// the anchor cell always holds the first character (so the "inner cell next to
/// the port symbol" is the name's leading char), and remaining characters extend
/// inward. Bounds against `area` are also checked (render_to may have clipped
/// the node). The name is drawn in **bold**.
///
/// Pure overlay: only called when a name exists, so no-name nodes render
/// identically to pre-Step-9.
fn write_port_name(
	buf: &mut Buffer,
	area: Rect,
	pos: Rect,
	x: u16,
	y: u16,
	dir: PortNameDir,
	name: &str,
) {
	let style = Style::default().add_modifier(Modifier::BOLD);
	let inner_left = pos.left() + 1;
	let inner_right = pos.right().saturating_sub(2);
	match dir {
		PortNameDir::Right => {
			let mut cx = x;
			for ch in name.chars() {
				if cx > inner_right {
					break;
				}
				if cx >= area.width || y >= area.height {
					break;
				}
				if let Some(cell) = buf.cell_mut(Position::new(cx, y)) {
					cell.set_symbol(ch.to_string().as_str()).set_style(style);
				}
				cx = cx.saturating_add(1);
			}
		}
		PortNameDir::Left => {
			let mut cx = x;
			for ch in name.chars() {
				if cx < inner_left {
					break;
				}
				if cx >= area.width || y >= area.height {
					break;
				}
				if let Some(cell) = buf.cell_mut(Position::new(cx, y)) {
					cell.set_symbol(ch.to_string().as_str()).set_style(style);
				}
				cx = cx.saturating_sub(1);
			}
		}
	}
}

/// Map a layout-coordinate main-axis value to its canvas-coordinate value,
/// mirroring about `size` when the direction's main axis is mirrored
/// (`Rtl`/`Btt`). `size` is the canvas extent on the main axis
/// (`self.width` for horizontal, `self.height` for vertical).
///
/// For non-mirrored directions (`Ltr`/`Ttb`) the value is unchanged.
fn mirror_axis(size: usize, coord: usize, dir: FlowDirection) -> usize {
	if dir.mirror_main_axis() { size.saturating_sub(coord) } else { coord }
}

impl<'a> NodeGraph<'a> {
	/// Render the graph's borders/ports/connections (but *not* node content)
	/// into `buf` at `area`. This is the shared implementation behind both the
	/// [`StatefulWidget`] impl (used by `split`-based rendering) and the
	/// off-screen canvas drawn during [`calculate`][Self::calculate] (used by
	/// [`NodeGraphView`]).
	///
	/// Takes `&self` (rather than consuming the widget) so the same graph can
	/// be rendered multiple times — once into the canvas during layout, and
	/// any number of times via the `StatefulWidget` impl for non-viewport use.
	pub(crate) fn render_to(&self, area: Rect, buf: &mut Buffer) {
		// draw connections
		self.conn_layout.render(area, buf);

		let vertical = !self.direction.is_horizontal();
		let mirror = self.direction.mirror_main_axis();

		// draw nodes
		'node: for (idx_node, ea_node) in &self.nodes {
			let idx_node = *idx_node;
			if let Some(mut pos) = self.placements.get(&idx_node).copied() {
				if pos.right() > area.width || pos.bottom() > area.height {
					continue 'node;
				}
				// draw box — mirror the main axis to screen coordinates when the
				// direction mirrors (Rtl mirrors x, Btt mirrors y); otherwise just
				// translate by the area origin.
				if self.direction.is_horizontal() {
					if mirror {
						pos.x = area.left() + area.width - pos.right();
					} else {
						pos.x += area.left();
					}
					pos.y += area.top();
				} else {
					pos.x += area.left();
					if mirror {
						pos.y = area.top() + area.height - pos.bottom();
					} else {
						pos.y += area.top();
					}
				}
				let block = ea_node.block();
				block.render(pos, buf);
				// For horizontal flows the input (to_node) port is on the LEFT edge
				// and the output (from_node) port on the RIGHT edge. For vertical flows
				// the input port is on the BOTTOM edge (faces the child below) and the
				// output port on the TOP edge (faces the parent above) — i.e. swapped
				// relative to horizontal, because the parent sits on the opposite side.
				// draw input ports (upstream / to_node)
				for ea_conn in get_upstream(&self.connections, idx_node) {
					let to_port =
						clamp_port(ea_conn.to_port.0 as usize, pos.height) as u16;
					// draw connection alias
					if let Some(alias_char) = self.conn_layout.alias_connections.get(&(
						true,
						idx_node,
						ea_conn.to_port,
					)) {
						if !vertical {
							let y = pos.top() + to_port + 1;
							if pos.left() > 0
								&& y < area.height && let Some(cell) =
								buf.cell_mut(Position::new(pos.left() - 1, y))
							{
								cell.set_symbol(alias_char).set_style(
									Style::default()
										.add_modifier(Modifier::BOLD)
										.bg(Color::Red),
								);
							}
						} else {
							// input alias one cell below the bottom edge
							let x = pos.left() + to_port + 1;
							if x < area.width
								&& let Some(cell) =
									buf.cell_mut(Position::new(x, pos.bottom()))
							{
								cell.set_symbol(alias_char).set_style(
									Style::default()
										.add_modifier(Modifier::BOLD)
										.bg(Color::Red),
								);
							}
						}
					}

					// draw port — the `to` (in) port. When `show_arrows` is on
					// (the default), this is a direction arrow pointing in the
					// flow direction (toward the inside of the `to` node);
					// otherwise it falls back to the in-port connection glyph
					// (`┤`/`┴` family) for Step-6-equivalent rendering.
					let in_symbol = if self.show_arrows {
						arrow_symbol(self.direction, ea_conn.line_type())
					} else {
						conn_symbol(
							true,
							ea_node.border_type(),
							ea_conn.line_type(),
							vertical,
						)
					};
					if !vertical {
						if let Some(cell) = buf
							.cell_mut(Position::new(pos.left(), pos.top() + to_port + 1))
						{
							cell.set_symbol(in_symbol);
						}
						// Step 9: port display name — drawn one cell inside the
						// left edge (toward the node interior), truncated to the
						// node's content area so it never crosses the far border.
						if let Some(name) = ea_node.port_name(ea_conn.to_port) {
							let y = pos.top() + to_port + 1;
							let anchor_x = pos.left() + 1;
							write_port_name(
								buf,
								area,
								pos,
								anchor_x,
								y,
								PortNameDir::Right,
								name,
							);
						}
					} else {
						// input port on the bottom edge, offset along width
						if let Some(cell) = buf.cell_mut(Position::new(
							pos.left() + to_port + 1,
							pos.bottom() - 1,
						)) {
							cell.set_symbol(in_symbol);
						}
						// Step 9: port name — one cell above the bottom edge
						// (into the node interior), written horizontally from the
						// port's x, truncated to the content area.
						if let Some(name) = ea_node.port_name(ea_conn.to_port) {
							let x = pos.left() + to_port + 1;
							let y = pos.bottom().saturating_sub(2);
							write_port_name(
								buf,
								area,
								pos,
								x,
								y,
								PortNameDir::Right,
								name,
							);
						}
					}
				}
				// draw output ports (downstream / from_node)
				for ea_conn in get_downstream(&self.connections, idx_node) {
					let from_port =
						clamp_port(ea_conn.from_port.0 as usize, pos.height) as u16;
					// draw connection alias
					if let Some(alias_char) = self.conn_layout.alias_connections.get(&(
						false,
						idx_node,
						ea_conn.from_port,
					)) {
						if !vertical {
							if let Some(cell) = buf.cell_mut(Position::new(
								pos.right(),
								pos.top() + from_port + 1,
							)) {
								cell.set_symbol(alias_char).set_style(
									Style::default()
										.add_modifier(Modifier::BOLD)
										.bg(Color::Red),
								);
							}
						} else {
							// output alias one cell above the top edge
							if pos.top() > 0
								&& let Some(cell) = buf.cell_mut(Position::new(
									pos.left() + from_port + 1,
									pos.top() - 1,
								)) {
								cell.set_symbol(alias_char).set_style(
									Style::default()
										.add_modifier(Modifier::BOLD)
										.bg(Color::Red),
								);
							}
						}
					}

					// draw port
					if !vertical {
						if let Some(cell) = buf.cell_mut(Position::new(
							pos.right() - 1,
							pos.top() + from_port + 1,
						)) {
							cell.set_symbol(conn_symbol(
								false,
								ea_node.border_type(),
								ea_conn.line_type(),
								false,
							));
						}
						// Step 9: out-port display name — one cell inside the
						// right edge (toward the node interior). First char on
						// the inner cell, remaining chars extend leftward.
						if let Some(name) = ea_node.port_name(ea_conn.from_port) {
							let y = pos.top() + from_port + 1;
							let anchor_x = pos.right().saturating_sub(2);
							write_port_name(
								buf,
								area,
								pos,
								anchor_x,
								y,
								PortNameDir::Left,
								name,
							);
						}
					} else {
						// output port on the top edge, offset along width
						if let Some(cell) = buf.cell_mut(Position::new(
							pos.left() + from_port + 1,
							pos.top(),
						)) {
							cell.set_symbol(conn_symbol(
								false,
								ea_node.border_type(),
								ea_conn.line_type(),
								true,
							));
						}
						// Step 9: out-port display name — one cell below the top
						// edge (into the node interior), first char on the inner
						// cell, extending leftward.
						if let Some(name) = ea_node.port_name(ea_conn.from_port) {
							let x = pos.left() + from_port + 1;
							let y = pos.top() + 1;
							write_port_name(
								buf,
								area,
								pos,
								x,
								y,
								PortNameDir::Left,
								name,
							);
						}
					}
				}
			} else {
				buf.set_string(
					0,
					idx_node.0 as u16,
					format!("{}", idx_node.0),
					Style::default(),
				);
			}
		}
	}
}

impl<'a> ratatui::widgets::StatefulWidget for NodeGraph<'a> {
	type State = crate::FlowState;

	fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
		// DEFAULT SAFE-NET (highest priority): a freshly-defaulted FlowState
		// (offset (0,0), no selection, no hover) must render byte-for-byte
		// identically to the legacy stateless render. Delegating straight to
		// `render_to` guarantees absolute zero change in that case — no blit,
		// no highlight overlay, nothing that could perturb a single cell.
		let is_default = state.view_offset == (0, 0)
			&& state.selection.is_none()
			&& state.hover.is_none();
		if is_default {
			self.render_to(area, buf);
			return;
		}

		// Non-default state.
		//
		// 1) Borders/ports/connections: if the view is panned, blit the visible
		//    window of the off-screen canvas onto `area` (the canvas was already
		//    rendered during `calculate`). At offset (0,0) this would be
		//    equivalent to `render_to`, but we blit anyway so the highlight
		//    overlay below operates on the same canvas-sourced cells regardless
		//    of pan. Blitting a (0,0) offset produces the same output as
		//    `render_to` would, so there's no divergence for the no-pan case.
		if state.view_offset == (0, 0) {
			// No pan: render the source directly (identical to the default
			// path's paint, minus the default short-circuit). This keeps the
			// no-pan highlight case byte-identical to render_to as a base.
			self.render_to(area, buf);
		} else {
			// Panned: blit the scrolled window from the canvas. The canvas
			// holds borders/ports/connections only (no content), so caller-
			// rendered content shows through the blank cells.
			blit_canvas(&self.canvas, area, buf, state.view_offset);
		}

		// 2) Selection / hover highlight overlay: recolor the border cells of
		//    the targeted node(s). We use `highlight_border` which preserves
		//    each cell's symbol (so the port glyphs ├/┬/etc. on the border
		//    survive — only their fg/modifier changes). Hover is drawn first so
		//    that a node that is both hovered and selected shows the selection
		//    (selection wins, drawn second).
		let hover_style = self.highlight_style.add_modifier(Modifier::DIM);
		if let Some(hover_id) = state.hover
			&& let Some(rect) = self.node_screen_rect(hover_id, area, state.view_offset)
		{
			self.highlight_border(buf, rect, hover_style);
		}
		if let Some(sel_id) = state.selection
			&& let Some(rect) = self.node_screen_rect(sel_id, area, state.view_offset)
		{
			self.highlight_border(buf, rect, self.highlight_style);
		}
	}
}