Skip to main content

forms/
labels.rs

1//! The typed text of a select control. A browser shows an entity by its
2//! label in a control named `label:<address>` and submits its id in a hidden
3//! input named by the address; the text is only echoed back, never resolved.
4
5use std::collections::BTreeMap;
6
7use crate::descriptor::{Form, Kind, Source};
8use crate::pairs::{Address, resolve};
9use crate::values::{FieldError, FormValues};
10
11pub const LABEL_PREFIX: &str = "label:";
12
13/// Names a select control whose text a fill wrote, so a later fill may move it.
14pub const FILLED_PREFIX: &str = "filled:";
15
16/// The value of a `filled:` mark whose cell was copied from the split above.
17pub const COPIED_MARK: &str = "copied";
18
19/// The message of a select control whose text picks no entity.
20pub const UNPICKED: &str = "pick an entry from the list";
21
22/// The select address `name` stands for once `prefix` is taken off.
23fn prefixed_select<'a>(form: &Form, name: &'a str, prefix: &str) -> Option<&'a str> {
24    let address = name.strip_prefix(prefix)?;
25    let field = match resolve(form, address)? {
26        Address::Flat(field) | Address::Cell(_, _, field) => field,
27        Address::Row(..) => return None,
28    };
29    matches!(field.kind, Kind::Select { .. }).then_some(address)
30}
31
32/// Whether `name` is a `label:` or `filled:` companion of a select control.
33pub(crate) fn is_select_companion(form: &Form, name: &str) -> bool {
34    [LABEL_PREFIX, FILLED_PREFIX]
35        .into_iter()
36        .any(|prefix| prefixed_select(form, name, prefix).is_some())
37}
38
39/// The typed text of every select control in `pairs`, by address.
40#[must_use]
41pub fn select_labels(form: &Form, pairs: &[(String, String)]) -> BTreeMap<String, String> {
42    pairs
43        .iter()
44        .filter_map(|(name, text)| {
45            Some((
46                prefixed_select(form, name, LABEL_PREFIX)?.to_string(),
47                text.clone(),
48            ))
49        })
50        .collect()
51}
52
53/// The select controls in `pairs` marked as written by a fill, by address;
54/// `true` marks a cell copied from the split above.
55#[must_use]
56pub fn select_filled(form: &Form, pairs: &[(String, String)]) -> BTreeMap<String, bool> {
57    pairs
58        .iter()
59        .filter_map(|(name, mark)| {
60            let address = prefixed_select(form, name, FILLED_PREFIX)?;
61            Some((address.to_string(), mark == COPIED_MARK))
62        })
63        .collect()
64}
65
66fn value_at<'v>(form: &Form, values: &'v FormValues, address: &str) -> Option<&'v str> {
67    match resolve(form, address)? {
68        Address::Flat(field) => values.text(field.key),
69        Address::Cell(field, index, cell) => values
70            .rows(field.key)?
71            .get(index)?
72            .get(cell.key)
73            .map(String::as_str),
74        Address::Row(..) => None,
75    }
76}
77
78fn source_at(form: &Form, address: &str) -> Option<Source> {
79    let field = match resolve(form, address)? {
80        Address::Flat(field) | Address::Cell(_, _, field) => field,
81        Address::Row(..) => return None,
82    };
83    match field.kind {
84        Kind::Select { source, .. } => Some(source),
85        _ => None,
86    }
87}
88
89fn unpicked_at(address: &str) -> FieldError {
90    FieldError {
91        field: address.to_string(),
92        message: UNPICKED.to_string(),
93    }
94}
95
96/// A field error at every select control holding text but no entity: such
97/// text is never submitted as a name.
98#[must_use]
99pub fn unpicked(
100    form: &Form,
101    labels: &BTreeMap<String, String>,
102    values: &FormValues,
103) -> Vec<FieldError> {
104    labels
105        .iter()
106        .filter(|(address, text)| {
107            !text.trim().is_empty()
108                && value_at(form, values, address).is_none_or(|id| id.trim().is_empty())
109        })
110        .map(|(address, _)| unpicked_at(address))
111        .collect()
112}
113
114/// A field error at every select control whose typed text is not the
115/// current label of the entity its value names: the text was retyped where
116/// no pick could see it. `label_of` gives that label, and `None` for a value
117/// naming no known entity, which resolution judges instead.
118#[must_use]
119pub fn mismatched(
120    form: &Form,
121    labels: &BTreeMap<String, String>,
122    values: &FormValues,
123    label_of: impl Fn(Source, &str) -> Option<String>,
124) -> Vec<FieldError> {
125    labels
126        .iter()
127        .filter(|(address, text)| {
128            let text = text.trim();
129            let current = source_at(form, address)
130                .zip(value_at(form, values, address))
131                .and_then(|(source, value)| label_of(source, value.trim()));
132            !text.is_empty() && current.is_some_and(|label| label != text)
133        })
134        .map(|(address, _)| unpicked_at(address))
135        .collect()
136}