Skip to main content

ratatui_flow/
node.rs

1use ratatui::{
2	style::Style,
3	widgets::{Block, BorderType, Borders},
4};
5use std::collections::HashMap as Map;
6use unicode_width::UnicodeWidthStr;
7
8use crate::id::PortId;
9
10/// Render information for a single node.
11///
12/// `size` is the node's *total* size **including** its 1-cell border, so the
13/// inner content area is `(size.0 - 2, size.1 - 2)`. This is the unit that
14/// [`crate::NodeGraph`] lays out.
15///
16/// Optional **port display names** can be attached via
17/// [`with_port_name`][Self::with_port_name]; when present, a port's name is
18/// drawn one cell *inside* the node from its port symbol (inward of the border).
19/// Port *positions* are unchanged — the name is a pure overlay. By default a
20/// node has no port names, so rendering is byte-for-byte identical to a node
21/// built without them (opt-in).
22#[derive(Debug, Clone)]
23pub struct NodeLayout<'a> {
24	pub size: (u16, u16),
25	border_type: BorderType,
26	title: &'a str,
27	border_style: Style,
28	/// Optional display names keyed by [`PortId`]. Drawn one cell inside the
29	/// node from the port symbol (Step 9). Defaults to empty — no names → no
30	/// rendering change.
31	port_names: Map<PortId, &'a str>,
32}
33
34impl<'a> NodeLayout<'a> {
35	pub fn new(size: (u16, u16)) -> Self {
36		Self {
37			size,
38			border_type: BorderType::Plain,
39			title: "",
40			border_style: Style::default(),
41			port_names: Map::new(),
42		}
43	}
44
45	/// Build a node whose size auto-fits the given multi-line `content`.
46	///
47	/// The inner content area is sized to the widest line (by display width)
48	/// and the number of lines; the returned `size` then adds 2 cells per axis
49	/// for the border, so the content fits exactly inside when rendered into
50	/// the rect returned by [`crate::NodeGraph::split`].
51	///
52	/// Only the *size* is derived from `content` — the node does not store or
53	/// render it. Render your own widget into the content rect yourself.
54	///
55	/// Display width uses `unicode-width`, so wide (e.g. CJK) and zero-width
56	/// characters are measured correctly.
57	pub fn from_content(content: &str) -> Self {
58		let inner_w = content.lines().map(UnicodeWidthStr::width).max().unwrap_or(0);
59		let inner_h = content.lines().count();
60		Self::new((inner_w.saturating_add(2) as u16, inner_h.saturating_add(2) as u16))
61	}
62
63	pub fn with_title(mut self, title: &'a str) -> Self {
64		self.title = title;
65		self
66	}
67
68	pub fn title(&self) -> &str {
69		self.title
70	}
71
72	pub fn with_border_type(mut self, border: BorderType) -> Self {
73		self.border_type = border;
74		self
75	}
76
77	pub fn border_type(&self) -> BorderType {
78		self.border_type
79	}
80
81	pub fn with_border_style(mut self, style: Style) -> Self {
82		self.border_style = style;
83		self
84	}
85
86	/// Attach a **display name** to a port (Step 9). When the graph renders a
87	/// port symbol (on the node's border), the name's first characters are
88	/// written starting one cell *inside* the node from that symbol, going
89	/// horizontally and truncated to the available inner width on that row.
90	///
91	/// Port *positions* are not affected — the [`PortId`] still maps to the same
92	/// y/x offset along the node's side (see [`crate::NodeGraph`]). This is a
93	/// pure visual overlay: a node with no port names renders byte-for-byte
94	/// identically to one without the feature (the field defaults to empty).
95	///
96	/// Names are best kept short (a few chars); long names get truncated to fit
97	/// the node's inner width. The name may collide visually with the node's own
98	/// content (which you render separately into the content rect), so prefer
99	/// short, distinctive labels.
100	///
101	/// `port` is matched against a connection's `to_port` (in port, drawn on the
102	/// left/top side) or `from_port` (out port, drawn on the right/bottom side)
103	/// depending on which connection references it.
104	#[must_use]
105	pub fn with_port_name(mut self, port: PortId, name: &'a str) -> Self {
106		self.port_names.insert(port, name);
107		self
108	}
109
110	/// The display name attached to `port`, if any (set via
111	/// [`with_port_name`][Self::with_port_name]). `None` for ports with no name
112	/// (the default).
113	pub fn port_name(&self, port: PortId) -> Option<&str> {
114		self.port_names.get(&port).copied()
115	}
116
117	pub fn block(&self) -> Block<'_> {
118		Block::default()
119			.borders(Borders::ALL)
120			.border_type(self.border_type)
121			.border_style(self.border_style)
122			.title(self.title)
123	}
124}
125
126#[cfg(test)]
127mod tests {
128	use super::*;
129
130	#[test]
131	fn from_content_single_line() {
132		// "hello" is 5 cells wide; +2 for borders on each axis, 1 line => +2 height.
133		let node = NodeLayout::from_content("hello");
134		assert_eq!(node.size, (7, 3));
135	}
136
137	#[test]
138	fn from_content_multi_line_width_is_widest() {
139		// widest line is "longer_line" = 11; 3 lines => height 3 + 2 = 5.
140		let node = NodeLayout::from_content("short\nlonger_line\ncat");
141		assert_eq!(node.size, ((11 + 2), (3 + 2)));
142	}
143
144	#[test]
145	fn from_content_empty_string() {
146		// "" has display width 0; `"".lines().count()` == 0 (no lines), so
147		// size = (0+2, 0+2). `.max()` on an empty iterator falls back to 0.
148		let node = NodeLayout::from_content("");
149		assert_eq!(node.size, (2, 2));
150	}
151
152	#[test]
153	fn from_content_single_char() {
154		let node = NodeLayout::from_content("x");
155		assert_eq!(node.size, ((1 + 2), (1 + 2)));
156	}
157
158	#[test]
159	fn from_content_trailing_newline_does_not_add_line() {
160		// `str::lines` does NOT yield a trailing empty element: "a\n" -> ["a"].
161		// So this is 1 line, width 1 — documents that `from_content` follows
162		// `str::lines` semantics (no phantom trailing line).
163		let node = NodeLayout::from_content("a\n");
164		assert_eq!(node.size, ((1 + 2), (1 + 2)));
165	}
166
167	#[test]
168	fn from_content_cjk_uses_display_width() {
169		// "中文" is 2 code points but 4 display cells wide (each CJK char is wide).
170		// This proves unicode-width is applied, not char count (which would give 2).
171		let node = NodeLayout::from_content("中文");
172		assert_eq!(node.size, ((4 + 2), (1 + 2)));
173	}
174
175	#[test]
176	fn from_content_cjk_mixed_with_ascii() {
177		// "中" (width 2) + "ab" (width 2) on line 1 = width 4; line 2 "abc" = width 3.
178		let node = NodeLayout::from_content("中ab\nabc");
179		assert_eq!(node.size, ((4 + 2), (2 + 2)));
180	}
181
182	#[test]
183	fn from_content_zero_width_chars_dont_add_width() {
184		// Combining mark U+0308 has zero display width; "a" + combining diaeresis
185		// displays as 1 cell. Width should be 1, not 2 (char count).
186		let node = NodeLayout::from_content("a\u{0308}");
187		assert_eq!(node.size, ((1 + 2), (1 + 2)));
188	}
189
190	#[test]
191	fn new_stores_size_directly() {
192		let node = NodeLayout::new((10, 4));
193		assert_eq!(node.size, (10, 4));
194	}
195
196	#[test]
197	fn port_name_defaults_to_none() {
198		// A fresh node has no port names — opt-in feature.
199		let node = NodeLayout::new((6, 4));
200		assert_eq!(node.port_name(PortId(0)), None);
201		assert_eq!(node.port_name(PortId(7)), None);
202	}
203
204	#[test]
205	fn with_port_name_sets_and_reads_back() {
206		let node = NodeLayout::new((6, 4)).with_port_name(PortId(0), "data");
207		assert_eq!(node.port_name(PortId(0)), Some("data"));
208		assert_eq!(node.port_name(PortId(1)), None);
209	}
210
211	#[test]
212	fn with_port_name_overwrites_existing() {
213		// setting the same port twice keeps the latest name.
214		let node = NodeLayout::new((6, 4))
215			.with_port_name(PortId(2), "old")
216			.with_port_name(PortId(2), "new");
217		assert_eq!(node.port_name(PortId(2)), Some("new"));
218	}
219
220	#[test]
221	fn node_layout_clones_with_port_names() {
222		// adding a field must not break Clone (HashMap<&'a str> is Clone).
223		let node = NodeLayout::new((6, 4))
224			.with_port_name(PortId(0), "in")
225			.with_port_name(PortId(1), "out");
226		let cloned = node.clone();
227		assert_eq!(cloned.port_name(PortId(0)), Some("in"));
228		assert_eq!(cloned.port_name(PortId(1)), Some("out"));
229	}
230}