1
use super::*;
2
use crate::modal::Modal;
3
use crate::widgets::SelectOption;
4
use crate::widgets::splits::{COL_FROM, COL_FROM_COMM, COL_TO, COL_TO_COMM, COL_VALUE};
5
use ratatui::Terminal;
6
use ratatui::backend::TestBackend;
7
use ratatui::buffer::Buffer;
8
use ratatui::layout::Position;
9

            
10
const SPLITS: usize = 3;
11

            
12
120
pub(super) fn options(labels: &[&str]) -> Vec<SelectOption> {
13
120
    labels
14
120
        .iter()
15
        .map(|label| SelectOption {
16
300
            id: label.to_lowercase(),
17
300
            label: (*label).to_string(),
18
300
        })
19
        .collect()
20
120
}
21

            
22
22
fn splits_form(edit: impl FnOnce(&mut crate::widgets::SplitsWidget)) -> Form {
23
22
    let mut form = Form::transaction_create();
24
22
    form.focus = SPLITS;
25
22
    let Widget::Splits(sw) = &mut form.fields[SPLITS].widget else {
26
        panic!("field {SPLITS} is the splits");
27
    };
28
22
    sw.set_account_options(options(&["Cash", "Bank", "Food"]));
29
22
    sw.set_commodity_options(options(&["USD", "EUR"]));
30
22
    edit(sw);
31
22
    form
32
22
}
33

            
34
63
pub(super) fn drawn(form: Form, size: (u16, u16)) -> (Buffer, Option<Position>) {
35
63
    let mut app = crate::test_support::app();
36
63
    app.overlays.push(Modal::Form(form));
37
63
    let mut terminal = Terminal::new(TestBackend::new(size.0, size.1)).expect("test terminal");
38
63
    terminal
39
63
        .draw(|frame| crate::draw::draw(frame, &app, &mut crate::hits::Hits::default()))
40
63
        .expect("the frame draws");
41
63
    let backend = terminal.backend();
42
63
    let cursor = backend.cursor_visible().then(|| backend.cursor_position());
43
63
    (backend.buffer().clone(), cursor)
44
63
}
45

            
46
2571
pub(super) fn row_text(buf: &Buffer, y: u16) -> String {
47
249790
    (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect()
48
2571
}
49

            
50
86
pub(super) fn find(buf: &Buffer, text: &str) -> Vec<Position> {
51
86
    let mut found = Vec::new();
52
86
    for y in 0..buf.area.height {
53
2460
        let row = row_text(buf, y);
54
2460
        for (byte, _) in row.match_indices(text) {
55
88
            let x = u16::try_from(row[..byte].chars().count()).unwrap_or(0);
56
88
            found.push(Position::new(x, y));
57
        }
58
    }
59
86
    found
60
86
}
61

            
62
1411
pub(super) fn role_of(buf: &Buffer, at: Position) -> Option<tvui::Role> {
63
1411
    let theme = crate::test_support::dn_theme();
64
1411
    let style = buf[at].style();
65
1411
    [tvui::Role::InputFocused, tvui::Role::Input]
66
1411
        .into_iter()
67
2692
        .find(|role| {
68
2692
            let want = theme.style(*role);
69
2692
            (style.fg, style.bg) == (want.fg, want.bg)
70
2692
        })
71
1411
}
72

            
73
/// The first cell of the first row of the grid in `buf`, where the row number is.
74
8
fn first_row(buf: &Buffer) -> Position {
75
8
    find(buf, "1.")[0]
76
8
}
77

            
78
#[test]
79
1
fn the_focused_cell_is_input_focused_the_others_input_and_no_marks_are_left() {
80
1
    let form = splits_form(|sw| sw.col_focus = COL_TO);
81
1
    let (buf, _) = drawn(form, (120, 36));
82
1
    let row = first_row(&buf);
83
1
    let text = row_text(&buf, row.y);
84
1
    assert!(!text.contains(['[', ']', '▸']), "{text}");
85
1
    let cash = find(&buf, "Cash");
86
1
    let (from, to) = (cash[0], cash[1]);
87
1
    assert_eq!((from.y, to.y), (row.y, row.y));
88
1
    assert_eq!(role_of(&buf, from), Some(tvui::Role::Input));
89
1
    assert_eq!(role_of(&buf, to), Some(tvui::Role::InputFocused));
90
1
    assert_eq!(buf[(from.x + 8, from.y)].symbol(), " ".to_string());
91
1
}
92

            
93
#[test]
94
1
fn an_unfocused_grid_field_has_no_focused_cell() {
95
1
    let mut form = splits_form(|_| {});
96
1
    form.focus = 0;
97
1
    let (buf, _) = drawn(form, (120, 36));
98
1
    let from = find(&buf, "Cash")[0];
99
1
    assert_eq!(role_of(&buf, from), Some(tvui::Role::Input));
100
1
}
101

            
102
#[test]
103
1
fn the_cursor_is_at_the_edit_position_of_an_amount_cell() {
104
1
    let form = splits_form(|sw| {
105
1
        sw.col_focus = COL_VALUE;
106
1
        for c in "125".chars() {
107
3
            if let Some(crate::widgets::FocusedSubWidget::Amount(amount)) =
108
3
                sw.focused_subwidget_mut()
109
            {
110
3
                amount.insert_char(c);
111
            }
112
        }
113
1
        if let Some(crate::widgets::FocusedSubWidget::Amount(amount)) = sw.focused_subwidget_mut() {
114
1
            amount.as_editor_mut().move_left();
115
        }
116
1
    });
117
1
    let (buf, cursor) = drawn(form, (120, 36));
118
1
    let typed = find(&buf, "125")[0];
119
1
    assert_eq!(cursor, Some(Position::new(typed.x + 2, typed.y)));
120
1
    assert_eq!(role_of(&buf, typed), Some(tvui::Role::InputFocused));
121
1
}
122

            
123
#[test]
124
1
fn no_cursor_on_a_closed_select_cell() {
125
1
    let (_, cursor) = drawn(splits_form(|_| {}), (120, 36));
126
1
    assert_eq!(cursor, None);
127
1
}
128

            
129
#[test]
130
1
fn an_open_select_cell_lists_its_options_under_that_cell() {
131
1
    let mut xs = Vec::new();
132
1
    for col in [COL_FROM, COL_TO, COL_FROM_COMM, COL_TO_COMM] {
133
4
        let form = splits_form(|sw| {
134
4
            sw.col_focus = col;
135
4
            sw.open_select();
136
4
        });
137
4
        let (buf, _) = drawn(form, (120, 36));
138
4
        let row = first_row(&buf);
139
4
        let focused: Vec<u16> = (0..buf.area.width)
140
480
            .filter(|&x| role_of(&buf, Position::new(x, row.y)) == Some(tvui::Role::InputFocused))
141
            .collect();
142
4
        let cell = focused[0];
143
4
        assert_eq!(buf[(cell, row.y + 1)].symbol(), "┌", "column {col}");
144
4
        xs.push(cell);
145
    }
146
1
    let mut distinct = xs.clone();
147
1
    distinct.sort_unstable();
148
1
    distinct.dedup();
149
1
    assert_eq!(distinct.len(), 4, "{xs:?}");
150
1
}
151

            
152
#[test]
153
1
fn an_open_select_cell_shows_its_filter_with_the_cursor_after_it() {
154
1
    let form = splits_form(|sw| {
155
1
        sw.col_focus = COL_TO;
156
1
        sw.open_select();
157
1
        sw.edit_select(|select| select.filter_push('b'));
158
1
    });
159
1
    let (buf, cursor) = drawn(form, (120, 36));
160
1
    let row = first_row(&buf);
161
1
    let cell = (0..buf.area.width)
162
53
        .find(|&x| role_of(&buf, Position::new(x, row.y)) == Some(tvui::Role::InputFocused))
163
1
        .expect("a focused cell");
164
1
    assert_eq!(buf[(cell + 1, row.y)].symbol(), "b");
165
1
    assert_eq!(cursor, Some(Position::new(cell + 2, row.y)));
166
1
}
167

            
168
#[test]
169
1
fn the_tag_grid_draws_under_its_split_further_in() {
170
1
    let form = splits_form(|sw| {
171
1
        sw.open_tags();
172
1
        sw.add_tag();
173
1
    });
174
1
    let (buf, _) = drawn(form, (120, 36));
175
1
    let row = first_row(&buf);
176
1
    let header = find(&buf, "Name")
177
1
        .into_iter()
178
2
        .find(|at| at.y == row.y + 1)
179
1
        .expect("the tag header is under the split");
180
1
    assert_eq!(header.x, row.x + 4);
181
1
}
182

            
183
#[test]
184
1
fn the_grid_scrolls_by_rows_to_keep_the_focused_row_in_view() {
185
19
    let form = splits_form(|sw| (0..19).for_each(|_| sw.add_row()));
186
1
    let (buf, _) = drawn(form, (80, 24));
187
1
    assert!(find(&buf, " 1.").is_empty());
188
1
    let last = find(&buf, "20.");
189
1
    assert_eq!(last.len(), 1);
190
1
    assert_eq!(
191
1
        role_of(&buf, Position::new(last[0].x + 9, last[0].y)),
192
1
        Some(tvui::Role::InputFocused)
193
    );
194
1
}
195

            
196
#[test]
197
1
fn the_rows_grid_draws_its_cells_with_the_focus_colour() {
198
1
    let mut form = Form::transaction_create();
199
1
    let tags = form
200
1
        .fields
201
1
        .iter()
202
3
        .position(|field| matches!(field.widget, Widget::Rows(_)))
203
1
        .expect("the transaction form has a rows field");
204
1
    form.focus = tags;
205
1
    let Widget::Rows(rw) = &mut form.fields[tags].widget else {
206
        panic!("a rows field");
207
    };
208
1
    rw.add_row();
209
1
    let (buf, cursor) = drawn(form, (120, 36));
210
1
    let header = find(&buf, "Name")[0];
211
1
    let cell = Position::new(header.x, header.y + 1);
212
1
    assert_eq!(role_of(&buf, cell), Some(tvui::Role::InputFocused));
213
1
    assert_eq!(cursor, Some(Position::new(cell.x + 1, cell.y)));
214
1
}
215

            
216
4
fn typed_amount(sw: &mut crate::widgets::SplitsWidget, text: &str) {
217
4
    sw.col_focus = COL_VALUE;
218
4
    for c in text.chars() {
219
28
        if let Some(crate::widgets::FocusedSubWidget::Amount(amount)) = sw.focused_subwidget_mut() {
220
28
            amount.insert_char(c);
221
        }
222
    }
223
4
}
224

            
225
#[test]
226
1
fn a_long_amount_shows_whole_focused_and_unfocused() {
227
1
    for col in [COL_VALUE, COL_FROM] {
228
2
        let form = splits_form(|sw| {
229
2
            typed_amount(sw, "1234567");
230
2
            sw.col_focus = col;
231
2
        });
232
2
        let (buf, _) = drawn(form, (120, 36));
233
2
        assert_eq!(find(&buf, "1234567").len(), 1, "focus on column {col}");
234
    }
235
1
}
236

            
237
#[test]
238
1
fn a_long_tag_value_shows_whole() {
239
1
    let mut form = splits_form(|_| {});
240
1
    let tags = form
241
1
        .fields
242
1
        .iter()
243
3
        .position(|field| matches!(field.widget, Widget::Rows(_)))
244
1
        .expect("a rows field");
245
1
    let Widget::Rows(rw) = &mut form.fields[tags].widget else {
246
        panic!("a rows field");
247
    };
248
1
    rw.add_row();
249
1
    rw.col_focus = 1;
250
1
    if let Some(editor) = rw.focused_editor_mut() {
251
9
        "groceries".chars().for_each(|c| editor.insert_char(c));
252
    }
253
1
    form.focus = tags;
254
1
    let (buf, cursor) = drawn(form, (120, 36));
255
1
    let at = find(&buf, "groceries");
256
1
    assert_eq!(at.len(), 1);
257
1
    assert_eq!(cursor, Some(Position::new(at[0].x + 9, at[0].y)));
258
1
}
259

            
260
#[test]
261
1
fn an_open_select_with_a_long_filter_shows_it_whole() {
262
1
    let form = splits_form(|sw| {
263
1
        sw.col_focus = COL_TO;
264
1
        sw.open_select();
265
1
        "Banana"
266
1
            .chars()
267
6
            .for_each(|c| sw.edit_select(|s| s.filter_push(c)));
268
1
    });
269
1
    let (buf, cursor) = drawn(form, (120, 36));
270
1
    let row = first_row(&buf);
271
1
    let at = find(&buf, "Banana");
272
1
    assert_eq!(at[0].y, row.y);
273
1
    assert_eq!(cursor, Some(Position::new(at[0].x + 6, row.y)));
274
1
}
275

            
276
#[test]
277
1
fn the_cursor_of_a_squeezed_select_cell_stays_inside_the_cell() {
278
1
    let form = splits_form(|sw| {
279
1
        sw.col_focus = COL_TO;
280
1
        sw.open_select();
281
1
        "x".repeat(80)
282
1
            .chars()
283
80
            .for_each(|c| sw.edit_select(|s| s.filter_push(c)));
284
1
    });
285
1
    let (buf, cursor) = drawn(form, (50, 24));
286
1
    let cursor = cursor.expect("the cursor shows");
287
1
    let focused: Vec<u16> = (0..50)
288
50
        .filter(|&x| role_of(&buf, Position::new(x, cursor.y)) == Some(tvui::Role::InputFocused))
289
        .collect();
290
1
    assert!(focused.contains(&cursor.x), "{cursor:?} {focused:?}");
291
1
}
292

            
293
2
fn dialog_x(buf: &Buffer) -> u16 {
294
2
    find(buf, "╔")[0].x
295
2
}
296

            
297
#[test]
298
1
fn the_dialog_stays_put_while_an_amount_is_typed_up_to_the_reserve() {
299
1
    let (empty, _) = drawn(splits_form(|_| {}), (80, 24));
300
1
    let form = splits_form(|sw| typed_amount(sw, "5829.00"));
301
1
    let (typed, _) = drawn(form, (80, 24));
302
1
    assert_eq!(dialog_x(&typed), dialog_x(&empty));
303
1
    assert_eq!(find(&typed, "5829.00").len(), 1);
304
1
    let form = splits_form(|sw| typed_amount(sw, "1234567"));
305
1
    assert_eq!(find(&drawn(form, (80, 24)).0, "1234567").len(), 1);
306
1
}
307

            
308
3
fn converting(sw: &mut crate::widgets::SplitsWidget, key: &str) {
309
3
    sw.col_focus = COL_FROM_COMM;
310
3
    sw.edit_select(|select| select.select_id("usd"));
311
3
    sw.col_focus = COL_TO_COMM;
312
3
    sw.edit_select(|select| select.select_id("eur"));
313
3
    sw.focus_cell(0, key);
314
3
}
315

            
316
#[test]
317
1
fn a_to_amount_cell_past_the_edge_is_shifted_into_view_with_its_cursor() {
318
1
    let form = splits_form(|sw| converting(sw, "to-amount"));
319
1
    let (buf, cursor) = drawn(form, (80, 24));
320
1
    let row = find(&buf, "1.")[0].y;
321
1
    let focused: Vec<u16> = (0..80)
322
80
        .filter(|&x| role_of(&buf, Position::new(x, row)) == Some(tvui::Role::InputFocused))
323
        .collect();
324
1
    assert!(focused.len() >= 10, "{focused:?}");
325
1
    let cursor = cursor.expect("the cursor shows");
326
1
    assert_eq!((cursor.y, cursor.x), (row, focused[0] + 1));
327
1
    let form = splits_form(|sw| converting(sw, "from"));
328
1
    let (buf, _) = drawn(form, (80, 24));
329
1
    assert_eq!(
330
1
        find(&buf, "1.").len(),
331
1
        1,
332
        "the row starts at its own left again"
333
    );
334
1
}
335

            
336
#[test]
337
1
fn a_cell_cut_at_the_left_by_the_shift_is_not_drawn_at_all() {
338
1
    let form = splits_form(|sw| {
339
1
        sw.col_focus = COL_TO;
340
1
        sw.edit_select(|select| select.select_id("bank"));
341
1
        converting(sw, "to-amount");
342
1
    });
343
1
    let (buf, _) = drawn(form, (60, 24));
344
1
    let rows: String = (0..buf.area.height)
345
24
        .map(|y| row_text(&buf, y))
346
        .collect::<Vec<_>>()
347
1
        .join("\n");
348
1
    assert!(!rows.contains("Ban"), "{rows}");
349
1
}
350

            
351
#[test]
352
1
fn a_note_with_tildes_is_drawn_as_typed() {
353
1
    let mut grid = crate::widgets::grid::Grid::default();
354
1
    grid.push_note(0, "a~b~c");
355
1
    let rects = grid.cell_rects(ratatui::layout::Rect::new(0, 0, 10, 1), 0);
356
1
    let mut terminal = Terminal::new(TestBackend::new(10, 1)).expect("test terminal");
357
1
    terminal
358
1
        .draw(|frame| {
359
1
            let screen = frame.area();
360
1
            let theme = crate::test_support::dn_theme();
361
1
            let at = tvui::Place::from(screen);
362
1
            let mut hits = crate::hits::Hits::default();
363
1
            crate::draw::canvas::draw_placed(frame, at, screen, &mut hits, |canvas, _, _| {
364
1
                super::grid::draw_grid(canvas, &grid, &rects, &theme);
365
1
            });
366
1
        })
367
1
        .expect("the grid draws");
368
1
    assert_eq!(row_text(terminal.backend().buffer(), 0).trim_end(), "a~b~c");
369
1
}