Skip to main content

ratatui_flow/
graph.rs

1use ratatui::buffer::Buffer;
2use ratatui::layout::Position;
3use ratatui::widgets::Widget;
4
5use super::*;
6use crate::id::{NodeId, PortId};
7
8const MARGIN: u16 = 5;
9
10/// Error returned by [`NodeGraph::add_node_with_id`] when the requested
11/// [`NodeId`] already exists in the graph.
12///
13/// Note: this is **not** pushed into [`NodeGraph::diagnostics`] (which is
14/// cleared on every [`calculate`][NodeGraph::calculate]); it is returned as a
15/// `Result` so the caller can react immediately.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum AddNodeError {
18	/// The given [`NodeId`] is already in use by an existing node.
19	ConflictingId,
20}
21
22impl std::fmt::Display for AddNodeError {
23	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24		match self {
25			AddNodeError::ConflictingId => write!(f, "node id already in use"),
26		}
27	}
28}
29
30impl std::error::Error for AddNodeError {}
31
32#[derive(Debug, Clone)]
33pub struct NodeGraph<'a> {
34	/// Nodes in render order, each tagged with its stable [`NodeId`].
35	///
36	/// This is a `Vec` of `(id, layout)` pairs (not indexed by id) so that
37	/// [`add_node_with_id`] can accept non-contiguous ids. Lookups happen by
38	/// scanning (node counts are in the low hundreds); the old "`NodeId(i)` is
39	/// the vector index" convention is preserved only for graphs built via
40	/// [`new`][Self::new], which assigns `NodeId(0..n)`.
41	nodes: Vec<(NodeId, NodeLayout<'a>)>,
42	connections: Vec<Connection<'a>>,
43	placements: Map<NodeId, Rect>,
44	conn_layout: ConnectionsLayout<'a>,
45	width: usize,
46	height: usize,
47	/// Which way the graph flows (root edge + child growth axis). Defaults to
48	/// [`FlowDirection::Rtl`], which is byte-for-byte identical to the
49	/// pre-parameterization hard-coded layout.
50	direction: FlowDirection,
51	/// Auto-incrementing counter for ids handed out by [`add_node`][Self::add_node].
52	/// `add_node_with_id` may push ids beyond this counter without bumping it.
53	next_id: u32,
54	/// True whenever a mutator changed the graph since the last
55	/// [`calculate`][Self::calculate]. Mutators do **not** re-run layout
56	/// automatically — callers must invoke `calculate` before reading
57	/// [`positions`][Self::positions] / [`split`][Self::split] / etc., or the
58	/// values will be stale.
59	dirty: bool,
60	/// Off-screen canvas holding the full graph's borders/ports/connections
61	/// (no node *content*) after [`calculate`][Self::calculate]. Used by
62	/// [`NodeGraphView`] to blit the visible window onto the screen.
63	canvas: Buffer,
64	/// Non-fatal problems detected during the last [`calculate`][Self::calculate]
65	/// (unreachable nodes, ignored bad connections, unrouted connections).
66	/// Cleared at the start of each `calculate`.
67	diagnostics: Vec<Diagnostic>,
68	/// Style applied to the selected node's border during stateful render (the
69	/// hover node gets this style with a `DIM` modifier added). Defaults to bold
70	/// yellow fg.
71	highlight_style: Style,
72	/// When `true`, the `to` (in) port of each connection is drawn as a direction
73	/// arrow ([`arrow_symbol`][crate] — ◄/►/▼/…) pointing in the flow direction,
74	/// instead of the in-port connection glyph (`┤`/`┴` family). The `from` (out)
75	/// port always keeps its `├`/`┬` glyph. **Off by default**; enable with
76	/// [`show_arrows`][Self::show_arrows].
77	show_arrows: bool,
78}
79
80impl<'a> NodeGraph<'a> {
81	pub fn new(
82		nodes: Vec<NodeLayout<'a>>,
83		connections: Vec<Connection<'a>>,
84		width: usize,
85		height: usize,
86	) -> Self {
87		let mut graph = Self::empty(width, height);
88		// Assign NodeId(0..n) to the incoming nodes so the legacy
89		// `rects[i]` / `NodeId(i)` semantics stay intact. We bump `next_id`
90		// to `n` so a subsequent `add_node` keeps handing out fresh ids.
91		for (i, node) in nodes.into_iter().enumerate() {
92			// ids 0..n are guaranteed unique here (graph is empty).
93			let _ = graph.add_node_with_id(NodeId(i as u32), node);
94		}
95		// Same for the supplied connections.
96		for conn in connections {
97			graph.add_connection(conn);
98		}
99		graph
100	}
101
102	/// Build an empty graph with the given canvas size. Single construction
103	/// path shared by [`new`][Self::new] and incremental callers.
104	fn empty(width: usize, height: usize) -> Self {
105		let canvas = Buffer::empty(Rect {
106			x: 0,
107			y: 0,
108			width: width as u16,
109			height: height as u16,
110		});
111		Self {
112			nodes: Vec::new(),
113			connections: Vec::new(),
114			conn_layout: ConnectionsLayout::new(width, height),
115			placements: Default::default(),
116			width,
117			height,
118			direction: FlowDirection::default(),
119			next_id: 0,
120			dirty: true,
121			canvas,
122			diagnostics: Vec::new(),
123			highlight_style: Style::default()
124				.add_modifier(Modifier::BOLD)
125				.fg(Color::Yellow),
126			show_arrows: false,
127		}
128	}
129
130	// ----- configuration --------------------------------------------------
131
132	/// Set the graph's [`FlowDirection`] (which edge the root anchors to and
133	/// which way children flow). The graph is marked dirty; call
134	/// [`calculate`][Self::calculate] before reading positions.
135	///
136	/// Defaults to [`FlowDirection::Rtl`] (the original hard-coded behavior).
137	#[must_use]
138	pub fn with_direction(mut self, direction: FlowDirection) -> Self {
139		self.direction = direction;
140		self.dirty = true;
141		self
142	}
143
144	/// The graph's configured [`FlowDirection`].
145	pub fn direction(&self) -> FlowDirection {
146		self.direction
147	}
148
149	/// Set the highlight [`Style`] applied to the **selected** node's border
150	/// during stateful render (see [`FlowState::selection`]). The **hover**
151	/// node's border gets this style with an added [`Modifier::DIM`] so the two
152	/// states stay visually distinct. Defaults to bold yellow foreground.
153	///
154	/// Only the border is recolored (the port glyphs on the border keep their
155	/// symbols and pick up the highlight's fg/modifier); node content is never
156	/// touched.
157	#[must_use]
158	pub fn highlight_style(self, style: Style) -> Self {
159		let mut this = self;
160		this.highlight_style = style;
161		this
162	}
163
164	/// Toggle drawing a **direction arrow** on each connection's `to` (in) port,
165	/// pointing in the flow direction (e.g. `◄` for `Rtl`, `▶` for `Ltr`, `▼`
166	/// for `Ttb`). **Off by default** — pass `true` to replace the in-port
167	/// connection glyph (`┤`/`┴` family) with an arrow so the flow direction
168	/// reads at a glance. The `from` (out) port always keeps its `├`/`┬` glyph.
169	#[must_use]
170	pub fn show_arrows(mut self, on: bool) -> Self {
171		self.show_arrows = on;
172		self
173	}
174
175	// ----- mutators -------------------------------------------------------
176
177	/// Append a node, assigning it the next fresh [`NodeId`] (and bumping the
178	/// internal counter). The graph is marked dirty; you must call
179	/// [`calculate`][Self::calculate] before reading positions.
180	///
181	/// `node.title`/content strings should outlive the graph; using a
182	/// `&'static str` is the common case.
183	pub fn add_node(&mut self, node: NodeLayout<'a>) -> NodeId {
184		let id = NodeId(self.next_id);
185		self.next_id += 1;
186		// next_id is monotonically increasing, so the id is guaranteed unique.
187		let _ = self.add_node_with_id(id, node);
188		id
189	}
190
191	/// Append a node with a caller-chosen [`NodeId`]. Returns
192	/// [`AddNodeError::ConflictingId`] if `id` is already in use; otherwise the
193	/// node is inserted (preserving render order) and the graph is marked dirty.
194	///
195	/// The id need not be contiguous — this is the path used to support
196	/// non-contiguous node ids. The auto-increment counter is bumped past `id`
197	/// only if `id` would otherwise collide with a future `add_node` result.
198	pub fn add_node_with_id(
199		&mut self,
200		id: NodeId,
201		node: NodeLayout<'a>,
202	) -> Result<(), AddNodeError> {
203		if self.has_node(id) {
204			return Err(AddNodeError::ConflictingId);
205		}
206		// keep next_id strictly greater than any id ever inserted so a later
207		// add_node() can't hand out an id that add_node_with_id already took.
208		if id.0 >= self.next_id {
209			self.next_id = id.0 + 1;
210		}
211		self.nodes.push((id, node));
212		self.dirty = true;
213		Ok(())
214	}
215
216	/// Append a [`Connection`]. The graph is marked dirty.
217	pub fn add_connection(&mut self, conn: Connection<'a>) {
218		self.connections.push(conn);
219		self.dirty = true;
220	}
221
222	/// Remove the node with the given [`NodeId`] and cascade-delete every
223	/// [`Connection`] that references it (on either endpoint). No-op (returns
224	/// `false`) if `id` is not in the graph. The graph is marked dirty.
225	///
226	/// Returns `true` if a node was actually removed.
227	pub fn remove_node(&mut self, id: NodeId) -> bool {
228		let before = self.nodes.len();
229		self.nodes.retain(|(nid, _)| *nid != id);
230		let removed = self.nodes.len() != before;
231		if removed {
232			// cascade: drop any connection touching the removed node.
233			self.connections.retain(|c| c.from_node != id && c.to_node != id);
234			self.dirty = true;
235		}
236		removed
237	}
238
239	/// Remove the first [`Connection`] matching the given endpoints. No-op
240	/// (returns `false`) if no such connection exists. The graph is marked dirty.
241	///
242	/// Returns `true` if a connection was removed.
243	pub fn remove_connection(
244		&mut self,
245		from: NodeId,
246		from_port: PortId,
247		to: NodeId,
248		to_port: PortId,
249	) -> bool {
250		let before = self.connections.len();
251		if let Some(pos) = self.connections.iter().position(|c| {
252			c.from_node == from
253				&& c.from_port == from_port
254				&& c.to_node == to
255				&& c.to_port == to_port
256		}) {
257			self.connections.remove(pos);
258		}
259		let removed = self.connections.len() != before;
260		if removed {
261			self.dirty = true;
262		}
263		removed
264	}
265
266	// ----- queries / getters ---------------------------------------------
267
268	/// `true` if a node with the given [`NodeId`] exists in the graph.
269	pub fn has_node(&self, id: NodeId) -> bool {
270		self.nodes.iter().any(|(nid, _)| *nid == id)
271	}
272
273	/// `true` if the graph changed since the last [`calculate`][Self::calculate]
274	/// (any node/connection added or removed). Mutators do not re-run layout
275	/// automatically, so a dirty graph means [`positions`] / [`split`] may be
276	/// stale until you call `calculate`.
277	///
278	/// [`positions`]: Self::positions
279	/// [`split`]: Self::split
280	pub fn is_dirty(&self) -> bool {
281		self.dirty
282	}
283
284	/// All node placements from the last [`calculate`][Self::calculate], keyed
285	/// by [`NodeId`]. Each [`Rect`] is the node's **full frame** (border
286	/// included) in **canvas coordinates** (origin top-left of the off-screen
287	/// canvas, x growing leftwards — see [`split`] for the mirroring).
288	///
289	/// [`split`]: Self::split
290	pub fn positions(&self) -> &Map<NodeId, Rect> {
291		&self.placements
292	}
293
294	/// The full-frame [`Rect`] (border included, canvas coordinates) of a
295	/// single node, or `None` if the node was not placed (unreachable / unknown
296	/// / never calculated).
297	pub fn node_rect(&self, id: NodeId) -> Option<Rect> {
298		self.placements.get(&id).copied()
299	}
300
301	/// Internal helper: borrow the [`NodeLayout`] for a node id, if present.
302	fn node_layout(&self, id: NodeId) -> Option<&NodeLayout<'a>> {
303		self.nodes.iter().find_map(|(nid, n)| (*nid == id).then_some(n))
304	}
305
306	/// The full-graph canvas (borders/ports/connections only, no content)
307	/// rendered during [`calculate`][Self::calculate]. Width/height match the
308	/// values passed to [`new`][Self::new].
309	///
310	/// Exposed so [`NodeGraphView`] can blit a scrolled window from it.
311	pub(crate) fn canvas(&self) -> &Buffer {
312		&self.canvas
313	}
314
315	pub fn calculate(&mut self) {
316		self.placements.clear();
317		self.diagnostics.clear();
318		self.dirty = false;
319
320		// Build the set of known node ids up front so the connection filter
321		// below doesn't need to re-borrow `self` (which would conflict with
322		// the `&mut self.diagnostics` push for invalid refs).
323		let known_ids: Set<NodeId> = self.nodes.iter().map(|(id, _)| *id).collect();
324
325		// filter out connections that reference unknown node ids. these
326		// would otherwise panic on indexing later. we keep `self.connections`
327		// untouched and only work off this local slice for the rest of
328		// calculate().
329		let mut bad_refs: Vec<Diagnostic> = Vec::new();
330		let valid_conns: Vec<Connection<'a>> = self
331			.connections
332			.iter()
333			.copied()
334			.filter(|ea| {
335				if !known_ids.contains(&ea.from_node) || !known_ids.contains(&ea.to_node)
336				{
337					log::warn!(
338						"skipping connection: node id not present \
339						 (from_node={}, to_node={})",
340						ea.from_node,
341						ea.to_node,
342					);
343					bad_refs.push(Diagnostic::InvalidConnectionRef {
344						from_node: ea.from_node,
345						to_node: ea.to_node,
346					});
347					false
348				} else {
349					true
350				}
351			})
352			.collect();
353		self.diagnostics.append(&mut bad_refs);
354
355		// find root nodes: every node id that is never a `from_node`.
356		let mut roots: Set<_> = self.nodes.iter().map(|(id, _)| *id).collect();
357		for ea_connection in valid_conns.iter() {
358			roots.remove(&ea_connection.from_node);
359		}
360
361		// place them and their children (recursively)
362		let mut main_chain = Vec::new();
363		let mut visited = Set::new();
364		for ea_root in roots {
365			self.place_node(ea_root, 0, 0, &mut main_chain, &mut visited, &valid_conns);
366			assert!(main_chain.is_empty());
367		}
368
369		// calculate connections (eventually, this should be done during node
370		// placement, but thats really complicated and i dont wanna deal with that
371		// right now. essentially, adding non-trivial connections nudges nodes,
372		// and nudging nodes nudges existing connections.)
373		let mut conn_map = Map::<(NodeId, PortId), usize>::new();
374		let mut next_idx = 1;
375		for ea_conn in valid_conns.iter() {
376			// a connection may reference a node that never got placed (e.g. one
377			// that was only reachable through a cycle that broke placement).
378			// skip those defensively instead of indexing into placements.
379			let (Some(&a_pos), Some(&b_pos)) = (
380				self.placements.get(&ea_conn.from_node),
381				self.placements.get(&ea_conn.to_node),
382			) else {
383				log::warn!(
384					"skipping connection layout: endpoint not placed \
385					 (from_node={}, to_node={})",
386					ea_conn.from_node,
387					ea_conn.to_node
388				);
389				continue;
390			};
391			// NOTE: canvas main axis is mirrored relative to layout coords for
392			// Rtl/Btt (see FlowDirection). Compute each port's canvas point from
393			// its layout rect + port index, parameterized by the flow direction.
394			//
395			// Horizontal (Ltr/Rtl): the main axis is x. The `from` (child) port
396			// sits at the node's main-axis leading edge (layout x), the `to`
397			// (parent) port one cell outside the trailing edge (layout right);
398			// the cross axis (y) is top + port + 1.
399			//
400			// Vertical (Ttb/Btt): the main axis is y, cross axis is x. Ports run
401			// along the node's width instead of its height, and the main-axis
402			// mirror (if any) is applied to y.
403			let dir = self.direction;
404			let (a_point, b_point) = if dir.is_horizontal() {
405				// defensively clamp port offsets to the node's inner height.
406				let from_port = clamp_port(ea_conn.from_port.0 as usize, a_pos.height);
407				let to_port = clamp_port(ea_conn.to_port.0 as usize, b_pos.height);
408				let mw = self.width;
409				// `from` (child) port at the node's main-axis leading edge
410				// (layout left); `to` (parent) port one cell outside the
411				// trailing edge (layout right). mirror_axis maps layout→canvas.
412				let ax = mirror_axis(mw, a_pos.left() as usize, dir);
413				let bx = mirror_axis(mw, b_pos.right() as usize, dir).saturating_sub(1);
414				let a = (ax, a_pos.top() as usize + from_port + 1);
415				let b = (bx, b_pos.top() as usize + to_port + 1);
416				(a, b)
417			} else {
418				// vertical: ports index along the node's width (cross axis = x).
419				// `from` (child) port at the node's top edge (layout top), `to`
420				// (parent) port one cell outside the bottom edge (layout bottom).
421				let from_port = clamp_port(ea_conn.from_port.0 as usize, a_pos.width);
422				let to_port = clamp_port(ea_conn.to_port.0 as usize, b_pos.width);
423				let mh = self.height;
424				let ay = mirror_axis(mh, a_pos.top() as usize, dir);
425				let by = mirror_axis(mh, b_pos.bottom() as usize, dir);
426				let a = (a_pos.left() as usize + from_port + 1, ay);
427				let b = (b_pos.left() as usize + to_port + 1, by);
428				(a, b)
429			};
430			self.conn_layout.insert_port(
431				false,
432				ea_conn.from_node,
433				ea_conn.from_port,
434				a_point,
435			);
436			self.conn_layout.insert_port(true, ea_conn.to_node, ea_conn.to_port, b_point);
437			let key = (ea_conn.from_node, ea_conn.from_port);
438			conn_map.entry(key).or_insert_with(|| {
439				let idx = next_idx;
440				next_idx += 1;
441				idx
442			});
443			self.conn_layout.push_connection((*ea_conn, conn_map[&key]));
444			let vertical = !dir.is_horizontal();
445			self.conn_layout.block_port(a_point, vertical);
446			self.conn_layout.block_port(b_point, vertical);
447		}
448		for mut ea_placement in self.placements.values().cloned() {
449			if self.direction.is_horizontal() && self.direction.mirror_main_axis() {
450				ea_placement.x = (self.width as u16)
451					.saturating_sub(ea_placement.x + ea_placement.width);
452			} else if !self.direction.is_horizontal() && self.direction.mirror_main_axis()
453			{
454				ea_placement.y = (self.height as u16)
455					.saturating_sub(ea_placement.y + ea_placement.height);
456			}
457			self.conn_layout.block_zone(ea_placement);
458		}
459		self.conn_layout.calculate(self.direction);
460
461		// pull routing failures (RoutingFailed) up from the connection layout
462		// into the graph-level diagnostics. `append` moves conn_layout's buffer
463		// in wholesale and leaves it empty, which is fine — conn_layout's
464		// diagnostics aren't read again after this point and are repopulated
465		// on the next calculate().
466		self.diagnostics.append(&mut self.conn_layout.diagnostics);
467
468		// any node that never got a placement is unreachable (not on any root's
469		// upstream chain — e.g. a pure cycle or an isolated node). record it.
470		for (node_id, _) in &self.nodes {
471			if !self.placements.contains_key(node_id) {
472				log::warn!("unreachable node not placed (node={})", node_id);
473				self.diagnostics.push(Diagnostic::UnplacedNode { node: *node_id });
474			}
475		}
476
477		// Re-render the whole graph's borders/ports/connections (no node
478		// *content*) into the off-screen canvas. This runs once per layout; the
479		// viewport widget then just blits a scrolled window from it each frame
480		// instead of re-laying-out.
481		//
482		// Render into a fresh local buffer first, then assign: `render_to` borrows
483		// `&self` (for nodes/placements/connections), so we can't hand it
484		// `&mut self.canvas` at the same time.
485		let canvas_rect = Rect {
486			x: 0,
487			y: 0,
488			width: self.width as u16,
489			height: self.height as u16,
490		};
491		let mut canvas = Buffer::empty(canvas_rect);
492		self.render_to(canvas_rect, &mut canvas);
493		self.canvas = canvas;
494	}
495
496	/// Non-fatal problems detected during the most recent
497	/// [`calculate`][Self::calculate]: unreachable (unplaced) nodes, ignored
498	/// out-of-bounds connections, and connections that couldn't be routed.
499	///
500	/// The slice is cleared at the start of each `calculate`, so it always
501	/// reflects the latest run. Each entry is also emitted via `log::warn!`.
502	pub fn diagnostics(&self) -> &[Diagnostic] {
503		&self.diagnostics
504	}
505
506	/// Place a node and recurse into its children.
507	///
508	/// `x` is the **main-axis** coordinate (the flow direction — children
509	/// advance along it away from the root); `y` is the **cross-axis**
510	/// coordinate (siblings stack along it). For horizontal flows (`Ltr`/`Rtl`)
511	/// the main axis is x and the cross axis is y; for vertical flows it is
512	/// reversed. The direction is read from `self.direction`.
513	fn place_node(
514		&mut self,
515		idx_node: NodeId,
516		x: u16,
517		y: u16,
518		main_chain: &mut Vec<NodeId>,
519		visited: &mut Set<NodeId>,
520		conns: &[Connection<'a>],
521	) {
522		// cycle guard: if this node was already placed (reachable again through
523		// a cycle), don't re-place or recurse. this is what prevents stack
524		// overflows on root-reachable cycles.
525		if self.placements.contains_key(&idx_node) || !visited.insert(idx_node) {
526			return;
527		}
528
529		// place the node
530		let Some(node_layout) = self.node_layout(idx_node) else {
531			// node id not present (defensive; calculate() already filtered).
532			return;
533		};
534		let size_me = node_layout.size;
535		let mut rect_me = Rect { x, y, width: size_me.0, height: size_me.1 };
536		let horiz = self.direction.is_horizontal();
537
538		// nudge placement. if a node intersects with another node, its entire
539		// main chain (largest subset of nodes including this one where every
540		// node is the first child of its parent) should be moved along the cross
541		// axis to not intersect.
542		//
543		// Repeat the for loop until it runs all the way through without any
544		// intersections. Surely there's a more efficient way to do this.
545		'outer: loop {
546			for (_, ea_them) in self.placements.iter() {
547				if rect_me.intersects(*ea_them) {
548					if horiz {
549						rect_me.y = rect_me.y.max(ea_them.bottom());
550					} else {
551						rect_me.x = rect_me.x.max(ea_them.right());
552					}
553					continue 'outer;
554				}
555			}
556			break;
557		}
558		for ea_node in main_chain.iter() {
559			if horiz {
560				let y = self.placements[ea_node].y.max(rect_me.y);
561				self.placements.get_mut(ea_node).unwrap().y = y;
562			} else {
563				let x = self.placements[ea_node].x.max(rect_me.x);
564				self.placements.get_mut(ea_node).unwrap().x = x;
565			}
566		}
567		self.placements.insert(idx_node, rect_me);
568
569		// find children and order them.
570		// Siblings stack along the cross axis; initialize the cross-axis cursor
571		// from this node's own cross-axis coordinate (NOT from a function param,
572		// since the param mapping to main/cross flips with direction).
573		let mut cross = if horiz { rect_me.y } else { rect_me.x };
574		let cur_main = if horiz { rect_me.x } else { rect_me.y };
575		let main_extent = if horiz { rect_me.width } else { rect_me.height };
576		main_chain.push(idx_node);
577		for ea_child in get_upstream(conns, idx_node) {
578			if self.placements.contains_key(&ea_child.from_node) {
579				// nudge it (if necessary). a fresh in_progress set per top-level
580				// nudge tracks the recursion stack to break cycles without
581				// blocking legitimate re-nudges. pass the new main-axis coordinate.
582				let mut in_progress = Set::new();
583				let new_main = cur_main + main_extent + MARGIN;
584				self.nudge(ea_child.from_node, new_main, &mut in_progress, conns);
585			} else {
586				// place it. child advances along the main axis; siblings stack
587				// along the cross axis. place_node takes (x, y) where for
588				// horizontal x=main,y=cross and for vertical x=cross,y=main.
589				let child_main = cur_main + main_extent + MARGIN;
590				let (px, py) =
591					if horiz { (child_main, cross) } else { (cross, child_main) };
592				self.place_node(ea_child.from_node, px, py, main_chain, visited, conns);
593				main_chain.clear();
594				// child may not have been placed (e.g. it's part of a cycle);
595				// only advance the cross axis if it actually got a rect.
596				if let Some(child_rect) = self.placements.get(&ea_child.from_node) {
597					if horiz {
598						cross += child_rect.height;
599					} else {
600						cross += child_rect.width;
601					}
602				}
603			}
604		}
605		main_chain.pop();
606	}
607
608	/// Push a node (and its subtree) further along the main axis if its
609	/// current main-axis coordinate is less than `main`. `main` is the
610	/// main-axis coordinate (x for horizontal, y for vertical).
611	fn nudge(
612		&mut self,
613		idx_node: NodeId,
614		main: u16,
615		in_progress: &mut Set<NodeId>,
616		conns: &[Connection<'a>],
617	) {
618		// cycle guard: break only if this node is already on the current
619		// recursion stack (i.e. we're inside a cycle). a node legitimately
620		// nudged twice through different paths must still be processed, so we
621		// use a per-recursion-stack set, not a global visited set.
622		if !in_progress.insert(idx_node) {
623			return;
624		}
625		let rect_me = self.placements[&idx_node];
626		let horiz = self.direction.is_horizontal();
627		let cur_main = if horiz { rect_me.x } else { rect_me.y };
628		let my_extent = if horiz { rect_me.width } else { rect_me.height };
629		if cur_main < main {
630			if horiz {
631				self.placements.get_mut(&idx_node).unwrap().x = main;
632			} else {
633				self.placements.get_mut(&idx_node).unwrap().y = main;
634			}
635			for ea_child in get_upstream(conns, idx_node) {
636				// the child must already be placed for nudging to make sense;
637				// skip defensively if not.
638				if self.placements.contains_key(&ea_child.from_node) {
639					self.nudge(
640						ea_child.from_node,
641						main + my_extent + MARGIN,
642						in_progress,
643						conns,
644					);
645				}
646			}
647		}
648		in_progress.remove(&idx_node);
649	}
650
651	pub fn split(&self, area: Rect) -> Vec<Rect> {
652		self.split_named(area).into_iter().map(|(_, r)| r).collect()
653	}
654
655	/// Like [`split`][Self::split], but each entry is tagged with its [`NodeId`].
656	/// The order matches [`split`] (nodes in render order) and the rects are the
657	/// same content rects (border removed, mirrored to screen coordinates within
658	/// `area`).
659	///
660	/// Useful when you need to map a placed rect back to the node it belongs to
661	/// (e.g. hit testing).
662	pub fn split_named(&self, area: Rect) -> Vec<(NodeId, Rect)> {
663		self.nodes
664			.iter()
665			.map(|(id, _)| {
666				let r = self
667					.placements
668					.get(id)
669					.map(|pos| {
670						if pos.right() > area.width || pos.bottom() > area.height {
671							return Rect { x: 0, y: 0, width: 0, height: 0 };
672						}
673						let mut pos = *pos;
674						if self.direction.is_horizontal() {
675							if self.direction.mirror_main_axis() {
676								pos.x = area.width - pos.right() + area.x;
677							} else {
678								pos.x += area.x;
679							}
680							pos.y += area.y;
681						} else {
682							pos.x += area.x;
683							if self.direction.mirror_main_axis() {
684								pos.y = area.height - pos.bottom() + area.y;
685							} else {
686								pos.y += area.y;
687							}
688						}
689						pos.inner(Margin { horizontal: 1, vertical: 1 })
690					})
691					.unwrap_or_default();
692				(*id, r)
693			})
694			.collect()
695	}
696
697	/// Hit-test a **screen** coordinate against the placed nodes and return the
698	/// [`NodeId`] of the node whose full frame (border included) contains
699	/// `(x, y)`, or `None` if the point falls in empty space or on a node that
700	/// was never placed.
701	///
702	/// `(x, y)` is interpreted relative to `area`'s top-left corner (i.e. they
703	/// are screen coordinates within `area`), exactly like the rects returned by
704	/// [`split`][Self::split] / [`split_named`][Self::split_named]. The hit area
705	/// is each node's **bordered** rect (a point on the border counts as a hit),
706	/// matching the granularity used by the off-screen canvas — so the inner
707	/// content rects from `split_named` are strictly contained in the hit rects.
708	///
709	/// Must be called **after** [`calculate`][Self::calculate]; before that,
710	/// [`positions`][Self::positions] is empty and `hit_test` always returns
711	/// `None`. The transformation honors [`direction`][Self::direction] (the same
712	/// canvas→screen mirror as `split_named`), so hit testing is correct for
713	/// `Ltr`/`Rtl`/`Ttb`/`Btt`.
714	///
715	/// Nodes never overlap in canvas space, so at most one node can contain a
716	/// given point; the first match (in render order) is returned. Viewport
717	/// offset is **not** applied here — for a scrolled graph use the upcoming
718	/// `hit_test_viewport` (Step 6), or pre-translate `(x, y)` by the offset.
719	pub fn hit_test(&self, area: Rect, x: u16, y: u16) -> Option<NodeId> {
720		for (id, canvas_rect) in self.placements.iter() {
721			// A 0×0 placement means the node never fit / was never placed —
722			// it has no on-screen extent to hit.
723			if canvas_rect.width == 0 || canvas_rect.height == 0 {
724				continue;
725			}
726			// Same bounds + canvas→screen transform as `split_named`, but kept
727			// WITHOUT `.inner(Margin{1,1})` so the border is part of the hit
728			// rect. Mirroring uses `self.direction` so Ltr/Btt/Ttb stay aligned.
729			if canvas_rect.right() > area.width || canvas_rect.bottom() > area.height {
730				continue;
731			}
732			let mut pos = *canvas_rect;
733			if self.direction.is_horizontal() {
734				if self.direction.mirror_main_axis() {
735					pos.x = area.width - pos.right() + area.x;
736				} else {
737					pos.x += area.x;
738				}
739				pos.y += area.y;
740			} else {
741				pos.x += area.x;
742				if self.direction.mirror_main_axis() {
743					pos.y = area.height - pos.bottom() + area.y;
744				} else {
745					pos.y += area.y;
746				}
747			}
748			if pos.contains(Position { x, y }) {
749				return Some(*id);
750			}
751		}
752		None
753	}
754
755	/// Like [`split`][Self::split], but returns each node's content rect in
756	/// **screen** coordinates for a scrolled viewport.
757	///
758	/// Each rect is the node's canvas-rect (mirrored, inner border removed),
759	/// translated by `-viewport.offset + area.origin`, then clipped to `area`.
760	/// A node fully scrolled off-screen yields a 0×0 rect (render it only when
761	/// `width > 0 && height > 0`).
762	///
763	/// Typical per-frame usage:
764	/// ```ignore
765	/// let zones = graph.split_viewport(view_area, &viewport);
766	/// for (i, z) in zones.iter().enumerate() {
767	///     if z.width > 0 && z.height > 0 {
768	///         f.render_widget(my_content[i], *z);
769	///     }
770	/// }
771	/// f.render_widget(NodeGraphView::new(&graph).viewport(viewport), view_area);
772	/// ```
773	#[deprecated(
774		since = "0.1.0",
775		note = "use `split_stateful(area, &FlowState)` with a FlowState whose `view_offset` is set"
776	)]
777	#[allow(deprecated)]
778	pub fn split_viewport(&self, area: Rect, viewport: &Viewport) -> Vec<Rect> {
779		let canvas_rect = Rect {
780			x: 0,
781			y: 0,
782			width: self.width as u16,
783			height: self.height as u16,
784		};
785		let (ox, oy) = viewport.offset;
786		self.split(canvas_rect)
787			.into_iter()
788			.map(|z| {
789				// A node whose entire rect sits above/left of the viewport
790				// (canvas right edge <= offset.x, or bottom edge <= offset.y) is
791				// fully scrolled off and must become 0×0. `saturating_sub` alone
792				// would clamp it to the screen's top-left edge and keep its size,
793				// wrongly painting a partial node in the corner — so detect that
794				// case first.
795				if z.right() <= ox || z.bottom() <= oy {
796					return Rect::default();
797				}
798				let mut z = z;
799				// translate canvas-coord rect to screen coordinates: subtract the
800				// viewport offset, then add the screen area's origin.
801				z.x = z.x.saturating_sub(ox).saturating_add(area.x);
802				z.y = z.y.saturating_sub(oy).saturating_add(area.y);
803				// clip to the visible area; `intersection` returns a 0×0 rect when
804				// the node is fully off the far edge.
805				z.intersection(area)
806			})
807			.collect()
808	}
809
810	/// Like [`split_named`][Self::split_named], but each content rect is
811	/// translated by `state.view_offset` and clipped to `area` — i.e. it returns
812	/// the screen-coordinate content rects for a scrolled/panned view driven by
813	/// a [`FlowState`].
814	///
815	/// This is the stateful-path counterpart of
816	/// [`split_viewport`][Self::split_viewport]: it yields `(NodeId, Rect)`
817	/// pairs (so the caller can route content to the right node), and the rect
818	/// math is identical — each node's canvas-rect (mirrored, inner border
819	/// removed) is shifted by `-view_offset + area.origin` and clipped to `area`.
820	/// A node fully scrolled off-screen yields a 0×0 rect (render it only when
821	/// `width > 0 && height > 0`).
822	///
823	/// Typical per-frame usage with the stateful render path:
824	/// ```ignore
825	/// let zones = graph.split_stateful(view_area, &flow_state);
826	/// for (id, z) in &zones {
827	///     if z.width > 0 && z.height > 0 {
828	///         f.render_widget(my_content_for(id), *z);
829	///     }
830	/// }
831	/// f.render_stateful_widget(graph, view_area, &mut flow_state);
832	/// ```
833	pub fn split_stateful(
834		&self,
835		area: Rect,
836		state: &crate::FlowState,
837	) -> Vec<(NodeId, Rect)> {
838		let canvas_rect = Rect {
839			x: 0,
840			y: 0,
841			width: self.width as u16,
842			height: self.height as u16,
843		};
844		let (ox, oy) = state.view_offset;
845		self.split_named(canvas_rect)
846			.into_iter()
847			.map(|(id, z)| {
848				// A node whose entire rect sits above/left of the viewport is
849				// fully scrolled off and must become 0×0 (see split_viewport).
850				if z.right() <= ox || z.bottom() <= oy {
851					return (id, Rect::default());
852				}
853				let mut z = z;
854				z.x = z.x.saturating_sub(ox).saturating_add(area.x);
855				z.y = z.y.saturating_sub(oy).saturating_add(area.y);
856				(id, z.intersection(area))
857			})
858			.collect()
859	}
860
861	/// Translate a node's canvas-rect (border included) into screen coordinates
862	/// under a panned view: apply the canvas→screen mirror (per `self.direction`)
863	/// and the `view_offset` pan, then return the (possibly clipped) rect. Used
864	/// by the stateful highlight overlay to find where a node's border lives on
865	/// screen. Returns `None` if the node isn't placed or its rect is 0×0.
866	fn node_screen_rect(
867		&self,
868		id: NodeId,
869		area: Rect,
870		view_offset: (u16, u16),
871	) -> Option<Rect> {
872		let canvas_rect = self.placements.get(&id).copied()?;
873		if canvas_rect.width == 0 || canvas_rect.height == 0 {
874			return None;
875		}
876		let (ox, oy) = view_offset;
877		// canvas-coord bordered rect -> screen: subtract the pan offset, add the
878		// area origin. No mirror here — the canvas already holds the mirrored
879		// rendering (render_to ran with the mirror during calculate), so the
880		// canvas cell at (cx, cy) corresponds to screen (cx - ox + area.x, ...).
881		let mut pos = canvas_rect;
882		// fully scrolled off the top/left edge -> not visible.
883		if pos.right() <= ox || pos.bottom() <= oy {
884			return None;
885		}
886		pos.x = pos.x.saturating_sub(ox).saturating_add(area.x);
887		pos.y = pos.y.saturating_sub(oy).saturating_add(area.y);
888		// clip to area; if no overlap, not visible.
889		let clipped = pos.intersection(area);
890		if clipped.width == 0 || clipped.height == 0 {
891			return None;
892		}
893		Some(clipped)
894	}
895
896	/// Recolor the **border** cells of a node's on-screen rect with `style`'s
897	/// foreground/add-modifier, preserving each cell's existing symbol (so the
898	/// port glyphs ├/┬/etc. that the canvas blit already placed on the border
899	/// survive — only their color changes). Only the perimeter cells are
900	/// touched; the node's inner content is left untouched.
901	///
902	/// This is the highlight mechanism used by the stateful render path: after
903	/// the (possibly scrolled) canvas is blitted, the selection/hover node's
904	/// border is recolored in place without re-running `Block::render` (which
905	/// would clobber the port symbols).
906	fn highlight_border(&self, buf: &mut Buffer, screen_rect: Rect, style: Style) {
907		let r = screen_rect;
908		// perimeter: top row, bottom row, left col, right col — clamped to the
909		// rect itself (a 1-wide/1-tall rect degenerates to a single row/col,
910		// which is correct: its only cells are border cells).
911		for x in r.left()..r.right() {
912			if let Some(cell) = buf.cell_mut(Position::new(x, r.top())) {
913				merge_style(cell, style);
914			}
915			if r.height > 1
916				&& let Some(cell) = buf.cell_mut(Position::new(x, r.bottom() - 1))
917			{
918				merge_style(cell, style);
919			}
920		}
921		for y in r.top()..r.bottom() {
922			if let Some(cell) = buf.cell_mut(Position::new(r.left(), y)) {
923				merge_style(cell, style);
924			}
925			if r.width > 1
926				&& let Some(cell) = buf.cell_mut(Position::new(r.right() - 1, y))
927			{
928				merge_style(cell, style);
929			}
930		}
931	}
932}
933
934/// Overlay `style` onto an existing cell without changing the cell's symbol.
935/// Used by the stateful highlight to recolor a node's border while preserving
936/// the port glyphs already on it.
937///
938/// `Style::patch` merges fg/bg with `or` and modifiers with `insert` (set
939/// union), which is exactly the "keep existing, add new" semantics we want.
940fn merge_style(cell: &mut ratatui::buffer::Cell, style: Style) {
941	let merged = cell.style().patch(style);
942	cell.set_style(merged);
943}
944
945/// Scroll position into a [`NodeGraph`]'s canvas.
946///
947/// `offset` is the (x, y) coordinate of the viewport's top-left corner within
948/// the off-screen canvas. (0, 0) shows the top-left of the graph; increasing x
949/// scrolls right, increasing y scrolls down.
950///
951/// Pass it to [`NodeGraph::split_viewport`] (for node content rects) and
952/// [`NodeGraphView`] (for borders/connections).
953#[deprecated(
954	since = "0.1.0",
955	note = "use `FlowState` (its `view_offset` field replaces `Viewport.offset`)"
956)]
957#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
958pub struct Viewport {
959	/// Top-left corner of the viewport in canvas coordinates.
960	pub offset: (u16, u16),
961}
962
963#[allow(deprecated)]
964impl Viewport {
965	/// Create a viewport at offset (0, 0) (top-left of the canvas).
966	pub fn new() -> Self {
967		Self::default()
968	}
969
970	/// Set the viewport's top-left offset in canvas coordinates.
971	#[must_use]
972	pub fn offset(mut self, x: u16, y: u16) -> Self {
973		self.offset = (x, y);
974		self
975	}
976}
977
978#[allow(deprecated)]
979impl std::fmt::Display for Viewport {
980	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
981		write!(f, "Viewport({}, {})", self.offset.0, self.offset.1)
982	}
983}
984
985/// A read-only [`Widget`] that renders a scrolled window of a [`NodeGraph`]'s
986/// borders/ports/connections (no node *content*).
987///
988/// The full graph is rendered once into an off-screen canvas during
989/// [`NodeGraph::calculate`]; this widget blits the visible window (determined
990/// by its [`Viewport`]) onto the frame each draw. Render your own node content
991/// into the rects from [`NodeGraph::split_viewport`] separately.
992///
993/// ```ignore
994/// f.render_widget(NodeGraphView::new(&graph).offset(x, y), area);
995/// ```
996#[deprecated(
997	since = "0.1.0",
998	note = "use `NodeGraph`'s `StatefulWidget` impl with `FlowState` (set `view_offset` for panning)"
999)]
1000pub struct NodeGraphView<'a> {
1001	graph: &'a NodeGraph<'a>,
1002	#[allow(deprecated)]
1003	viewport: Viewport,
1004}
1005
1006#[allow(deprecated)]
1007impl<'a> NodeGraphView<'a> {
1008	/// Create a view over `graph` at offset (0, 0).
1009	pub fn new(graph: &'a NodeGraph<'a>) -> Self {
1010		Self { graph, viewport: Viewport::default() }
1011	}
1012
1013	/// Set the viewport (offset into the canvas).
1014	#[must_use]
1015	pub fn viewport(mut self, viewport: Viewport) -> Self {
1016		self.viewport = viewport;
1017		self
1018	}
1019
1020	/// Convenience: set the viewport offset directly (x, y).
1021	#[must_use]
1022	pub fn offset(mut self, x: u16, y: u16) -> Self {
1023		self.viewport.offset = (x, y);
1024		self
1025	}
1026}
1027
1028#[allow(deprecated)]
1029impl Widget for NodeGraphView<'_> {
1030	fn render(self, area: Rect, buf: &mut Buffer) {
1031		let canvas = self.graph.canvas();
1032		let (ox, oy) = self.viewport.offset;
1033		blit_canvas(canvas, area, buf, (ox, oy));
1034	}
1035}
1036
1037/// Blit the visible window of `canvas` onto `area` of `buf`, cell by cell.
1038///
1039/// `offset` is the top-left corner of the visible window inside `canvas`. For
1040/// each screen cell `(vx, vy)` in `area`, the canvas cell at
1041/// `(offset.x + vx, offset.y + vy)` is looked up; if it's non-blank, its symbol
1042/// and style are copied into the matching `buf` cell. Blank canvas cells (node
1043/// content / background) are left untouched so caller-rendered content shows
1044/// through.
1045///
1046/// Shared between [`NodeGraphView::render`] (the legacy stateless viewport
1047/// widget) and [`NodeGraph`]'s stateful render path so both blit identically.
1048pub(crate) fn blit_canvas(
1049	canvas: &Buffer,
1050	area: Rect,
1051	buf: &mut Buffer,
1052	offset: (u16, u16),
1053) {
1054	let (ox, oy) = offset;
1055	for vy in 0..area.height {
1056		for vx in 0..area.width {
1057			let sx = ox.saturating_add(vx);
1058			let sy = oy.saturating_add(vy);
1059			let src = match canvas.cell(Position::new(sx, sy)) {
1060				Some(c) => c,
1061				None => continue,
1062			};
1063			// Blank canvas cells are node content areas / background — leave
1064			// them untouched so content the caller rendered into the
1065			// `split_viewport` rects shows through. Only copy cells the canvas
1066			// actually drew (borders / ports / connections).
1067			if src.symbol() == " " {
1068				continue;
1069			}
1070			if let Some(dst) = buf.cell_mut(Position::new(area.x + vx, area.y + vy)) {
1071				dst.set_symbol(src.symbol());
1072				dst.set_style(src.style());
1073			}
1074		}
1075	}
1076}
1077
1078fn get_upstream<'a>(conns: &[Connection<'a>], idx_node: NodeId) -> Vec<Connection<'a>> {
1079	// find children and order them
1080	let mut upstream: Vec<_> =
1081		conns.iter().filter(|ea| ea.to_node == idx_node).copied().collect();
1082	upstream.sort_by_key(|a| a.to_port);
1083	upstream
1084}
1085
1086fn get_downstream<'a>(conns: &[Connection<'a>], idx_node: NodeId) -> Vec<Connection<'a>> {
1087	// find parents and order them
1088	let mut downstream: Vec<_> =
1089		conns.iter().filter(|ea| ea.from_node == idx_node).copied().collect();
1090	downstream.sort_by_key(|a| a.from_port);
1091	downstream
1092}
1093
1094/// Clamp a port index into the valid range of inner rows for a node of the
1095/// given height. Ports are used as a y-offset into the node's frame; an
1096/// out-of-range value would draw outside the frame (or past the buffer). The
1097/// usable inner rows are `0..=height-2` (height includes the top/bottom
1098/// borders), so the largest valid offset is `height-2`.
1099fn clamp_port(port: usize, node_height: u16) -> usize {
1100	let max = (node_height as usize).saturating_sub(2);
1101	port.min(max)
1102}
1103
1104/// Direction a port name grows from its anchor cell (Step 9).
1105enum PortNameDir {
1106	/// First char at the anchor cell, subsequent chars to the right (used for
1107	/// **in** ports on the left/top edge, so the name grows toward the node
1108	/// interior).
1109	Right,
1110	/// First char at the anchor cell, subsequent chars to the left (used for
1111	/// **out** ports on the right/bottom edge, so the name grows toward the node
1112	/// interior). The anchor cell is thus the inner-most cell and holds the
1113	/// name's first character.
1114	Left,
1115}
1116
1117/// Draw a port's display name horizontally, anchored at `(x, y)` (one cell
1118/// *inside* the node from its port symbol) and growing in `dir`. The name is
1119/// truncated so it never leaves the node's inner content area (`pos` is the
1120/// node's full frame, so the inner row is `pos.left()+1 ..= pos.right()-2`):
1121/// the anchor cell always holds the first character (so the "inner cell next to
1122/// the port symbol" is the name's leading char), and remaining characters extend
1123/// inward. Bounds against `area` are also checked (render_to may have clipped
1124/// the node). The name is drawn in **bold**.
1125///
1126/// Pure overlay: only called when a name exists, so no-name nodes render
1127/// identically to pre-Step-9.
1128fn write_port_name(
1129	buf: &mut Buffer,
1130	area: Rect,
1131	pos: Rect,
1132	x: u16,
1133	y: u16,
1134	dir: PortNameDir,
1135	name: &str,
1136) {
1137	let style = Style::default().add_modifier(Modifier::BOLD);
1138	let inner_left = pos.left() + 1;
1139	let inner_right = pos.right().saturating_sub(2);
1140	match dir {
1141		PortNameDir::Right => {
1142			let mut cx = x;
1143			for ch in name.chars() {
1144				if cx > inner_right {
1145					break;
1146				}
1147				if cx >= area.width || y >= area.height {
1148					break;
1149				}
1150				if let Some(cell) = buf.cell_mut(Position::new(cx, y)) {
1151					cell.set_symbol(ch.to_string().as_str()).set_style(style);
1152				}
1153				cx = cx.saturating_add(1);
1154			}
1155		}
1156		PortNameDir::Left => {
1157			let mut cx = x;
1158			for ch in name.chars() {
1159				if cx < inner_left {
1160					break;
1161				}
1162				if cx >= area.width || y >= area.height {
1163					break;
1164				}
1165				if let Some(cell) = buf.cell_mut(Position::new(cx, y)) {
1166					cell.set_symbol(ch.to_string().as_str()).set_style(style);
1167				}
1168				cx = cx.saturating_sub(1);
1169			}
1170		}
1171	}
1172}
1173
1174/// Map a layout-coordinate main-axis value to its canvas-coordinate value,
1175/// mirroring about `size` when the direction's main axis is mirrored
1176/// (`Rtl`/`Btt`). `size` is the canvas extent on the main axis
1177/// (`self.width` for horizontal, `self.height` for vertical).
1178///
1179/// For non-mirrored directions (`Ltr`/`Ttb`) the value is unchanged.
1180fn mirror_axis(size: usize, coord: usize, dir: FlowDirection) -> usize {
1181	if dir.mirror_main_axis() { size.saturating_sub(coord) } else { coord }
1182}
1183
1184impl<'a> NodeGraph<'a> {
1185	/// Render the graph's borders/ports/connections (but *not* node content)
1186	/// into `buf` at `area`. This is the shared implementation behind both the
1187	/// [`StatefulWidget`] impl (used by `split`-based rendering) and the
1188	/// off-screen canvas drawn during [`calculate`][Self::calculate] (used by
1189	/// [`NodeGraphView`]).
1190	///
1191	/// Takes `&self` (rather than consuming the widget) so the same graph can
1192	/// be rendered multiple times — once into the canvas during layout, and
1193	/// any number of times via the `StatefulWidget` impl for non-viewport use.
1194	pub(crate) fn render_to(&self, area: Rect, buf: &mut Buffer) {
1195		// draw connections
1196		self.conn_layout.render(area, buf);
1197
1198		let vertical = !self.direction.is_horizontal();
1199		let mirror = self.direction.mirror_main_axis();
1200
1201		// draw nodes
1202		'node: for (idx_node, ea_node) in &self.nodes {
1203			let idx_node = *idx_node;
1204			if let Some(mut pos) = self.placements.get(&idx_node).copied() {
1205				if pos.right() > area.width || pos.bottom() > area.height {
1206					continue 'node;
1207				}
1208				// draw box — mirror the main axis to screen coordinates when the
1209				// direction mirrors (Rtl mirrors x, Btt mirrors y); otherwise just
1210				// translate by the area origin.
1211				if self.direction.is_horizontal() {
1212					if mirror {
1213						pos.x = area.left() + area.width - pos.right();
1214					} else {
1215						pos.x += area.left();
1216					}
1217					pos.y += area.top();
1218				} else {
1219					pos.x += area.left();
1220					if mirror {
1221						pos.y = area.top() + area.height - pos.bottom();
1222					} else {
1223						pos.y += area.top();
1224					}
1225				}
1226				let block = ea_node.block();
1227				block.render(pos, buf);
1228				// For horizontal flows the input (to_node) port is on the LEFT edge
1229				// and the output (from_node) port on the RIGHT edge. For vertical flows
1230				// the input port is on the BOTTOM edge (faces the child below) and the
1231				// output port on the TOP edge (faces the parent above) — i.e. swapped
1232				// relative to horizontal, because the parent sits on the opposite side.
1233				// draw input ports (upstream / to_node)
1234				for ea_conn in get_upstream(&self.connections, idx_node) {
1235					let to_port =
1236						clamp_port(ea_conn.to_port.0 as usize, pos.height) as u16;
1237					// draw connection alias
1238					if let Some(alias_char) = self.conn_layout.alias_connections.get(&(
1239						true,
1240						idx_node,
1241						ea_conn.to_port,
1242					)) {
1243						if !vertical {
1244							let y = pos.top() + to_port + 1;
1245							if pos.left() > 0
1246								&& y < area.height && let Some(cell) =
1247								buf.cell_mut(Position::new(pos.left() - 1, y))
1248							{
1249								cell.set_symbol(alias_char).set_style(
1250									Style::default()
1251										.add_modifier(Modifier::BOLD)
1252										.bg(Color::Red),
1253								);
1254							}
1255						} else {
1256							// input alias one cell below the bottom edge
1257							let x = pos.left() + to_port + 1;
1258							if x < area.width
1259								&& let Some(cell) =
1260									buf.cell_mut(Position::new(x, pos.bottom()))
1261							{
1262								cell.set_symbol(alias_char).set_style(
1263									Style::default()
1264										.add_modifier(Modifier::BOLD)
1265										.bg(Color::Red),
1266								);
1267							}
1268						}
1269					}
1270
1271					// draw port — the `to` (in) port. When `show_arrows` is on
1272					// (the default), this is a direction arrow pointing in the
1273					// flow direction (toward the inside of the `to` node);
1274					// otherwise it falls back to the in-port connection glyph
1275					// (`┤`/`┴` family) for Step-6-equivalent rendering.
1276					let in_symbol = if self.show_arrows {
1277						arrow_symbol(self.direction, ea_conn.line_type())
1278					} else {
1279						conn_symbol(
1280							true,
1281							ea_node.border_type(),
1282							ea_conn.line_type(),
1283							vertical,
1284						)
1285					};
1286					if !vertical {
1287						if let Some(cell) = buf
1288							.cell_mut(Position::new(pos.left(), pos.top() + to_port + 1))
1289						{
1290							cell.set_symbol(in_symbol);
1291						}
1292						// Step 9: port display name — drawn one cell inside the
1293						// left edge (toward the node interior), truncated to the
1294						// node's content area so it never crosses the far border.
1295						if let Some(name) = ea_node.port_name(ea_conn.to_port) {
1296							let y = pos.top() + to_port + 1;
1297							let anchor_x = pos.left() + 1;
1298							write_port_name(
1299								buf,
1300								area,
1301								pos,
1302								anchor_x,
1303								y,
1304								PortNameDir::Right,
1305								name,
1306							);
1307						}
1308					} else {
1309						// input port on the bottom edge, offset along width
1310						if let Some(cell) = buf.cell_mut(Position::new(
1311							pos.left() + to_port + 1,
1312							pos.bottom() - 1,
1313						)) {
1314							cell.set_symbol(in_symbol);
1315						}
1316						// Step 9: port name — one cell above the bottom edge
1317						// (into the node interior), written horizontally from the
1318						// port's x, truncated to the content area.
1319						if let Some(name) = ea_node.port_name(ea_conn.to_port) {
1320							let x = pos.left() + to_port + 1;
1321							let y = pos.bottom().saturating_sub(2);
1322							write_port_name(
1323								buf,
1324								area,
1325								pos,
1326								x,
1327								y,
1328								PortNameDir::Right,
1329								name,
1330							);
1331						}
1332					}
1333				}
1334				// draw output ports (downstream / from_node)
1335				for ea_conn in get_downstream(&self.connections, idx_node) {
1336					let from_port =
1337						clamp_port(ea_conn.from_port.0 as usize, pos.height) as u16;
1338					// draw connection alias
1339					if let Some(alias_char) = self.conn_layout.alias_connections.get(&(
1340						false,
1341						idx_node,
1342						ea_conn.from_port,
1343					)) {
1344						if !vertical {
1345							if let Some(cell) = buf.cell_mut(Position::new(
1346								pos.right(),
1347								pos.top() + from_port + 1,
1348							)) {
1349								cell.set_symbol(alias_char).set_style(
1350									Style::default()
1351										.add_modifier(Modifier::BOLD)
1352										.bg(Color::Red),
1353								);
1354							}
1355						} else {
1356							// output alias one cell above the top edge
1357							if pos.top() > 0
1358								&& let Some(cell) = buf.cell_mut(Position::new(
1359									pos.left() + from_port + 1,
1360									pos.top() - 1,
1361								)) {
1362								cell.set_symbol(alias_char).set_style(
1363									Style::default()
1364										.add_modifier(Modifier::BOLD)
1365										.bg(Color::Red),
1366								);
1367							}
1368						}
1369					}
1370
1371					// draw port
1372					if !vertical {
1373						if let Some(cell) = buf.cell_mut(Position::new(
1374							pos.right() - 1,
1375							pos.top() + from_port + 1,
1376						)) {
1377							cell.set_symbol(conn_symbol(
1378								false,
1379								ea_node.border_type(),
1380								ea_conn.line_type(),
1381								false,
1382							));
1383						}
1384						// Step 9: out-port display name — one cell inside the
1385						// right edge (toward the node interior). First char on
1386						// the inner cell, remaining chars extend leftward.
1387						if let Some(name) = ea_node.port_name(ea_conn.from_port) {
1388							let y = pos.top() + from_port + 1;
1389							let anchor_x = pos.right().saturating_sub(2);
1390							write_port_name(
1391								buf,
1392								area,
1393								pos,
1394								anchor_x,
1395								y,
1396								PortNameDir::Left,
1397								name,
1398							);
1399						}
1400					} else {
1401						// output port on the top edge, offset along width
1402						if let Some(cell) = buf.cell_mut(Position::new(
1403							pos.left() + from_port + 1,
1404							pos.top(),
1405						)) {
1406							cell.set_symbol(conn_symbol(
1407								false,
1408								ea_node.border_type(),
1409								ea_conn.line_type(),
1410								true,
1411							));
1412						}
1413						// Step 9: out-port display name — one cell below the top
1414						// edge (into the node interior), first char on the inner
1415						// cell, extending leftward.
1416						if let Some(name) = ea_node.port_name(ea_conn.from_port) {
1417							let x = pos.left() + from_port + 1;
1418							let y = pos.top() + 1;
1419							write_port_name(
1420								buf,
1421								area,
1422								pos,
1423								x,
1424								y,
1425								PortNameDir::Left,
1426								name,
1427							);
1428						}
1429					}
1430				}
1431			} else {
1432				buf.set_string(
1433					0,
1434					idx_node.0 as u16,
1435					format!("{}", idx_node.0),
1436					Style::default(),
1437				);
1438			}
1439		}
1440	}
1441}
1442
1443impl<'a> ratatui::widgets::StatefulWidget for NodeGraph<'a> {
1444	type State = crate::FlowState;
1445
1446	fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1447		// DEFAULT SAFE-NET (highest priority): a freshly-defaulted FlowState
1448		// (offset (0,0), no selection, no hover) must render byte-for-byte
1449		// identically to the legacy stateless render. Delegating straight to
1450		// `render_to` guarantees absolute zero change in that case — no blit,
1451		// no highlight overlay, nothing that could perturb a single cell.
1452		let is_default = state.view_offset == (0, 0)
1453			&& state.selection.is_none()
1454			&& state.hover.is_none();
1455		if is_default {
1456			self.render_to(area, buf);
1457			return;
1458		}
1459
1460		// Non-default state.
1461		//
1462		// 1) Borders/ports/connections: if the view is panned, blit the visible
1463		//    window of the off-screen canvas onto `area` (the canvas was already
1464		//    rendered during `calculate`). At offset (0,0) this would be
1465		//    equivalent to `render_to`, but we blit anyway so the highlight
1466		//    overlay below operates on the same canvas-sourced cells regardless
1467		//    of pan. Blitting a (0,0) offset produces the same output as
1468		//    `render_to` would, so there's no divergence for the no-pan case.
1469		if state.view_offset == (0, 0) {
1470			// No pan: render the source directly (identical to the default
1471			// path's paint, minus the default short-circuit). This keeps the
1472			// no-pan highlight case byte-identical to render_to as a base.
1473			self.render_to(area, buf);
1474		} else {
1475			// Panned: blit the scrolled window from the canvas. The canvas
1476			// holds borders/ports/connections only (no content), so caller-
1477			// rendered content shows through the blank cells.
1478			blit_canvas(&self.canvas, area, buf, state.view_offset);
1479		}
1480
1481		// 2) Selection / hover highlight overlay: recolor the border cells of
1482		//    the targeted node(s). We use `highlight_border` which preserves
1483		//    each cell's symbol (so the port glyphs ├/┬/etc. on the border
1484		//    survive — only their fg/modifier changes). Hover is drawn first so
1485		//    that a node that is both hovered and selected shows the selection
1486		//    (selection wins, drawn second).
1487		let hover_style = self.highlight_style.add_modifier(Modifier::DIM);
1488		if let Some(hover_id) = state.hover
1489			&& let Some(rect) = self.node_screen_rect(hover_id, area, state.view_offset)
1490		{
1491			self.highlight_border(buf, rect, hover_style);
1492		}
1493		if let Some(sel_id) = state.selection
1494			&& let Some(rect) = self.node_screen_rect(sel_id, area, state.view_offset)
1495		{
1496			self.highlight_border(buf, rect, self.highlight_style);
1497		}
1498	}
1499}