Lines
99.65 %
Functions
50.46 %
Branches
100 %
//! The cell model of a grid field (splits, rows) and its layout.
//!
//! A grid is lines of items; the columns of the cell lines with one indent align, so a line
//! with fewer items leaves the later columns blank.
use std::cell::Cell;
use std::collections::BTreeMap;
use ratatui::layout::{Position, Rect};
use ratatui::text::Span;
use tvui::{ARROW_CELLS, InputLine, Viewport};
use super::SelectWidget;
mod tail;
mod width;
use width::Width;
use width::{Column, frozen_edge, gap, resolve};
/// How far a field's lines sit in from its label.
pub const GRID_INDENT: u16 = 4;
/// A text cell reserves this much, so typing a usual amount does not reflow the grid.
const TEXT_RESERVE: u16 = 10 + ARROW_CELLS;
const MIN_SELECT: u16 = 6 + ARROW_CELLS;
/// The cells the `▼` mark of a select cell takes at the end of its field.
const MARK_CELLS: u16 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ItemKind {
Label,
Text,
Select,
}
/// The cell of its widget an item edits: a cell of a rows or splits widget, or of the tag list
/// a splits widget has open under its split.
pub struct CellId {
pub tag: bool,
pub row: usize,
pub col: usize,
/// One drawn thing of a cell line: a fixed label, a text cell or a select cell.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Item<'a> {
pub kind: ItemKind,
pub text: String,
pub cursor: usize,
pub focused: bool,
/// Whether the terminal cursor shows at `cursor` while the item is focused.
pub caret: bool,
/// The cell a click on the item focuses; labels have none.
pub cell: Option<CellId>,
/// Where the draw of the text keeps its scroll between frames; a label has none.
pub scroll: Option<&'a Cell<Viewport>>,
min: u16,
rule: Width,
frozen: bool,
tail: bool,
fn width_of(text: &str) -> u16 {
u16::try_from(Span::raw(text).width()).unwrap_or(u16::MAX)
impl<'a> Item<'a> {
#[must_use]
pub fn label(text: impl Into<String>) -> Self {
Item {
kind: ItemKind::Label,
text: text.into(),
cursor: 0,
focused: false,
caret: false,
cell: None,
scroll: None,
min: 0,
rule: Width::Fit,
frozen: false,
tail: false,
/// A text cell with its cursor as a character index.
pub fn text(text: impl Into<String>, cursor: usize, focused: bool) -> Self {
kind: ItemKind::Text,
cursor,
focused,
caret: true,
/// The item scrolled through `scroll`, the handle of the editor its text is edited in.
pub fn scrolled(mut self, scroll: &'a Cell<Viewport>) -> Self {
self.scroll = Some(scroll);
self
/// A select cell: the typed filter while there is one, else the selected label (`?` when
/// none). The width holds the widest option, so filtering does not reflow the grid.
pub fn select(select: &'a SelectWidget, focused: bool) -> Self {
let text = match select.shown() {
"" => "?",
shown => shown,
};
let widest = select
.options()
.iter()
.map(|option| width_of(&option.label));
let widest = widest.max().unwrap_or(0).max(width_of(select.query()));
kind: ItemKind::Select,
text: text.to_string(),
cursor: select.query().chars().count(),
caret: select.open,
scroll: Some(select.scroll()),
min: widest.saturating_add(ARROW_CELLS).max(MIN_SELECT),
/// The item as the cell at `row` and `col` of its widget.
pub fn at(mut self, row: usize, col: usize) -> Self {
self.cell = Some(CellId {
tag: false,
row,
col,
});
/// The item in `width` cells whatever it shows, the mark of a select included; a text
/// cell scrolls inside.
pub fn fixed(mut self, width: u16) -> Self {
self.rule = Width::Fixed(width);
/// The item stays in place when its line scrolls to show a focused cell; the leading
/// run of such items is the line's frozen columns.
pub fn frozen(mut self) -> Self {
self.frozen = true;
/// The item in a share of the leftover width, within `min..=max` cells.
pub fn flex(mut self, min: u16, max: u16) -> Self {
self.rule = Width::Flex { min, max };
/// A select without a rule sizes to its widest option; text has a column for its cursor.
fn fit_width(&self) -> u16 {
match self.kind {
ItemKind::Label => width_of(&self.text),
ItemKind::Text => width_of(&self.text)
.saturating_add(ARROW_CELLS)
.max(TEXT_RESERVE),
ItemKind::Select => self.min.saturating_add(MARK_CELLS),
/// The width the item takes when there is room.
pub fn width(&self) -> u16 {
match self.rule {
Width::Fit => self.fit_width(),
Width::Fixed(width) => width,
Width::Flex { max, .. } => max,
fn floor(&self) -> u16 {
Width::Flex { min, .. } => min,
_ => self.width(),
/// The part of the item's `rect` its text is drawn in: a select ends in its `▼` mark.
pub fn area(&self, rect: Rect) -> Rect {
let mark = if self.kind == ItemKind::Select {
MARK_CELLS
} else {
0
Rect {
width: rect.width.saturating_sub(mark),
..rect
pub enum GridLine<'a> {
Text {
indent: u16,
text: String,
focused: bool,
},
Cells {
items: Vec<Item<'a>>,
impl GridLine<'_> {
fn indent(&self) -> u16 {
match self {
GridLine::Text { indent, .. } | GridLine::Cells { indent, .. } => *indent,
fn indented(mut self, by: u16) -> Self {
match &mut self {
GridLine::Text { indent, .. } | GridLine::Cells { indent, .. } => {
*indent = indent.saturating_add(by);
fn frozen_count(&self) -> usize {
GridLine::Text { .. } => 0,
GridLine::Cells { items, .. } => items.iter().take_while(|item| item.frozen).count(),
fn len(&self) -> usize {
GridLine::Text { .. } => 1,
GridLine::Cells { items, .. } => items.len(),
/// The `(left, width)` of each item in the line, from the grid's left edge.
fn spans(&self, widths: &[u16]) -> Vec<(u16, u16)> {
GridLine::Text { indent, .. } => vec![(*indent, u16::MAX)],
GridLine::Cells { indent, items } => {
let mut x = *indent;
let columns = items.iter().zip(widths);
columns
.map(|(_, &width)| {
let span = (x, width);
x = x.saturating_add(width).saturating_add(gap(width));
span
})
.collect()
/// The item rects in `strip`, cut to it on the right. The columns after the first `frozen`
/// shift left by `shift`; with frozen columns one cut on the left is clipped at the frozen
/// edge, without them it has an empty rect.
fn rects(&self, strip: Rect, widths: &[u16], shift: u16) -> Vec<Rect> {
let frozen = self.frozen_count();
let spans = self.spans(widths);
let edge = frozen_edge(&spans, frozen);
let cut = |(at, (left, width)): (usize, (u16, u16))| {
let scrolled = at >= frozen;
let by = if scrolled { shift } else { 0 };
if frozen == 0 && left < by {
return Rect::new(strip.x, strip.y, 0, 1);
let start = if scrolled { edge } else { 0 };
let from = left.saturating_sub(by).max(start).min(strip.width);
let to = left
.saturating_add(width)
.saturating_sub(by)
.min(strip.width);
let wide = to.saturating_sub(from);
Rect::new(strip.x.saturating_add(from), strip.y, wide, 1)
spans.into_iter().enumerate().map(cut).collect()
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Grid<'a> {
pub lines: Vec<GridLine<'a>>,
/// The line to keep in view.
pub focus_line: usize,
impl<'a> Grid<'a> {
pub fn push_cells(&mut self, indent: u16, items: Vec<Item<'a>>) {
self.lines.push(GridLine::Cells { indent, items });
pub fn push_note(&mut self, indent: u16, text: impl Into<String>) {
self.lines.push(GridLine::Text {
indent,
/// Add the lines of `other`, `indent` further in; the view follows them when `focused`.
pub fn append(&mut self, other: Grid<'a>, indent: u16, focused: bool) {
if focused {
self.focus_line = self.lines.len() + other.focus_line;
self.lines
.extend(other.lines.into_iter().map(|line| line.indented(indent)));
/// The grid under a `title` line, its lines in by [`GRID_INDENT`].
pub fn titled(self, title: impl Into<String>, focused: bool) -> Self {
let mut titled = Grid::default();
titled.lines.push(GridLine::Text {
indent: 0,
text: title.into(),
titled.append(self, GRID_INDENT, true);
titled
/// The grid with every cell id taken as a cell of the open tag list.
pub fn of_tags(mut self) -> Self {
for line in &mut self.lines {
if let GridLine::Cells { items, .. } = line {
for cell in items.iter_mut().filter_map(|item| item.cell.as_mut()) {
cell.tag = true;
/// The width of each column of the cell lines of each indent: the flexible ones share what
/// `avail` columns leave over, with no `avail` every column has the width it wants.
fn column_widths(&self, avail: Option<u16>) -> BTreeMap<u16, Vec<u16>> {
let mut columns: BTreeMap<u16, Vec<Column>> = BTreeMap::new();
for line in &self.lines {
let GridLine::Cells { indent, items } = line else {
continue;
let group = columns.entry(*indent).or_default();
if group.len() < items.len() {
group.resize(items.len(), Column::default());
for (column, item) in group.iter_mut().zip(items) {
column.absorb(item);
let resolved = |(indent, group): (u16, Vec<Column>)| {
(
resolve(&group, avail.map(|a| a.saturating_sub(indent))),
)
columns.into_iter().map(resolved).collect()
/// The columns the grid needs: the far edge of its widest line.
pub fn width(&self) -> usize {
let widths = self.column_widths(None);
let ends = self.lines.iter().map(|line| match line {
GridLine::Text { indent, text, .. } => usize::from(*indent) + Span::raw(text).width(),
GridLine::Cells { indent, .. } => {
let spans = line.spans(widths.get(indent).map_or(&[][..], Vec::as_slice));
let edges = spans.iter().filter(|(_, width)| *width > 0);
edges
.map(|(left, width)| usize::from(*left) + usize::from(*width))
.max()
.unwrap_or(0)
ends.max().unwrap_or(0)
/// The indent of the column group holding the focused cell and how far to shift its
/// columns after the frozen ones left to bring the cell fully into `width` columns, never
/// past the frozen ones; the columns stay aligned.
fn focus_shift(&self, widths: &BTreeMap<u16, Vec<u16>>, width: u16) -> Option<(u16, u16)> {
self.lines.iter().find_map(|line| {
return None;
let index = items.iter().position(|item| item.focused)?;
let spans = line.spans(widths.get(indent)?);
let (left, cell) = *spans.get(index)?;
let edge = frozen_edge(&spans, line.frozen_count());
let over = left.saturating_add(cell).saturating_sub(width);
let room = if index < line.frozen_count() {
left.saturating_sub(edge)
Some((*indent, over.min(room)))
/// The area of every item of every line (one rect for a text line) in `area`, the lines
/// scrolled up by `scroll`. The column group of the focused cell shifts left to show it whole;
/// cells cut at an edge are clipped. A line out of view, or a column beyond the area, gets
/// an empty rect.
pub fn cell_rects(&self, area: Rect, scroll: u16) -> Vec<Vec<Rect>> {
let widths = self.column_widths(Some(area.width));
let focus = self.focus_shift(&widths, area.width);
let lines = self.lines.iter().enumerate();
lines
.map(|(at, line)| {
let row = at
.checked_sub(usize::from(scroll))
.and_then(|row| u16::try_from(row).ok())
.filter(|&row| row < area.height);
let Some(row) = row else {
return vec![Rect::default(); line.len()];
let strip = Rect::new(area.x, area.y + row, area.width, 1);
let columns = widths.get(&line.indent()).map_or(&[][..], Vec::as_slice);
let grouped = matches!(line, GridLine::Cells { .. });
let shift = focus
.filter(|(indent, _)| grouped && *indent == line.indent())
.map_or(0, |(_, by)| by);
line.rects(strip, columns, shift)
/// The focused cell item with its rect.
fn focused<'b>(&'b self, rects: &'b [Vec<Rect>]) -> Option<(&'b Item<'a>, Rect)> {
let cells = self.lines.iter().zip(rects).filter_map(|(line, rects)| {
let GridLine::Cells { items, .. } = line else {
Some(items.iter().zip(rects))
cells
.flatten()
.find(|(item, _)| item.focused)
.map(|(item, rect)| (item, *rect))
/// The terminal cursor: at the edit position of the focused cell, when it has one in view.
pub fn caret(&self, rects: &[Vec<Rect>]) -> Option<Position> {
let (item, rect) = self.focused(rects)?;
let area = item.area(rect);
(item.caret && area.width > 0).then(|| {
InputLine::cursor(
area,
&item.text,
item.cursor,
item.scroll.map_or_else(Viewport::default, Cell::get),
/// The rect of the focused select cell, which its list opens under.
pub fn anchor(&self, rects: &[Vec<Rect>]) -> Option<Rect> {
(item.kind == ItemKind::Select).then_some(rect)
#[cfg(test)]
mod tests;