1
//! What a select control shows for the reference it carries.
2

            
3
use std::collections::BTreeMap;
4

            
5
use forms::Source;
6
use 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)]
11
pub 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

            
19
impl References {
20
330
    fn options(&self, source: Source) -> &[FormOption] {
21
330
        match source {
22
139
            Source::Accounts => &self.accounts,
23
189
            Source::Commodities => &self.commodities,
24
2
            Source::Templates => &self.templates,
25
            // No web form selects a script yet; the script pages add the options.
26
            Source::Scripts => &[],
27
        }
28
330
    }
29

            
30
    /// The option whose id a cell carries.
31
1695
    pub(super) fn resolve(&self, source: Source, value: &str) -> Option<&FormOption> {
32
1695
        let id = uuid::Uuid::parse_str(value.trim()).ok()?;
33
482
        self.options(source).iter().find(|option| option.id == id)
34
1695
    }
35

            
36
    /// The current label of the entity a UUID value names; `None` for a value
37
    /// no option has.
38
158
    pub fn label_of(&self, source: Source, value: &str) -> Option<String> {
39
158
        self.resolve(source, value)
40
129
            .map(|option| option.label.clone())
41
158
    }
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
1376
    pub(super) fn shown(&self, source: Source, address: &str, value: &str) -> String {
46
1376
        if let Some(typed) = self.typed.get(address) {
47
27
            return typed.clone();
48
1349
        }
49
1349
        self.resolve(source, value)
50
1216
            .map_or_else(|| value.to_string(), |option| option.label.clone())
51
1376
    }
52
}