Lines
99.35 %
Functions
74.48 %
Branches
100 %
//! Server-side HTML for a [`forms::Form`]: every control is named by its
//! address, so the posted body decodes with `FormValues::from_pairs`.
use askama::Template;
use forms::{
Action, Field, FieldError, Form, FormValues, Kind, LINK_CELL, PARENT_KEY_CELL, Row, SPLITS_KEY,
TAGS_KEY, address,
};
/// Row index in the names inside a `<template>`; the browser renumbers it.
pub const INDEX_PLACEHOLDER: &str = "__INDEX__";
#[derive(Debug, Clone, PartialEq, Eq)]
enum Input {
Text,
/// Textarea body: browsers drop one leading newline, so one is added.
Multiline(String),
/// The report filter text, which the visual builder edits.
Filter(String),
Select(&'static str),
Amount,
Date,
/// A whole calendar day, as the report forms take their dates.
Day,
/// A fixed set of values, shown by label.
Choice(Vec<Choice>),
}
struct Choice {
value: &'static str,
label: String,
selected: bool,
struct Control {
class: &'static str,
/// The field key, which places the control in its row's grid.
cell: &'static str,
input: Input,
name: String,
label: &'static str,
value: String,
errors: Vec<String>,
/// The commodity cells this cell is the converted amount of.
converts: Option<(&'static str, &'static str)>,
/// Rendered hidden and disabled so the browser does not post it.
dormant: bool,
suggest: Option<forms::Suggest>,
/// The cell a pick here fills when it is empty.
fills: Option<&'static str>,
/// What an empty select cell means, shown as its placeholder.
empty: Option<&'static str>,
/// What a select control shows for the reference it carries.
shown: String,
/// A fill wrote the select control's text; a later fill may move it.
filled: bool,
/// The filled text was copied from the split above; a fill never clears it.
copied: bool,
impl Control {
/// The cell of the same row whose text selects the suggestions.
fn suggest_by(&self) -> Option<&'static str> {
match self.suggest? {
forms::Suggest::TagValues(_) => Some("name"),
forms::Suggest::TagNames(_) => None,
/// The name of a select control's visible text: never its address, which
/// names the hidden input carrying the reference.
fn typed_name(&self) -> String {
format!("{}{}", forms::labels::LABEL_PREFIX, self.name)
struct Hidden {
enum Cell {
Control(Control),
Hidden(Hidden),
struct RowView {
kind: &'static str,
remove: String,
cells: Vec<Cell>,
/// The rows of a child field that belong to one parent row.
struct NestedView {
key: &'static str,
add: String,
link: &'static str,
rows: Vec<RowView>,
blank: RowView,
struct Group {
key_cell: Option<&'static str>,
row: RowView,
nested: Option<NestedView>,
/// An "Add row" button and the id of the rows container it adds to.
struct AddButton {
target: String,
struct RowsView {
adds: Vec<AddButton>,
container: String,
markers: Vec<String>,
groups: Vec<Group>,
blank: Group,
orphans: Vec<RowView>,
enum Node {
Cell(Box<Cell>),
Rows(Box<RowsView>),
#[derive(Template)]
#[template(path = "forms/form.html")]
struct FormTemplate {
id: String,
submit: String,
action: String,
method: &'static str,
banner: Vec<String>,
reload: bool,
reload_url: String,
nodes: Vec<Node>,
/// Identity cells carry no meaning for a person, so they render hidden.
fn is_identity(form: &Form, rows: &str, cell: &str) -> bool {
form.fields.iter().any(|child| {
child.nested_under().is_some_and(|parent| {
(rows == parent && cell == PARENT_KEY_CELL) || (rows == child.key && cell == LINK_CELL)
})
fn find<'a>(fields: &'a [Field], key: &str) -> Option<&'a Field> {
fields.iter().find(|f| f.key == key)
fn field_class(errors: &[String]) -> &'static str {
if errors.is_empty() {
"field"
} else {
"field invalid"
fn row_class(errors: &[String]) -> &'static str {
"form-row"
"form-row invalid"
fn method_of(action: Action) -> &'static str {
match action {
Action::Query => "get",
Action::Mutation | Action::LoadMutation => "post",
fn suggest_of(field: &Field) -> Option<forms::Suggest> {
match field.kind {
Kind::Text { suggest, .. } => suggest,
_ => None,
fn fills_of(field: &Field) -> Option<&'static str> {
Kind::Select { fills, .. } => fills,
fn empty_of(field: &Field) -> Option<&'static str> {
Kind::Select { empty, .. } => empty,
fn input_of(field: &Field, value: &str) -> Input {
Kind::Text {
multiline: true, ..
} => Input::Multiline(format!("\n{value}")),
Kind::Select { source, .. } => Input::Select(source.name()),
Kind::Amount => Input::Amount,
Kind::Date {
whole_day: true, ..
} => Input::Day,
Kind::Date { .. } => Input::Date,
Kind::Choice { options, default } => {
widgets::field_choice(options, default, field.required, value)
multiline: false, ..
| Kind::Hidden
| Kind::Rows { .. } => Input::Text,
struct Builder<'a> {
form: &'static Form,
values: &'a FormValues,
errors: Errors,
references: &'a References,
/// The child rows of a nested field, in the order they are rendered.
struct Child {
field: &'static Field,
fields: &'static [Field],
fn is_hidden(form: &Form, rows: &str, field: &Field) -> bool {
field.kind == Kind::Hidden || is_identity(form, rows, field.key)
/// Child row indices per parent, and the ones no parent claims.
fn assign(parents: &[Row], children: &[Row]) -> (Vec<Vec<usize>>, Vec<usize>) {
let mut owned = vec![Vec::new(); parents.len()];
let mut orphans = Vec::new();
for (index, child) in children.iter().enumerate() {
let link = child.get(LINK_CELL).filter(|k| !k.is_empty());
let owner = link.and_then(|k| {
parents
.iter()
.position(|p| p.get(PARENT_KEY_CELL) == Some(k))
});
match owner {
Some(parent) => owned[parent].push(index),
None => orphans.push(index),
(owned, orphans)
impl Builder<'_> {
fn cell(&mut self, rows: &str, field: &Field, name: String, at: &str, value: &str) -> Cell {
if is_hidden(self.form, rows, field) {
return Cell::Hidden(Hidden {
name,
value: value.into(),
let errors = self.errors.take(at);
let shown = match field.kind {
Kind::Select { source, .. } => self.references.shown(source, at, value),
_ => String::new(),
Cell::Control(Control {
class: field_class(&errors),
cell: field.key,
input: input_of(field, value),
errors,
label: field.label,
converts: None,
dormant: false,
suggest: suggest_of(field),
fills: fills_of(field),
empty: empty_of(field),
shown,
filled: self.references.filled.contains_key(at),
copied: self.references.filled.get(at) == Some(&true),
/// `index` names the controls, `error_index` finds the errors of the row
/// as it was submitted; they differ once rows are regrouped.
fn row(
&mut self,
fields: &[Field],
(index, error_index): (&str, &str),
row: Option<&Row>,
) -> RowView {
let mut errors = self.errors.take(&address::row(kind, error_index));
let mut cells = Vec::new();
let differs = CONVERSION.differs(row, self.references);
for sub in CONVERSION.flow(kind, fields) {
let value = row.and_then(|r| r.get(sub.key)).map_or("", String::as_str);
let at = address::cell(kind, error_index, sub.key);
if is_hidden(self.form, kind, sub) {
let hidden = self.errors.take(&at);
errors.extend(hidden.into_iter().map(|m| format!("{}: {m}", sub.label)));
let mut cell = self.cell(kind, sub, address::cell(kind, index, sub.key), &at, value);
CONVERSION.mark(kind, sub.key, &mut cell, differs);
widgets::mark(kind, sub.key, &mut cell);
cells.push(cell);
RowView {
kind,
remove: widgets::remove_text(kind),
class: row_class(&errors),
cells,
fn blank_row(&mut self, kind: &'static str, fields: &[Field]) -> RowView {
self.row(kind, fields, (INDEX_PLACEHOLDER, INDEX_PLACEHOLDER), None)
fn child_of(&self, key: &str) -> Option<Child> {
let field = self
.form
.fields
.find(|field| field.nested_under() == Some(key))?;
let Kind::Rows { fields, .. } = field.kind else {
return None;
Some(Child { field, fields })
fn nested(&mut self, child: &Child, rows: Vec<RowView>) -> NestedView {
NestedView {
key: child.field.key,
add: widgets::add_text(child.field.key),
link: LINK_CELL,
rows,
blank: self.blank_row(child.field.key, child.fields),
fn child_rows(
child: &Child,
indices: &[usize],
rendered: &mut usize,
) -> Vec<RowView> {
let all = self.values.rows(child.field.key).unwrap_or_default();
let mut views = Vec::new();
for &index in indices {
let at = (rendered.to_string(), index.to_string());
views.push(self.row(
child.field.key,
child.fields,
(&at.0, &at.1),
all.get(index),
));
*rendered += 1;
views
fn groups(&mut self, field: &Field, fields: &[Field], child: Option<&Child>) -> Vec<Group> {
let parents = self.values.rows(field.key).unwrap_or_default();
let children = child
.and_then(|c| self.values.rows(c.field.key))
.unwrap_or_default();
let (owned, _) = assign(parents, children);
let mut rendered = 0;
let mut groups = Vec::new();
for (index, row) in parents.iter().enumerate() {
let at = index.to_string();
let row = self.row(field.key, fields, (&at, &at), Some(row));
let nested = child.map(|c| {
let rows = self.child_rows(c, &owned[index], &mut rendered);
self.nested(c, rows)
groups.push(Group {
key_cell: nested.is_some().then_some(PARENT_KEY_CELL),
row,
nested,
groups
fn orphans(&mut self, field: &Field, child: Option<&Child>) -> Vec<RowView> {
let Some(child) = child else {
return Vec::new();
let children = self.values.rows(child.field.key).unwrap_or_default();
let (owned, orphans) = assign(parents, children);
let mut rendered = owned.iter().map(Vec::len).sum();
self.child_rows(child, &orphans, &mut rendered)
fn rows(&mut self, field: &'static Field, fields: &'static [Field]) -> RowsView {
let key = field.key;
let child = self.child_of(key);
let groups = self.groups(field, fields, child.as_ref());
let orphans = self.orphans(field, child.as_ref());
let blank_row = self.blank_row(key, fields);
let blank_nested = child.as_ref().map(|c| self.nested(c, Vec::new()));
let markers: Vec<String> = [Some(field), child.as_ref().map(|c| c.field)]
.into_iter()
.flatten()
.filter(|f| self.values.rows(f.key).is_some())
.map(|f| f.key.to_string())
.collect();
let mut errors = self.errors.take(key);
errors.extend(child.iter().flat_map(|c| self.errors.take(c.field.key)));
let container = format!("nf-{}-{key}", self.form.name);
RowsView {
key,
adds: vec![AddButton {
target: container.clone(),
label: widgets::add_text(key),
}],
container,
markers,
groups,
blank: Group {
key_cell: blank_nested.is_some().then_some(PARENT_KEY_CELL),
row: blank_row,
nested: blank_nested,
},
orphans,
fn nodes(&mut self) -> Vec<Node> {
let mut nodes = Vec::new();
for field in self.form.fields {
let node = match field.kind {
Kind::Rows { .. } if self.is_nested_child(field) => continue,
Kind::Rows { fields, .. } => Node::Rows(Box::new(self.rows(field, fields))),
_ => {
let value = self.values.text(field.key).unwrap_or_default();
let mut cell = self.cell("", field, field.key.into(), field.key, value);
widgets::mark("", field.key, &mut cell);
Node::Cell(Box::new(cell))
nodes.push(node);
hoist_tag_adds(&mut nodes);
nodes
fn is_nested_child(&self, field: &Field) -> bool {
field
.nested_under()
.is_some_and(|parent| find(self.form.fields, parent).is_some())
fn rows_of<'a>(nodes: &'a mut [Node], key: &str) -> Option<&'a mut RowsView> {
nodes.iter_mut().find_map(|node| match node {
Node::Rows(rows) if rows.key == key => Some(rows.as_mut()),
/// A person reaches "Add tag" after the splits, so it is rendered just before
/// "Add split" and the document, screen and Tab orders agree.
fn hoist_tag_adds(nodes: &mut [Node]) {
if rows_of(nodes, SPLITS_KEY).is_none() {
return;
let tags = rows_of(nodes, TAGS_KEY).map(|rows| std::mem::take(&mut rows.adds));
if let (Some(tags), Some(splits)) = (tags, rows_of(nodes, SPLITS_KEY)) {
splits.adds.splice(0..0, tags);
/// Render `form` filled from `values`, marking `errors` at their addresses.
/// A select control shows the label of the entity `references` resolves its
/// value to, or the text typed into it.
///
/// # Errors
/// Returns the template error if rendering fails.
pub fn render_form(
values: &FormValues,
errors: &[FieldError],
action: &str,
references: &References,
) -> askama::Result<String> {
render_form_reloading(form, values, errors, action, references, "")
/// [`render_form`] whose stale banner links to `reload_url`, the page that
/// loads the entity afresh; empty reloads the current page.
pub fn render_form_reloading(
reload_url: &str,
let mut builder = Builder {
form,
values,
errors: Errors::new(errors),
references,
let nodes = builder.nodes();
let reload = errors.iter().any(|e| e.field == "revision");
FormTemplate {
id: format!("nf-{}", form.name),
submit: widgets::submit_text(form.name),
action: action.into(),
method: method_of(form.action),
banner: builder.errors.banner(form),
reload,
reload_url: reload_url.into(),
nodes,
.render()
mod conversion;
mod errors;
mod references;
mod widgets;
mod without;
use conversion::CONVERSION;
use errors::Errors;
pub use references::References;
pub use without::without;
#[cfg(test)]
mod choice_tests;
pub(crate) mod fixture;
mod nested_tests;
mod reference_tests;
mod tests;
mod widget_tests;