Skip to main content

web/form_render/
references.rs

1//! What a select control shows for the reference it carries.
2
3use std::collections::BTreeMap;
4
5use forms::Source;
6use rpc::forms::FormOption;
7
8/// The options of every source, the text typed into each select control and
9/// the controls a fill wrote (`true` if copied), by their submitted addresses.
10#[derive(Debug, Default)]
11pub struct References {
12    pub accounts: Vec<FormOption>,
13    pub commodities: Vec<FormOption>,
14    pub templates: Vec<FormOption>,
15    pub typed: BTreeMap<String, String>,
16    pub filled: BTreeMap<String, bool>,
17}
18
19impl References {
20    fn options(&self, source: Source) -> &[FormOption] {
21        match source {
22            Source::Accounts => &self.accounts,
23            Source::Commodities => &self.commodities,
24            Source::Templates => &self.templates,
25            // No web form selects a script yet; the script pages add the options.
26            Source::Scripts => &[],
27        }
28    }
29
30    /// The option whose id a cell carries.
31    pub(super) fn resolve(&self, source: Source, value: &str) -> Option<&FormOption> {
32        let id = uuid::Uuid::parse_str(value.trim()).ok()?;
33        self.options(source).iter().find(|option| option.id == id)
34    }
35
36    /// The current label of the entity a UUID value names; `None` for a value
37    /// no option has.
38    pub fn label_of(&self, source: Source, value: &str) -> Option<String> {
39        self.resolve(source, value)
40            .map(|option| option.label.clone())
41    }
42
43    /// The text a select control shows: what was typed into it, else the
44    /// label of the entity its value names, else the value as it is.
45    pub(super) fn shown(&self, source: Source, address: &str, value: &str) -> String {
46        if let Some(typed) = self.typed.get(address) {
47            return typed.clone();
48        }
49        self.resolve(source, value)
50            .map_or_else(|| value.to_string(), |option| option.label.clone())
51    }
52}