//! Shared-border multi-panel layout widget. //! //! A [`Panel`] is a handle into a small layout tree. Splitting a handle replaces //! that leaf with two child panels, and rendering any handle draws one border //! grid around every visible leaf in that handle's subtree. use std::collections::BTreeMap; use std::sync::{Arc, Mutex, MutexGuard}; use rustik_tui_core::{Buffer, Point, Rect, Style, colors}; /// Handle to one panel in a shared-border layout tree. #[derive(Clone, Debug)] pub struct Panel { /// Shared layout tree. tree: Arc>, /// Root node for area lookups. root: PanelId, /// Node represented by this handle. id: PanelId, } /// Stable node identifier inside a [`PanelTree`]. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] struct PanelId(usize); /// Mutable panel layout tree. #[derive(Clone, Debug)] struct PanelTree { /// All panel nodes. nodes: Vec, } /// One node in a panel tree. #[derive(Clone, Debug)] struct PanelNode { /// Whether this node participates in layout. visible: bool, /// Leaf or split node state. kind: PanelNodeKind, } impl PanelNode { /// Returns a visible leaf node. fn leaf() -> Self { Self { visible: true, kind: PanelNodeKind::Leaf, } } } /// Layout role for a panel node. #[derive(Clone, Debug)] enum PanelNodeKind { /// Content leaf. Leaf, /// Split container. Split { /// Split orientation. direction: PanelSplit, /// First child node. first: PanelId, /// Second child node. second: PanelId, /// Minimum frame size reserved for the first child. first_min: usize, /// Fraction of available frame size preferred for the first child. first_ratio: f32, }, } /// Panel split orientation. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum PanelSplit { /// Horizontal divider producing top and bottom children. Horizontal, /// Vertical divider producing left and right children. Vertical, } /// One visible panel region. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct PanelRegion { /// Leaf panel id. id: PanelId, /// Frame rectangle including borders. frame: Rect, /// Content rectangle inside borders. body: Rect, } /// Directional border connections for one cell. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] struct Connections { /// Connection to the row above. north: bool, /// Connection to the row below. south: bool, /// Connection to the previous column. west: bool, /// Connection to the next column. east: bool, } impl Panel { /// Number of border columns around one leaf panel. pub const BORDER_COLS: usize = 2; /// Number of border rows around one leaf panel. pub const BORDER_ROWS: usize = 2; /// Returns the frame width for `content_cols`, fitted within `available_cols`. /// /// The returned width includes the panel border, and the content is clamped /// to whatever space remains after reserving that border. pub fn frame_cols(content_cols: usize, available_cols: usize) -> usize { content_cols .min(available_cols.saturating_sub(Self::BORDER_COLS)) .saturating_add(Self::BORDER_COLS) } /// Creates a new root panel. pub fn new() -> Self { let tree = PanelTree { nodes: vec![PanelNode::leaf()], }; Self { tree: Arc::new(Mutex::new(tree)), root: PanelId(0), id: PanelId(0), } } /// Splits this panel with a horizontal divider, returning top and bottom panels. pub fn split_h(&self, first_min: usize, first_ratio: f32) -> (Self, Self) { self.split(PanelSplit::Horizontal, first_min, first_ratio) } /// Splits this panel with a vertical divider, returning left and right panels. pub fn split_v(&self, first_min: usize, first_ratio: f32) -> (Self, Self) { self.split(PanelSplit::Vertical, first_min, first_ratio) } /// Shows this panel and its subtree. pub fn show(&self) { self.set_visible(true); } /// Hides this panel and its subtree. pub fn hide(&self) { self.set_visible(false); } /// Sets whether this panel participates in layout. pub fn set_visible(&self, visible: bool) { if let Some(node) = self.lock().nodes.get_mut(self.id.0) { node.visible = visible; } } /// Returns this panel's content rectangle for `area`. pub fn area(&self, area: Rect) -> Option { self.regions_from(self.root, area) .into_iter() .find_map(|region| (region.id == self.id).then_some(region.body)) .filter(|body| !body.is_empty()) } /// Draws the shared border grid for this panel's visible leaves. pub fn render(&self, area: Rect, buf: &mut Buffer) { let regions = self.regions_from(self.id, area); let mut cells = BTreeMap::::new(); for region in regions { add_frame(region.frame, &mut cells); } for (point, connections) in cells { if let Some(glyph) = connections.glyph() { buf.set_glyph( point.x, point.y, glyph.to_string(), Style::new(colors::FAINT), ); } } } /// Splits this panel with `direction`. fn split(&self, direction: PanelSplit, first_min: usize, first_ratio: f32) -> (Self, Self) { let mut tree = self.lock(); let first = tree.push_leaf(); let second = tree.push_leaf(); if let Some(node) = tree.nodes.get_mut(self.id.0) { node.kind = PanelNodeKind::Split { direction, first, second, first_min, first_ratio, }; } drop(tree); (self.handle(first), self.handle(second)) } /// Returns another handle into the same tree. fn handle(&self, id: PanelId) -> Self { Self { tree: Arc::clone(&self.tree), root: self.root, id, } } /// Returns visible leaf regions under `id`. fn regions_from(&self, id: PanelId, area: Rect) -> Vec { let tree = self.lock(); let mut regions = Vec::new(); tree.layout(id, area, &mut regions); regions } /// Locks the shared panel tree. fn lock(&self) -> MutexGuard<'_, PanelTree> { self.tree .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } } impl Default for Panel { fn default() -> Self { Self::new() } } impl PanelTree { /// Appends a new visible leaf node and returns its id. fn push_leaf(&mut self) -> PanelId { let id = PanelId(self.nodes.len()); self.nodes.push(PanelNode::leaf()); id } /// Appends visible leaf regions for `id`. fn layout(&self, id: PanelId, area: Rect, regions: &mut Vec) { if area.is_empty() { return; } let Some(node) = self.nodes.get(id.0) else { return; }; if !node.visible { return; } match node.kind { PanelNodeKind::Leaf => regions.push(PanelRegion { id, frame: area, body: area.inner(1), }), PanelNodeKind::Split { direction, first, second, first_min, first_ratio, } => { let first_visible = self.visible(first); let second_visible = self.visible(second); match (first_visible, second_visible) { (true, true) => { let (first_area, second_area) = split_area(area, direction, first_min, first_ratio); self.layout(first, first_area, regions); self.layout(second, second_area, regions); } (true, false) => self.layout(first, area, regions), (false, true) => self.layout(second, area, regions), (false, false) => {} } } } } /// Returns whether `id` has at least one visible leaf. fn visible(&self, id: PanelId) -> bool { let Some(node) = self.nodes.get(id.0) else { return false; }; if !node.visible { return false; } match node.kind { PanelNodeKind::Leaf => true, PanelNodeKind::Split { first, second, .. } => { self.visible(first) || self.visible(second) } } } } impl Connections { /// Returns the box-drawing glyph represented by these connections. fn glyph(self) -> Option { match (self.north, self.south, self.west, self.east) { (false, true, false, true) => Some('╭'), (false, true, true, false) => Some('╮'), (true, false, false, true) => Some('╰'), (true, false, true, false) => Some('╯'), (true, true, false, false) => Some('│'), (false, false, true, true) => Some('─'), (true, true, false, true) => Some('├'), (true, true, true, false) => Some('┤'), (false, true, true, true) => Some('┬'), (true, false, true, true) => Some('┴'), (true, true, true, true) => Some('┼'), _ => None, } } } /// Splits `area` into two frame rectangles sharing one divider line. fn split_area( area: Rect, direction: PanelSplit, first_min: usize, first_ratio: f32, ) -> (Rect, Rect) { let total = match direction { PanelSplit::Horizontal => area.rows, PanelSplit::Vertical => area.cols, }; if total <= 1 { return (area, Rect::ZERO); } let ratio = first_ratio.clamp(0.0, 1.0); let first = ((total.saturating_sub(1) as f32) * ratio).round() as usize; let first = first.max(first_min).clamp(1, total); match direction { PanelSplit::Horizontal => { let top = Rect::new(area.x, area.y, area.cols, first); let bottom = Rect::new( area.x, area.y.saturating_add(first).saturating_sub(1), area.cols, area.rows.saturating_sub(first).saturating_add(1), ); (top, bottom) } PanelSplit::Vertical => { let left = Rect::new(area.x, area.y, first, area.rows); let right = Rect::new( area.x.saturating_add(first).saturating_sub(1), area.y, area.cols.saturating_sub(first).saturating_add(1), area.rows, ); (left, right) } } } /// Adds every border cell from `frame` into `cells`. /// /// Each edge is laid down by linking neighbouring cells: shared bits combine /// into junctions where frames meet, so corners need no special casing. fn add_frame(frame: Rect, cells: &mut BTreeMap) { if frame.is_empty() { return; } let right = frame.right().saturating_sub(1); let bottom = frame.bottom().saturating_sub(1); link_row(cells, frame.y, frame.x, right); link_row(cells, bottom, frame.x, right); link_col(cells, frame.x, frame.y, bottom); link_col(cells, right, frame.y, bottom); } /// Connects each cell in row `y` from `x0` to `x1` to its eastern neighbour. fn link_row(cells: &mut BTreeMap, y: usize, x0: usize, x1: usize) { for x in x0..x1 { cells.entry(Point::new(x, y)).or_default().east = true; cells.entry(Point::new(x + 1, y)).or_default().west = true; } } /// Connects each cell in column `x` from `y0` to `y1` to its southern neighbour. fn link_col(cells: &mut BTreeMap, x: usize, y0: usize, y1: usize) { for y in y0..y1 { cells.entry(Point::new(x, y)).or_default().south = true; cells.entry(Point::new(x, y + 1)).or_default().north = true; } } #[cfg(test)] mod tests { use super::*; #[test] fn split_v_draws_shared_vertical_divider() { let root = Panel::new(); let (left, right) = root.split_v(4, 0.5); let area = Rect::new(0, 0, 9, 4); let mut buffer = Buffer::empty(area); root.render(area, &mut buffer); assert_eq!(left.area(area), Some(Rect::new(1, 1, 2, 2))); assert_eq!(right.area(area), Some(Rect::new(4, 1, 4, 2))); assert_eq!(buffer.line(0), "╭──┬────╮"); assert_eq!(buffer.line(1), "│ │ │"); assert_eq!(buffer.line(3), "╰──┴────╯"); } #[test] fn split_h_draws_shared_horizontal_divider() { let root = Panel::new(); let (top, bottom) = root.split_h(3, 0.5); let area = Rect::new(0, 0, 8, 7); let mut buffer = Buffer::empty(area); root.render(area, &mut buffer); assert_eq!(top.area(area), Some(Rect::new(1, 1, 6, 1))); assert_eq!(bottom.area(area), Some(Rect::new(1, 3, 6, 3))); assert_eq!(buffer.line(0), "╭──────╮"); assert_eq!(buffer.line(2), "├──────┤"); assert_eq!(buffer.line(6), "╰──────╯"); } #[test] fn hidden_panel_collapses_out_of_layout() { let root = Panel::new(); let (left, right) = root.split_v(4, 0.5); let area = Rect::new(0, 0, 9, 4); let mut buffer = Buffer::empty(area); left.hide(); root.render(area, &mut buffer); assert_eq!(left.area(area), None); assert_eq!(right.area(area), Some(Rect::new(1, 1, 7, 2))); assert_eq!(buffer.line(0), "╭───────╮"); assert_eq!(buffer.line(3), "╰───────╯"); } #[test] fn nested_splits_share_junctions() { let root = Panel::new(); let (left, rest) = root.split_v(5, 0.35); let (_top, _bottom) = left.split_h(4, 0.7); let (_middle, _right) = rest.split_v(8, 0.6); let area = Rect::new(0, 0, 16, 7); let mut buffer = Buffer::empty(area); root.render(area, &mut buffer); assert_eq!(buffer.line(0), "╭───┬──────┬───╮"); assert_eq!(buffer.line(3), "├───┤ │ │"); assert_eq!(buffer.line(6), "╰───┴──────┴───╯"); } #[test] fn grid_split_forms_cross_junction() { // Two columns, each split into two rows at the same line, so the // vertical divider crosses both horizontal dividers in a `┼`. let root = Panel::new(); let (left, right) = root.split_v(2, 0.5); let (left_top, left_bottom) = left.split_h(2, 0.5); let (right_top, right_bottom) = right.split_h(2, 0.5); let area = Rect::new(0, 0, 11, 7); let mut buffer = Buffer::empty(area); root.render(area, &mut buffer); assert_eq!(buffer.line(0), "╭───┬─────╮"); assert_eq!(buffer.line(2), "├───┼─────┤"); assert_eq!(buffer.line(6), "╰───┴─────╯"); assert_eq!(left_top.area(area), Some(Rect::new(1, 1, 3, 1))); assert_eq!(left_bottom.area(area), Some(Rect::new(1, 3, 3, 3))); assert_eq!(right_top.area(area), Some(Rect::new(5, 1, 5, 1))); assert_eq!(right_bottom.area(area), Some(Rect::new(5, 3, 5, 3))); } #[test] fn hiding_a_split_collapses_its_whole_subtree() { // `right` is an interior split node, not a leaf; hiding it must drop // both of its children and let `left` reclaim the full area. let root = Panel::new(); let (left, right) = root.split_v(3, 0.5); let (top, bottom) = right.split_h(2, 0.5); let area = Rect::new(0, 0, 9, 4); let mut buffer = Buffer::empty(area); right.hide(); root.render(area, &mut buffer); assert_eq!(top.area(area), None); assert_eq!(bottom.area(area), None); assert_eq!(left.area(area), Some(Rect::new(1, 1, 7, 2))); assert_eq!(buffer.line(0), "╭───────╮"); assert_eq!(buffer.line(3), "╰───────╯"); } #[test] fn show_restores_a_hidden_panel() { let root = Panel::new(); let (left, right) = root.split_v(4, 0.5); let area = Rect::new(0, 0, 9, 4); let mut buffer = Buffer::empty(area); left.hide(); left.show(); root.render(area, &mut buffer); assert_eq!(left.area(area), Some(Rect::new(1, 1, 2, 2))); assert_eq!(right.area(area), Some(Rect::new(4, 1, 4, 2))); assert_eq!(buffer.line(0), "╭──┬────╮"); assert_eq!(buffer.line(3), "╰──┴────╯"); } #[test] fn both_children_hidden_renders_nothing() { let root = Panel::new(); let (left, right) = root.split_v(2, 0.5); let area = Rect::new(0, 0, 9, 4); let mut buffer = Buffer::empty(area); left.hide(); right.hide(); root.render(area, &mut buffer); assert_eq!(left.area(area), None); assert_eq!(right.area(area), None); // A split node is never itself a leaf region, so it has no body. assert_eq!(root.area(area), None); assert_eq!(buffer.line(0), " "); assert_eq!(buffer.line(3), " "); } #[test] fn single_row_frame_has_no_corners() { // A frame only one row tall cannot form corners, so its endpoints stay // blank and the body is too small to exist. let root = Panel::new(); let (left, right) = root.split_v(1, 0.5); let area = Rect::new(0, 0, 6, 1); let mut buffer = Buffer::empty(area); root.render(area, &mut buffer); assert_eq!(buffer.line(0), " ──── "); assert_eq!(left.area(area), None); assert_eq!(right.area(area), None); } #[test] fn frame_cols_reserves_border_and_clamps_to_available() { // Content plus the two border columns when it fits. assert_eq!(Panel::frame_cols(5, 20), 7); // Clamped so the frame never exceeds the available width. assert_eq!(Panel::frame_cols(50, 20), 20); // Zero content still reserves the border. assert_eq!(Panel::frame_cols(0, 20), 2); // Too little room for content collapses to the bare border. assert_eq!(Panel::frame_cols(5, 2), 2); assert_eq!(Panel::frame_cols(5, 1), 2); } }