1
//! Binds a TUI form to its shared descriptor: widgets, submit values and the
2
//! focus and wording of server rejections.
3

            
4
use cli_core::render::FieldError;
5
use 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

            
11
use super::{Field, Form, FormKind, filter_row, options};
12
use crate::overlay::Placement;
13
use crate::widgets::rows::is_text_rows;
14
use crate::widgets::splits::rows_of;
15
use 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.
20
pub(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.
36
pub(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.
53
enum 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

            
68
3818
fn widget_for(descriptor: &Descriptor) -> Option<Widget> {
69
3818
    match descriptor.kind {
70
1264
        Kind::Text { multiline, .. } => Some(Widget::Text(Editor::default().multiline(multiline))),
71
        Kind::Choice { options, default } => {
72
234
            Some(Widget::Select(SelectWidget::choice(options, default)))
73
        }
74
269
        Kind::Select { .. } => Some(Widget::Select(SelectWidget::new())),
75
14
        Kind::Amount => Some(Widget::Amount(AmountWidget::default())),
76
630
        Kind::Date { .. } => Some(Widget::Date(DateWidget::default())),
77
1183
        Kind::Rows { .. } if descriptor.is_nested() => None,
78
813
        Kind::Rows { fields, .. } if is_text_rows(fields) => {
79
443
            Some(Widget::Rows(RowsWidget::new(fields)))
80
        }
81
370
        Kind::Rows { .. } => Some(Widget::Splits(SplitsWidget::default())),
82
224
        Kind::Hidden => None,
83
    }
84
3818
}
85

            
86
impl Form {
87
985
    pub(super) fn from_descriptor(form: &forms::Form, kind: FormKind) -> Self {
88
985
        Self::from_fields(form.fields.iter(), kind)
89
985
    }
90

            
91
1000
    pub(super) fn from_fields<'a>(
92
1000
        descriptors: impl Iterator<Item = &'a Descriptor>,
93
1000
        kind: FormKind,
94
1000
    ) -> Self {
95
1000
        let descriptors: Vec<&Descriptor> = descriptors.collect();
96
1000
        let fields = descriptors
97
1000
            .iter()
98
3818
            .filter_map(|descriptor| {
99
                Some(Field {
100
3818
                    key: Some(descriptor.key),
101
3818
                    label: descriptor.label,
102
3818
                    widget: widget_for(descriptor)?,
103
                })
104
3818
            })
105
            .collect();
106
1000
        let hidden = descriptors
107
1000
            .iter()
108
3818
            .filter(|descriptor| descriptor.kind == Kind::Hidden)
109
224
            .map(|descriptor| (descriptor.key, String::new()))
110
            .collect();
111
1000
        Self {
112
1000
            fields,
113
1000
            focus: 0,
114
1000
            kind,
115
1000
            hidden,
116
1000
            errors: Vec::new(),
117
1000
            notices: Vec::new(),
118
1000
            baseline: None,
119
1000
            hints: Hints::default(),
120
1000
            completing: None,
121
1000
            origin: None,
122
1000
            placement: Placement::default(),
123
1000
        }
124
1000
    }
125

            
126
    /// Replaces the widgets' and hidden fields' contents with `loaded`; keys
127
    /// the payload does not hold keep their empty value.
128
359
    pub fn load(&mut self, loaded: &FormValues) {
129
359
        let descriptor = self.descriptor();
130
359
        for field in &mut self.fields {
131
1442
            let Some(key) = field.key else { continue };
132
1442
            match &mut field.widget {
133
                Widget::Splits(sw) => {
134
78
                    sw.load_rows(loaded.rows(key).unwrap_or_default());
135
78
                    if let Some(nested) = nested_key(descriptor, key) {
136
78
                        sw.load_tags(loaded.rows(nested));
137
                    }
138
                }
139
144
                Widget::Rows(rw) => rw.load_rows(loaded.rows(key)),
140
                widget => {
141
1220
                    if let Some(text) = loaded.text(key) {
142
572
                        widget.set_text(text);
143
648
                    }
144
                }
145
            }
146
        }
147
359
        for (key, value) in &mut self.hidden {
148
224
            *value = loaded.text(key).unwrap_or_default().to_string();
149
        }
150
359
    }
151

            
152
5062
    fn descriptor(&self) -> &'static forms::Form {
153
5062
        match self.kind {
154
1147
            FormKind::TransactionCreate => &TRANSACTION_CREATE,
155
667
            FormKind::TransactionEdit => &TRANSACTION_EDIT,
156
73
            FormKind::AccountEdit => &ACCOUNT_EDIT,
157
133
            FormKind::AccountMerge => &ACCOUNT_MERGE,
158
56
            FormKind::AccountCreate => &ACCOUNT_CREATE,
159
73
            FormKind::TransactionFilter => &TRANSACTION_QUERY,
160
83
            FormKind::CommodityCreate => &COMMODITY_CREATE,
161
26
            FormKind::CommodityEdit => &COMMODITY_EDIT,
162
56
            FormKind::CommodityConvert => &CONVERT,
163
420
            FormKind::ConfigSet => &CONFIG_SET,
164
1184
            FormKind::Options => &options::OPTIONS,
165
18
            FormKind::SshKeyAdd => &forms::SSH_KEY_ADD,
166
4
            FormKind::CsvSave => &CSV_SAVE,
167
88
            FormKind::TagCreate => &forms::TAG_CREATE,
168
62
            FormKind::TagEdit => &forms::TAG_EDIT,
169
18
            FormKind::TemplateCreate => &forms::TEMPLATE_CREATE,
170
45
            FormKind::TemplateEdit => &forms::TEMPLATE_EDIT,
171
22
            FormKind::ScriptCreate => &forms::SCRIPT_CREATE,
172
27
            FormKind::ScriptEdit => &forms::SCRIPT_EDIT,
173
22
            FormKind::TemplatePick => &TEMPLATE_PICK,
174
124
            FormKind::FilterAdd => &filter_row::ADD,
175
235
            FormKind::FilterRow(shape) => filter_row::shape_descriptor(shape),
176
479
            FormKind::Report(kind) => kind.descriptor(),
177
        }
178
5062
    }
179

            
180
    /// Remembers the current values as the clean state, once.
181
957
    pub fn snapshot(&mut self) {
182
957
        if self.baseline.is_none() {
183
888
            self.baseline = Some(self.values());
184
69
        }
185
957
    }
186

            
187
    /// Takes the current values as the clean state.
188
101
    pub fn rebaseline(&mut self) {
189
101
        self.baseline = Some(self.values());
190
101
    }
191

            
192
    /// Whether the values differ from those the form opened with.
193
    #[must_use]
194
132
    pub fn is_dirty(&self) -> bool {
195
132
        self.baseline
196
132
            .as_ref()
197
132
            .is_some_and(|baseline| *baseline != self.values())
198
132
    }
199

            
200
    #[must_use]
201
2231
    pub fn is_template(&self) -> bool {
202
2231
        matches!(self.kind, FormKind::TemplateCreate | FormKind::TemplateEdit)
203
2231
    }
204

            
205
    #[must_use]
206
101
    pub fn is_transaction(&self) -> bool {
207
101
        matches!(
208
101
            self.kind,
209
            FormKind::TransactionCreate | FormKind::TransactionEdit
210
        )
211
101
    }
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
2045
    pub fn values(&self) -> FormValues {
217
2045
        let mut values = FormValues::default();
218
2045
        for (key, value) in &self.hidden {
219
574
            values.set(key, value);
220
        }
221
2045
        let row_fields = self.row_fields();
222
2045
        for field in &self.fields {
223
7546
            let Some(key) = field.key else { continue };
224
7442
            match &field.widget {
225
                Widget::Splits(sw) => {
226
571
                    for row in sw.rows() {
227
851
                        values.push_row(key, row_values(row_fields, row));
228
                    }
229
571
                    self.push_nested(key, sw, &mut values);
230
                }
231
                Widget::Rows(rw) => {
232
674
                    if let Some(rows) = rw.values() {
233
98
                        values.set_rows(key);
234
290
                        rows.into_iter().for_each(|row| values.push_row(key, row));
235
576
                    }
236
                }
237
6197
                widget => values.set(key, widget.value()),
238
            }
239
        }
240
2045
        drop_orphans(self.descriptor(), &mut values);
241
2045
        values
242
2045
    }
243

            
244
    /// Writes the nested rows; an edit always sends the field, even empty.
245
571
    fn push_nested(&self, parent: &str, sw: &SplitsWidget, values: &mut FormValues) {
246
571
        let Some(key) = nested_key(self.descriptor(), parent) else {
247
            return;
248
        };
249
571
        let rows = sw.tag_rows();
250
571
        if self.kind == FormKind::TransactionEdit || sw.tags_present() || !rows.is_empty() {
251
215
            values.set_rows(key);
252
356
        }
253
571
        rows.into_iter().for_each(|row| values.push_row(key, row));
254
571
    }
255

            
256
    /// Select `id` in the account select `key`; kept until the options arrive.
257
23
    pub fn preselect_account(&mut self, key: &str, id: &str) {
258
46
        for field in self.fields.iter_mut().filter(|f| f.key == Some(key)) {
259
23
            if let Widget::Select(sw) = &mut field.widget {
260
23
                sw.select_id(id);
261
            }
262
        }
263
23
    }
264

            
265
    /// Select `id` as the first split row's From account.
266
5
    pub fn preselect_from_account(&mut self, id: &str) {
267
5
        for field in &mut self.fields {
268
20
            if let Widget::Splits(sw) = &mut field.widget {
269
5
                sw.preselect_from(id);
270
15
            }
271
        }
272
5
    }
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
50
    pub fn show_errors(&mut self, errors: &[FieldError]) {
277
55
        self.errors = errors.iter().map(|e| self.error_line(e)).collect();
278
50
        let first = errors.iter().find_map(|e| self.target(&e.field));
279
50
        if let Some(target) = first {
280
32
            self.focus_target(target);
281
18
        }
282
50
    }
283

            
284
104
    fn target<'a>(&self, address: &'a str) -> Option<Target<'a>> {
