f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! `IF` fields: the condition of the code, with the values of the fields nested in it, and
//! the text of the branch that it chooses.

use std::cmp::Ordering;

use crate::body::{CodePart, Content, IfField};

use super::Layout;

impl Layout<'_> {
    /// The text that an `IF` field shows: the text of its first branch when its condition
    /// holds, and else of its second branch. A code that is not a condition with a branch
    /// keeps the stored result.
    pub(super) fn if_text(&self, field: &IfField) -> String {
        let words = words(&field.parts, |content| self.nested_text(content));
        choose(&words).unwrap_or_else(|| field.stored.clone())
    }

    /// The text of a field nested in the code of an `IF` field.
    fn nested_text(&self, content: &Content) -> String {
        match content {
            Content::Text(text) => text.clone(),
            Content::If(field) => self.if_text(field),
            other => self.field_text(other),
        }
    }
}

/// Splits a field code into its words. Outside quotes, a word ends at white space, a nested
/// field is a word of its own, and so is a quoted text: an operator right after a nested field,
/// as in `{PAGE}= 1`, is a word of its own, and so is one between quotes, as in `"a"="a"`. Inside
/// quotes a nested field's value joins the quoted word, and no character escapes a quote.
///
/// It reads quotes in its own way, not in one of the readings of `body::field_code`, because it
/// reads the code's parts with the values of nested fields.
fn words(parts: &[CodePart], value: impl Fn(&Content) -> String) -> Vec<String> {
    let mut words = Words::default();
    for part in parts {
        match part {
            CodePart::Text(text) => text.chars().for_each(|ch| words.text(ch)),
            CodePart::Field(content) => words.field(value(content)),
        }
    }
    words.end();
    words.done
}

/// The words of a field code as far as it is read.
#[derive(Default)]
struct Words {
    /// The words that have ended.
    done: Vec<String>,
    /// The word that is open, if any.
    word: Option<String>,
    /// Whether the open word is in quotes.
    quoted: bool,
}

impl Words {
    /// Reads one character of the code's own text.
    fn text(&mut self, ch: char) {
        match (ch, self.quoted) {
            ('"', true) => {
                self.done.push(self.word.take().unwrap_or_default());
                self.quoted = false;
            }
            ('"', false) => {
                self.end();
                self.word = Some(String::new());
                self.quoted = true;
            }
            (ch, false) if ch.is_whitespace() => self.end(),
            (ch, _) => self.word.get_or_insert_with(String::new).push(ch),
        }
    }

    /// Reads the value of a nested field: a word of its own outside quotes, and a part of the
    /// quoted word inside them.
    fn field(&mut self, value: String) {
        if self.quoted {
            self.word.get_or_insert_with(String::new).push_str(&value);
        } else {
            self.end();
            self.done.push(value);
        }
    }

    /// Ends the open word, if any.
    fn end(&mut self) {
        self.done.extend(self.word.take());
    }
}

/// The number that a comparison value gives, if any: its text without white space at either end
/// and without commas, which Word reads as thousands separators, so that `0,` is 0 and `1,000` is
/// 1000.
fn number(value: &str) -> Option<f64> {
    let digits: String = value.trim().chars().filter(|&ch| ch != ',').collect();
    digits.parse().ok()
}

/// The branch that the condition `IF left operator right "then" "else"` chooses. Two numbers
/// compare as numbers, and other values as text.
fn choose(words: &[String]) -> Option<String> {
    let [keyword, left, operator, right, then, rest @ ..] = words else {
        return None;
    };
    if !keyword.eq_ignore_ascii_case("IF") {
        return None;
    }
    let order = match (number(left), number(right)) {
        (Some(a), Some(b)) => a.partial_cmp(&b)?,
        _ => left.cmp(right),
    };
    let holds = match operator.as_str() {
        "=" => order == Ordering::Equal,
        "<>" => order != Ordering::Equal,
        "<" => order == Ordering::Less,
        "<=" => order != Ordering::Greater,
        ">" => order == Ordering::Greater,
        ">=" => order != Ordering::Less,
        _ => return None,
    };
    let otherwise = rest.first().cloned().unwrap_or_default();
    Some(if holds { then.clone() } else { otherwise })
}

