crates/tui-widgets/src/panel.rs 18.6 KiB raw
1
//! Shared-border multi-panel layout widget.
2
//!
3
//! A [`Panel`] is a handle into a small layout tree. Splitting a handle replaces
4
//! that leaf with two child panels, and rendering any handle draws one border
5
//! grid around every visible leaf in that handle's subtree.
6
7
use std::collections::BTreeMap;
8
use std::sync::{Arc, Mutex, MutexGuard};
9
10
use rustik_tui_core::{Buffer, Point, Rect, Style, colors};
11
12
/// Handle to one panel in a shared-border layout tree.
13
#[derive(Clone, Debug)]
14
pub struct Panel {
15
    /// Shared layout tree.
16
    tree: Arc<Mutex<PanelTree>>,
17
    /// Root node for area lookups.
18
    root: PanelId,
19
    /// Node represented by this handle.
20
    id: PanelId,
21
}
22
23
/// Stable node identifier inside a [`PanelTree`].
24
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
25
struct PanelId(usize);
26
27
/// Mutable panel layout tree.
28
#[derive(Clone, Debug)]
29
struct PanelTree {
30
    /// All panel nodes.
31
    nodes: Vec<PanelNode>,
32
}
33
34
/// One node in a panel tree.
35
#[derive(Clone, Debug)]
36
struct PanelNode {
37
    /// Whether this node participates in layout.
38
    visible: bool,
39
    /// Leaf or split node state.
40
    kind: PanelNodeKind,
41
}
42
43
impl PanelNode {
44
    /// Returns a visible leaf node.
45
    fn leaf() -> Self {
46
        Self {
47
            visible: true,
48
            kind: PanelNodeKind::Leaf,
49
        }
50
    }
51
}
52
53
/// Layout role for a panel node.
54
#[derive(Clone, Debug)]
55
enum PanelNodeKind {
56
    /// Content leaf.
57
    Leaf,
58
    /// Split container.
59
    Split {
60
        /// Split orientation.
61
        direction: PanelSplit,
62
        /// First child node.
63
        first: PanelId,
64
        /// Second child node.
65
        second: PanelId,
66
        /// Minimum frame size reserved for the first child.
67
        first_min: usize,
68
        /// Fraction of available frame size preferred for the first child.
69
        first_ratio: f32,
70
    },
71
}
72
73
/// Panel split orientation.
74
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
75
enum PanelSplit {
76
    /// Horizontal divider producing top and bottom children.
77
    Horizontal,
78
    /// Vertical divider producing left and right children.
79
    Vertical,
80
}
81
82
/// One visible panel region.
83
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
84
struct PanelRegion {
85
    /// Leaf panel id.
86
    id: PanelId,
87
    /// Frame rectangle including borders.
88
    frame: Rect,
89
    /// Content rectangle inside borders.
90
    body: Rect,
91
}
92
93
/// Directional border connections for one cell.
94
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
95
struct Connections {
96
    /// Connection to the row above.
97
    north: bool,
98
    /// Connection to the row below.
99
    south: bool,
100
    /// Connection to the previous column.
101
    west: bool,
102
    /// Connection to the next column.
103
    east: bool,
104
}
105
106
impl Panel {
107
    /// Number of border columns around one leaf panel.
108
    pub const BORDER_COLS: usize = 2;
109
    /// Number of border rows around one leaf panel.
110
    pub const BORDER_ROWS: usize = 2;
111
112
    /// Returns the frame width for `content_cols`, fitted within `available_cols`.
113
    ///
114
    /// The returned width includes the panel border, and the content is clamped
115
    /// to whatever space remains after reserving that border.
116
    pub fn frame_cols(content_cols: usize, available_cols: usize) -> usize {
117
        content_cols
118
            .min(available_cols.saturating_sub(Self::BORDER_COLS))
119
            .saturating_add(Self::BORDER_COLS)
120
    }
121
122
    /// Creates a new root panel.
123
    pub fn new() -> Self {
124
        let tree = PanelTree {
125
            nodes: vec![PanelNode::leaf()],
126
        };
127
128
        Self {
129
            tree: Arc::new(Mutex::new(tree)),
130
            root: PanelId(0),
131
            id: PanelId(0),
132
        }
133
    }
134
135
    /// Splits this panel with a horizontal divider, returning top and bottom panels.
136
    pub fn split_h(&self, first_min: usize, first_ratio: f32) -> (Self, Self) {
137
        self.split(PanelSplit::Horizontal, first_min, first_ratio)
138
    }
139
140
    /// Splits this panel with a vertical divider, returning left and right panels.
141
    pub fn split_v(&self, first_min: usize, first_ratio: f32) -> (Self, Self) {
142
        self.split(PanelSplit::Vertical, first_min, first_ratio)
143
    }
144
145
    /// Shows this panel and its subtree.
146
    pub fn show(&self) {
147
        self.set_visible(true);
148
    }
149
150
    /// Hides this panel and its subtree.
151
    pub fn hide(&self) {
152
        self.set_visible(false);
153
    }
154
155
    /// Sets whether this panel participates in layout.
156
    pub fn set_visible(&self, visible: bool) {
157
        if let Some(node) = self.lock().nodes.get_mut(self.id.0) {
158
            node.visible = visible;
159
        }
160
    }
161
162
    /// Returns this panel's content rectangle for `area`.
163
    pub fn area(&self, area: Rect) -> Option<Rect> {
164
        self.regions_from(self.root, area)
165
            .into_iter()
166
            .find_map(|region| (region.id == self.id).then_some(region.body))
167
            .filter(|body| !body.is_empty())
168
    }
169
170
    /// Draws the shared border grid for this panel's visible leaves.
171
    pub fn render(&self, area: Rect, buf: &mut Buffer) {
172
        let regions = self.regions_from(self.id, area);
173
        let mut cells = BTreeMap::<Point, Connections>::new();
174
175
        for region in regions {
176
            add_frame(region.frame, &mut cells);
177
        }
178
        for (point, connections) in cells {
179
            if let Some(glyph) = connections.glyph() {
180
                buf.set_glyph(
181
                    point.x,
182
                    point.y,
183
                    glyph.to_string(),
184
                    Style::new(colors::FAINT),
185
                );
186
            }
187
        }
188
    }
189
190
    /// Splits this panel with `direction`.
191
    fn split(&self, direction: PanelSplit, first_min: usize, first_ratio: f32) -> (Self, Self) {
192
        let mut tree = self.lock();
193
        let first = tree.push_leaf();
194
        let second = tree.push_leaf();
195
        if let Some(node) = tree.nodes.get_mut(self.id.0) {
196
            node.kind = PanelNodeKind::Split {
197
                direction,
198
                first,
199
                second,
200
                first_min,
201
                first_ratio,
202
            };
203
        }
204
        drop(tree);
205
206
        (self.handle(first), self.handle(second))
207
    }
208
209
    /// Returns another handle into the same tree.
210
    fn handle(&self, id: PanelId) -> Self {
211
        Self {
212
            tree: Arc::clone(&self.tree),
213
            root: self.root,
214
            id,
215
        }
216
    }
217
218
    /// Returns visible leaf regions under `id`.
219
    fn regions_from(&self, id: PanelId, area: Rect) -> Vec<PanelRegion> {
220
        let tree = self.lock();
221
        let mut regions = Vec::new();
222
223
        tree.layout(id, area, &mut regions);
224
        regions
225
    }
226
227
    /// Locks the shared panel tree.
228
    fn lock(&self) -> MutexGuard<'_, PanelTree> {
229
        self.tree
230
            .lock()
231
            .unwrap_or_else(|poisoned| poisoned.into_inner())
232
    }
