1
//! Server-side HTML for a [`forms::Form`]: every control is named by its
2
//! address, so the posted body decodes with `FormValues::from_pairs`.
3

            
4
use askama::Template;
5
use forms::{
6
    Action, Field, FieldError, Form, FormValues, Kind, LINK_CELL, PARENT_KEY_CELL, Row, SPLITS_KEY,
7
    TAGS_KEY, address,
8
};
9

            
10
/// Row index in the names inside a `<template>`; the browser renumbers it.
11
pub const INDEX_PLACEHOLDER: &str = "__INDEX__";
12

            
13
#[derive(Debug, Clone, PartialEq, Eq)]
14
enum Input {
15
    Text,
16
    /// Textarea body: browsers drop one leading newline, so one is added.
17
    Multiline(String),
18
    /// The report filter text, which the visual builder edits.
19
    Filter(String),
20
    Select(&'static str),
21
    Amount,
22
    Date,
23
    /// A whole calendar day, as the report forms take their dates.
24
    Day,
25
    /// A fixed set of values, shown by label.
26
    Choice(Vec<Choice>),
27
}
28

            
29
#[derive(Debug, Clone, PartialEq, Eq)]
30
struct Choice {
31
    value: &'static str,
32
    label: String,
33
    selected: bool,
34
}
35

            
36
struct Control {
37
    class: &'static str,
38
    /// The field key, which places the control in its row's grid.
39
    cell: &'static str,
40
    input: Input,
41
    name: String,
42
    label: &'static str,
43
    value: String,
44
    errors: Vec<String>,
45
    /// The commodity cells this cell is the converted amount of.
46
    converts: Option<(&'static str, &'static str)>,
47
    /// Rendered hidden and disabled so the browser does not post it.
48
    dormant: bool,
49
    suggest: Option<forms::Suggest>,
50
    /// The cell a pick here fills when it is empty.
51
    fills: Option<&'static str>,
52
    /// What an empty select cell means, shown as its placeholder.
53
    empty: Option<&'static str>,
54
    /// What a select control shows for the reference it carries.
55
    shown: String,
56
    /// A fill wrote the select control's text; a later fill may move it.
57
    filled: bool,
58
    /// The filled text was copied from the split above; a fill never clears it.
59
    copied: bool,
60
}
61

            
62
impl Control {
63
    /// The cell of the same row whose text selects the suggestions.
64
1427
    fn suggest_by(&self) -> Option<&'static str> {
65
1427
        match self.suggest? {
66
698
            forms::Suggest::TagValues(_) => Some("name"),
67
729
            forms::Suggest::TagNames(_) => None,
68
        }
69
1427
    }
70

            
71
    /// The name of a select control's visible text: never its address, which
72
    /// names the hidden input carrying the reference.
73
1376
    fn typed_name(&self) -> String {
74
1376
        format!("{}{}", forms::labels::LABEL_PREFIX, self.name)
75
1376
    }
76
}
77

            
78
struct Hidden {
79
    name: String,
80
    value: String,
81
}
82

            
83
enum Cell {
84
    Control(Control),
85
    Hidden(Hidden),
86
}
87

            
88
struct RowView {
89
    kind: &'static str,
90
    remove: String,
91
    class: &'static str,
92
    cells: Vec<Cell>,
93
    errors: Vec<String>,
94
}
95

            
96
/// The rows of a child field that belong to one parent row.
97
struct NestedView {
98
    key: &'static str,
99
    add: String,
100
    link: &'static str,
101
    rows: Vec<RowView>,
102
    blank: RowView,
103
}
104

            
105
struct Group {
106
    key_cell: Option<&'static str>,
107
    row: RowView,
108
    nested: Option<NestedView>,
109
}
110

            
111
/// An "Add row" button and the id of the rows container it adds to.
112
struct AddButton {
113
    target: String,
114
    label: String,
115
}
116

            
117
struct RowsView {
118
    key: &'static str,
119
    adds: Vec<AddButton>,
120
    label: &'static str,
121
    container: String,
122
    markers: Vec<String>,
123
    groups: Vec<Group>,
124
    blank: Group,
125
    orphans: Vec<RowView>,
126
    errors: Vec<String>,
127
}
128

            
129
enum Node {
130
    Cell(Box<Cell>),
131
    Rows(Box<RowsView>),
132
}
133

            
134
#[derive(Template)]
135
#[template(path = "forms/form.html")]
136
struct FormTemplate {
137
    id: String,
138
    submit: String,
139
    action: String,
140
    method: &'static str,
141
    banner: Vec<String>,
142
    reload: bool,
143
    reload_url: String,
144
    nodes: Vec<Node>,
145
}
146

            
147
/// Identity cells carry no meaning for a person, so they render hidden.
148
11449
fn is_identity(form: &Form, rows: &str, cell: &str) -> bool {
149
65985
    form.fields.iter().any(|child| {
150
65985
        child.nested_under().is_some_and(|parent| {
151
9694
            (rows == parent && cell == PARENT_KEY_CELL) || (rows == child.key && cell == LINK_CELL)
152
9694
        })
153
65985
    })
154
11449
}
155

            
156
158
fn find<'a>(fields: &'a [Field], key: &str) -> Option<&'a Field> {
157
742
    fields.iter().find(|f| f.key == key)
