summaryrefslogtreecommitdiff
path: root/src/itemized_list.rs
blob: 36a2252bef1bb137a46ca0908daddd4960db211a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//! Itemized list.
use crate::paragraph::{
    Error as ParagraphError,
    Paragraph,
    PartError as ParagraphPartError,
};
use crate::xml::element::{Element, FromElements};

/// Itemized list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ItemizedList
{
    items: Vec<Item>,
}

impl ItemizedList
{
    /// Returns a new `ItemizedList`.
    pub fn new(entries: impl IntoIterator<Item = Item>) -> Self
    {
        Self {
            items: entries.into_iter().collect(),
        }
    }

    /// Returns the itemized list's items.
    #[must_use]
    pub fn items(&self) -> &[Item]
    {
        &self.items
    }
}

impl FromElements for ItemizedList
{
    type Error = Error;

    fn from_elements(
        elements: &crate::xml::element::Elements,
    ) -> Result<Self, Self::Error>
    {
        let items = elements
            .get_all_tagged_elements_with_name("listitem")
            .into_iter()
            .map(|entry_elem| Item::from_elements(entry_elem.child_elements()))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(Self { items })
    }
}

/// [`ItemizedList`] error.
#[derive(Debug, thiserror::Error)]
pub enum Error
{
    /// Invalid item.
    #[error("Invalid item")]
    InvalidItem(#[from] ItemError),
}

/// Itemized list item.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Item
{
    paragraphs: Vec<Paragraph>,
}

impl Item
{
    /// Returns a new `Item`.
    pub fn new(paragraphs: impl IntoIterator<Item = Paragraph>) -> Self
    {
        Self {
            paragraphs: paragraphs.into_iter().collect(),
        }
    }

    /// Returns the itemized list item paragraphs.
    #[must_use]
    pub fn paragraphs(&self) -> &[Paragraph]
    {
        &self.paragraphs
    }
}

impl FromElements for Item
{
    type Error = ItemError;

    fn from_elements(
        elements: &crate::xml::element::Elements,
    ) -> Result<Self, Self::Error>
    {
        let item = elements
            .into_iter()
            .filter_map(|elem| match elem {
                Element::Tagged(tagged_elem) if tagged_elem.name() == "para" => {
                    Some(tagged_elem)
                }
                _ => None,
            })
            .map(|para_elem| Paragraph::from_elements(para_elem.child_elements()))
            .collect::<Result<Vec<_>, _>>()
            .map_err(|err| Self::Error::InvalidItemParagraph(Box::new(err)))?;

        Ok(Self { paragraphs: item })
    }
}

/// [`Item`] error.
#[derive(Debug, thiserror::Error)]
pub enum ItemError
{
    /// Missing tagged element with name 'term'.
    #[error("Missing tagged element with name 'term'")]
    MissingTerm,

    /// Missing tagged element with name 'listitem'.
    #[error("Missing tagged element with name 'listitem'")]
    MissingListItem,

    /// Invalid term.
    #[error("Invalid term")]
    InvalidTerm(#[source] Box<ParagraphPartError>),

    /// Invalid item paragraph.
    #[error("Invalid item paragraph")]
    InvalidItemParagraph(#[source] Box<ParagraphError>),
}

#[cfg(test)]
mod tests
{
    use super::*;
    use crate::paragraph::Part as ParagraphPart;
    use crate::xml::element::{Element, Elements, Tagged};

    #[test]
    fn itemized_list_from_elements_works()
    {
        let itemized_list = ItemizedList::from_elements(&Elements::from([
            Element::Tagged(Tagged::new(
                &"listitem",
                [Element::Tagged(Tagged::new(
                    &"para",
                    [Element::Text("Hello hello.".to_string())],
                    [],
                ))],
                [],
            )),
            Element::Tagged(Tagged::new(
                &"listitem",
                [Element::Tagged(Tagged::new(
                    &"para",
                    [
                        Element::Text("Tosche station".to_string()),
                        Element::Text("Power converters".to_string()),
                    ],
                    [],
                ))],
                [],
            )),
            Element::Tagged(Tagged::new(
                &"listitem",
                [Element::Tagged(Tagged::new(
                    &"para",
                    [Element::Text("It's a trap".to_string())],
                    [],
                ))],
                [],
            )),
        ]))
        .expect("Expected Ok");

        assert_eq!(itemized_list.items.len(), 3);
    }

    #[test]
    fn item_from_elements_works()
    {
        let item = Item::from_elements(&Elements::from([
            Element::Tagged(Tagged::new(&"para", [Element::Text("bar".to_string())], [])),
            Element::Tagged(Tagged::new(
                &"para",
                [Element::Text("Hello there.".to_string())],
                [],
            )),
        ]))
        .expect("Expected Ok");

        assert_eq!(
            item.paragraphs,
            vec![
                Paragraph::new([ParagraphPart::Text("bar".to_string())]),
                Paragraph::new([ParagraphPart::Text("Hello there.".to_string())]),
            ]
        );
    }
}