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

            
25
use cli_core::forms::FormOption;
26
use forms::{Kind, Row, TRANSACTION_CREATE};
27

            
28
use crate::widgets::{AmountWidget, SelectOption, SelectWidget, WidgetKind};
29

            
30
mod grid;
31
mod row;
32
mod tags;
33
use row::PENDING_LABEL;
34

            
35
pub use row::SplitRow;
36

            
37
/// The row fields of a form's `splits` field.
38
11700
pub fn rows_of(form: &'static forms::Form) -> &'static [forms::Field] {
39
11700
    form.fields
40
11700
        .iter()
41
46815
        .find_map(|field| match field.kind {
42
20554
            Kind::Rows { fields, .. } if field.key == "splits" => Some(fields),
43
36584
            _ => None,
44
46815
        })
45
        .unwrap_or_default()
46
11700
}
47

            
48
/// The widget's columns: create and edit share one split row definition
49
/// (pinned by a test), so either descriptor names them.
50
9650
pub fn row_fields() -> &'static [forms::Field] {
51
9650
    rows_of(&TRANSACTION_CREATE)
52
9650
}
53

            
54
/// The cells of a split tag row; create and edit share them like the split row.
55
714
pub fn tag_fields() -> &'static [forms::Field] {
56
714
    TRANSACTION_CREATE
57
714
        .fields
58
714
        .iter()
59
3570
        .find_map(|field| match field.kind {
60
2142
            Kind::Rows { fields, .. } if field.nested_under() == Some("splits") => Some(fields),
61
2856
            _ => None,
62
3570
        })
63
        .unwrap_or_default()
64
714
}
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.
68
9649
pub fn columns() -> impl Iterator<Item = &'static forms::Field> {
69
9649
    row_fields()
70
9649
        .iter()
71
45419
        .filter(|field| field.key != "key" && field.kind != Kind::Hidden)
72
9649
}
73

            
74
/// The `(source, target)` columns of each fill the descriptor declares.
75
699
fn declared_fills() -> impl Iterator<Item = (usize, usize)> {
76
699
    columns()
77
699
        .enumerate()
78
4194
        .filter_map(|(source, field)| match field.kind {
79
            Kind::Select {
80
                fills: Some(key), ..
81
1398
            } => columns()
82
4893
                .position(|target| target.key == key)
83
1398
                .map(|target| (source, target)),
84
2796
            _ => None,
85
4194
        })
86
699
}
87

            
88
79
fn column_count() -> usize {
89
79
    columns().count()
90
79
}
91

            
92
// Slot indices are pinned to the descriptor keys by a unit test.
93
pub const COL_FROM: usize = 0;
94
pub const COL_TO: usize = 1;
95
pub const COL_FROM_COMM: usize = 2;
96
pub const COL_TO_COMM: usize = 3;
97
pub const COL_VALUE: usize = 4;
98
pub const COL_TO_AMOUNT: usize = 5;
99

            
100
/// Mutable reference to the focused sub-widget for intent routing in `event.rs`.
101
pub 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)]
111
pub 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.
128
impl Default for SplitsWidget {
129
427
    fn default() -> Self {
130
427
        Self {
131
427
            rows: vec![SplitRow::new(&[], &[])],
132
427
            row_focus: 0,
133
427
            col_focus: 0,
134
427
            account_options: Vec::new(),
135
427
            commodity_options: Vec::new(),
136
427
            account_fills: Vec::new(),
137
427
            tags_open: false,
138
427
            tags_present: false,
139
427
            fills_at_open: Vec::new(),
140
427
        }
141
427
    }
142
}
143

            
144
impl SplitsWidget {
145
    /// Read-only view of the rows (for validation and display).
146
    #[must_use]
147
676
    pub fn rows(&self) -> &[SplitRow] {
148
676
        &self.rows
149
676
    }
150

            
151
    /// WidgetKind of the focused column.
152
    #[must_use]
153
183
    pub fn focused_subwidget_kind(&self) -> WidgetKind {
154
183
        if let Some(tags) = self.tags() {
155
            return tags.focused_kind();
156
183
        }
157
183
        SplitRow::col_kind(self.col_focus)
158
183
    }
159

            
160
    /// Mutable reference to the focused sub-widget for intent routing.
161
281
    pub fn focused_subwidget_mut(&mut self) -> Option<FocusedSubWidget<'_>> {
162
281
        let row = self.rows.get_mut(self.row_focus)?;
163
281
        match SplitRow::col_kind(self.col_focus) {
164
98
            WidgetKind::Select => row.select_mut(self.col_focus).map(FocusedSubWidget::Select),
165
183
            _ => row.amount_mut(self.col_focus).map(FocusedSubWidget::Amount),
166
        }
167
281
    }
