Skip to main content

tui/widgets/
splits.rs

1//! Multi-row split editor widget for the transaction create and edit forms.
2//!
3//! ## Key scheme (while Splits field is focused)
4//!
5//! | Key        | Effect                                                       |
6//! |------------|-------------------------------------------------------------|
7//! | Tab        | Next cell (col→next row's first col); at the last cell of   |
8//! |            | the last row it YIELDS to the outer form (→ Date)           |
9//! | BackTab    | Previous cell; at (row 0, col 0) it YIELDS to the outer     |
10//! |            | form (→ Note)                                               |
11//! | Up         | Prev Select option (col is Select) / prev row               |
12//! | Down       | Next Select option (col is Select) / next row               |
13//! | Enter      | Submit the transaction (from anywhere in the form)          |
14//! | Ctrl+N / + | Add a new row below (inherits the fetched option lists)     |
15//! | - / Ctrl+D | Remove the focused row (minimum 1 kept)                     |
16//! | Ctrl+T     | Open the focused split's tag list (again: back to splits)   |
17//!
18//! In the tag list Tab/BackTab walk the cells (name, value, description, side),
19//! Ctrl+N adds a tag, Ctrl+D removes one, Up/Down pick the side, Ctrl+O fills
20//! the name or value from the suggestions and Esc goes back to the splits.
21//!
22//! The outer form cycles Date→Note→Splits→Date; the boundary yields above let
23//! the user leave the Splits editor by Tab/BackTab without submitting.
24
25use cli_core::forms::FormOption;
26use forms::{Kind, Row, TRANSACTION_CREATE};
27
28use crate::widgets::{AmountWidget, SelectOption, SelectWidget, WidgetKind};
29
30mod grid;
31mod row;
32mod tags;
33use row::PENDING_LABEL;
34
35pub use row::SplitRow;
36
37/// The row fields of a form's `splits` field.
38pub fn rows_of(form: &'static forms::Form) -> &'static [forms::Field] {
39    form.fields
40        .iter()
41        .find_map(|field| match field.kind {
42            Kind::Rows { fields, .. } if field.key == "splits" => Some(fields),
43            _ => None,
44        })
45        .unwrap_or_default()
46}
47
48/// The widget's columns: create and edit share one split row definition
49/// (pinned by a test), so either descriptor names them.
50pub fn row_fields() -> &'static [forms::Field] {
51    rows_of(&TRANSACTION_CREATE)
52}
53
54/// The cells of a split tag row; create and edit share them like the split row.
55pub fn tag_fields() -> &'static [forms::Field] {
56    TRANSACTION_CREATE
57        .fields
58        .iter()
59        .find_map(|field| match field.kind {
60            Kind::Rows { fields, .. } if field.nested_under() == Some("splits") => Some(fields),
61            _ => None,
62        })
63        .unwrap_or_default()
64}
65
66/// The visible cells of a split row, in descriptor order. `key` and `hidden`
67/// exist only for edit round trips and are not shown on create.
68pub fn columns() -> impl Iterator<Item = &'static forms::Field> {
69    row_fields()
70        .iter()
71        .filter(|field| field.key != "key" && field.kind != Kind::Hidden)
72}
73
74/// The `(source, target)` columns of each fill the descriptor declares.
75fn declared_fills() -> impl Iterator<Item = (usize, usize)> {
76    columns()
77        .enumerate()
78        .filter_map(|(source, field)| match field.kind {
79            Kind::Select {
80                fills: Some(key), ..
81            } => columns()
82                .position(|target| target.key == key)
83                .map(|target| (source, target)),
84            _ => None,
85        })
86}
87
88fn column_count() -> usize {
89    columns().count()
90}
91
92// Slot indices are pinned to the descriptor keys by a unit test.
93pub const COL_FROM: usize = 0;
94pub const COL_TO: usize = 1;
95pub const COL_FROM_COMM: usize = 2;
96pub const COL_TO_COMM: usize = 3;
97pub const COL_VALUE: usize = 4;
98pub const COL_TO_AMOUNT: usize = 5;
99
100/// Mutable reference to the focused sub-widget for intent routing in `event.rs`.
101pub enum FocusedSubWidget<'a> {
102    Select(&'a mut SelectWidget),
103    Amount(&'a mut AmountWidget),
104}
105
106/// Multi-row split editor.
107///
108/// `row_focus` is always `< rows.len()` (minimum 1 row).
109/// `col_focus` is always `< column_count()`.
110#[derive(Debug)]
111pub struct SplitsWidget {
112    rows: Vec<SplitRow>,
113    pub row_focus: usize,
114    pub col_focus: usize,
115    /// Cached fetched option lists, applied to every current row and to any
116    /// row added later so a late `add_row` is not stuck with empty Selects.
117    account_options: Vec<SelectOption>,
118    commodity_options: Vec<SelectOption>,
119    account_fills: Vec<FormOption>,
120    /// Whether keys edit the focused split's tag list instead of the rows.
121    tags_open: bool,
122    tags_present: bool,
123    /// Every fill target the open list can change, with its value and auto flag, for Esc.
124    fills_at_open: Vec<(usize, (bool, String))>,
125}
126
127/// A widget with one empty row.
128impl Default for SplitsWidget {
129    fn default() -> Self {
130        Self {
131            rows: vec![SplitRow::new(&[], &[])],
132            row_focus: 0,
133            col_focus: 0,
134            account_options: Vec::new(),
135            commodity_options: Vec::new(),
136            account_fills: Vec::new(),
137            tags_open: false,
138            tags_present: false,
139            fills_at_open: Vec::new(),
140        }
141    }
142}
143
144impl SplitsWidget {
145    /// Read-only view of the rows (for validation and display).
146    #[must_use]
147    pub fn rows(&self) -> &[SplitRow] {
148        &self.rows
149    }
150
151    /// WidgetKind of the focused column.
152    #[must_use]
153    pub fn focused_subwidget_kind(&self) -> WidgetKind {
154        if let Some(tags) = self.tags() {
155            return tags.focused_kind();
156        }
157        SplitRow::col_kind(self.col_focus)
158    }
159
160    /// Mutable reference to the focused sub-widget for intent routing.
161    pub fn focused_subwidget_mut(&mut self) -> Option<FocusedSubWidget<'_>> {
162        let row = self.rows.get_mut(self.row_focus)?;
163        match SplitRow::col_kind(self.col_focus) {
164            WidgetKind::Select => row.select_mut(self.col_focus).map(FocusedSubWidget::Select),
165            _ => row.amount_mut(self.col_focus).map(FocusedSubWidget::Amount),
166        }
167    }
168
169    /// The focused cell's select, a tag's while the tags are open; `None` on another cell.
170    #[must_use]
171    pub fn focused_select(&self) -> Option<&SelectWidget> {
172        if let Some(tags) = self.tags() {
173            return tags.focused_select();
174        }
175        self.rows.get(self.row_focus)?.select(self.col_focus)
176    }
177
178    pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
179        if self.tags_open() {
180            return self
181                .tags_mut()
182                .and_then(super::rows::RowsWidget::focused_select_mut);
183        }
184        match self.focused_subwidget_mut()? {
185            FocusedSubWidget::Select(select) => Some(select),
186            FocusedSubWidget::Amount(_) => None,
187        }
188    }
189
190    /// Advance one cell: next column, or the next row's first column at a row
191    /// boundary. A no-op at the last cell of the last row (the caller yields to
192    /// the outer form there — see [`at_last_cell`](Self::at_last_cell)).
193    pub fn advance_cell(&mut self) {
194        if self.col_focus + 1 < column_count() {
195            self.col_focus += 1;
196        } else if self.row_focus + 1 < self.rows.len() {
197            self.row_focus += 1;
198            self.col_focus = 0;
199        }
200    }
201
202    /// Retreat one cell: previous column, or the previous row's last column at
203    /// a row boundary. A no-op at the first cell (the caller yields there).
204    pub fn retreat_cell(&mut self) {
205        if self.col_focus > 0 {
206            self.col_focus -= 1;
207        } else if self.row_focus > 0 {
208            self.row_focus -= 1;
209            self.col_focus = column_count().saturating_sub(1);
210        }
211    }
212
213    /// `true` when focus is on the very first cell (row 0, column 0); BackTab
214    /// here should yield to the outer form rather than move within the editor.
215    #[must_use]
216    pub fn at_first_cell(&self) -> bool {
217        self.row_focus == 0 && self.col_focus == 0
218    }
219
220    /// `true` when focus is on the very last cell (last row, last column); Tab
221    /// here should yield to the outer form rather than move within the editor.
222    #[must_use]
223    pub fn at_last_cell(&self) -> bool {
224        self.row_focus + 1 == self.rows.len() && self.col_focus + 1 == column_count()
225    }
226
227    #[must_use]
228    pub fn at_first_row(&self) -> bool {
229        self.row_focus == 0
230    }
231
232    #[must_use]
233    pub fn at_last_row(&self) -> bool {
234        self.row_focus + 1 >= self.rows.len()
235    }
236
237    pub fn next_row(&mut self) {
238        self.row_focus = (self.row_focus + 1).min(self.rows.len().saturating_sub(1));
239    }
240
241    pub fn prev_row(&mut self) {
242        self.row_focus = self.row_focus.saturating_sub(1);
243    }
244
245    /// Append a new row after `row_focus`, pre-seeded from the cached option
246    /// lists, and focus it.
247    pub fn add_row(&mut self) {
248        let insert_at = self.row_focus + 1;
249        let row = SplitRow::new(&self.account_options, &self.commodity_options);
250        self.rows.insert(insert_at, row);
251        self.row_focus = insert_at;
252    }
253
254    /// Focus the cell of `row` holding descriptor field `key`; an unknown key
255    /// focuses the row's first cell.
256    pub fn focus_cell(&mut self, row: usize, key: &str) {
257        self.row_focus = row.min(self.rows.len().saturating_sub(1));
258        self.col_focus = columns().position(|field| field.key == key).unwrap_or(0);
259    }
260
261    /// Focus column `col` of `row`, both held inside the rows and columns there are.
262    fn focus_at(&mut self, row: usize, col: usize) {
263        self.row_focus = row.min(self.rows.len().saturating_sub(1));
264        self.col_focus = col.min(column_count().saturating_sub(1));
265    }
266
267    /// Select `id` as the first row's From account until the option list
268    /// arrives and gives it its label.
269    pub fn preselect_from(&mut self, id: &str) {
270        let Some(row) = self.rows.first_mut() else {
271            return;
272        };
273        row.from.set_options(vec![SelectOption {
274            id: id.to_string(),
275            label: PENDING_LABEL.to_string(),
276        }]);
277    }
278
279    /// Remove the focused row; keeps at least one row.
280    pub fn remove_row(&mut self) {
281        if self.rows.len() <= 1 {
282            return;
283        }
284        self.rows.remove(self.row_focus);
285        if self.row_focus >= self.rows.len() {
286            self.row_focus = self.rows.len() - 1;
287        }
288    }
289
290    /// Cache the account options and apply them to every row's from/to selects.
291    /// A loaded cell keeps its selection and its exact text as the option id.
292    pub fn set_account_options(&mut self, options: Vec<SelectOption>) {
293        self.account_options = options;
294        for row in &mut self.rows {
295            row.bind_accounts(&self.account_options);
296        }
297    }
298
299    /// The accounts' only commodities; every row refills its declared fill targets from them.
300    pub fn set_account_fills(&mut self, fills: Vec<FormOption>) {
301        self.account_fills = fills;
302        for row in &mut self.rows {
303            declared_fills().for_each(|fill| row.refill(fill, &self.account_fills));
304        }
305    }
306
307    /// Open the focused select; it remembers every fill target its edits can refill, for Esc.
308    pub fn open_select(&mut self) {
309        let col = self.col_focus;
310        let Some(row) = self.rows.get_mut(self.row_focus) else {
311            return;
312        };
313        self.fills_at_open = declared_fills()
314            .filter(|(_, target)| *target >= col)
315            .filter_map(|(_, target)| Some((target, row.commodity_state(target)?)))
316            .collect();
317        if let Some(select) = row.select_mut(col) {
318            select.open_list();
319        }
320    }
321
322    /// Edit the focused select; a from-account change refills the row's commodity, a commodity
323    /// change makes it the user's.
324    pub fn edit_select(&mut self, edit: impl FnOnce(&mut SelectWidget)) {
325        let col = self.col_focus;
326        let Some(row) = self.rows.get_mut(self.row_focus) else {
327            return;
328        };
329        let Some(select) = row.select_mut(col) else {
330            return;
331        };
332        edit(select);
333        row.picked(col);
334        // Fills come in column order, so a chained fill reads its source's refill.
335        declared_fills()
336            .filter(|(source, _)| *source >= col)
337            .for_each(|fill| row.refill(fill, &self.account_fills));
338    }
339
340    /// Close the focused list on the value it had, commodity included.
341    pub fn cancel_select(&mut self) {
342        let col = self.col_focus;
343        let Some(row) = self.rows.get_mut(self.row_focus) else {
344            return;
345        };
346        if let Some(select) = row.select_mut(col) {
347            select.cancel();
348        }
349        for (target, state) in std::mem::take(&mut self.fills_at_open) {
350            row.restore_commodity(target, state);
351        }
352    }
353
354    /// Commodity counterpart of [`set_account_options`](Self::set_account_options).
355    pub fn set_commodity_options(&mut self, options: Vec<SelectOption>) {
356        self.commodity_options = options;
357        for row in &mut self.rows {
358            row.bind_commodities(&self.commodity_options);
359            declared_fills().for_each(|fill| row.refill(fill, &self.account_fills));
360        }
361    }
362
363    /// Replace all rows with the loaded ones; every cell, key and hidden text
364    /// is kept exactly. Guarantees at least one row.
365    pub fn load_rows(&mut self, rows: &[Row]) {
366        self.rows = rows.iter().map(SplitRow::loaded).collect();
367        self.row_focus = 0;
368        self.col_focus = 0;
369        self.tags_open = false;
370        if self.rows.is_empty() {
371            self.rows.push(SplitRow::new(
372                &self.account_options,
373                &self.commodity_options,
374            ));
375        }
376    }
377
378    /// Display summary for the generic [`Widget::display`](crate::widgets::Widget) contract.
379    #[must_use]
380    pub fn display(&self) -> String {
381        let n = self.rows.len();
382        format!(
383            "{n} split(s) [row {}, col {}]",
384            self.row_focus, self.col_focus
385        )
386    }
387}
388
389#[cfg(test)]
390mod same_commodity_tests;
391#[cfg(test)]
392mod tags_tests;
393#[cfg(test)]
394mod tests;