Skip to main content

web/
form_render.rs

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
4use askama::Template;
5use 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.
11pub const INDEX_PLACEHOLDER: &str = "__INDEX__";
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14enum 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)]
30struct Choice {
31    value: &'static str,
32    label: String,
33    selected: bool,
34}
35
36struct 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
62impl Control {
63    /// The cell of the same row whose text selects the suggestions.
64    fn suggest_by(&self) -> Option<&'static str> {
65        match self.suggest? {
66            forms::Suggest::TagValues(_) => Some("name"),
67            forms::Suggest::TagNames(_) => None,
68        }
69    }
70
71    /// The name of a select control's visible text: never its address, which
72    /// names the hidden input carrying the reference.
73    fn typed_name(&self) -> String {
74        format!("{}{}", forms::labels::LABEL_PREFIX, self.name)
75    }
76}
77
78struct Hidden {
79    name: String,
80    value: String,
81}
82
83enum Cell {
84    Control(Control),
85    Hidden(Hidden),
86}
87
88struct 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.
97struct NestedView {
98    key: &'static str,
99    add: String,
100    link: &'static str,
101    rows: Vec<RowView>,
102    blank: RowView,
103}
104
105struct 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.
112struct AddButton {
113    target: String,
114    label: String,
115}
116
117struct 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
129enum Node {
130    Cell(Box<Cell>),
131    Rows(Box<RowsView>),
132}
133
134#[derive(Template)]
135#[template(path = "forms/form.html")]
136struct 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.
148fn is_identity(form: &Form, rows: &str, cell: &str) -> bool {
149    form.fields.iter().any(|child| {
150        child.nested_under().is_some_and(|parent| {
151            (rows == parent && cell == PARENT_KEY_CELL) || (rows == child.key && cell == LINK_CELL)
152        })
153    })
154}
155
156fn find<'a>(fields: &'a [Field], key: &str) -> Option<&'a Field> {
157    fields.iter().find(|f| f.key == key)
158}
159
160fn field_class(errors: &[String]) -> &'static str {
161    if errors.is_empty() {
162        "field"
163    } else {
164        "field invalid"
165    }
166}
167
168fn row_class(errors: &[String]) -> &'static str {
169    if errors.is_empty() {
170        "form-row"
171    } else {
172        "form-row invalid"
173    }
174}
175
176fn method_of(action: Action) -> &'static str {
177    match action {
178        Action::Query => "get",
179        Action::Mutation | Action::LoadMutation => "post",
180    }
181}
182
183fn suggest_of(field: &Field) -> Option<forms::Suggest> {
184    match field.kind {
185        Kind::Text { suggest, .. } => suggest,
186        _ => None,
187    }
188}
189
190fn fills_of(field: &Field) -> Option<&'static str> {
191    match field.kind {
192        Kind::Select { fills, .. } => fills,
193        _ => None,
194    }
195}
196
197fn empty_of(field: &Field) -> Option<&'static str> {
198    match field.kind {
199        Kind::Select { empty, .. } => empty,
200        _ => None,
201    }
202}
203
204fn input_of(field: &Field, value: &str) -> Input {
205    match field.kind {
206        Kind::Text {
207            multiline: true, ..
208        } => Input::Multiline(format!("\n{value}")),
209        Kind::Select { source, .. } => Input::Select(source.name()),
210        Kind::Amount => Input::Amount,
211        Kind::Date {
212            whole_day: true, ..
213        } => Input::Day,
214        Kind::Date { .. } => Input::Date,
215        Kind::Choice { options, default } => {
216            widgets::field_choice(options, default, field.required, value)
217        }
218        Kind::Text {
219            multiline: false, ..
220        }
221        | Kind::Hidden
222        | Kind::Rows { .. } => Input::Text,
223    }
224}
225
226struct 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.
234struct Child {
235    field: &'static Field,
236    fields: &'static [Field],
237}
238
239fn is_hidden(form: &Form, rows: &str, field: &Field) -> bool {
240    field.kind == Kind::Hidden || is_identity(form, rows, field.key)
241}
242
243/// Child row indices per parent, and the ones no parent claims.
244fn assign(parents: &[Row], children: &[Row]) -> (Vec<Vec<usize>>, Vec<usize>) {
245    let mut owned = vec![Vec::new(); parents.len()];
246    let mut orphans = Vec::new();
247    for (index, child) in children.iter().enumerate() {
248        let link = child.get(LINK_CELL).filter(|k| !k.is_empty());
249        let owner = link.and_then(|k| {
250            parents
251                .iter()
252                .position(|p| p.get(PARENT_KEY_CELL) == Some(k))
253        });
254        match owner {
255            Some(parent) => owned[parent].push(index),
256            None => orphans.push(index),
257        }
258    }
259    (owned, orphans)
260}
261
262impl Builder<'_> {
263    fn cell(&mut self, rows: &str, field: &Field, name: String, at: &str, value: &str) -> Cell {
264        if is_hidden(self.form, rows, field) {
265            return Cell::Hidden(Hidden {
266                name,
267                value: value.into(),
268            });
269        }
270        let errors = self.errors.take(at);
271        let shown = match field.kind {
272            Kind::Select { source, .. } => self.references.shown(source, at, value),
273            _ => String::new(),
274        };
275        Cell::Control(Control {
276            class: field_class(&errors),
277            cell: field.key,
278            input: input_of(field, value),
279            errors,
280            name,
281            label: field.label,
282            value: value.into(),
283            converts: None,
284            dormant: false,
285            suggest: suggest_of(field),
286            fills: fills_of(field),
287            empty: empty_of(field),
288            shown,
289            filled: self.references.filled.contains_key(at),
290            copied: self.references.filled.get(at) == Some(&true),
291        })
292    }
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    fn row(
297        &mut self,
298        kind: &'static str,
299        fields: &[Field],
300        (index, error_index): (&str, &str),
301        row: Option<&Row>,
302    ) -> RowView {
303        let mut errors = self.errors.take(&address::row(kind, error_index));
304        let mut cells = Vec::new();
305        let differs = CONVERSION.differs(row, self.references);
306        for sub in CONVERSION.flow(kind, fields) {
307            let value = row.and_then(|r| r.get(sub.key)).map_or("", String::as_str);
308            let at = address::cell(kind, error_index, sub.key);
309            if is_hidden(self.form, kind, sub) {
310                let hidden = self.errors.take(&at);
311                errors.extend(hidden.into_iter().map(|m| format!("{}: {m}", sub.label)));
312            }
313            let mut cell = self.cell(kind, sub, address::cell(kind, index, sub.key), &at, value);
314            CONVERSION.mark(kind, sub.key, &mut cell, differs);
315            widgets::mark(kind, sub.key, &mut cell);
316            cells.push(cell);
317        }
318        RowView {
319            kind,
320            remove: widgets::remove_text(kind),
321            class: row_class(&errors),
322            cells,
323            errors,
324        }
325    }
326
327    fn blank_row(&mut self, kind: &'static str, fields: &[Field]) -> RowView {
328        self.row(kind, fields, (INDEX_PLACEHOLDER, INDEX_PLACEHOLDER), None)
329    }
330
331    fn child_of(&self, key: &str) -> Option<Child> {
332        let field = self
333            .form
334            .fields
335            .iter()
336            .find(|field| field.nested_under() == Some(key))?;
337        let Kind::Rows { fields, .. } = field.kind else {
338            return None;
339        };
340        Some(Child { field, fields })
341    }
342
343    fn nested(&mut self, child: &Child, rows: Vec<RowView>) -> NestedView {
344        NestedView {
345            key: child.field.key,
346            add: widgets::add_text(child.field.key),
347            link: LINK_CELL,
348            rows,
349            blank: self.blank_row(child.field.key, child.fields),
350        }
351    }
352
353    fn child_rows(
354        &mut self,
355        child: &Child,
356        indices: &[usize],
357        rendered: &mut usize,
358    ) -> Vec<RowView> {
359        let all = self.values.rows(child.field.key).unwrap_or_default();
360        let mut views = Vec::new();
361        for &index in indices {
362            let at = (rendered.to_string(), index.to_string());
363            views.push(self.row(
364                child.field.key,
365                child.fields,
366                (&at.0, &at.1),
367                all.get(index),
368            ));
369            *rendered += 1;
370        }
371        views
372    }
373
374    fn groups(&mut self, field: &Field, fields: &[Field], child: Option<&Child>) -> Vec<Group> {
375        let parents = self.values.rows(field.key).unwrap_or_default();
376        let children = child
377            .and_then(|c| self.values.rows(c.field.key))
378            .unwrap_or_default();
379        let (owned, _) = assign(parents, children);
380        let mut rendered = 0;
381        let mut groups = Vec::new();
382        for (index, row) in parents.iter().enumerate() {
383            let at = index.to_string();
384            let row = self.row(field.key, fields, (&at, &at), Some(row));
385            let nested = child.map(|c| {
386                let rows = self.child_rows(c, &owned[index], &mut rendered);
387                self.nested(c, rows)
388            });
389            groups.push(Group {
390                key_cell: nested.is_some().then_some(PARENT_KEY_CELL),
391                row,
392                nested,
393            });
394        }
395        groups
396    }
397
398    fn orphans(&mut self, field: &Field, child: Option<&Child>) -> Vec<RowView> {
399        let Some(child) = child else {
400            return Vec::new();
401        };
402        let parents = self.values.rows(field.key).unwrap_or_default();
403        let children = self.values.rows(child.field.key).unwrap_or_default();
404        let (owned, orphans) = assign(parents, children);
405        let mut rendered = owned.iter().map(Vec::len).sum();
406        self.child_rows(child, &orphans, &mut rendered)
407    }
408
409    fn rows(&mut self, field: &'static Field, fields: &'static [Field]) -> RowsView {
410        let key = field.key;
411        let child = self.child_of(key);
412        let groups = self.groups(field, fields, child.as_ref());
413        let orphans = self.orphans(field, child.as_ref());
414        let blank_row = self.blank_row(key, fields);
415        let blank_nested = child.as_ref().map(|c| self.nested(c, Vec::new()));
416        let markers: Vec<String> = [Some(field), child.as_ref().map(|c| c.field)]
417            .into_iter()
418            .flatten()
419            .filter(|f| self.values.rows(f.key).is_some())
420            .map(|f| f.key.to_string())
421            .collect();
422        let mut errors = self.errors.take(key);
423        errors.extend(child.iter().flat_map(|c| self.errors.take(c.field.key)));
424        let container = format!("nf-{}-{key}", self.form.name);
425        RowsView {
426            key,
427            adds: vec![AddButton {
428                target: container.clone(),
429                label: widgets::add_text(key),
430            }],
431            label: field.label,
432            container,
433            markers,
434            groups,
435            blank: Group {
436                key_cell: blank_nested.is_some().then_some(PARENT_KEY_CELL),
437                row: blank_row,
438                nested: blank_nested,
439            },
440            orphans,
441            errors,
442        }
443    }
444
445    fn nodes(&mut self) -> Vec<Node> {
446        let mut nodes = Vec::new();
447        for field in self.form.fields {
448            let node = match field.kind {
449                Kind::Rows { .. } if self.is_nested_child(field) => continue,
450                Kind::Rows { fields, .. } => Node::Rows(Box::new(self.rows(field, fields))),
451                _ => {
452                    let value = self.values.text(field.key).unwrap_or_default();
453                    let mut cell = self.cell("", field, field.key.into(), field.key, value);
454                    widgets::mark("", field.key, &mut cell);
455                    Node::Cell(Box::new(cell))
456                }
457            };
458            nodes.push(node);
459        }
460        hoist_tag_adds(&mut nodes);
461        nodes
462    }
463
464    fn is_nested_child(&self, field: &Field) -> bool {
465        field
466            .nested_under()
467            .is_some_and(|parent| find(self.form.fields, parent).is_some())
468    }
469}
470
471fn rows_of<'a>(nodes: &'a mut [Node], key: &str) -> Option<&'a mut RowsView> {
472    nodes.iter_mut().find_map(|node| match node {
473        Node::Rows(rows) if rows.key == key => Some(rows.as_mut()),
474        _ => None,
475    })
476}
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.
480fn hoist_tag_adds(nodes: &mut [Node]) {
481    if rows_of(nodes, SPLITS_KEY).is_none() {
482        return;
483    }
484    let tags = rows_of(nodes, TAGS_KEY).map(|rows| std::mem::take(&mut rows.adds));
485    if let (Some(tags), Some(splits)) = (tags, rows_of(nodes, SPLITS_KEY)) {
486        splits.adds.splice(0..0, tags);
487    }
488}
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.
496pub fn render_form(
497    form: &'static Form,
498    values: &FormValues,
499    errors: &[FieldError],
500    action: &str,
501    references: &References,
502) -> askama::Result<String> {
503    render_form_reloading(form, values, errors, action, references, "")
504}
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.
511pub fn render_form_reloading(
512    form: &'static Form,
513    values: &FormValues,
514    errors: &[FieldError],
515    action: &str,
516    references: &References,
517    reload_url: &str,
518) -> askama::Result<String> {
519    let mut builder = Builder {
520        form,
521        values,
522        errors: Errors::new(errors),
523        references,
524    };
525    let nodes = builder.nodes();
526    let reload = errors.iter().any(|e| e.field == "revision");
527    FormTemplate {
528        id: format!("nf-{}", form.name),
529        submit: widgets::submit_text(form.name),
530        action: action.into(),
531        method: method_of(form.action),
532        banner: builder.errors.banner(form),
533        reload,
534        reload_url: reload_url.into(),
535        nodes,
536    }
537    .render()
538}
539
540mod conversion;
541mod errors;
542mod references;
543mod widgets;
544mod without;
545use conversion::CONVERSION;
546use errors::Errors;
547pub use references::References;
548pub use without::without;
549
550#[cfg(test)]
551mod choice_tests;
552#[cfg(test)]
553pub(crate) mod fixture;
554#[cfg(test)]
555mod nested_tests;
556#[cfg(test)]
557mod reference_tests;
558#[cfg(test)]
559mod tests;
560#[cfg(test)]
561mod widget_tests;