168

            
169
    /// The focused cell's select, a tag's while the tags are open; `None` on another cell.
170
    #[must_use]
171
1067
    pub fn focused_select(&self) -> Option<&SelectWidget> {
172
1067
        if let Some(tags) = self.tags() {
173
94
            return tags.focused_select();
174
973
        }
175
973
        self.rows.get(self.row_focus)?.select(self.col_focus)
176
1067
    }
177

            
178
103
    pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
179
103
        if self.tags_open() {
180
23
            return self
181
23
                .tags_mut()
182
23
                .and_then(super::rows::RowsWidget::focused_select_mut);
183
80
        }
184
80
        match self.focused_subwidget_mut()? {
185
63
            FocusedSubWidget::Select(select) => Some(select),
186
17
            FocusedSubWidget::Amount(_) => None,
187
        }
188
103
    }
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
12
    pub fn advance_cell(&mut self) {
194
12
        if self.col_focus + 1 < column_count() {
195
10
            self.col_focus += 1;
196
2
        } else if self.row_focus + 1 < self.rows.len() {
197
1
            self.row_focus += 1;
198
1
            self.col_focus = 0;
199
1
        }
200
12
    }
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
4
    pub fn retreat_cell(&mut self) {
205
4
        if self.col_focus > 0 {
206
2
            self.col_focus -= 1;
207
2
        } else if self.row_focus > 0 {
208
1
            self.row_focus -= 1;
209
1
            self.col_focus = column_count().saturating_sub(1);
210
1
        }
211
4
    }
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
10
    pub fn at_first_cell(&self) -> bool {
217
10
        self.row_focus == 0 && self.col_focus == 0
218
10
    }
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
10
    pub fn at_last_cell(&self) -> bool {
224
10
        self.row_focus + 1 == self.rows.len() && self.col_focus + 1 == column_count()
225
10
    }
226

            
227
    #[must_use]
228
21
    pub fn at_first_row(&self) -> bool {
229
21
        self.row_focus == 0
230
21
    }
231

            
232
    #[must_use]
233
21
    pub fn at_last_row(&self) -> bool {
234
21
        self.row_focus + 1 >= self.rows.len()
235
21
    }
236

            
237
14
    pub fn next_row(&mut self) {
238
14
        self.row_focus = (self.row_focus + 1).min(self.rows.len().saturating_sub(1));
239
14
    }
240

            
241
6
    pub fn prev_row(&mut self) {
242
6
        self.row_focus = self.row_focus.saturating_sub(1);
243
6
    }
244

            
245
    /// Append a new row after `row_focus`, pre-seeded from the cached option
246
    /// lists, and focus it.
247
130
    pub fn add_row(&mut self) {
248
130
        let insert_at = self.row_focus + 1;
249
130
        let row = SplitRow::new(&self.account_options, &self.commodity_options);
250
130
        self.rows.insert(insert_at, row);
251
130
        self.row_focus = insert_at;
252
130
    }
253

            
254
    /// Focus the cell of `row` holding descriptor field `key`; an unknown key
255
    /// focuses the row's first cell.
256
19
    pub fn focus_cell(&mut self, row: usize, key: &str) {
257
19
        self.row_focus = row.min(self.rows.len().saturating_sub(1));
258
91
        self.col_focus = columns().position(|field| field.key == key).unwrap_or(0);
259
19
    }
260

            
261
    /// Focus column `col` of `row`, both held inside the rows and columns there are.
262
60
    fn focus_at(&mut self, row: usize, col: usize) {
263
60
        self.row_focus = row.min(self.rows.len().saturating_sub(1));
264
60
        self.col_focus = col.min(column_count().saturating_sub(1));
265
60
    }
266

            
267
    /// Select `id` as the first row's From account until the option list
268
    /// arrives and gives it its label.
269
7
    pub fn preselect_from(&mut self, id: &str) {
270
7
        let Some(row) = self.rows.first_mut() else {
271
            return;
272
        };
273
7
        row.from.set_options(vec![SelectOption {
274
7
            id: id.to_string(),
275
7
            label: PENDING_LABEL.to_string(),
276
7
        }]);
277
7
    }
