1
use crate::app::App;
2
use crate::event::Intent;
3
use crate::form::{Field, Form, FormKind};
4
use crate::keymap;
5
use crate::widgets::rows::empty_note;
6
use crate::widgets::{Editor, SelectWidget, Widget};
7
use ratatui::text::Line;
8
use std::cell::Cell;
9
use tvui::Viewport;
10

            
11
use footer::footer_lines;
12

            
13
mod body;
14
pub(super) use body::FormBody;
15
mod footer;
16
mod grid;
17
mod text_area;
18

            
19
pub(super) use body::draw_form;
20
use body::{Block, Input, Popup};
21
use text_area::TextArea;
22

            
23
1533
pub(super) fn render_field<'a>(
24
1533
    i: usize,
25
1533
    f: &'a Field,
26
1533
    focus: usize,
27
1533
    width: usize,
28
1533
    suggestions: Option<&str>,
29
1533
    add_key: Option<&str>,
30
1533
) -> Block<'a> {
31
1533
    let focused = i == focus;
32
1533
    let label = format!("  {:<width$}", format!("{}:", f.label));
33
1533
    let column = u16::try_from(width + 3).unwrap_or(u16::MAX);
34
    let input =
35
687
        |text: String, cursor: usize, scroll: Option<&'a Cell<Viewport>>, open: Option<bool>| {
36
687
            Block::Input(Input {
37
687
                label: label.clone(),
38
687
                column,
39
687
                text,
40
687
                cursor,
41
687
                scroll,
42
687
                focused,
43
687
                combo: open.is_some(),
44
687
                caret: open.unwrap_or(true),
45
687
            })
46
687
        };
47
274
    let plain = |ed: &'a Editor| {
48
274
        input(
49
274
            ed.buffer().to_string(),
50
274
            ed.cursor(),
51
274
            Some(ed.scroll()),
52
274
            None,
53
274
        )
54
274
    };
55
1533
    match &f.widget {
56
595
        Widget::Text(ed) if ed.is_multiline() => {
57
306
            Block::Text(TextArea::new(label, column, ed, focused))
58
        }
59
289
        Widget::Text(ed) => input(
60
289
            ed.buffer().replace('\n', "\u{23ce}"),
61
289
            ed.cursor(),
62
289
            Some(ed.scroll()),
63
289
            None,
64
289
        ),
65
1
        Widget::Amount(aw) => plain(aw.editor()),
66
273
        Widget::Date(dw) => plain(dw.editor()),
67
124
        Widget::Select(sw) => input(
68
124
            sw.shown().to_string(),
69
124
            sw.query().chars().count(),
70
124
            Some(sw.scroll()),
71
124
            Some(sw.open),
72
124
        ),
73
269
        Widget::Splits(sw) => Block::Grid(
74
269
            sw.grid(focused, suggestions, add_key)
75
269
                .titled(format!("  {}:", f.label), focused),
76
269
        ),
77
        Widget::Rows(rw) => {
78
271
            let note = empty_note(&f.label.to_lowercase(), add_key);
79
271
            Block::Grid(
80
271
                rw.grid(focused, suggestions, Some(&note))
81
271
                    .titled(format!("  {}:", f.label), focused),
82
271
            )
83
        }
84
    }
85
1533
}
86

            
87
78
fn popup_of(sw: &SelectWidget) -> Popup<'_> {
88
78
    let options = sw.options();
89
    Popup {
90
78
        labels: sw
91
78
            .matches()
92
78
            .into_iter()
93
993
            .map(|index| options[index].label.clone())
94
            .collect(),
95
78
        selected: sw.focused_in_filtered(),
96
78
        window: sw.window(),
97
    }