#[cfg(test)]
mod tests {
    use super::{choose, words};
    use crate::body::{CodePart, Content};

    fn text(s: &str) -> CodePart {
        CodePart::Text(s.to_owned())
    }

    #[test]
    fn splits_words_and_keeps_nested_values_inside_quotes() {
        let parts = [
            text(" IF 0 = 0 \""),
            CodePart::Field(Content::PageNumber),
            text(" two\" \"no\" "),
        ];
        let words = words(&parts, |_| "7".to_owned());
        assert_eq!(words, ["IF", "0", "=", "0", "7 two", "no"]);
    }

    #[test]
    fn chooses_a_branch_by_numbers_or_text() {
        let pick = |code: &str| choose(&words(&[text(code)], |_| String::new()));
        assert_eq!(pick("IF 10 > 9 \"yes\" \"no\"").as_deref(), Some("yes"));
        assert_eq!(pick("IF a = b \"yes\" \"no\"").as_deref(), Some("no"));
        assert_eq!(pick("IF 1 <> 1 \"yes\"").as_deref(), Some(""));
        assert_eq!(pick("IF 1 ~ 1 \"yes\"").as_deref(), None);
        assert_eq!(pick("IF 1 = 1").as_deref(), None);
    }

    #[test]
    fn reads_commas_in_a_number_as_thousands_separators() {
        let pick = |code: &str| choose(&words(&[text(code)], |_| String::new()));
        assert_eq!(pick("IF 0 = 0, \"yes\" \"no\"").as_deref(), Some("yes"));
        assert_eq!(pick("IF 0 = 0,\"\" \"no\"").as_deref(), Some(""));
        assert_eq!(pick("IF 1 = 1,000 \"yes\" \"no\"").as_deref(), Some("no"));
        assert_eq!(
            pick("IF 1000 = 1,000 \"yes\" \"no\"").as_deref(),
            Some("yes")
        );
        assert_eq!(pick("IF 0 = 0,5 \"yes\" \"no\"").as_deref(), Some("no"));
    }

    #[test]
    fn ends_a_word_at_a_nested_field_outside_quotes() {
        let page = || CodePart::Field(Content::PageNumber);
        let read = |parts: &[CodePart]| words(parts, |_| "1".to_owned());
        assert_eq!(
            read(&[text(" IF "), page(), text("= 1 \"y\" \"n\"")]),
            ["IF", "1", "=", "1", "y", "n"]
        );
        assert_eq!(read(&[text(" IF 1 ="), page()]), ["IF", "1", "=", "1"]);
        assert_eq!(
            read(&[text(" IF "), page(), text("1 = 11")]),
            ["IF", "1", "1", "=", "11"]
        );
        assert_eq!(
            read(&[text(" IF 1"), page(), text(" = 11")]),
            ["IF", "1", "1", "=", "11"]
        );
        assert_eq!(read(&[text(" IF "), page(), page()]), ["IF", "1", "1"]);
        assert_eq!(
            read(&[text(" IF \""), page(), text("1\" = 11")]),
            ["IF", "11", "=", "11"]
        );
    }

    #[test]
    fn ends_a_word_at_each_quote_mark() {
        let read = |code: &str| words(&[text(code)], |_| String::new());
        assert_eq!(read(" IF \"a\"=\"a\" \"y\""), ["IF", "a", "=", "a", "y"]);
        assert_eq!(read(" IF 1\"1\" = 11"), ["IF", "1", "1", "=", "11"]);
        assert_eq!(read(" IF 1=1 \"\""), ["IF", "1=1", ""]);
    }

    #[test]
    fn compares_an_empty_nested_value_with_an_empty_text() {
        let parts = [
            text(" IF "),
            CodePart::Field(Content::PageNumber),
            text("= \"\" \"empty\" \"text\""),
        ];
        let pick = |value: &'static str| choose(&words(&parts, |_| value.to_owned()));
        assert_eq!(pick("").as_deref(), Some("empty"));
        assert_eq!(pick("A1").as_deref(), Some("text"));
    }
}