278

            
279
    /// Remove the focused row; keeps at least one row.
280
8
    pub fn remove_row(&mut self) {
281
8
        if self.rows.len() <= 1 {
282
1
            return;
283
7
        }
284
7
        self.rows.remove(self.row_focus);
285
7
        if self.row_focus >= self.rows.len() {
286
5
            self.row_focus = self.rows.len() - 1;
287
2
        }
288
8
    }
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
190
    pub fn set_account_options(&mut self, options: Vec<SelectOption>) {
293
190
        self.account_options = options;
294
190
        for row in &mut self.rows {
295
257
            row.bind_accounts(&self.account_options);
296
        }
297
190
    }
298

            
299
    /// The accounts' only commodities; every row refills its declared fill targets from them.
300
54
    pub fn set_account_fills(&mut self, fills: Vec<FormOption>) {
301
54
        self.account_fills = fills;
302
54
        for row in &mut self.rows {
303
164
            declared_fills().for_each(|fill| row.refill(fill, &self.account_fills));
304
        }
305
54
    }
306

            
307
    /// Open the focused select; it remembers every fill target its edits can refill, for Esc.
308
57
    pub fn open_select(&mut self) {
309
57
        let col = self.col_focus;
310
57
        let Some(row) = self.rows.get_mut(self.row_focus) else {
311
            return;
312
        };
313
57
        self.fills_at_open = declared_fills()
314
114
            .filter(|(_, target)| *target >= col)
315
109
            .filter_map(|(_, target)| Some((target, row.commodity_state(target)?)))
316
            .collect();
317
57
        if let Some(select) = row.select_mut(col) {
318
57
            select.open_list();
319
        }
320
57
    }
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
331
    pub fn edit_select(&mut self, edit: impl FnOnce(&mut SelectWidget)) {
325
331
        let col = self.col_focus;
326
331
        let Some(row) = self.rows.get_mut(self.row_focus) else {
327
            return;
328
        };
329
331
        let Some(select) = row.select_mut(col) else {
330
            return;
331
        };
332
331
        edit(select);
333
331
        row.picked(col);
334
        // Fills come in column order, so a chained fill reads its source's refill.
335
331
        declared_fills()
336
662
            .filter(|(source, _)| *source >= col)
337
468
            .for_each(|fill| row.refill(fill, &self.account_fills));
338
331
    }
339

            
340
    /// Close the focused list on the value it had, commodity included.
341
12
    pub fn cancel_select(&mut self) {
342
12
        let col = self.col_focus;
343
12
        let Some(row) = self.rows.get_mut(self.row_focus) else {
344
            return;
345
        };
346
12
        if let Some(select) = row.select_mut(col) {
347
12
            select.cancel();
348
        }
349
12
        for (target, state) in std::mem::take(&mut self.fills_at_open) {
350
23
            row.restore_commodity(target, state);
351
        }
352
12
    }
353

            
354
    /// Commodity counterpart of [`set_account_options`](Self::set_account_options).
355
165
    pub fn set_commodity_options(&mut self, options: Vec<SelectOption>) {
356
165
        self.commodity_options = options;
357
165
        for row in &mut self.rows {
358
228
            row.bind_commodities(&self.commodity_options);
359
456
            declared_fills().for_each(|fill| row.refill(fill, &self.account_fills));
360
        }
361
165
    }
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
97
    pub fn load_rows(&mut self, rows: &[Row]) {
366
97
        self.rows = rows.iter().map(SplitRow::loaded).collect();
367
97
        self.row_focus = 0;
368
97
        self.col_focus = 0;
369
97
        self.tags_open = false;
370
97
        if self.rows.is_empty() {
371
18
            self.rows.push(SplitRow::new(
372
18
                &self.account_options,
373
18
                &self.commodity_options,
374
18
            ));
375
79
        }
376
97
    }
377

            
378
    /// Display summary for the generic [`Widget::display`](crate::widgets::Widget) contract.
379
    #[must_use]
380
1
    pub fn display(&self) -> String {
381
1
        let n = self.rows.len();
382
1
        format!(
383
1
            "{n} split(s) [row {}, col {}]",
384
1
            self.row_focus, self.col_focus
385
        )
386
1
    }
387
}
388

            
389
#[cfg(test)]
390
mod same_commodity_tests;
391
#[cfg(test)]
392
mod tags_tests;
393
#[cfg(test)]
394
mod tests;