98
78
}
99

            
100
464
pub(super) fn title(kind: FormKind) -> &'static str {
101
464
    match kind {
102
138
        FormKind::ConfigSet => "Set config",
103
9
        FormKind::Options => "Options",
104
1
        FormKind::SshKeyAdd => "Add SSH key",
105
        FormKind::CsvSave => "Save CSV",
106
2
        FormKind::Report(kind) => kind.descriptor().title,
107
11
        FormKind::CommodityCreate => "Create Commodity",
108
13
        FormKind::AccountCreate => "Create Account",
109
246
        FormKind::TransactionCreate => "Create Transaction",
110
24
        FormKind::TransactionEdit => "Edit Transaction",
111
        FormKind::AccountEdit => "Edit Account",
112
        FormKind::CommodityEdit => "Edit Commodity",
113
8
        FormKind::TagCreate => "Create Tag",
114
        FormKind::TagEdit => "Edit Tag",
115
2
        FormKind::TemplateCreate => "Create Template",
116
        FormKind::TemplateEdit => "Edit Template",
117
        FormKind::TemplatePick => "New from Template",
118
        FormKind::ScriptCreate => "Create Script",
119
2
        FormKind::ScriptEdit => "Edit Script",
120
5
        FormKind::AccountMerge => "Merge Accounts",
121
2
        FormKind::TransactionFilter => "Filter Transactions",
122
        FormKind::FilterAdd => "Add Filter Row",
123
        FormKind::FilterRow(shape) => shape.title(),
124
1
        FormKind::CommodityConvert => "Convert Amount",
125
    }
126
464
}
127

            
128
463
pub(super) fn form_body<'a>(
129
463
    form: &'a Form,
130
463
    (pending, active): (bool, bool),
131
463
    app: &App,
132
463
) -> body::FormBody<'a> {
133
463
    let keys = keymap::in_form(app, form);
134
463
    let popup = form.focused_select().filter(|sw| sw.open && active);
135
463
    let focus = if active { form.focus } else { usize::MAX };
136
463
    let footer = match pending {
137
5
        true => vec!["Submitting… (input locked until the server replies)".to_string()],
138
458
        false => footer_lines(form.kind),
139
    };
140
1530
    let width = form.fields.iter().map(|f| f.label.len()).max().unwrap_or(0) + 1;
141
463
    let suggestions = form.suggestion_line(keys.key(Intent::CompleteSuggestion));
142
463
    let add_key = keymap::in_rows(app).key(Intent::SplitAddRow);
143
1530
    let blocks = form.fields.iter().enumerate().map(|(i, f)| {
144
1530
        let shown = suggestions.as_deref().filter(|_| i == focus);
145
1530
        render_field(i, f, focus, width, shown, add_key.as_deref())
146
1530
    });
147
463
    let mut tail = super::messages::message_lines("! ", &form.errors);
148
463
    if !footer.is_empty() {
149
289
        tail.push(Line::from(""));
150
289
        tail.extend(footer.into_iter().map(Line::from));
151
174
    }
152
    body::FormBody {
153
463
        title: title(form.kind),
154
463
        notices: super::messages::message_lines("note: ", &form.notices),
155
463
        blocks: blocks.collect(),
156
463
        tail,
157
463
        focus: form.focus,
158
463
        button: form.focused_button().filter(|_| active),
159
463
        pressed: app.pressed_button().filter(|_| !pending && active),
160
463
        dragging: app.dragging_layer() && !pending && active,
161
463
        active,
162
463
        popup: popup.map(popup_of),
163
    }
164
463
}
165

            
166
#[cfg(test)]
167
mod body_tests;
168
#[cfg(test)]
169
mod empty_note_tests;
170
#[cfg(test)]
171
mod field_look_tests;
172
#[cfg(test)]
173
mod grid_tests;
174
#[cfg(test)]
175
mod history_tests;
176
#[cfg(test)]
177
mod select_tests;
178
#[cfg(test)]
179
mod split_columns_tests;
180
#[cfg(test)]
181
pub(super) mod tests;
182
#[cfg(test)]
183
mod text_area_tests;