285
104
        let mut parts = address.split('.');
286
104
        let key = parts.next()?;
287
272
        let Some(field) = self.fields.iter().position(|f| f.key == Some(key)) else {
288
39
            let field = self.nested_field(key)?;
289
2
            let index = parts.next()?.parse().ok()?;
290
2
            return Some(Target::Tag {
291
2
                field,
292
2
                index,
293
2
                key: parts.next(),
294
2
            });
295
        };
296
65
        let Some(row) = parts.next() else {
297
52
            return Some(Target::Field(field));
298
        };
299
        Some(Target::Cell {
300
13
            field,
301
13
            row: row.parse().ok()?,
302
13
            key: parts.next(),
303
        })
304
104
    }
305

            
306
    /// The index of the field holding the editor of the nested rows field `key`.
307
39
    fn nested_field(&self, key: &str) -> Option<usize> {
308
39
        let descriptor = self.descriptor();
309
122
        self.fields.iter().position(|field| {
310
122
            let parent = field.key.unwrap_or_default();
311
122
            nested_key(descriptor, parent) == Some(key) && matches!(field.widget, Widget::Splits(_))
312
122
        })
313
39
    }
314

            
315
55
    fn error_line(&self, error: &FieldError) -> String {
316
55
        let message = &error.message;
317
55
        let label = self.target(&error.field).and_then(|t| self.label(&t));
318
55
        match (error.field.as_str(), label) {
319
12
            ("", _) => message.clone(),
320
43
            (address, _) if self.is_hidden(address) => message.clone(),
321
35
            (_, Some(label)) => format!("{label}: {message}"),
322
2
            (address, None) => format!("{address}: {message}"),
323
        }
324
55
    }
