Lines
96.26 %
Functions
77.69 %
Branches
100 %
//! Multi-row split editor widget for the transaction create and edit forms.
//!
//! ## Key scheme (while Splits field is focused)
//! | Key | Effect |
//! |------------|-------------------------------------------------------------|
//! | Tab | Next cell (col→next row's first col); at the last cell of |
//! | | the last row it YIELDS to the outer form (→ Date) |
//! | BackTab | Previous cell; at (row 0, col 0) it YIELDS to the outer |
//! | | form (→ Note) |
//! | Up | Prev Select option (col is Select) / prev row |
//! | Down | Next Select option (col is Select) / next row |
//! | Enter | Submit the transaction (from anywhere in the form) |
//! | Ctrl+N / + | Add a new row below (inherits the fetched option lists) |
//! | - / Ctrl+D | Remove the focused row (minimum 1 kept) |
//! | Ctrl+T | Open the focused split's tag list (again: back to splits) |
//! In the tag list Tab/BackTab walk the cells (name, value, description, side),
//! Ctrl+N adds a tag, Ctrl+D removes one, Up/Down pick the side, Ctrl+O fills
//! the name or value from the suggestions and Esc goes back to the splits.
//! The outer form cycles Date→Note→Splits→Date; the boundary yields above let
//! the user leave the Splits editor by Tab/BackTab without submitting.
use cli_core::forms::FormOption;
use forms::{Kind, Row, TRANSACTION_CREATE};
use crate::widgets::{AmountWidget, SelectOption, SelectWidget, WidgetKind};
mod grid;
mod row;
mod tags;
use row::PENDING_LABEL;
pub use row::SplitRow;
/// The row fields of a form's `splits` field.
pub fn rows_of(form: &'static forms::Form) -> &'static [forms::Field] {
form.fields
.iter()
.find_map(|field| match field.kind {
Kind::Rows { fields, .. } if field.key == "splits" => Some(fields),
_ => None,
})
.unwrap_or_default()
}
/// The widget's columns: create and edit share one split row definition
/// (pinned by a test), so either descriptor names them.
pub fn row_fields() -> &'static [forms::Field] {
rows_of(&TRANSACTION_CREATE)
/// The cells of a split tag row; create and edit share them like the split row.
pub fn tag_fields() -> &'static [forms::Field] {
TRANSACTION_CREATE
.fields
Kind::Rows { fields, .. } if field.nested_under() == Some("splits") => Some(fields),
/// The visible cells of a split row, in descriptor order. `key` and `hidden`
/// exist only for edit round trips and are not shown on create.
pub fn columns() -> impl Iterator<Item = &'static forms::Field> {
row_fields()
.filter(|field| field.key != "key" && field.kind != Kind::Hidden)
/// The `(source, target)` columns of each fill the descriptor declares.
fn declared_fills() -> impl Iterator<Item = (usize, usize)> {
columns()
.enumerate()
.filter_map(|(source, field)| match field.kind {
Kind::Select {
fills: Some(key), ..
} => columns()
.position(|target| target.key == key)
.map(|target| (source, target)),
fn column_count() -> usize {
columns().count()
// Slot indices are pinned to the descriptor keys by a unit test.
pub const COL_FROM: usize = 0;
pub const COL_TO: usize = 1;
pub const COL_FROM_COMM: usize = 2;
pub const COL_TO_COMM: usize = 3;
pub const COL_VALUE: usize = 4;
pub const COL_TO_AMOUNT: usize = 5;
/// Mutable reference to the focused sub-widget for intent routing in `event.rs`.
pub enum FocusedSubWidget<'a> {
Select(&'a mut SelectWidget),
Amount(&'a mut AmountWidget),
/// Multi-row split editor.
///
/// `row_focus` is always `< rows.len()` (minimum 1 row).
/// `col_focus` is always `< column_count()`.
#[derive(Debug)]
pub struct SplitsWidget {
rows: Vec<SplitRow>,
pub row_focus: usize,
pub col_focus: usize,
/// Cached fetched option lists, applied to every current row and to any
/// row added later so a late `add_row` is not stuck with empty Selects.
account_options: Vec<SelectOption>,
commodity_options: Vec<SelectOption>,
account_fills: Vec<FormOption>,
/// Whether keys edit the focused split's tag list instead of the rows.
tags_open: bool,
tags_present: bool,
/// Every fill target the open list can change, with its value and auto flag, for Esc.
fills_at_open: Vec<(usize, (bool, String))>,
/// A widget with one empty row.
impl Default for SplitsWidget {
fn default() -> Self {
Self {
rows: vec![SplitRow::new(&[], &[])],
row_focus: 0,
col_focus: 0,
account_options: Vec::new(),
commodity_options: Vec::new(),
account_fills: Vec::new(),
tags_open: false,
tags_present: false,
fills_at_open: Vec::new(),
impl SplitsWidget {
/// Read-only view of the rows (for validation and display).
#[must_use]
pub fn rows(&self) -> &[SplitRow] {
&self.rows
/// WidgetKind of the focused column.
pub fn focused_subwidget_kind(&self) -> WidgetKind {
if let Some(tags) = self.tags() {
return tags.focused_kind();
SplitRow::col_kind(self.col_focus)
/// Mutable reference to the focused sub-widget for intent routing.
pub fn focused_subwidget_mut(&mut self) -> Option<FocusedSubWidget<'_>> {
let row = self.rows.get_mut(self.row_focus)?;
match SplitRow::col_kind(self.col_focus) {
WidgetKind::Select => row.select_mut(self.col_focus).map(FocusedSubWidget::Select),
_ => row.amount_mut(self.col_focus).map(FocusedSubWidget::Amount),
/// The focused cell's select, a tag's while the tags are open; `None` on another cell.
pub fn focused_select(&self) -> Option<&SelectWidget> {
return tags.focused_select();
self.rows.get(self.row_focus)?.select(self.col_focus)
pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
if self.tags_open() {
return self
.tags_mut()
.and_then(super::rows::RowsWidget::focused_select_mut);
match self.focused_subwidget_mut()? {
FocusedSubWidget::Select(select) => Some(select),
FocusedSubWidget::Amount(_) => None,
/// Advance one cell: next column, or the next row's first column at a row
/// boundary. A no-op at the last cell of the last row (the caller yields to
/// the outer form there — see [`at_last_cell`](Self::at_last_cell)).
pub fn advance_cell(&mut self) {
if self.col_focus + 1 < column_count() {
self.col_focus += 1;
} else if self.row_focus + 1 < self.rows.len() {
self.row_focus += 1;
self.col_focus = 0;
/// Retreat one cell: previous column, or the previous row's last column at
/// a row boundary. A no-op at the first cell (the caller yields there).
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 = column_count().saturating_sub(1);
/// `true` when focus is on the very first cell (row 0, column 0); BackTab
/// here should yield to the outer form rather than move within the editor.
pub fn at_first_cell(&self) -> bool {
self.row_focus == 0 && self.col_focus == 0
/// `true` when focus is on the very last cell (last row, last column); Tab
pub fn at_last_cell(&self) -> bool {
self.row_focus + 1 == self.rows.len() && self.col_focus + 1 == 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);
/// Append a new row after `row_focus`, pre-seeded from the cached option
/// lists, and focus it.
pub fn add_row(&mut self) {
let insert_at = self.row_focus + 1;
let row = SplitRow::new(&self.account_options, &self.commodity_options);
self.rows.insert(insert_at, row);
self.row_focus = insert_at;
/// Focus the cell of `row` holding descriptor field `key`; 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 = columns().position(|field| field.key == key).unwrap_or(0);
/// Focus column `col` of `row`, both held inside the rows and columns there are.
fn focus_at(&mut self, row: usize, col: usize) {
self.col_focus = col.min(column_count().saturating_sub(1));
/// Select `id` as the first row's From account until the option list
/// arrives and gives it its label.
pub fn preselect_from(&mut self, id: &str) {
let Some(row) = self.rows.first_mut() else {
return;
};
row.from.set_options(vec![SelectOption {
id: id.to_string(),
label: PENDING_LABEL.to_string(),
}]);
/// Remove the focused row; keeps at least one row.
pub fn remove_row(&mut self) {
if self.rows.len() <= 1 {
self.rows.remove(self.row_focus);
if self.row_focus >= self.rows.len() {
self.row_focus = self.rows.len() - 1;
/// Cache the account options and apply them to every row's from/to selects.
/// A loaded cell keeps its selection and its exact text as the option id.
pub fn set_account_options(&mut self, options: Vec<SelectOption>) {
self.account_options = options;
for row in &mut self.rows {
row.bind_accounts(&self.account_options);
/// The accounts' only commodities; every row refills its declared fill targets from them.
pub fn set_account_fills(&mut self, fills: Vec<FormOption>) {
self.account_fills = fills;
declared_fills().for_each(|fill| row.refill(fill, &self.account_fills));
/// Open the focused select; it remembers every fill target its edits can refill, for Esc.
pub fn open_select(&mut self) {
let col = self.col_focus;
let Some(row) = self.rows.get_mut(self.row_focus) else {
self.fills_at_open = declared_fills()
.filter(|(_, target)| *target >= col)
.filter_map(|(_, target)| Some((target, row.commodity_state(target)?)))
.collect();
if let Some(select) = row.select_mut(col) {
select.open_list();
/// Edit the focused select; a from-account change refills the row's commodity, a commodity
/// change makes it the user's.
pub fn edit_select(&mut self, edit: impl FnOnce(&mut SelectWidget)) {
let Some(select) = row.select_mut(col) else {
edit(select);
row.picked(col);
// Fills come in column order, so a chained fill reads its source's refill.
declared_fills()
.filter(|(source, _)| *source >= col)
.for_each(|fill| row.refill(fill, &self.account_fills));
/// Close the focused list on the value it had, commodity included.
pub fn cancel_select(&mut self) {
select.cancel();
for (target, state) in std::mem::take(&mut self.fills_at_open) {
row.restore_commodity(target, state);
/// Commodity counterpart of [`set_account_options`](Self::set_account_options).
pub fn set_commodity_options(&mut self, options: Vec<SelectOption>) {
self.commodity_options = options;
row.bind_commodities(&self.commodity_options);
/// Replace all rows with the loaded ones; every cell, key and hidden text
/// is kept exactly. Guarantees at least one row.
pub fn load_rows(&mut self, rows: &[Row]) {
self.rows = rows.iter().map(SplitRow::loaded).collect();
self.row_focus = 0;
self.tags_open = false;
if self.rows.is_empty() {
self.rows.push(SplitRow::new(
&self.account_options,
&self.commodity_options,
));
/// Display summary for the generic [`Widget::display`](crate::widgets::Widget) contract.
pub fn display(&self) -> String {
let n = self.rows.len();
format!(
"{n} split(s) [row {}, col {}]",
self.row_focus, self.col_focus
)
#[cfg(test)]
mod same_commodity_tests;
mod tags_tests;
mod tests;