1use std::cell::Cell;
7use std::collections::BTreeMap;
8
9use ratatui::layout::{Position, Rect};
10use ratatui::text::Span;
11use tvui::{ARROW_CELLS, InputLine, Viewport};
12
13use super::SelectWidget;
14
15mod tail;
16mod width;
17use width::Width;
18use width::{Column, frozen_edge, gap, resolve};
19
20pub const GRID_INDENT: u16 = 4;
22const TEXT_RESERVE: u16 = 10 + ARROW_CELLS;
24const MIN_SELECT: u16 = 6 + ARROW_CELLS;
25const MARK_CELLS: u16 = 1;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum ItemKind {
30 Label,
31 Text,
32 Select,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct CellId {
39 pub tag: bool,
40 pub row: usize,
41 pub col: usize,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct Item<'a> {
47 pub kind: ItemKind,
48 pub text: String,
49 pub cursor: usize,
50 pub focused: bool,
51 pub caret: bool,
53 pub cell: Option<CellId>,
55 pub scroll: Option<&'a Cell<Viewport>>,
57 min: u16,
58 rule: Width,
59 frozen: bool,
60 tail: bool,
61}
62
63fn width_of(text: &str) -> u16 {
64 u16::try_from(Span::raw(text).width()).unwrap_or(u16::MAX)
65}
66
67impl<'a> Item<'a> {
68 #[must_use]
69 pub fn label(text: impl Into<String>) -> Self {
70 Item {
71 kind: ItemKind::Label,
72 text: text.into(),
73 cursor: 0,
74 focused: false,
75 caret: false,
76 cell: None,
77 scroll: None,
78 min: 0,
79 rule: Width::Fit,
80 frozen: false,
81 tail: false,
82 }
83 }
84
85 #[must_use]
87 pub fn text(text: impl Into<String>, cursor: usize, focused: bool) -> Self {
88 Item {
89 kind: ItemKind::Text,
90 text: text.into(),
91 cursor,
92 focused,
93 caret: true,
94 cell: None,
95 scroll: None,
96 min: 0,
97 rule: Width::Fit,
98 frozen: false,
99 tail: false,
100 }
101 }
102
103 #[must_use]
105 pub fn scrolled(mut self, scroll: &'a Cell<Viewport>) -> Self {
106 self.scroll = Some(scroll);
107 self
108 }
109
110 #[must_use]
113 pub fn select(select: &'a SelectWidget, focused: bool) -> Self {
114 let text = match select.shown() {
115 "" => "?",
116 shown => shown,
117 };
118 let widest = select
119 .options()
120 .iter()
121 .map(|option| width_of(&option.label));
122 let widest = widest.max().unwrap_or(0).max(width_of(select.query()));
123 Item {
124 kind: ItemKind::Select,
125 text: text.to_string(),
126 cursor: select.query().chars().count(),
127 focused,
128 caret: select.open,
129 cell: None,
130 scroll: Some(select.scroll()),
131 min: widest.saturating_add(ARROW_CELLS).max(MIN_SELECT),
132 rule: Width::Fit,
133 frozen: false,
134 tail: false,
135 }
136 }
137
138 #[must_use]
140 pub fn at(mut self, row: usize, col: usize) -> Self {
141 self.cell = Some(CellId {
142 tag: false,
143 row,
144 col,
145 });
146 self
147 }
148
149 #[must_use]
152 pub fn fixed(mut self, width: u16) -> Self {
153 self.rule = Width::Fixed(width);
154 self
155 }
156
157 #[must_use]
160 pub fn frozen(mut self) -> Self {
161 self.frozen = true;
162 self
163 }
164
165 #[must_use]
167 pub fn flex(mut self, min: u16, max: u16) -> Self {
168 self.rule = Width::Flex { min, max };
169 self
170 }
171
172 fn fit_width(&self) -> u16 {
174 match self.kind {
175 ItemKind::Label => width_of(&self.text),
176 ItemKind::Text => width_of(&self.text)
177 .saturating_add(ARROW_CELLS)
178 .max(TEXT_RESERVE),
179 ItemKind::Select => self.min.saturating_add(MARK_CELLS),
180 }
181 }
182
183 #[must_use]
185 pub fn width(&self) -> u16 {
186 match self.rule {
187 Width::Fit => self.fit_width(),
188 Width::Fixed(width) => width,
189 Width::Flex { max, .. } => max,
190 }
191 }
192
193 fn floor(&self) -> u16 {
194 match self.rule {
195 Width::Flex { min, .. } => min,
196 _ => self.width(),
197 }
198 }
199
200 #[must_use]
202 pub fn area(&self, rect: Rect) -> Rect {
203 let mark = if self.kind == ItemKind::Select {
204 MARK_CELLS
205 } else {
206 0
207 };
208 Rect {
209 width: rect.width.saturating_sub(mark),
210 ..rect
211 }
212 }
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub enum GridLine<'a> {
217 Text {
218 indent: u16,
219 text: String,
220 focused: bool,
221 },
222 Cells {
223 indent: u16,
224 items: Vec<Item<'a>>,
225 },
226}
227
228impl GridLine<'_> {
229 fn indent(&self) -> u16 {
230 match self {
231 GridLine::Text { indent, .. } | GridLine::Cells { indent, .. } => *indent,
232 }
233 }
234
235 fn indented(mut self, by: u16) -> Self {
236 match &mut self {
237 GridLine::Text { indent, .. } | GridLine::Cells { indent, .. } => {
238 *indent = indent.saturating_add(by);
239 }
240 }
241 self
242 }
243
244 fn frozen_count(&self) -> usize {
245 match self {
246 GridLine::Text { .. } => 0,
247 GridLine::Cells { items, .. } => items.iter().take_while(|item| item.frozen).count(),
248 }
249 }
250
251 fn len(&self) -> usize {
252 match self {
253 GridLine::Text { .. } => 1,
254 GridLine::Cells { items, .. } => items.len(),
255 }
256 }
257
258 fn spans(&self, widths: &[u16]) -> Vec<(u16, u16)> {
260 match self {
261 GridLine::Text { indent, .. } => vec![(*indent, u16::MAX)],
262 GridLine::Cells { indent, items } => {
263 let mut x = *indent;
264 let columns = items.iter().zip(widths);
265 columns
266 .map(|(_, &width)| {
267 let span = (x, width);
268 x = x.saturating_add(width).saturating_add(gap(width));
269 span
270 })
271 .collect()
272 }
273 }
274 }
275
276 fn rects(&self, strip: Rect, widths: &[u16], shift: u16) -> Vec<Rect> {
280 let frozen = self.frozen_count();
281 let spans = self.spans(widths);
282 let edge = frozen_edge(&spans, frozen);
283 let cut = |(at, (left, width)): (usize, (u16, u16))| {
284 let scrolled = at >= frozen;
285 let by = if scrolled { shift } else { 0 };
286 if frozen == 0 && left < by {
287 return Rect::new(strip.x, strip.y, 0, 1);
288 }
289 let start = if scrolled { edge } else { 0 };
290 let from = left.saturating_sub(by).max(start).min(strip.width);
291 let to = left
292 .saturating_add(width)
293 .saturating_sub(by)
294 .min(strip.width);
295 let wide = to.saturating_sub(from);
296 Rect::new(strip.x.saturating_add(from), strip.y, wide, 1)
297 };
298 spans.into_iter().enumerate().map(cut).collect()
299 }
300}
301
302#[derive(Debug, Clone, Default, PartialEq, Eq)]
303pub struct Grid<'a> {
304 pub lines: Vec<GridLine<'a>>,
305 pub focus_line: usize,
307}
308
309impl<'a> Grid<'a> {
310 pub fn push_cells(&mut self, indent: u16, items: Vec<Item<'a>>) {
311 self.lines.push(GridLine::Cells { indent, items });
312 }
313
314 pub fn push_note(&mut self, indent: u16, text: impl Into<String>) {
315 self.lines.push(GridLine::Text {
316 indent,
317 text: text.into(),
318 focused: false,
319 });
320 }
321
322 pub fn append(&mut self, other: Grid<'a>, indent: u16, focused: bool) {
324 if focused {
325 self.focus_line = self.lines.len() + other.focus_line;
326 }
327 self.lines
328 .extend(other.lines.into_iter().map(|line| line.indented(indent)));
329 }
330
331 #[must_use]
333 pub fn titled(self, title: impl Into<String>, focused: bool) -> Self {
334 let mut titled = Grid::default();
335 titled.lines.push(GridLine::Text {
336 indent: 0,
337 text: title.into(),
338 focused,
339 });
340 titled.append(self, GRID_INDENT, true);
341 titled
342 }
343
344 #[must_use]
346 pub fn of_tags(mut self) -> Self {
347 for line in &mut self.lines {
348 if let GridLine::Cells { items, .. } = line {
349 for cell in items.iter_mut().filter_map(|item| item.cell.as_mut()) {
350 cell.tag = true;
351 }
352 }
353 }
354 self
355 }
356
357 fn column_widths(&self, avail: Option<u16>) -> BTreeMap<u16, Vec<u16>> {
360 let mut columns: BTreeMap<u16, Vec<Column>> = BTreeMap::new();
361 for line in &self.lines {
362 let GridLine::Cells { indent, items } = line else {
363 continue;
364 };
365 let group = columns.entry(*indent).or_default();
366 if group.len() < items.len() {
367 group.resize(items.len(), Column::default());
368 }
369 for (column, item) in group.iter_mut().zip(items) {
370 column.absorb(item);
371 }
372 }
373 let resolved = |(indent, group): (u16, Vec<Column>)| {
374 (
375 indent,
376 resolve(&group, avail.map(|a| a.saturating_sub(indent))),
377 )
378 };
379 columns.into_iter().map(resolved).collect()
380 }
381
382 #[must_use]
384 pub fn width(&self) -> usize {
385 let widths = self.column_widths(None);
386 let ends = self.lines.iter().map(|line| match line {
387 GridLine::Text { indent, text, .. } => usize::from(*indent) + Span::raw(text).width(),
388 GridLine::Cells { indent, .. } => {
389 let spans = line.spans(widths.get(indent).map_or(&[][..], Vec::as_slice));
390 let edges = spans.iter().filter(|(_, width)| *width > 0);
391 edges
392 .map(|(left, width)| usize::from(*left) + usize::from(*width))
393 .max()
394 .unwrap_or(0)
395 }
396 });
397 ends.max().unwrap_or(0)
398 }
399
400 fn focus_shift(&self, widths: &BTreeMap<u16, Vec<u16>>, width: u16) -> Option<(u16, u16)> {
404 self.lines.iter().find_map(|line| {
405 let GridLine::Cells { indent, items } = line else {
406 return None;
407 };
408 let index = items.iter().position(|item| item.focused)?;
409 let spans = line.spans(widths.get(indent)?);
410 let (left, cell) = *spans.get(index)?;
411 let edge = frozen_edge(&spans, line.frozen_count());
412 let over = left.saturating_add(cell).saturating_sub(width);
413 let room = if index < line.frozen_count() {
414 0
415 } else {
416 left.saturating_sub(edge)
417 };
418 Some((*indent, over.min(room)))
419 })
420 }
421
422 #[must_use]
427 pub fn cell_rects(&self, area: Rect, scroll: u16) -> Vec<Vec<Rect>> {
428 let widths = self.column_widths(Some(area.width));
429 let focus = self.focus_shift(&widths, area.width);
430 let lines = self.lines.iter().enumerate();
431 lines
432 .map(|(at, line)| {
433 let row = at
434 .checked_sub(usize::from(scroll))
435 .and_then(|row| u16::try_from(row).ok())
436 .filter(|&row| row < area.height);
437 let Some(row) = row else {
438 return vec![Rect::default(); line.len()];
439 };
440 let strip = Rect::new(area.x, area.y + row, area.width, 1);
441 let columns = widths.get(&line.indent()).map_or(&[][..], Vec::as_slice);
442 let grouped = matches!(line, GridLine::Cells { .. });
443 let shift = focus
444 .filter(|(indent, _)| grouped && *indent == line.indent())
445 .map_or(0, |(_, by)| by);
446 line.rects(strip, columns, shift)
447 })
448 .collect()
449 }
450
451 fn focused<'b>(&'b self, rects: &'b [Vec<Rect>]) -> Option<(&'b Item<'a>, Rect)> {
453 let cells = self.lines.iter().zip(rects).filter_map(|(line, rects)| {
454 let GridLine::Cells { items, .. } = line else {
455 return None;
456 };
457 Some(items.iter().zip(rects))
458 });
459 cells
460 .flatten()
461 .find(|(item, _)| item.focused)
462 .map(|(item, rect)| (item, *rect))
463 }
464
465 #[must_use]
467 pub fn caret(&self, rects: &[Vec<Rect>]) -> Option<Position> {
468 let (item, rect) = self.focused(rects)?;
469 let area = item.area(rect);
470 (item.caret && area.width > 0).then(|| {
471 InputLine::cursor(
472 area,
473 &item.text,
474 item.cursor,
475 item.scroll.map_or_else(Viewport::default, Cell::get),
476 )
477 })
478 }
479
480 #[must_use]
482 pub fn anchor(&self, rects: &[Vec<Rect>]) -> Option<Rect> {
483 let (item, rect) = self.focused(rects)?;
484 (item.kind == ItemKind::Select).then_some(rect)
485 }
486}
487
488#[cfg(test)]
489mod tests;