325

            
326
2048
    fn row_fields(&self) -> &'static [Descriptor] {
327
2048
        rows_of(self.descriptor())
328
2048
    }
329

            
330
6
    fn cell_label(&self, field: usize, key: &str) -> Option<&'static str> {
331
6
        match &self.fields.get(field)?.widget {
332
3
            Widget::Rows(rw) => rw.cell_label(key),
333
3
            _ => self
334
3
                .row_fields()
335
3
                .iter()
336
20
                .find(|d| d.key == key)
337
3
                .map(|d| d.label),
338
        }
339
6
    }
340

            
341
49
    fn is_hidden(&self, address: &str) -> bool {
342
49
        self.hidden.iter().any(|(key, _)| *key == address)
343
49
    }
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
39
    pub fn is_stale(&self, errors: &[FieldError]) -> bool {
349
39
        errors
350
39
            .iter()
351
40
            .any(|e| e.field == "revision" && self.is_hidden("revision"))
352
39
    }
353

            
354
35
    fn label(&self, target: &Target<'_>) -> Option<String> {
355
35
        match *target {
356
27
            Target::Field(field) => Some(self.fields.get(field)?.label.to_string()),
357
            Target::Tag { index, key, .. } => {
358
1
                let label = format!("Tag {}", index + 1);
359
1
                let cell = key.map(|key| tag_cell_label(key).unwrap_or(key));
360
1
                Some(match cell {
361
1
                    Some(cell) => format!("{label} \u{b7} {cell}"),
362
                    None => label,
363
                })
364
            }
365
            Target::Cell { field, row, key } => {
366
7
                let row_label = format!("Row {}", row + 1);
367
7
                let cell = key.map(|key| self.cell_label(field, key).unwrap_or(key));
368
7
                Some(match cell {
369
6
                    Some(cell) => format!("{row_label} \u{b7} {cell}"),
370
1
                    None => row_label,
371
                })
372
            }
373
        }
374
35
    }
