Lines
98.31 %
Functions
50 %
Branches
100 %
//! Generic editor for a rows field whose cells are all text or hidden.
//!
//! Keys while focused: Tab/BackTab walk the cells and yield to the outer form
//! at the first and last one, Up/Down change the row, Ctrl+N adds a row below
//! and Ctrl+D removes the focused one. A printable non-space key on an empty
//! field starts a row; any other key edits the focused cell.
use forms::{Field, Kind, LINK_CELL, Row, Suggest};
use crate::widgets::grid::{CellId, Grid, Item};
use crate::widgets::{Editor, SelectWidget, WidgetKind};
/// Whether a rows field's own cells are text, choice or hidden only, so this
/// widget can edit it; a choice cell is a pick among its options. Any other cell
/// kind belongs to the splits editor.
#[must_use]
pub fn is_text_rows(cells: &[Field]) -> bool {
cells.iter().all(|cell| {
matches!(
cell.kind,
Kind::Text { .. } | Kind::Choice { .. } | Kind::Hidden
)
})
}
/// One shown cell: typed text, or a pick among a choice field's options.
#[derive(Debug)]
enum Cell {
Text(Editor),
Choice(SelectWidget),
impl Cell {
fn loaded(field: &Field, text: &str) -> Self {
match field.kind {
Kind::Choice { options, default } => {
let mut select = SelectWidget::choice(options, default);
if !text.is_empty() {
select.select_id(text);
Self::Choice(select)
_ => Self::Text(Editor::with_buffer(text)),
fn value(&self) -> &str {
match self {
Self::Text(editor) => editor.buffer(),
Self::Choice(select) => select.value(),
fn item(&self, focused: bool) -> Item<'_> {
Self::Text(editor) => Item::text(
editor.buffer().replace('\n', "\u{23ce}"),
editor.cursor(),
focused,
.scrolled(editor.scroll()),
Self::Choice(select) => Item::select(select, focused),
struct RowCells {
cells: Vec<Cell>,
hidden: Row,
/// Shown cells the loaded row held as empty text: written back empty, not left out.
blank: Vec<&'static str>,
/// Rows of text cells. `row_focus` is `< rows.len()` and `col_focus` is
/// `< columns().count()` while any row exists.
pub struct RowsWidget {
cells: &'static [Field],
rows: Vec<RowCells>,
/// Whether the field is part of the values: absent until loaded or edited.
present: bool,
pub row_focus: usize,
pub col_focus: usize,
impl RowsWidget {
pub fn new(cells: &'static [Field]) -> Self {
Self {
cells,
rows: Vec::new(),
present: false,
row_focus: 0,
col_focus: 0,
/// The shown cells in descriptor order; the link to a parent row is not one.
pub fn columns(&self) -> impl Iterator<Item = &'static Field> + use<> {
self.cells.iter().filter(|cell| {
cell.key != LINK_CELL && matches!(cell.kind, Kind::Text { .. } | Kind::Choice { .. })
fn column_count(&self) -> usize {
self.columns().count()
/// The label of cell `key`, if the row defines it.
pub fn cell_label(&self, key: &str) -> Option<&'static str> {
self.cells
.iter()
.find(|cell| cell.key == key)
.map(|cell| cell.label)
/// Replaces the rows; `None` makes the field absent again.
pub fn load_rows(&mut self, rows: Option<&[Row]>) {
self.present = rows.is_some();
self.rows = rows
.unwrap_or_default()
.map(|row| self.loaded_row(row))
.collect();
self.row_focus = 0;
self.col_focus = 0;
fn loaded_row(&self, row: &Row) -> RowCells {
let text = |key: &str| row.get(key).map_or("", String::as_str);
RowCells {
cells: self
.columns()
.map(|cell| Cell::loaded(cell, text(cell.key)))
.collect(),
hidden: self
.cells
.filter(|cell| cell.kind == Kind::Hidden)
.filter_map(|cell| Some((cell.key.to_string(), row.get(cell.key)?.clone())))
blank: self
.filter(|cell| row.get(cell.key).is_some_and(String::is_empty))
.map(|cell| cell.key)
/// The rows as values: empty cells are left out. `None` when absent.
pub fn values(&self) -> Option<Vec<Row>> {
self.present.then(|| self.rows())
/// The rows as values whether or not the field is present.
pub fn rows(&self) -> Vec<Row> {
self.rows.iter().map(|r| self.row(r)).collect()
fn row(&self, row: &RowCells) -> Row {
let shown = self
.zip(&row.cells)
.map(|(cell, shown)| (cell.key, shown.value()))
.filter(|(key, text)| !text.is_empty() || row.blank.contains(key))
.map(|(key, text)| (key.to_string(), text.to_string()));
let hidden = row.hidden.iter().filter(|(_, text)| !text.is_empty());
shown
.chain(hidden.map(|(key, text)| (key.clone(), text.clone())))
.collect()
/// Inserts an empty row after the focused one and focuses its first cell.
pub fn add_row(&mut self) {
let at = if self.rows.is_empty() {
0
} else {
self.row_focus + 1
};
let row = self.loaded_row(&Row::new());
self.rows.insert(at, row);
self.present = true;
self.row_focus = at;
/// Removes the focused row; an emptied field stays present.
pub fn remove_row(&mut self) {
if self.row_focus >= self.rows.len() {
return;
self.rows.remove(self.row_focus);
self.row_focus = self.row_focus.min(self.rows.len().saturating_sub(1));
pub fn advance_cell(&mut self) {
if self.col_focus + 1 < self.column_count() {
self.col_focus += 1;
} else if self.row_focus + 1 < self.rows.len() {
self.row_focus += 1;
pub fn retreat_cell(&mut self) {
if self.col_focus > 0 {
self.col_focus -= 1;
} else if self.row_focus > 0 {
self.row_focus -= 1;
self.col_focus = self.column_count().saturating_sub(1);
pub fn at_first_cell(&self) -> bool {
self.row_focus == 0 && self.col_focus == 0
pub fn at_last_cell(&self) -> bool {
self.rows.is_empty()
|| (self.row_focus + 1 == self.rows.len() && self.col_focus + 1 == self.column_count())
pub fn at_first_row(&self) -> bool {
self.row_focus == 0
pub fn at_last_row(&self) -> bool {
self.row_focus + 1 >= self.rows.len()
pub fn next_row(&mut self) {
self.row_focus = (self.row_focus + 1).min(self.rows.len().saturating_sub(1));
pub fn prev_row(&mut self) {
self.row_focus = self.row_focus.saturating_sub(1);
/// Focuses cell `key` of `row`; an unknown key focuses the row's first cell.
pub fn focus_cell(&mut self, row: usize, key: &str) {
self.row_focus = row.min(self.rows.len().saturating_sub(1));
self.col_focus = self.columns().position(|cell| cell.key == key).unwrap_or(0);
/// Focuses the cell at `row` and `col`, both held inside the rows and columns there are.
pub fn focus_at(&mut self, row: usize, col: usize) {
self.col_focus = col.min(self.column_count().saturating_sub(1));
/// The focused cell.
pub fn focused_cell(&self) -> CellId {
CellId {
tag: false,
row: self.row_focus,
col: self.col_focus,
pub fn focused_editor_mut(&mut self) -> Option<&mut Editor> {
match self.focused_cell_mut()? {
Cell::Text(editor) => Some(editor),
Cell::Choice(_) => None,
pub fn focused_select(&self) -> Option<&SelectWidget> {
match self.rows.get(self.row_focus)?.cells.get(self.col_focus)? {
Cell::Choice(select) => Some(select),
Cell::Text(_) => None,
pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
fn focused_cell_mut(&mut self) -> Option<&mut Cell> {
self.rows
.get_mut(self.row_focus)?
.get_mut(self.col_focus)
/// The widget kind of the focused cell.
pub fn focused_kind(&self) -> WidgetKind {
match self.columns().nth(self.col_focus).map(|cell| cell.kind) {
Some(Kind::Choice { .. }) => WidgetKind::Select,
_ => WidgetKind::Text,
/// The descriptor key of the focused cell.
pub fn focused_key(&self) -> Option<&'static str> {
self.columns().nth(self.col_focus).map(|cell| cell.key)
/// What the focused cell asks to be suggested.
pub fn focused_suggest(&self) -> Option<Suggest> {
match self.columns().nth(self.col_focus)?.kind {
Kind::Text { suggest, .. } if !self.rows.is_empty() => suggest,
_ => None,
/// The text of cell `key` in the focused row.
pub fn focused_text(&self, key: &str) -> &str {
let col = self.columns().position(|cell| cell.key == key);
let cell = col.and_then(|col| self.rows.get(self.row_focus)?.cells.get(col));
cell.map_or("", Cell::value)
/// Replaces the focused text cell's content.
pub fn set_focused_text(&mut self, text: &str) {
if let Some(editor) = self.focused_editor_mut() {
*editor = Editor::with_buffer(text);
pub fn is_empty(&self) -> bool {
pub fn display(&self) -> String {
format!("{} row(s)", self.rows.len())
/// A header line and a line of cells per row, `active` when the field has the focus;
/// `suggestion` follows the rows, and an empty field shows `empty`.
pub fn grid(&self, active: bool, suggestion: Option<&str>, empty: Option<&str>) -> Grid<'_> {
let mut grid = Grid::default();
let header = self.columns().map(|cell| Item::label(cell.label));
grid.push_cells(0, header.collect());
for (at, row) in self.rows.iter().enumerate() {
if at == self.row_focus {
grid.focus_line = at + 1;
let focus = |col| active && (at, col) == (self.row_focus, self.col_focus);
let items = row
.enumerate()
.map(|(col, cell)| cell.item(focus(col)).at(at, col));
grid.push_cells(0, items.collect());
if let Some(note) = empty.filter(|_| self.rows.is_empty()) {
grid.push_note(0, note);
if let Some(line) = suggestion {
grid.push_note(0, line);
grid
/// The note of an empty field of `what`, naming the key that adds one.
pub fn empty_note(what: &str, add_key: Option<&str>) -> String {
let hint = add_key.map_or_else(String::new, |key| format!(": {key} adds one"));
format!("(no {what}{hint})")
#[cfg(test)]
mod tests;