158
158
}
159

            
160
5776
fn field_class(errors: &[String]) -> &'static str {
161
5776
    if errors.is_empty() {
162
5711
        "field"
163
    } else {
164
65
        "field invalid"
165
    }
166
5776
}
167

            
168
1008
fn row_class(errors: &[String]) -> &'static str {
169
1008
    if errors.is_empty() {
170
1001
        "form-row"
171
    } else {
172
7
        "form-row invalid"
173
    }
174
1008
}
175

            
176
487
fn method_of(action: Action) -> &'static str {
177
487
    match action {
178
151
        Action::Query => "get",
179
336
        Action::Mutation | Action::LoadMutation => "post",
180
    }
181
487
}
182

            
183
5776
fn suggest_of(field: &Field) -> Option<forms::Suggest> {
184
5776
    match field.kind {
185
2832
        Kind::Text { suggest, .. } => suggest,
186
2944
        _ => None,
187
    }
188
5776
}
189

            
190
5776
fn fills_of(field: &Field) -> Option<&'static str> {
191
5776
    match field.kind {
192
1376
        Kind::Select { fills, .. } => fills,
193
4400
        _ => None,
194
    }
195
5776
}
196

            
197
5776
fn empty_of(field: &Field) -> Option<&'static str> {
198
5776
    match field.kind {
199
1376
        Kind::Select { empty, .. } => empty,
200
4400
        _ => None,
201
    }
202
5776
}
203

            
204
5776
fn input_of(field: &Field, value: &str) -> Input {
205
5776
    match field.kind {
206
        Kind::Text {
207
            multiline: true, ..
208
935
        } => Input::Multiline(format!("\n{value}")),
209
1376
        Kind::Select { source, .. } => Input::Select(source.name()),
210
601
        Kind::Amount => Input::Amount,
211
        Kind::Date {
212
            whole_day: true, ..
213
236
        } => Input::Day,
214
140
        Kind::Date { .. } => Input::Date,
215
        Kind::Choice { options, default } => {
216
591
            widgets::field_choice(options, default, field.required, value)
217
        }
218
        Kind::Text {
219
            multiline: false, ..
220
        }
221
        | Kind::Hidden
222
1897
        | Kind::Rows { .. } => Input::Text,
223
    }
224
5776
}
225

            
226
struct Builder<'a> {
227
    form: &'static Form,
228
    values: &'a FormValues,
229
    errors: Errors,
230
    references: &'a References,