375

            
376
32
    fn focus_target(&mut self, target: Target<'_>) {
377
32
        match target {
378
25
            Target::Field(field) => self.focus = field,
379
            Target::Tag { field, index, key } => {
380
1
                self.focus = field;
381
1
                if let Some(Widget::Splits(sw)) = self.fields.get_mut(field).map(|f| &mut f.widget)
382
                {
383
1
                    sw.focus_tag(index, key.unwrap_or_default());
384
                }
385
            }
386
            Target::Cell { field, row, key } => {
387
6
                self.focus = field;
388
6
                let key = key.unwrap_or_default();
389
6
                match self.fields.get_mut(field).map(|f| &mut f.widget) {
390
3
                    Some(Widget::Splits(sw)) => sw.focus_cell(row, key),
391
3
                    Some(Widget::Rows(rw)) => rw.focus_cell(row, key),
392
                    _ => {}
393
                }
394
            }
395
        }
396
32
    }
397
}
398

            
399
/// The key of the rows field `form` nests under `parent`.
400
771
fn nested_key(form: &'static forms::Form, parent: &str) -> Option<&'static str> {
401
4321
    let nested = |field: &&Descriptor| field.nested_under() == Some(parent);
402
771
    form.fields.iter().find(nested).map(|f| f.key)
403
771
}
404

            
405
1
fn tag_cell_label(key: &str) -> Option<&'static str> {
406
1
    let mut cell = crate::widgets::splits::tag_fields().iter();
407
3
    cell.find(|cell| cell.key == key).map(|cell| cell.label)
408
1
}
409

            
410
851
fn row_values(row_fields: &[Descriptor], row: &crate::widgets::SplitRow) -> Row {
411
851
    row_fields
412
851
        .iter()
413
6808
        .map(|field| (field.key, row.text(field.key)))
414
6808
        .filter(|(_, text)| !text.is_empty())
415
2965
        .map(|(key, text)| (key.to_string(), text.to_string()))
416
        .collect()
417
851
}