f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
//! The custom properties of a document (`docProps/custom.xml`, ECMA-376 Part 1, 15.2.12.2),
//! which `DOCPROPERTY` fields show.

use std::collections::HashMap;

use f_office_xml::{Document, NodeId};

use crate::dates::DateTime;
use crate::ns::{CUSTOM_PROPERTIES, VT};

/// The value types whose text a field shows as it is: text and numbers.
const TEXT_TYPES: [&str; 14] = [
    "lpwstr", "lpstr", "bstr", "i1", "i2", "i4", "i8", "int", "ui1", "ui2", "ui4", "ui8", "uint",
    "decimal",
];

/// The value of a custom property.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Property {
    /// Text or a number, as written.
    Text(String),
    /// A date and time in UTC (`vt:filetime`).
    Date(DateTime),
}

/// The custom properties of a document by name.
pub type Properties = HashMap<String, Property>;

/// Reads a custom properties part: the name of each property with its value as text or as a
/// date. Values of other types, such as yes or no, are left out.
#[must_use]
pub fn read(doc: &Document, root: NodeId) -> Properties {
    doc.child_elements(root)
        .filter(|node| doc.is(*node, CUSTOM_PROPERTIES, "property"))
        .filter_map(|property| {
            let name = doc.attribute(property, None, "name")?;
            doc.child_elements(property).find_map(|value| {
                let text = || doc.text_content(value);
                let found = if TEXT_TYPES.iter().any(|kind| doc.is(value, VT, kind)) {
                    Property::Text(text())
                } else if doc.is(value, VT, "filetime") {
                    Property::Date(DateTime::parse_utc(&text())?)
                } else {
                    return None;
                };
                Some((name.to_owned(), found))
            })
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use f_office_xml::{Document, Limits};

    use super::{Property, read};
    use crate::dates::DateTime;
    use crate::ns::{CUSTOM_PROPERTIES, VT};

    #[test]
    fn reads_text_number_and_date_properties() {
        let xml = format!(
            r#"<Properties xmlns="{CUSTOM_PROPERTIES}" xmlns:vt="{VT}"><property fmtid="x" pid="2" name="AsAtDate"><vt:lpwstr>04 Mar 1977</vt:lpwstr></property><property fmtid="x" pid="3" name="Count"><vt:i4>7</vt:i4></property><property fmtid="x" pid="4" name="Start"><vt:filetime>2018-12-28T13:00:00Z</vt:filetime></property><property fmtid="x" pid="5" name="Done"><vt:bool>false</vt:bool></property><property fmtid="x" pid="6" name="Bad"><vt:filetime>2018-12-28</vt:filetime></property></Properties>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let properties = read(&doc, doc.root().unwrap());
        let text = |s: &str| Some(Property::Text(s.to_owned()));
        assert_eq!(properties.get("AsAtDate").cloned(), text("04 Mar 1977"));
        assert_eq!(properties.get("Count").cloned(), text("7"));
        let start = DateTime {
            year: 2018,
            month: 12,
            day: 28,
            hour: 13,
            minute: 0,
            second: 0,
        };
        assert_eq!(
            properties.get("Start").cloned(),
            Some(Property::Date(start))
        );
        assert_eq!(
            (properties.get("Done"), properties.get("Bad")),
            (None, None)
        );
    }
}