1
//! Generic input form used by all overlay modals that collect user input.
2
//!
3
//! Replaces the per-modal `ConfigSetModal` duplicates.
4
//! [`Form`] is a list of [`Field`]s with a focused index and a [`FormKind`]
5
//! that identifies the submit target.
6

            
7
mod descriptor;
8
mod filter_field;
9
mod filter_row;
10
mod options;
11
mod pointer;
12
mod suggest;
13

            
14
use forms::FormValues;
15

            
16
pub use filter_row::RowShape;
17
pub use options::OPTIONS_BUTTONS;
18

            
19
use crate::event::Intent;
20
use crate::modal::Spec;
21
use crate::overlay::Placement;
22
use crate::tabs::reports::ReportKind;
23
use crate::widgets::{Editor, Hints, SelectOption, SelectWidget, Widget, WidgetKind};
24
use crate::window::Origin;
25

            
26
#[cfg(test)]
27
mod tests;
28

            
29
/// The buttons of a form dialog, in focus order, and the intent each presses.
30
pub const BUTTONS: [Spec; 2] = [("~O~K", Intent::Submit), ("~C~lose", Intent::CloseTopmost)];
31

            
32
/// A single labelled input field.
33
#[derive(Debug)]
34
pub struct Field {
35
    /// Descriptor key for descriptor-backed forms; `None` for hand-built ones.
36
    pub key: Option<&'static str>,
37
    pub label: &'static str,
38
    pub widget: Widget,
39
}
40

            
41
/// What to do when the form is submitted.
42
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43
pub enum FormKind {
44
    ConfigSet,
45
    /// The Options dialog: theme, keymap and colour depth.
46
    Options,
47
    /// Register a public key for the SSH keys tab.
48
    SshKeyAdd,
49
    /// Ask for the path the shown CSV is saved to.
50
    CsvSave,
51
    Report(ReportKind),
52
    TagCreate,
53
    /// Edit an existing tag; its id and revision are hidden values.
54
    TagEdit,
55
    TemplateCreate,
56
    /// Edit an existing template; its id and revision are hidden values.
57
    TemplateEdit,
58
    ScriptCreate,
59
    /// Edit an existing script; its id and revision are hidden values.
60
    ScriptEdit,
61
    /// Pick the template a new transaction starts from.
62
    TemplatePick,
63
    CommodityCreate,
64
    CommodityConvert,
65
    AccountCreate,
66
    TransactionCreate,
67
    /// Edit an existing transaction; its id and revision are hidden values.
68
    TransactionEdit,
69
    /// Edit an existing account; its id and revision are hidden values.
70
    AccountEdit,
71
    /// Edit an existing commodity; its id and revision are hidden values.
72
    CommodityEdit,
73
    /// Merge one account into another, after a confirmation.
74
    AccountMerge,
75
    /// The Transactions tab filter: the `transaction-query` fields minus paging.
76
    TransactionFilter,
77
    /// Pick the kind of a new filter builder row.
78
    FilterAdd,
79
    /// Fill one filter builder row.
80
    FilterRow(RowShape),
81
}
82

            
83
/// A generic multi-field input form.
84
#[derive(Debug)]
85
pub struct Form {
86
    pub fields: Vec<Field>,
87
    /// The stop of the focus ring: a field, or past the last field one of the form's buttons.
88
    pub focus: usize,
89
    pub kind: FormKind,
90
    /// Descriptor `hidden` fields: carried to the submit, never rendered.
91
    pub hidden: Vec<(&'static str, String)>,
92
    /// Server rejection messages shown below the fields after an unlock.
93
    pub errors: Vec<String>,
94
    /// Server notes about the loaded entity, shown above the fields.
95
    pub notices: Vec<String>,
96
    /// Values the form was opened with, taken when it joins the overlay stack.
97
    pub baseline: Option<FormValues>,
98
    /// Answers to the tag name and value lookups, kept for the form's lifetime.
99
    pub hints: Hints,
100
    /// The text typed before the current run of completions, and the last one filled.
101
    pub completing: Option<(String, String)>,
102
    /// The window the form's dialog started from; it travels with the form while the stack is
103
    /// empty, between submit and reply.
104
    pub origin: Option<Origin>,
105
    /// Where the user moved or sized the dialog; it travels with the form through submit and
106
    /// reopen.
107
    pub placement: Placement,
108
}
109

            
110
impl Form {
111
    /// The `config-set` form: a key and a value.
112
    #[must_use]
113
193
    pub fn config_set() -> Self {
114
193
        Self::from_descriptor(&forms::CONFIG_SET, FormKind::ConfigSet)
115
193
    }
116

            
117
    /// The `ssh-key-add` form: a public key line and an optional label.
118
    #[must_use]
119
6
    pub fn ssh_key_add() -> Self {
120
6
        Self::from_descriptor(&forms::SSH_KEY_ADD, FormKind::SshKeyAdd)
121
6
    }
122

            
123
    /// The save-path prompt of the CSV pane, offering `path`.
124
    #[must_use]
125
1
    pub fn csv_save(path: &str) -> Self {
126
1
        let mut form = Self::from_descriptor(&descriptor::CSV_SAVE, FormKind::CsvSave);
127
1
        for field in &mut form.fields {
128
1
            field.widget.set_text(path);
129
        }
130
1
        form
131
1
    }
132

            
133
    /// A report's setup form from its descriptor: dates blank and the other
134
    /// fields at their defaults unless `prefill` holds them.
135
    #[must_use]
136
115
    pub fn report(kind: ReportKind, prefill: &forms::FormValues) -> Self {
137
115
        let mut form = Self::from_descriptor(kind.descriptor(), FormKind::Report(kind));
138
115
        for field in &mut form.fields {
139
580
            if matches!(field.widget, Widget::Date(_)) {
140
230
                field.widget.set_text("");
141
350
            }
142
        }
143
115
        form.load(prefill);
144
115
        form
145
115
    }
146

            
147
    /// The `commodity-create` form: symbol and name.
148
    #[must_use]
149
30
    pub fn commodity_create() -> Self {
150
30
        Self::from_descriptor(&forms::COMMODITY_CREATE, FormKind::CommodityCreate)
151
30
    }
152

            
153
    /// The `convert` form: amount and two commodity selects, filled from `form-options`.
154
    #[must_use]
155
14
    pub fn commodity_convert() -> Self {
156
14
        Self::from_descriptor(&forms::CONVERT, FormKind::CommodityConvert)
157
14
    }
158

            
159
    /// The `account-create` form: a name and a parent select.
160
    #[must_use]
161
23
    pub fn account_create() -> Self {
162
23
        Self::from_descriptor(&forms::ACCOUNT_CREATE, FormKind::AccountCreate)
163
23
    }
164

            
165
    /// Transaction create form built from the shared descriptor: date, note, splits.
166
    #[must_use]
167
295
    pub fn transaction_create() -> Self {
168
295
        Self::from_descriptor(&forms::TRANSACTION_CREATE, FormKind::TransactionCreate)
169
295
    }
170

            
171
    /// The `account-merge` form: two account selects.
172
    #[must_use]
173
23
    pub fn account_merge() -> Self {
174
23
        Self::from_descriptor(&forms::ACCOUNT_MERGE, FormKind::AccountMerge)
175
23
    }
176

            
177
    /// The Transactions tab filter form, prefilled with the active `filter`.
178
    #[must_use]
179
15
    pub fn transaction_filter(filter: &FormValues) -> Self {
180
15
        let mut form = Self::from_fields(
181
15
            forms::TRANSACTION_QUERY.filter_fields(),
182
15
            FormKind::TransactionFilter,
183
15
        );
184
15
        for field in &mut form.fields {
185
45
            if matches!(field.widget, Widget::Date(_)) {
186
30
                field.widget.set_text("");
187
15
            }
188
        }
189
15
        form.load(filter);
190
15
        form
191
15
    }
192

            
193
    /// The label the select field `key` shows.
194
    #[must_use]
195
52
    pub fn select_label(&self, key: &str) -> Option<&str> {
196
52
        self.fields
197
52
            .iter()
198
88
            .find(|field| field.key == Some(key))
199
52
            .and_then(|field| match &field.widget {
200
52
                Widget::Select(sw) => Some(sw.display()),
201
                _ => None,
202
52
            })
203
52
    }
204

            
205
    /// The `tag-create` form from the shared descriptor.
206
    #[must_use]
207
27
    pub fn tag_create() -> Self {
208
27
        Self::from_descriptor(&forms::TAG_CREATE, FormKind::TagCreate)
209
27
    }
210

            
211
    /// Tag edit form built from the shared descriptor and the values
212
    /// `load-form` returned. Hidden values ride along unrendered.
213
    #[must_use]
214
10
    pub fn tag_edit(loaded: &forms::FormValues) -> Self {
215
10
        let mut form = Self::from_descriptor(&forms::TAG_EDIT, FormKind::TagEdit);
216
10
        form.load(loaded);
217
10
        form
218
10
    }
219

            
220
    /// The `template-create` form from the shared descriptor.
221
    #[must_use]
222
6
    pub fn template_create() -> Self {
223
6
        Self::from_descriptor(&forms::TEMPLATE_CREATE, FormKind::TemplateCreate)
224
6
    }
225

            
226
    /// Template edit form built from the shared descriptor and the values
227
    /// `load-form` returned. Hidden values ride along unrendered.
228
    #[must_use]
229
7
    pub fn template_edit(loaded: &forms::FormValues) -> Self {
230
7
        let mut form = Self::from_descriptor(&forms::TEMPLATE_EDIT, FormKind::TemplateEdit);
231
7
        form.load(loaded);
232
7
        form
233
7
    }
234

            
235
    /// The template picker over `options`.
236
    #[must_use]
237
6
    pub fn template_pick(options: &[SelectOption]) -> Self {
238
6
        let mut form = Self::from_descriptor(&descriptor::TEMPLATE_PICK, FormKind::TemplatePick);
239
6
        for field in &mut form.fields {
240
6
            if let Widget::Select(select) = &mut field.widget {
241
6
                select.set_options(options.to_vec());
242
            }
243
        }
244
6
        form
245
6
    }
246

            
247
    /// Transaction create form filled from the `load-form` draft of a template.
248
    #[must_use]
249
4
    pub fn transaction_from_template(loaded: &forms::FormValues) -> Self {
250
4
        let mut form = Self::transaction_create();
251
4
        form.load(loaded);
252
4
        form
253
4
    }
254

            
255
    /// The `script-create` form from the shared descriptor.
256
    #[must_use]
257
7
    pub fn script_create() -> Self {
258
7
        Self::from_descriptor(&forms::SCRIPT_CREATE, FormKind::ScriptCreate)
259
7
    }
260

            
261
    /// Script edit form built from the shared descriptor and the values
262
    /// `load-form` returned. Hidden values ride along unrendered.
263
    #[must_use]
264
5
    pub fn script_edit(loaded: &forms::FormValues) -> Self {
265
5
        let mut form = Self::from_descriptor(&forms::SCRIPT_EDIT, FormKind::ScriptEdit);
266
5
        form.load(loaded);
267
5
        form
268
5
    }
269

            
270
    /// Transaction edit form built from the shared descriptor and the values
271
    /// `load-form` returned. Hidden values ride along unrendered.
272
    #[must_use]
273
65
    pub fn transaction_edit(loaded: &forms::FormValues) -> Self {
274
65
        let mut form = Self::from_descriptor(&forms::TRANSACTION_EDIT, FormKind::TransactionEdit);
275
65
        form.load(loaded);
276
65
        form
277
65
    }
278

            
279
    /// Account edit form built from the shared descriptor and the values
280
    /// `load-form` returned. Hidden values ride along unrendered.
281
    #[must_use]
282
17
    pub fn account_edit(loaded: &forms::FormValues) -> Self {
283
17
        let mut form = Self::from_descriptor(&forms::ACCOUNT_EDIT, FormKind::AccountEdit);
284
17
        form.load(loaded);
285
17
        form
286
17
    }
287

            
288
    /// Commodity edit form built from the shared descriptor and the values
289
    /// `load-form` returned. Hidden values ride along unrendered.
290
    #[must_use]
291
8
    pub fn commodity_edit(loaded: &forms::FormValues) -> Self {
292
8
        let mut form = Self::from_descriptor(&forms::COMMODITY_EDIT, FormKind::CommodityEdit);
293
8
        form.load(loaded);
294
8
        form
295
8
    }
296

            
297
    /// Closes the open split tag list; `false` when none was open.
298
35
    pub fn close_tags(&mut self) -> bool {
299
111
        self.fields.iter_mut().any(|field| match &mut field.widget {
300
2
            Widget::Splits(sw) => sw.close_tags(),
301
109
            _ => false,
302
111
        })
303
35
    }
304

            
305
    /// Closes the focused select's open list; `false` when none was open.
306
430
    pub fn close_select(&mut self) -> bool {
307
430
        match self.focused_select_mut() {
308
127
            Some(select) if select.open => {
309
1
                select.close();
310
1
                true
311
            }
312
429
            _ => false,
313
        }
314
430
    }
315

            
316
    /// The select the focus is on: the field itself or the focused cell of a grid.
317
    #[must_use]
318
3513
    pub fn focused_select(&self) -> Option<&SelectWidget> {
319
3513
        match &self.fields.get(self.focus)?.widget {
320
589
            Widget::Select(select) => Some(select),
321
1065
            Widget::Splits(sw) => sw.focused_select(),
322
76
            Widget::Rows(rw) => rw.focused_select(),
323
1682
            _ => None,
324
        }
325
3513
    }
326

            
327
430
    pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
328
430
        match &mut self.fields.get_mut(self.focus)?.widget {
329
89
            Widget::Select(select) => Some(select),
330
74
            Widget::Splits(sw) => sw.focused_select_mut(),
331
12
            Widget::Rows(rw) => rw.focused_select_mut(),
332
208
            _ => None,
333
        }
334
430
    }
335

            
336
    /// Advance or retreat focus by one step through the fields, then the buttons, wrapping.
337
295
    pub fn cycle(&mut self, forward: bool) {
338
295
        self.close_select();
339
295
        let len = self.fields.len() + self.buttons().len();
340
295
        self.focus = if forward {
341
251
            (self.focus + 1) % len
342
        } else {
343
44
            (self.focus + len - 1) % len
344
        };
345
295
    }
346

            
347
    /// Focuses field `index`; an index past the fields changes nothing.
348
107
    pub fn focus_field(&mut self, index: usize) {
349
107
        if index < self.fields.len() {
350
106
            self.close_select();
351
106
            self.focus = index;
352
1
        }
353
107
    }
354

            
355
    /// The index of the focused button when the focus is on the buttons.
356
    #[must_use]
357
849
    pub fn focused_button(&self) -> Option<usize> {
358
849
        self.focus.checked_sub(self.fields.len())
359
849
    }
360

            
361
    /// Mutable reference to the currently focused field, if any.
362
1145
    pub fn focused_field_mut(&mut self) -> Option<&mut Field> {
363
1145
        self.fields.get_mut(self.focus)
364
1145
    }
365

            
366
    /// Mutable reference to the inner [`Editor`] of the focused field.
367
    ///
368
    /// Returns `None` when the form is empty or the focused widget is not
369
    /// `Text`, `Amount`, or `Date` (i.e. a `Select` or `Splits`).
370
25
    pub fn focused_editor_mut(&mut self) -> Option<&mut Editor> {
371
25
        self.focused_field_mut()
372
25
            .and_then(|f| f.widget.as_text_mut())
373
25
    }
374

            
375
    /// Widget kind of the focused field, or `None` when the form is empty.
376
    #[must_use]
377
4414
    pub fn focused_widget_kind(&self) -> Option<WidgetKind> {
378
4414
        self.fields.get(self.focus).map(|f| f.widget.kind())
379
4414
    }
380

            
381
    /// When the focused field is a Splits or Rows widget, returns `(at_first_cell,
382
    /// at_last_cell)`; Tab/BackTab yield to the field cycle at those edges.
383
    #[must_use]
384
29
    pub fn focused_cells_boundary(&self) -> Option<(bool, bool)> {
385
29
        match self.fields.get(self.focus)?.widget {
386
28
            Widget::Splits(ref sw) if sw.tags_open() => Some((false, false)),
387
9
            Widget::Splits(ref sw) => Some((sw.at_first_cell(), sw.at_last_cell())),
388
1
            Widget::Rows(ref rw) => Some((rw.at_first_cell(), rw.at_last_cell())),
389
            _ => None,
390
        }
391
29
    }
392

            
393
    /// `(at_first_row, at_last_row)` of the focused grid or text area, where Up/Down yield
394
    /// to the field cycle; `None` where Up/Down step nothing of the form (a field, a button).
395
    #[must_use]
396
53
    pub fn focused_vertical_boundary(&self) -> Option<(bool, bool)> {
397
53
        match self.fields.get(self.focus)?.widget {
398
26
            Widget::Splits(ref sw) if sw.tags_open() => sw
399
5
                .tags()
400
5
                .map(|tags| (tags.at_first_row(), tags.at_last_row())),
401
21
            Widget::Splits(ref sw) => Some((sw.at_first_row(), sw.at_last_row())),
402
6
            Widget::Rows(ref rw) => Some((rw.at_first_row(), rw.at_last_row())),
403
21
            Widget::Text(ref ed) if ed.is_multiline() => {
404
21
                Some((ed.at_first_line(), ed.at_last_line()))
405
            }
406
            _ => None,
407
        }
408
53
    }
409
}