Skip to main content

tui/
form.rs

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
7mod descriptor;
8mod filter_field;
9mod filter_row;
10mod options;
11mod pointer;
12mod suggest;
13
14use forms::FormValues;
15
16pub use filter_row::RowShape;
17pub use options::OPTIONS_BUTTONS;
18
19use crate::event::Intent;
20use crate::modal::Spec;
21use crate::overlay::Placement;
22use crate::tabs::reports::ReportKind;
23use crate::widgets::{Editor, Hints, SelectOption, SelectWidget, Widget, WidgetKind};
24use crate::window::Origin;
25
26#[cfg(test)]
27mod tests;
28
29/// The buttons of a form dialog, in focus order, and the intent each presses.
30pub const BUTTONS: [Spec; 2] = [("~O~K", Intent::Submit), ("~C~lose", Intent::CloseTopmost)];
31
32/// A single labelled input field.
33#[derive(Debug)]
34pub 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)]
43pub 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)]
85pub 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
110impl Form {
111    /// The `config-set` form: a key and a value.
112    #[must_use]
113    pub fn config_set() -> Self {
114        Self::from_descriptor(&forms::CONFIG_SET, FormKind::ConfigSet)
115    }
116
117    /// The `ssh-key-add` form: a public key line and an optional label.
118    #[must_use]
119    pub fn ssh_key_add() -> Self {
120        Self::from_descriptor(&forms::SSH_KEY_ADD, FormKind::SshKeyAdd)
121    }
122
123    /// The save-path prompt of the CSV pane, offering `path`.
124    #[must_use]
125    pub fn csv_save(path: &str) -> Self {
126        let mut form = Self::from_descriptor(&descriptor::CSV_SAVE, FormKind::CsvSave);
127        for field in &mut form.fields {
128            field.widget.set_text(path);
129        }
130        form
131    }
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    pub fn report(kind: ReportKind, prefill: &forms::FormValues) -> Self {
137        let mut form = Self::from_descriptor(kind.descriptor(), FormKind::Report(kind));
138        for field in &mut form.fields {
139            if matches!(field.widget, Widget::Date(_)) {
140                field.widget.set_text("");
141            }
142        }
143        form.load(prefill);
144        form
145    }
146
147    /// The `commodity-create` form: symbol and name.
148    #[must_use]
149    pub fn commodity_create() -> Self {
150        Self::from_descriptor(&forms::COMMODITY_CREATE, FormKind::CommodityCreate)
151    }
152
153    /// The `convert` form: amount and two commodity selects, filled from `form-options`.
154    #[must_use]
155    pub fn commodity_convert() -> Self {
156        Self::from_descriptor(&forms::CONVERT, FormKind::CommodityConvert)
157    }
158
159    /// The `account-create` form: a name and a parent select.
160    #[must_use]
161    pub fn account_create() -> Self {
162        Self::from_descriptor(&forms::ACCOUNT_CREATE, FormKind::AccountCreate)
163    }
164
165    /// Transaction create form built from the shared descriptor: date, note, splits.
166    #[must_use]
167    pub fn transaction_create() -> Self {
168        Self::from_descriptor(&forms::TRANSACTION_CREATE, FormKind::TransactionCreate)
169    }
170
171    /// The `account-merge` form: two account selects.
172    #[must_use]
173    pub fn account_merge() -> Self {
174        Self::from_descriptor(&forms::ACCOUNT_MERGE, FormKind::AccountMerge)
175    }
176
177    /// The Transactions tab filter form, prefilled with the active `filter`.
178    #[must_use]
179    pub fn transaction_filter(filter: &FormValues) -> Self {
180        let mut form = Self::from_fields(
181            forms::TRANSACTION_QUERY.filter_fields(),
182            FormKind::TransactionFilter,
183        );
184        for field in &mut form.fields {
185            if matches!(field.widget, Widget::Date(_)) {
186                field.widget.set_text("");
187            }
188        }
189        form.load(filter);
190        form
191    }
192
193    /// The label the select field `key` shows.
194    #[must_use]
195    pub fn select_label(&self, key: &str) -> Option<&str> {
196        self.fields
197            .iter()
198            .find(|field| field.key == Some(key))
199            .and_then(|field| match &field.widget {
200                Widget::Select(sw) => Some(sw.display()),
201                _ => None,
202            })
203    }
204
205    /// The `tag-create` form from the shared descriptor.
206    #[must_use]
207    pub fn tag_create() -> Self {
208        Self::from_descriptor(&forms::TAG_CREATE, FormKind::TagCreate)
209    }
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    pub fn tag_edit(loaded: &forms::FormValues) -> Self {
215        let mut form = Self::from_descriptor(&forms::TAG_EDIT, FormKind::TagEdit);
216        form.load(loaded);
217        form
218    }
219
220    /// The `template-create` form from the shared descriptor.
221    #[must_use]
222    pub fn template_create() -> Self {
223        Self::from_descriptor(&forms::TEMPLATE_CREATE, FormKind::TemplateCreate)
224    }
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    pub fn template_edit(loaded: &forms::FormValues) -> Self {
230        let mut form = Self::from_descriptor(&forms::TEMPLATE_EDIT, FormKind::TemplateEdit);
231        form.load(loaded);
232        form
233    }
234
235    /// The template picker over `options`.
236    #[must_use]
237    pub fn template_pick(options: &[SelectOption]) -> Self {
238        let mut form = Self::from_descriptor(&descriptor::TEMPLATE_PICK, FormKind::TemplatePick);
239        for field in &mut form.fields {
240            if let Widget::Select(select) = &mut field.widget {
241                select.set_options(options.to_vec());
242            }
243        }
244        form
245    }
246
247    /// Transaction create form filled from the `load-form` draft of a template.
248    #[must_use]
249    pub fn transaction_from_template(loaded: &forms::FormValues) -> Self {
250        let mut form = Self::transaction_create();
251        form.load(loaded);
252        form
253    }
254
255    /// The `script-create` form from the shared descriptor.
256    #[must_use]
257    pub fn script_create() -> Self {
258        Self::from_descriptor(&forms::SCRIPT_CREATE, FormKind::ScriptCreate)
259    }
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    pub fn script_edit(loaded: &forms::FormValues) -> Self {
265        let mut form = Self::from_descriptor(&forms::SCRIPT_EDIT, FormKind::ScriptEdit);
266        form.load(loaded);
267        form
268    }
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    pub fn transaction_edit(loaded: &forms::FormValues) -> Self {
274        let mut form = Self::from_descriptor(&forms::TRANSACTION_EDIT, FormKind::TransactionEdit);
275        form.load(loaded);
276        form
277    }
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    pub fn account_edit(loaded: &forms::FormValues) -> Self {
283        let mut form = Self::from_descriptor(&forms::ACCOUNT_EDIT, FormKind::AccountEdit);
284        form.load(loaded);
285        form
286    }
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    pub fn commodity_edit(loaded: &forms::FormValues) -> Self {
292        let mut form = Self::from_descriptor(&forms::COMMODITY_EDIT, FormKind::CommodityEdit);
293        form.load(loaded);
294        form
295    }
296
297    /// Closes the open split tag list; `false` when none was open.
298    pub fn close_tags(&mut self) -> bool {
299        self.fields.iter_mut().any(|field| match &mut field.widget {
300            Widget::Splits(sw) => sw.close_tags(),
301            _ => false,
302        })
303    }
304
305    /// Closes the focused select's open list; `false` when none was open.
306    pub fn close_select(&mut self) -> bool {
307        match self.focused_select_mut() {
308            Some(select) if select.open => {
309                select.close();
310                true
311            }
312            _ => false,
313        }
314    }
315
316    /// The select the focus is on: the field itself or the focused cell of a grid.
317    #[must_use]
318    pub fn focused_select(&self) -> Option<&SelectWidget> {
319        match &self.fields.get(self.focus)?.widget {
320            Widget::Select(select) => Some(select),
321            Widget::Splits(sw) => sw.focused_select(),
322            Widget::Rows(rw) => rw.focused_select(),
323            _ => None,
324        }
325    }
326
327    pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
328        match &mut self.fields.get_mut(self.focus)?.widget {
329            Widget::Select(select) => Some(select),
330            Widget::Splits(sw) => sw.focused_select_mut(),
331            Widget::Rows(rw) => rw.focused_select_mut(),
332            _ => None,
333        }
334    }
335
336    /// Advance or retreat focus by one step through the fields, then the buttons, wrapping.
337    pub fn cycle(&mut self, forward: bool) {
338        self.close_select();
339        let len = self.fields.len() + self.buttons().len();
340        self.focus = if forward {
341            (self.focus + 1) % len
342        } else {
343            (self.focus + len - 1) % len
344        };
345    }
346
347    /// Focuses field `index`; an index past the fields changes nothing.
348    pub fn focus_field(&mut self, index: usize) {
349        if index < self.fields.len() {
350            self.close_select();
351            self.focus = index;
352        }
353    }
354
355    /// The index of the focused button when the focus is on the buttons.
356    #[must_use]
357    pub fn focused_button(&self) -> Option<usize> {
358        self.focus.checked_sub(self.fields.len())
359    }
360
361    /// Mutable reference to the currently focused field, if any.
362    pub fn focused_field_mut(&mut self) -> Option<&mut Field> {
363        self.fields.get_mut(self.focus)
364    }
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    pub fn focused_editor_mut(&mut self) -> Option<&mut Editor> {
371        self.focused_field_mut()
372            .and_then(|f| f.widget.as_text_mut())
373    }
374
375    /// Widget kind of the focused field, or `None` when the form is empty.
376    #[must_use]
377    pub fn focused_widget_kind(&self) -> Option<WidgetKind> {
378        self.fields.get(self.focus).map(|f| f.widget.kind())
379    }
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    pub fn focused_cells_boundary(&self) -> Option<(bool, bool)> {
385        match self.fields.get(self.focus)?.widget {
386            Widget::Splits(ref sw) if sw.tags_open() => Some((false, false)),
387            Widget::Splits(ref sw) => Some((sw.at_first_cell(), sw.at_last_cell())),
388            Widget::Rows(ref rw) => Some((rw.at_first_cell(), rw.at_last_cell())),
389            _ => None,
390        }
391    }
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    pub fn focused_vertical_boundary(&self) -> Option<(bool, bool)> {
397        match self.fields.get(self.focus)?.widget {
398            Widget::Splits(ref sw) if sw.tags_open() => sw
399                .tags()
400                .map(|tags| (tags.at_first_row(), tags.at_last_row())),
401            Widget::Splits(ref sw) => Some((sw.at_first_row(), sw.at_last_row())),
402            Widget::Rows(ref rw) => Some((rw.at_first_row(), rw.at_last_row())),
403            Widget::Text(ref ed) if ed.is_multiline() => {
404                Some((ed.at_first_line(), ed.at_last_line()))
405            }
406            _ => None,
407        }
408    }
409}