use ratatui::buffer::Buffer;
use ratatui::layout::Position;
use ratatui::widgets::Widget;
use super::*;
use crate::id::{NodeId, PortId};
const MARGIN: u16 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AddNodeError {
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: Vec<(NodeId, NodeLayout<'a>)>,
connections: Vec<Connection<'a>>,
placements: Map<NodeId, Rect>,
conn_layout: ConnectionsLayout<'a>,
width: usize,
height: usize,
direction: FlowDirection,
next_id: u32,
dirty: bool,
canvas: Buffer,
diagnostics: Vec<Diagnostic>,
highlight_style: Style,
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);
for (i, node) in nodes.into_iter().enumerate() {
let _ = graph.add_node_with_id(NodeId(i as u32), node);
}
for conn in connections {
graph.add_connection(conn);
}
graph
}
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,
}
}
#[must_use]
pub fn with_direction(mut self, direction: FlowDirection) -> Self {
self.direction = direction;
self.dirty = true;
self
}
pub fn direction(&self) -> FlowDirection {
self.direction
}
#[must_use]
pub fn highlight_style(self, style: Style) -> Self {
let mut this = self;
this.highlight_style = style;
this
}
#[must_use]
pub fn show_arrows(mut self, on: bool) -> Self {
self.show_arrows = on;
self
}
pub fn add_node(&mut self, node: NodeLayout<'a>) -> NodeId {
let id = NodeId(self.next_id);
self.next_id += 1;
let _ = self.add_node_with_id(id, node);
id
}
pub fn add_node_with_id(
&mut self,
id: NodeId,
node: NodeLayout<'a>,
) -> Result<(), AddNodeError> {
if self.has_node(id) {
return Err(AddNodeError::ConflictingId);
}
if id.0 >= self.next_id {
self.next_id = id.0 + 1;
}
self.nodes.push((id, node));
self.dirty = true;
Ok(())
}
pub fn add_connection(&mut self, conn: Connection<'a>) {
self.connections.push(conn);
self.dirty = true;
}
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 {
self.connections.retain(|c| c.from_node != id && c.to_node != id);
self.dirty = true;
}
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
}
pub fn has_node(&self, id: NodeId) -> bool {
self.nodes.iter().any(|(nid, _)| *nid == id)
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
pub fn positions(&self) -> &Map<NodeId, Rect> {
&self.placements
}
pub fn node_rect(&self, id: NodeId) -> Option<Rect> {
self.placements.get(&id).copied()
}
fn node_layout(&self, id: NodeId) -> Option<&NodeLayout<'a>> {
self.nodes.iter().find_map(|(nid, n)| (*nid == id).then_some(n))
}
pub(crate) fn canvas(&self) -> &Buffer {
&self.canvas
}
pub fn calculate(&mut self) {
self.placements.clear();
self.diagnostics.clear();
self.dirty = false;
let known_ids: Set<NodeId> = self.nodes.iter().map(|(id, _)| *id).collect();
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);
let mut roots: Set<_> = self.nodes.iter().map(|(id, _)| *id).collect();
for ea_connection in valid_conns.iter() {
roots.remove(&ea_connection.from_node);
}
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());
}
let mut conn_map = Map::<(NodeId, PortId), usize>::new();
let mut next_idx = 1;
for ea_conn in valid_conns.iter() {
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;
};
let dir = self.direction;
let (a_point, b_point) = if dir.is_horizontal() {
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;
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 {
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);
self.diagnostics.append(&mut self.conn_layout.diagnostics);
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 });
}
}
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;
}
pub fn diagnostics(&self) -> &[Diagnostic] {
&self.diagnostics
}
fn place_node(
&mut self,
idx_node: NodeId,
x: u16,
y: u16,
main_chain: &mut Vec<NodeId>,
visited: &mut Set<NodeId>,
conns: &[Connection<'a>],
) {
if self.placements.contains_key(&idx_node) || !visited.insert(idx_node) {
return;
}
let Some(node_layout) = self.node_layout(idx_node) else {
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();
'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);
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) {
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 {
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();
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();
}
fn nudge(
&mut self,
idx_node: NodeId,
main: u16,
in_progress: &mut Set<NodeId>,
conns: &[Connection<'a>],
) {
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) {
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()
}
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()
}
pub fn hit_test(&self, area: Rect, x: u16, y: u16) -> Option<NodeId> {
for (id, canvas_rect) in self.placements.iter() {
if canvas_rect.width == 0 || canvas_rect.height == 0 {
continue;
}
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
}
#[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| {
if z.right() <= ox || z.bottom() <= oy {
return 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);
z.intersection(area)
})
.collect()
}
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)| {
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()
}
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;
let mut pos = canvas_rect;
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);
let clipped = pos.intersection(area);
if clipped.width == 0 || clipped.height == 0 {
return None;
}
Some(clipped)
}
fn highlight_border(&self, buf: &mut Buffer, screen_rect: Rect, style: Style) {
let r = screen_rect;
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);
}
}
}
}
fn merge_style(cell: &mut ratatui::buffer::Cell, style: Style) {
let merged = cell.style().patch(style);
cell.set_style(merged);
}
#[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 {
pub offset: (u16, u16),
}
#[allow(deprecated)]
impl Viewport {
pub fn new() -> Self {
Self::default()
}
#[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)
}
}
#[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> {
pub fn new(graph: &'a NodeGraph<'a>) -> Self {
Self { graph, viewport: Viewport::default() }
}
#[must_use]
pub fn viewport(mut self, viewport: Viewport) -> Self {
self.viewport = viewport;
self
}
#[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));
}
}
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,
};
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>> {
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>> {
let mut downstream: Vec<_> =
conns.iter().filter(|ea| ea.from_node == idx_node).copied().collect();
downstream.sort_by_key(|a| a.from_port);
downstream
}
fn clamp_port(port: usize, node_height: u16) -> usize {
let max = (node_height as usize).saturating_sub(2);
port.min(max)
}
enum PortNameDir {
Right,
Left,
}
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);
}
}
}
}
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> {
pub(crate) fn render_to(&self, area: Rect, buf: &mut Buffer) {
self.conn_layout.render(area, buf);
let vertical = !self.direction.is_horizontal();
let mirror = self.direction.mirror_main_axis();
'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;
}
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 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;
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 {
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),
);
}
}
}
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);
}
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 {
if let Some(cell) = buf.cell_mut(Position::new(
pos.left() + to_port + 1,
pos.bottom() - 1,
)) {
cell.set_symbol(in_symbol);
}
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,
);
}
}
}
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;
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 {
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),
);
}
}
}
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,
));
}
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 {
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,
));
}
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) {
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;
}
if state.view_offset == (0, 0) {
self.render_to(area, buf);
} else {
blit_canvas(&self.canvas, area, buf, state.view_offset);
}
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);
}
}
}