233
}
234
235
impl Default for Panel {
236
    fn default() -> Self {
237
        Self::new()
238
    }
239
}
240
241
impl PanelTree {
242
    /// Appends a new visible leaf node and returns its id.
243
    fn push_leaf(&mut self) -> PanelId {
244
        let id = PanelId(self.nodes.len());
245
        self.nodes.push(PanelNode::leaf());
246
        id
247
    }
248
249
    /// Appends visible leaf regions for `id`.
250
    fn layout(&self, id: PanelId, area: Rect, regions: &mut Vec<PanelRegion>) {
251
        if area.is_empty() {
252
            return;
253
        }
254
        let Some(node) = self.nodes.get(id.0) else {
255
            return;
256
        };
257
        if !node.visible {
258
            return;
259
        }
260
        match node.kind {
261
            PanelNodeKind::Leaf => regions.push(PanelRegion {
262
                id,
263
                frame: area,
264
                body: area.inner(1),
265
            }),
266
            PanelNodeKind::Split {
267
                direction,
268
                first,
269
                second,
270
                first_min,
271
                first_ratio,
272
            } => {
273
                let first_visible = self.visible(first);
274
                let second_visible = self.visible(second);
275
276
                match (first_visible, second_visible) {
277
                    (true, true) => {
278
                        let (first_area, second_area) =
279
                            split_area(area, direction, first_min, first_ratio);
280
                        self.layout(first, first_area, regions);
281
                        self.layout(second, second_area, regions);
282
                    }
283
                    (true, false) => self.layout(first, area, regions),
284
                    (false, true) => self.layout(second, area, regions),
285
                    (false, false) => {}
286
                }
287
            }
288
        }
289
    }
290
291
    /// Returns whether `id` has at least one visible leaf.
292
    fn visible(&self, id: PanelId) -> bool {
293
        let Some(node) = self.nodes.get(id.0) else {
294
            return false;
295
        };
296
        if !node.visible {
297
            return false;
298
        }
299
        match node.kind {
300
            PanelNodeKind::Leaf => true,
301
            PanelNodeKind::Split { first, second, .. } => {
302
                self.visible(first) || self.visible(second)
303
            }
304
        }
305
    }
306
}
307
308
impl Connections {
309
    /// Returns the box-drawing glyph represented by these connections.
310
    fn glyph(self) -> Option<char> {
311
        match (self.north, self.south, self.west, self.east) {
312
            (false, true, false, true) => Some('╭'),
313
            (false, true, true, false) => Some('╮'),
314
            (true, false, false, true) => Some('╰'),
315
            (true, false, true, false) => Some('╯'),
316
            (true, true, false, false) => Some('│'),
317
            (false, false, true, true) => Some('─'),
318
            (true, true, false, true) => Some('├'),
319
            (true, true, true, false) => Some('┤'),
320
            (false, true, true, true) => Some('┬'),
321
            (true, false, true, true) => Some('┴'),
322
            (true, true, true, true) => Some('┼'),
323
            _ => None,
324
        }
325
    }
326
}
327
328
/// Splits `area` into two frame rectangles sharing one divider line.
329
fn split_area(
330
    area: Rect,
331
    direction: PanelSplit,
332
    first_min: usize,
333
    first_ratio: f32,
334
) -> (Rect, Rect) {
335
    let total = match direction {
336
        PanelSplit::Horizontal => area.rows,
337
        PanelSplit::Vertical => area.cols,
338
    };
339
    if total <= 1 {
340
        return (area, Rect::ZERO);
341
    }
342
343
    let ratio = first_ratio.clamp(0.0, 1.0);
344
    let first = ((total.saturating_sub(1) as f32) * ratio).round() as usize;
345
    let first = first.max(first_min).clamp(1, total);
346
347
    match direction {
348
        PanelSplit::Horizontal => {
349
            let top = Rect::new(area.x, area.y, area.cols, first);
350
            let bottom = Rect::new(
351
                area.x,
352
                area.y.saturating_add(first).saturating_sub(1),
353
                area.cols,
354
                area.rows.saturating_sub(first).saturating_add(1),
355
            );
356
            (top, bottom)
357
        }
358
        PanelSplit::Vertical => {
359
            let left = Rect::new(area.x, area.y, first, area.rows);
360
            let right = Rect::new(
361
                area.x.saturating_add(first).saturating_sub(1),
362
                area.y,
363
                area.cols.saturating_sub(first).saturating_add(1),
364
                area.rows,
365
            );
366
            (left, right)
367
        }
368
    }
369
}
370
371
/// Adds every border cell from `frame` into `cells`.
372
///
373
/// Each edge is laid down by linking neighbouring cells: shared bits combine
374
/// into junctions where frames meet, so corners need no special casing.
375
fn add_frame(frame: Rect, cells: &mut BTreeMap<Point, Connections>) {
376
    if frame.is_empty() {
377
        return;
378
    }
379
    let right = frame.right().saturating_sub(1);
380
    let bottom = frame.bottom().saturating_sub(1);
381
382
    link_row(cells, frame.y, frame.x, right);
383
    link_row(cells, bottom, frame.x, right);
384
    link_col(cells, frame.x, frame.y, bottom);
385
    link_col(cells, right, frame.y, bottom);
386
}
387
388
/// Connects each cell in row `y` from `x0` to `x1` to its eastern neighbour.
389
fn link_row(cells: &mut BTreeMap<Point, Connections>, y: usize, x0: usize, x1: usize) {
390
    for x in x0..x1 {
391
        cells.entry(Point::new(x, y)).or_default().east = true;
392
        cells.entry(Point::new(x + 1, y)).or_default().west = true;
393
    }
394
}
395
396
/// Connects each cell in column `x` from `y0` to `y1` to its southern neighbour.
397
fn link_col(cells: &mut BTreeMap<Point, Connections>, x: usize, y0: usize, y1: usize) {
398
    for y in y0..y1 {
399
        cells.entry(Point::new(x, y)).or_default().south = true;
400
        cells.entry(Point::new(x, y + 1)).or_default().north = true;
401
    }
402
}
403
404
#[cfg(test)]
405
mod tests {
406
    use super::*;
407
408
    #[test]
409
    fn split_v_draws_shared_vertical_divider() {
410
        let root = Panel::new();
411
        let (left, right) = root.split_v(4, 0.5);
412
        let area = Rect::new(0, 0, 9, 4);
413
        let mut buffer = Buffer::empty(area);
414
415
        root.render(area, &mut buffer);
416
417
        assert_eq!(left.area(area), Some(Rect::new(1, 1, 2, 2)));
418
        assert_eq!(right.area(area), Some(Rect::new(4, 1, 4, 2)));
419
        assert_eq!(buffer.line(0), "╭──┬────╮");
420
        assert_eq!(buffer.line(1), "│  │    │");
421
        assert_eq!(buffer.line(3), "╰──┴────╯");
422
    }
423
424
    #[test]
425
    fn split_h_draws_shared_horizontal_divider() {
426
        let root = Panel::new();
427
        let (top, bottom) = root.split_h(3, 0.5);
428
        let area = Rect::new(0, 0, 8, 7);
429
        let mut buffer = Buffer::empty(area);
430
431
        root.render(area, &mut buffer);
432
433
        assert_eq!(top.area(area), Some(Rect::new(1, 1, 6, 1)));
434
        assert_eq!(bottom.area(area), Some(Rect::new(1, 3, 6, 3)));
435
        assert_eq!(buffer.line(0), "╭──────╮");
436
        assert_eq!(buffer.line(2), "├──────┤");
437
        assert_eq!(buffer.line(6), "╰──────╯");
438
    }
439
440
    #[test]
441
    fn hidden_panel_collapses_out_of_layout() {
442
        let root = Panel::new();
443
        let (left, right) = root.split_v(4, 0.5);
444
        let area = Rect::new(0, 0, 9, 4);
445
        let mut buffer = Buffer::empty(area);
446
447
        left.hide();
448
        root.render(area, &mut buffer);
449
450
        assert_eq!(left.area(area), None);
451
        assert_eq!(right.area(area), Some(Rect::new(1, 1, 7, 2)));
452
        assert_eq!(buffer.line(0), "╭───────╮");
453
        assert_eq!(buffer.line(3), "╰───────╯");
454
    }
455
456
    #[test]
457
    fn nested_splits_share_junctions() {
458
        let root = Panel::new();
459
        let (left, rest) = root.split_v(5, 0.35);
460
        let (_top, _bottom) = left.split_h(4, 0.7);
461
        let (_middle, _right) = rest.split_v(8, 0.6);
462
        let area = Rect::new(0, 0, 16, 7);
463
        let mut buffer = Buffer::empty(area);
464
465
        root.render(area, &mut buffer);
466
467
        assert_eq!(buffer.line(0), "╭───┬──────┬───╮");
468
        assert_eq!(buffer.line(3), "├───┤      │   │");
469
        assert_eq!(buffer.line(6), "╰───┴──────┴───╯");
470
    }
471
472
    #[test]
473
    fn grid_split_forms_cross_junction() {
474
        // Two columns, each split into two rows at the same line, so the
475
        // vertical divider crosses both horizontal dividers in a `┼`.
476
        let root = Panel::new();
477
        let (left, right) = root.split_v(2, 0.5);
478
        let (left_top, left_bottom) = left.split_h(2, 0.5);
479
        let (right_top, right_bottom) = right.split_h(2, 0.5);
480
        let area = Rect::new(0, 0, 11, 7);
481
        let mut buffer = Buffer::empty(area);
482
483
        root.render(area, &mut buffer);
484
485
        assert_eq!(buffer.line(0), "╭───┬─────╮");
486
        assert_eq!(buffer.line(2), "├───┼─────┤");
487
        assert_eq!(buffer.line(6), "╰───┴─────╯");
488
        assert_eq!(left_top.area(area), Some(Rect::new(1, 1, 3, 1)));
489
        assert_eq!(left_bottom.area(area), Some(Rect::new(1, 3, 3, 3)));
490
        assert_eq!(right_top.area(area), Some(Rect::new(5, 1, 5, 1)));
491
        assert_eq!(right_bottom.area(area), Some(Rect::new(5, 3, 5, 3)));
492
    }
493
494
    #[test]
495
    fn hiding_a_split_collapses_its_whole_subtree() {
496
        // `right` is an interior split node, not a leaf; hiding it must drop
497
        // both of its children and let `left` reclaim the full area.
498
        let root = Panel::new();
499
        let (left, right) = root.split_v(3, 0.5);
500
        let (top, bottom) = right.split_h(2, 0.5);
501
        let area = Rect::new(0, 0, 9, 4);
502
        let mut buffer = Buffer::empty(area);
503
504
        right.hide();
505
        root.render(area, &mut buffer);
506
507
        assert_eq!(top.area(area), None);
508
        assert_eq!(bottom.area(area), None);
509
        assert_eq!(left.area(area), Some(Rect::new(1, 1, 7, 2)));
510
        assert_eq!(buffer.line(0), "╭───────╮");
511
        assert_eq!(buffer.line(3), "╰───────╯");
512
    }
513
514
    #[test]
515
    fn show_restores_a_hidden_panel() {
516
        let root = Panel::new();
517
        let (left, right) = root.split_v(4, 0.5);
518
        let area = Rect::new(0, 0, 9, 4);
519
        let mut buffer = Buffer::empty(area);
520
521
        left.hide();
522
        left.show();
523
        root.render(area, &mut buffer);
524
525
        assert_eq!(left.area(area), Some(Rect::new(1, 1, 2, 2)));
526
        assert_eq!(right.area(area), Some(Rect::new(4, 1, 4, 2)));
527
        assert_eq!(buffer.line(0), "╭──┬────╮");
528
        assert_eq!(buffer.line(3), "╰──┴────╯");
529
    }
530
531
    #[test]
532
    fn both_children_hidden_renders_nothing() {
533
        let root = Panel::new();
534
        let (left, right) = root.split_v(2, 0.5);
535
        let area = Rect::new(0, 0, 9, 4);
536
        let mut buffer = Buffer::empty(area);
537
538
        left.hide();
539
        right.hide();
540
        root.render(area, &mut buffer);
541
542
        assert_eq!(left.area(area), None);
543
        assert_eq!(right.area(area), None);
544
        // A split node is never itself a leaf region, so it has no body.
545
        assert_eq!(root.area(area), None);
546
        assert_eq!(buffer.line(0), "         ");
547
        assert_eq!(buffer.line(3), "         ");
548
    }
549
550
    #[test]
551
    fn single_row_frame_has_no_corners() {
552
        // A frame only one row tall cannot form corners, so its endpoints stay
553
        // blank and the body is too small to exist.
554
        let root = Panel::new();
555
        let (left, right) = root.split_v(1, 0.5);
556
        let area = Rect::new(0, 0, 6, 1);
557
        let mut buffer = Buffer::empty(area);
558
559
        root.render(area, &mut buffer);
560
561
        assert_eq!(buffer.line(0), " ──── ");
562
        assert_eq!(left.area(area), None);
563
        assert_eq!(right.area(area), None);
564
    }
565
566
    #[test]
567
    fn frame_cols_reserves_border_and_clamps_to_available() {
568
        // Content plus the two border columns when it fits.
569
        assert_eq!(Panel::frame_cols(5, 20), 7);
570
        // Clamped so the frame never exceeds the available width.
571
        assert_eq!(Panel::frame_cols(50, 20), 20);
572
        // Zero content still reserves the border.
573
        assert_eq!(Panel::frame_cols(0, 20), 2);
574
        // Too little room for content collapses to the bare border.
575
        assert_eq!(Panel::frame_cols(5, 2), 2);
576
        assert_eq!(Panel::frame_cols(5, 1), 2);
577
    }
578
}