Skip to main content

tui/form/
descriptor.rs

1//! Binds a TUI form to its shared descriptor: widgets, submit values and the
2//! focus and wording of server rejections.
3
4use cli_core::render::FieldError;
5use forms::{
6    ACCOUNT_CREATE, ACCOUNT_EDIT, ACCOUNT_MERGE, COMMODITY_CREATE, COMMODITY_EDIT, CONFIG_SET,
7    CONVERT, Field as Descriptor, FormValues, Kind, Row, TRANSACTION_CREATE, TRANSACTION_EDIT,
8    TRANSACTION_QUERY, drop_orphans,
9};
10
11use super::{Field, Form, FormKind, filter_row, options};
12use crate::overlay::Placement;
13use crate::widgets::rows::is_text_rows;
14use crate::widgets::splits::rows_of;
15use crate::widgets::{
16    AmountWidget, DateWidget, Editor, Hints, RowsWidget, SelectWidget, SplitsWidget, Widget,
17};
18
19/// The CSV save prompt; local only, so it has no server form.
20pub(super) const CSV_SAVE: forms::Form = forms::Form {
21    name: "save-csv",
22    title: "Save CSV",
23    fields: &[Descriptor {
24        key: "path",
25        label: "File",
26        kind: Kind::Text {
27            multiline: false,
28            suggest: None,
29        },
30        required: true,
31    }],
32    action: forms::Action::Mutation,
33};
34
35/// The template picker of create-from-template; local only, so it has no server form.
36pub(super) const TEMPLATE_PICK: forms::Form = forms::Form {
37    name: "template-pick",
38    title: "New from template",
39    fields: &[Descriptor {
40        key: "template",
41        label: "Template",
42        kind: Kind::Select {
43            source: forms::Source::Templates,
44            fills: None,
45            empty: None,
46        },
47        required: true,
48    }],
49    action: forms::Action::Mutation,
50};
51
52/// Where a field address points inside the form.
53enum Target<'a> {
54    Field(usize),
55    Cell {
56        field: usize,
57        row: usize,
58        key: Option<&'a str>,
59    },
60    /// A cell of the `index`th split tag, counted over all splits.
61    Tag {
62        field: usize,
63        index: usize,
64        key: Option<&'a str>,
65    },
66}
67
68fn widget_for(descriptor: &Descriptor) -> Option<Widget> {
69    match descriptor.kind {
70        Kind::Text { multiline, .. } => Some(Widget::Text(Editor::default().multiline(multiline))),
71        Kind::Choice { options, default } => {
72            Some(Widget::Select(SelectWidget::choice(options, default)))
73        }
74        Kind::Select { .. } => Some(Widget::Select(SelectWidget::new())),
75        Kind::Amount => Some(Widget::Amount(AmountWidget::default())),
76        Kind::Date { .. } => Some(Widget::Date(DateWidget::default())),
77        Kind::Rows { .. } if descriptor.is_nested() => None,
78        Kind::Rows { fields, .. } if is_text_rows(fields) => {
79            Some(Widget::Rows(RowsWidget::new(fields)))
80        }
81        Kind::Rows { .. } => Some(Widget::Splits(SplitsWidget::default())),
82        Kind::Hidden => None,
83    }
84}
85
86impl Form {
87    pub(super) fn from_descriptor(form: &forms::Form, kind: FormKind) -> Self {
88        Self::from_fields(form.fields.iter(), kind)
89    }
90
91    pub(super) fn from_fields<'a>(
92        descriptors: impl Iterator<Item = &'a Descriptor>,
93        kind: FormKind,
94    ) -> Self {
95        let descriptors: Vec<&Descriptor> = descriptors.collect();
96        let fields = descriptors
97            .iter()
98            .filter_map(|descriptor| {
99                Some(Field {
100                    key: Some(descriptor.key),
101                    label: descriptor.label,
102                    widget: widget_for(descriptor)?,
103                })
104            })
105            .collect();
106        let hidden = descriptors
107            .iter()
108            .filter(|descriptor| descriptor.kind == Kind::Hidden)
109            .map(|descriptor| (descriptor.key, String::new()))
110            .collect();
111        Self {
112            fields,
113            focus: 0,
114            kind,
115            hidden,
116            errors: Vec::new(),
117            notices: Vec::new(),
118            baseline: None,
119            hints: Hints::default(),
120            completing: None,
121            origin: None,
122            placement: Placement::default(),
123        }
124    }
125
126    /// Replaces the widgets' and hidden fields' contents with `loaded`; keys
127    /// the payload does not hold keep their empty value.
128    pub fn load(&mut self, loaded: &FormValues) {
129        let descriptor = self.descriptor();
130        for field in &mut self.fields {
131            let Some(key) = field.key else { continue };
132            match &mut field.widget {
133                Widget::Splits(sw) => {
134                    sw.load_rows(loaded.rows(key).unwrap_or_default());
135                    if let Some(nested) = nested_key(descriptor, key) {
136                        sw.load_tags(loaded.rows(nested));
137                    }
138                }
139                Widget::Rows(rw) => rw.load_rows(loaded.rows(key)),
140                widget => {
141                    if let Some(text) = loaded.text(key) {
142                        widget.set_text(text);
143                    }
144                }
145            }
146        }
147        for (key, value) in &mut self.hidden {
148            *value = loaded.text(key).unwrap_or_default().to_string();
149        }
150    }
151
152    fn descriptor(&self) -> &'static forms::Form {
153        match self.kind {
154            FormKind::TransactionCreate => &TRANSACTION_CREATE,
155            FormKind::TransactionEdit => &TRANSACTION_EDIT,
156            FormKind::AccountEdit => &ACCOUNT_EDIT,
157            FormKind::AccountMerge => &ACCOUNT_MERGE,
158            FormKind::AccountCreate => &ACCOUNT_CREATE,
159            FormKind::TransactionFilter => &TRANSACTION_QUERY,
160            FormKind::CommodityCreate => &COMMODITY_CREATE,
161            FormKind::CommodityEdit => &COMMODITY_EDIT,
162            FormKind::CommodityConvert => &CONVERT,
163            FormKind::ConfigSet => &CONFIG_SET,
164            FormKind::Options => &options::OPTIONS,
165            FormKind::SshKeyAdd => &forms::SSH_KEY_ADD,
166            FormKind::CsvSave => &CSV_SAVE,
167            FormKind::TagCreate => &forms::TAG_CREATE,
168            FormKind::TagEdit => &forms::TAG_EDIT,
169            FormKind::TemplateCreate => &forms::TEMPLATE_CREATE,
170            FormKind::TemplateEdit => &forms::TEMPLATE_EDIT,
171            FormKind::ScriptCreate => &forms::SCRIPT_CREATE,
172            FormKind::ScriptEdit => &forms::SCRIPT_EDIT,
173            FormKind::TemplatePick => &TEMPLATE_PICK,
174            FormKind::FilterAdd => &filter_row::ADD,
175            FormKind::FilterRow(shape) => filter_row::shape_descriptor(shape),
176            FormKind::Report(kind) => kind.descriptor(),
177        }
178    }
179
180    /// Remembers the current values as the clean state, once.
181    pub fn snapshot(&mut self) {
182        if self.baseline.is_none() {
183            self.baseline = Some(self.values());
184        }
185    }
186
187    /// Takes the current values as the clean state.
188    pub fn rebaseline(&mut self) {
189        self.baseline = Some(self.values());
190    }
191
192    /// Whether the values differ from those the form opened with.
193    #[must_use]
194    pub fn is_dirty(&self) -> bool {
195        self.baseline
196            .as_ref()
197            .is_some_and(|baseline| *baseline != self.values())
198    }
199
200    #[must_use]
201    pub fn is_template(&self) -> bool {
202        matches!(self.kind, FormKind::TemplateCreate | FormKind::TemplateEdit)
203    }
204
205    #[must_use]
206    pub fn is_transaction(&self) -> bool {
207        matches!(
208            self.kind,
209            FormKind::TransactionCreate | FormKind::TransactionEdit
210        )
211    }
212
213    /// The raw values of a descriptor form, hidden ones included; empty cells
214    /// are left out so the server reports a missing required value by address.
215    #[must_use]
216    pub fn values(&self) -> FormValues {
217        let mut values = FormValues::default();
218        for (key, value) in &self.hidden {
219            values.set(key, value);
220        }
221        let row_fields = self.row_fields();
222        for field in &self.fields {
223            let Some(key) = field.key else { continue };
224            match &field.widget {
225                Widget::Splits(sw) => {
226                    for row in sw.rows() {
227                        values.push_row(key, row_values(row_fields, row));
228                    }
229                    self.push_nested(key, sw, &mut values);
230                }
231                Widget::Rows(rw) => {
232                    if let Some(rows) = rw.values() {
233                        values.set_rows(key);
234                        rows.into_iter().for_each(|row| values.push_row(key, row));
235                    }
236                }
237                widget => values.set(key, widget.value()),
238            }
239        }
240        drop_orphans(self.descriptor(), &mut values);
241        values
242    }
243
244    /// Writes the nested rows; an edit always sends the field, even empty.
245    fn push_nested(&self, parent: &str, sw: &SplitsWidget, values: &mut FormValues) {
246        let Some(key) = nested_key(self.descriptor(), parent) else {
247            return;
248        };
249        let rows = sw.tag_rows();
250        if self.kind == FormKind::TransactionEdit || sw.tags_present() || !rows.is_empty() {
251            values.set_rows(key);
252        }
253        rows.into_iter().for_each(|row| values.push_row(key, row));
254    }
255
256    /// Select `id` in the account select `key`; kept until the options arrive.
257    pub fn preselect_account(&mut self, key: &str, id: &str) {
258        for field in self.fields.iter_mut().filter(|f| f.key == Some(key)) {
259            if let Widget::Select(sw) = &mut field.widget {
260                sw.select_id(id);
261            }
262        }
263    }
264
265    /// Select `id` as the first split row's From account.
266    pub fn preselect_from_account(&mut self, id: &str) {
267        for field in &mut self.fields {
268            if let Widget::Splits(sw) = &mut field.widget {
269                sw.preselect_from(id);
270            }
271        }
272    }
273
274    /// Lists every rejection with its address translated to labels and
275    /// focuses the first one that points at a field or a cell.
276    pub fn show_errors(&mut self, errors: &[FieldError]) {
277        self.errors = errors.iter().map(|e| self.error_line(e)).collect();
278        let first = errors.iter().find_map(|e| self.target(&e.field));
279        if let Some(target) = first {
280            self.focus_target(target);
281        }
282    }
283
284    fn target<'a>(&self, address: &'a str) -> Option<Target<'a>> {
285        let mut parts = address.split('.');
286        let key = parts.next()?;
287        let Some(field) = self.fields.iter().position(|f| f.key == Some(key)) else {
288            let field = self.nested_field(key)?;
289            let index = parts.next()?.parse().ok()?;
290            return Some(Target::Tag {
291                field,
292                index,
293                key: parts.next(),
294            });
295        };
296        let Some(row) = parts.next() else {
297            return Some(Target::Field(field));
298        };
299        Some(Target::Cell {
300            field,
301            row: row.parse().ok()?,
302            key: parts.next(),
303        })
304    }
305
306    /// The index of the field holding the editor of the nested rows field `key`.
307    fn nested_field(&self, key: &str) -> Option<usize> {
308        let descriptor = self.descriptor();
309        self.fields.iter().position(|field| {
310            let parent = field.key.unwrap_or_default();
311            nested_key(descriptor, parent) == Some(key) && matches!(field.widget, Widget::Splits(_))
312        })
313    }
314
315    fn error_line(&self, error: &FieldError) -> String {
316        let message = &error.message;
317        let label = self.target(&error.field).and_then(|t| self.label(&t));
318        match (error.field.as_str(), label) {
319            ("", _) => message.clone(),
320            (address, _) if self.is_hidden(address) => message.clone(),
321            (_, Some(label)) => format!("{label}: {message}"),
322            (address, None) => format!("{address}: {message}"),
323        }
324    }
325
326    fn row_fields(&self) -> &'static [Descriptor] {
327        rows_of(self.descriptor())
328    }
329
330    fn cell_label(&self, field: usize, key: &str) -> Option<&'static str> {
331        match &self.fields.get(field)?.widget {
332            Widget::Rows(rw) => rw.cell_label(key),
333            _ => self
334                .row_fields()
335                .iter()
336                .find(|d| d.key == key)
337                .map(|d| d.label),
338        }
339    }
340
341    fn is_hidden(&self, address: &str) -> bool {
342        self.hidden.iter().any(|(key, _)| *key == address)
343    }
344
345    /// Whether a rejection says the loaded entry changed on the server: it is
346    /// addressed to the hidden `revision` field, which has nothing to focus.
347    #[must_use]
348    pub fn is_stale(&self, errors: &[FieldError]) -> bool {
349        errors
350            .iter()
351            .any(|e| e.field == "revision" && self.is_hidden("revision"))
352    }
353
354    fn label(&self, target: &Target<'_>) -> Option<String> {
355        match *target {
356            Target::Field(field) => Some(self.fields.get(field)?.label.to_string()),
357            Target::Tag { index, key, .. } => {
358                let label = format!("Tag {}", index + 1);
359                let cell = key.map(|key| tag_cell_label(key).unwrap_or(key));
360                Some(match cell {
361                    Some(cell) => format!("{label} \u{b7} {cell}"),
362                    None => label,
363                })
364            }
365            Target::Cell { field, row, key } => {
366                let row_label = format!("Row {}", row + 1);
367                let cell = key.map(|key| self.cell_label(field, key).unwrap_or(key));
368                Some(match cell {
369                    Some(cell) => format!("{row_label} \u{b7} {cell}"),
370                    None => row_label,
371                })
372            }
373        }
374    }
375
376    fn focus_target(&mut self, target: Target<'_>) {
377        match target {
378            Target::Field(field) => self.focus = field,
379            Target::Tag { field, index, key } => {
380                self.focus = field;
381                if let Some(Widget::Splits(sw)) = self.fields.get_mut(field).map(|f| &mut f.widget)
382                {
383                    sw.focus_tag(index, key.unwrap_or_default());
384                }
385            }
386            Target::Cell { field, row, key } => {
387                self.focus = field;
388                let key = key.unwrap_or_default();
389                match self.fields.get_mut(field).map(|f| &mut f.widget) {
390                    Some(Widget::Splits(sw)) => sw.focus_cell(row, key),
391                    Some(Widget::Rows(rw)) => rw.focus_cell(row, key),
392                    _ => {}
393                }
394            }
395        }
396    }
397}
398
399/// The key of the rows field `form` nests under `parent`.
400fn nested_key(form: &'static forms::Form, parent: &str) -> Option<&'static str> {
401    let nested = |field: &&Descriptor| field.nested_under() == Some(parent);
402    form.fields.iter().find(nested).map(|f| f.key)
403}
404
405fn tag_cell_label(key: &str) -> Option<&'static str> {
406    let mut cell = crate::widgets::splits::tag_fields().iter();
407    cell.find(|cell| cell.key == key).map(|cell| cell.label)
408}
409
410fn row_values(row_fields: &[Descriptor], row: &crate::widgets::SplitRow) -> Row {
411    row_fields
412        .iter()
413        .map(|field| (field.key, row.text(field.key)))
414        .filter(|(_, text)| !text.is_empty())
415        .map(|(key, text)| (key.to_string(), text.to_string()))
416        .collect()
417}