231
}
232

            
233
/// The child rows of a nested field, in the order they are rendered.
234
struct Child {
235
    field: &'static Field,
236
    fields: &'static [Field],
237
}
238

            
239
12329
fn is_hidden(form: &Form, rows: &str, field: &Field) -> bool {
240
12329
    field.kind == Kind::Hidden || is_identity(form, rows, field.key)
241
12329
}
242

            
243
/// Child row indices per parent, and the ones no parent claims.
244
471
fn assign(parents: &[Row], children: &[Row]) -> (Vec<Vec<usize>>, Vec<usize>) {
245
471
    let mut owned = vec![Vec::new(); parents.len()];
246
471
    let mut orphans = Vec::new();
247
471
    for (index, child) in children.iter().enumerate() {
248
198
        let link = child.get(LINK_CELL).filter(|k| !k.is_empty());
249
198
        let owner = link.and_then(|k| {
250
198
            parents
251
198
                .iter()
252
282
                .position(|p| p.get(PARENT_KEY_CELL) == Some(k))
253
198
        });
254
198
        match owner {
255
114
            Some(parent) => owned[parent].push(index),
256
84
            None => orphans.push(index),
257
        }
258
    }
259
471
    (owned, orphans)
260
471
}
261

            
262
impl Builder<'_> {
263
7049
    fn cell(&mut self, rows: &str, field: &Field, name: String, at: &str, value: &str) -> Cell {
264
7049
        if is_hidden(self.form, rows, field) {
265
1273
            return Cell::Hidden(Hidden {
266
1273
                name,
267
1273
                value: value.into(),
268
1273
            });
269
5776
        }
270
5776
        let errors = self.errors.take(at);
271
5776
        let shown = match field.kind {
272
1376
            Kind::Select { source, .. } => self.references.shown(source, at, value),
273
4400
            _ => String::new(),
274
        };
275
5776
        Cell::Control(Control {
276
5776
            class: field_class(&errors),
277
5776
            cell: field.key,
278
5776
            input: input_of(field, value),
279
5776
            errors,
280
5776
            name,
281
5776
            label: field.label,
282
5776
            value: value.into(),
283
5776
            converts: None,
284
5776
            dormant: false,
285
5776
            suggest: suggest_of(field),
286
5776
            fills: fills_of(field),
287
5776
            empty: empty_of(field),
288
5776
            shown,
289
5776
            filled: self.references.filled.contains_key(at),
290
5776
            copied: self.references.filled.get(at) == Some(&true),
291
5776
        })
292
7049
    }
293

            
294
    /// `index` names the controls, `error_index` finds the errors of the row
295
    /// as it was submitted; they differ once rows are regrouped.
296
1008
    fn row(
297
1008
        &mut self,
298
1008
        kind: &'static str,
299
1008
        fields: &[Field],
300
1008
        (index, error_index): (&str, &str),
301
1008
        row: Option<&Row>,
302
1008
    ) -> RowView {
303
1008
        let mut errors = self.errors.take(&address::row(kind, error_index));
304
1008
        let mut cells = Vec::new();
305
1008
        let differs = CONVERSION.differs(row, self.references);
306
1008
        for sub in CONVERSION.flow(kind, fields) {
307
5280
            let value = row.and_then(|r| r.get(sub.key)).map_or("", String::as_str);
308
5280
            let at = address::cell(kind, error_index, sub.key);
309
5280
            if is_hidden(self.form, kind, sub) {
310
981
                let hidden = self.errors.take(&at);
311
981
                errors.extend(hidden.into_iter().map(|m| format!("{}: {m}", sub.label)));
312
4299
            }
313
5280
            let mut cell = self.cell(kind, sub, address::cell(kind, index, sub.key), &at, value);
314
5280
            CONVERSION.mark(kind, sub.key, &mut cell, differs);
315
5280
            widgets::mark(kind, sub.key, &mut cell);
316
5280
            cells.push(cell);
317
        }
318
1008
        RowView {
319
1008
            kind,
320
1008
            remove: widgets::remove_text(kind),
321
1008
            class: row_class(&errors),
322
1008
            cells,
323
1008
            errors,
324
1008
        }
325
1008
    }
326

            
327
625
    fn blank_row(&mut self, kind: &'static str, fields: &[Field]) -> RowView {
328
625
        self.row(kind, fields, (INDEX_PLACEHOLDER, INDEX_PLACEHOLDER), None)
329
625
    }
330

            
331
331
    fn child_of(&self, key: &str) -> Option<Child> {
332
331
        let field = self
333
331
            .form
334
331
            .fields
335
331
            .iter()
336
1871
            .find(|field| field.nested_under() == Some(key))?;
337
140
        let Kind::Rows { fields, .. } = field.kind else {
338
            return None;
339
        };
340
140
        Some(Child { field, fields })
341
331
    }
342

            
343
294
    fn nested(&mut self, child: &Child, rows: Vec<RowView>) -> NestedView {
344
294
        NestedView {
345
294
            key: child.field.key,
346
294
            add: widgets::add_text(child.field.key),
347
294
            link: LINK_CELL,
348
294
            rows,
349
294
            blank: self.blank_row(child.field.key, child.fields),
350
294
        }
351
294
    }
352

            
353
294
    fn child_rows(
354
294
        &mut self,
355
294
        child: &Child,
356
294
        indices: &[usize],
357
294
        rendered: &mut usize,
358
294
    ) -> Vec<RowView> {
359
294
        let all = self.values.rows(child.field.key).unwrap_or_default();
360
294
        let mut views = Vec::new();
361
294
        for &index in indices {
362
99
            let at = (rendered.to_string(), index.to_string());
363
99
            views.push(self.row(
364
99
                child.field.key,
365
99
                child.fields,
366
99
                (&at.0, &at.1),
367
99
                all.get(index),
368
99
            ));
369
99
            *rendered += 1;
370
        }
371
294
        views
372
294
    }
373

            
374
331
    fn groups(&mut self, field: &Field, fields: &[Field], child: Option<&Child>) -> Vec<Group> {
375
331
        let parents = self.values.rows(field.key).unwrap_or_default();
376
331
        let children = child
377
140
            .and_then(|c| self.values.rows(c.field.key))
378
            .unwrap_or_default();
379
331
        let (owned, _) = assign(parents, children);
380
331
        let mut rendered = 0;
381
331
        let mut groups = Vec::new();
382
331
        for (index, row) in parents.iter().enumerate() {
383
284
            let at = index.to_string();
384
284
            let row = self.row(field.key, fields, (&at, &at), Some(row));
385
284
            let nested = child.map(|c| {
386
154
                let rows = self.child_rows(c, &owned[index], &mut rendered);
387
154
                self.nested(c, rows)
388
154
            });
389
284
            groups.push(Group {
390
284
                key_cell: nested.is_some().then_some(PARENT_KEY_CELL),
391
284
                row,
392
284
                nested,
393
284
            });
394
        }
395
331
        groups
396
331
    }
397

            
398
331
    fn orphans(&mut self, field: &Field, child: Option<&Child>) -> Vec<RowView> {
399
331
        let Some(child) = child else {
400
191
            return Vec::new();
401
        };
402
140
        let parents = self.values.rows(field.key).unwrap_or_default();
403
140
        let children = self.values.rows(child.field.key).unwrap_or_default();
404
140
        let (owned, orphans) = assign(parents, children);
405
140
        let mut rendered = owned.iter().map(Vec::len).sum();
406
140
        self.child_rows(child, &orphans, &mut rendered)
407
331
    }
408

            
409
331
    fn rows(&mut self, field: &'static Field, fields: &'static [Field]) -> RowsView {
410
331
        let key = field.key;
411
331
        let child = self.child_of(key);
412
331
        let groups = self.groups(field, fields, child.as_ref());
413
331
        let orphans = self.orphans(field, child.as_ref());
414
331
        let blank_row = self.blank_row(key, fields);
415
331
        let blank_nested = child.as_ref().map(|c| self.nested(c, Vec::new()));
416
331
        let markers: Vec<String> = [Some(field), child.as_ref().map(|c| c.field)]
417
            .into_iter()
418
            .flatten()
419
471
            .filter(|f| self.values.rows(f.key).is_some())
420
337
            .map(|f| f.key.to_string())
421
            .collect();
422
331
        let mut errors = self.errors.take(key);
423
331
        errors.extend(child.iter().flat_map(|c| self.errors.take(c.field.key)));
424
331
        let container = format!("nf-{}-{key}", self.form.name);
425
331
        RowsView {
426
331
            key,
427
331
            adds: vec![AddButton {
428
331
                target: container.clone(),
429
331
                label: widgets::add_text(key),
430
331
            }],
431
331
            label: field.label,
432
331
            container,
433
331
            markers,
434
331
            groups,
435
331
            blank: Group {
436
331
                key_cell: blank_nested.is_some().then_some(PARENT_KEY_CELL),
437
331
                row: blank_row,
438
331
                nested: blank_nested,
439
331
            },
440
331
            orphans,
441
331
            errors,
442
331
        }
443
331
    }
444

            
445
487
    fn nodes(&mut self) -> Vec<Node> {
446
487
        let mut nodes = Vec::new();
447
487
        for field in self.form.fields {
448
2240
            let node = match field.kind {
449
471
                Kind::Rows { .. } if self.is_nested_child(field) => continue,
450
331
                Kind::Rows { fields, .. } => Node::Rows(Box::new(self.rows(field, fields))),
451
                _ => {
452
1769
                    let value = self.values.text(field.key).unwrap_or_default();
453
1769
                    let mut cell = self.cell("", field, field.key.into(), field.key, value);
454
1769
                    widgets::mark("", field.key, &mut cell);
455
1769
                    Node::Cell(Box::new(cell))
456
                }
457
            };
458
2100
            nodes.push(node);
459
        }
460
487
        hoist_tag_adds(&mut nodes);
461
487
        nodes
462
487
    }
463

            
464
471
    fn is_nested_child(&self, field: &Field) -> bool {
465
471
        field
466
471
            .nested_under()
467
140
            .is_some_and(|parent| find(self.form.fields, parent).is_some())
468
471
    }
469
}
470

            
471
767
fn rows_of<'a>(nodes: &'a mut [Node], key: &str) -> Option<&'a mut RowsView> {
472
3288
    nodes.iter_mut().find_map(|node| match node {
473
751
        Node::Rows(rows) if rows.key == key => Some(rows.as_mut()),
474
2868
        _ => None,
475
3288
    })
476
767
}
477

            
478
/// A person reaches "Add tag" after the splits, so it is rendered just before
479
/// "Add split" and the document, screen and Tab orders agree.
480
487
fn hoist_tag_adds(nodes: &mut [Node]) {
481
487
    if rows_of(nodes, SPLITS_KEY).is_none() {
482
347
        return;
483
140
    }
484
140
    let tags = rows_of(nodes, TAGS_KEY).map(|rows| std::mem::take(&mut rows.adds));
485
140
    if let (Some(tags), Some(splits)) = (tags, rows_of(nodes, SPLITS_KEY)) {
486
140
        splits.adds.splice(0..0, tags);
487
    }
488
487
}
489

            
490
/// Render `form` filled from `values`, marking `errors` at their addresses.
491
/// A select control shows the label of the entity `references` resolves its
492
/// value to, or the text typed into it.
493
///
494
/// # Errors
495
/// Returns the template error if rendering fails.
496
423
pub fn render_form(
497
423
    form: &'static Form,
498
423
    values: &FormValues,
499
423
    errors: &[FieldError],
500
423
    action: &str,
501
423
    references: &References,
502
423
) -> askama::Result<String> {
503
423
    render_form_reloading(form, values, errors, action, references, "")
504
423
}
505

            
506
/// [`render_form`] whose stale banner links to `reload_url`, the page that
507
/// loads the entity afresh; empty reloads the current page.
508
///
509
/// # Errors
510
/// Returns the template error if rendering fails.
511
487
pub fn render_form_reloading(
512
487
    form: &'static Form,
513
487
    values: &FormValues,
514
487
    errors: &[FieldError],
515
487
    action: &str,
516
487
    references: &References,
517
487
    reload_url: &str,
518
487
) -> askama::Result<String> {
519
487
    let mut builder = Builder {
520
487
        form,
521
487
        values,
522
487
        errors: Errors::new(errors),
523
487
        references,
524
487
    };
525
487
    let nodes = builder.nodes();
526
487
    let reload = errors.iter().any(|e| e.field == "revision");
527
487
    FormTemplate {
528
487
        id: format!("nf-{}", form.name),
529
487
        submit: widgets::submit_text(form.name),
530
487
        action: action.into(),
531
487
        method: method_of(form.action),
532
487
        banner: builder.errors.banner(form),
533
487
        reload,
534
487
        reload_url: reload_url.into(),
535
487
        nodes,
536
487
    }
537
487
    .render()
538
487
}
539

            
540
mod conversion;
541
mod errors;
542
mod references;
543
mod widgets;
544
mod without;
545
use conversion::CONVERSION;
546
use errors::Errors;
547
pub use references::References;
548
pub use without::without;
549

            
550
#[cfg(test)]
551
mod choice_tests;
552
#[cfg(test)]
553
pub(crate) mod fixture;
554
#[cfg(test)]
555
mod nested_tests;
556
#[cfg(test)]
557
mod reference_tests;
558
#[cfg(test)]
559
mod tests;
560
#[cfg(test)]
561
mod widget_tests;