f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! Character styles of hyperlinks inside stored TOC results. This changes only the
//! parsed copy used for layout; the package and its editing tree stay intact.

use f_office_xml::{Document, NodeId};

use crate::body::field_code;
use crate::body::{FIELD_CHAR, FieldChar, ParagraphIds};
use crate::props::{RunProps, UNDERLINE, Underline};
use crate::{ns::W, reader::PartReader, styles::Styles};

/// A field that is open at the current node: its code until its result starts, and whether
/// its result has started and the field is a TOC.
#[derive(Default)]
struct Field {
    code: String,
    result: bool,
    toc: bool,
}

/// The fields that are open at the current node, with the count of those whose result has
/// started and that are a TOC, so that a text node asks one count and not every open field.
#[derive(Default)]
struct Fields {
    open: Vec<Field>,
    toc_results: usize,
}

impl Fields {
    /// Opens a field at its begin character.
    fn begin(&mut self) {
        self.open.push(Field::default());
    }

    /// Opens a simple field, whose result starts at once.
    fn simple(&mut self, code: &str) {
        self.open.push(Field {
            code: code.to_owned(),
            ..Field::default()
        });
        self.separate();
    }

    /// Adds instruction text to the code of the innermost field, if its result has not
    /// started.
    fn code(&mut self, text: &str) {
        if let Some(field) = self.open.last_mut().filter(|f| !f.result) {
            field.code.push_str(text);
        }
    }

    /// Starts the result of the innermost field; its code is whole from here on.
    fn separate(&mut self) {
        if let Some(field) = self.open.last_mut().filter(|f| !f.result) {
            field.result = true;
            field.toc =
                field_code::kind(&field.code).is_some_and(|kind| kind.eq_ignore_ascii_case("TOC"));
            self.toc_results += usize::from(field.toc);
        }
    }

    /// Closes the innermost field.
    fn end(&mut self) {
        if let Some(field) = self.open.pop() {
            self.toc_results -= usize::from(field.toc);
        }
    }

    /// Whether the current node is inside the result of a TOC.
    const fn in_toc_result(&self) -> bool {
        self.toc_results > 0
    }
}

/// Prepares the links of the tables of contents before runs lose their XML context, in the part
/// `part`, whose XML is `doc`, as a target whose TOC links leave out the style that the TOC
/// selects reads them (the reader's settings choose it). Its readers of values read no paragraph, but take the
/// document's source of paragraph IDs `ids`, as every part reader does.
pub(crate) fn prepare(doc: &mut Document, (part, ids): (&str, &ParagraphIds), styles: &Styles) {
    if let Ok(root) = doc.root() {
        walk(
            doc,
            (part, ids),
            root,
            styles,
            false,
            &mut Fields::default(),
        );
    }
}

/// Return whether text was seen inside and outside the combined TOC-link context.
fn walk(
    doc: &mut Document,
    (part, ids): (&str, &ParagraphIds),
    node: NodeId,
    styles: &Styles,
    linked: bool,
    fields: &mut Fields,
) -> (bool, bool) {
    if crate::ns::is_text_box_content(doc, node)
        || ["footnote", "endnote"]
            .iter()
            .any(|name| doc.is(node, W, name))
    {
        let mut own = Fields::default();
        let children = doc.child_elements(node).collect::<Vec<_>>();
        for child in children {
            walk(doc, (part, ids), child, styles, false, &mut own);
        }
        return (false, false);
    }
    let simple = doc.is(node, W, "fldSimple");
    if simple {
        fields.simple(doc.attribute(node, Some(W), "instr").unwrap_or_default());
    }
    read_field(doc, (part, ids), node, fields);
    let linked = linked || doc.is(node, W, "hyperlink");
    let mut seen = (false, false);
    if doc.is(node, W, "t") || doc.is(node, W, "delText") {
        let inside = linked && fields.in_toc_result();
        seen = (inside, !inside);
    }
    let children = doc.child_elements(node).collect::<Vec<_>>();
    for child in children {
        let child = walk(doc, (part, ids), child, styles, linked, fields);
        seen.0 |= child.0;
        seen.1 |= child.1;
    }
    if doc.is(node, W, "r") && seen.0 && !seen.1 {
        omit_style(doc, (part, ids), node, styles);
    }
    if simple {
        fields.end();
    }
    seen
}

fn read_field(
    doc: &Document,
    (part, ids): (&str, &ParagraphIds),
    node: NodeId,
    fields: &mut Fields,
) {
    if doc.is(node, W, "fldChar") {
        // The reader of the part reads this field character again and keeps its warnings.
        match PartReader::of_part(doc, part, ids).enumeration(node, "fldCharType", FIELD_CHAR) {
            Some(FieldChar::Begin) => fields.begin(),
            Some(FieldChar::Separate) => fields.separate(),
            Some(FieldChar::End) => fields.end(),
            None => {}
        }
    } else if doc.is(node, W, "instrText") {
        fields.code(&doc.text_content(node));
    }
}

fn omit_style(
    doc: &mut Document,
    (part, ids): (&str, &ParagraphIds),
    run: NodeId,
    styles: &Styles,
) {
    let Some(rpr) = doc.child(run, W, "rPr") else {
        return;
    };
    let Some(style_node) = doc.child(rpr, W, "rStyle") else {
        return;
    };
    let Some(id) = doc
        .attribute(style_node, Some(W), "val")
        .filter(|id| styles.is_link_style(id))
    else {
        return;
    };
    let style = styles.character(id);
    // The reader of the part reads this `w:rPr` again and keeps the warnings of its values.
    let direct = RunProps::read(&mut PartReader::of_part(doc, part, ids), rpr);
    let underline = styles.character_underline(id);
    let children = doc
        .children(rpr)
        .iter()
        .copied()
        .filter(|child| {
            if *child == style_node {
                return false;
            }
            if doc.is(*child, W, "color") && direct.color.is_some() && direct.color == style.color {
                return false;
            }
            if doc.is(*child, W, "b") && direct.bold.is_some() && direct.bold == style.bold {
                return false;
            }
            // The reader of the part reads this `w:u` again and keeps the warning of its value.
            let kind = || {
                PartReader::of_part(doc, part, ids)
                    .enumeration(*child, "val", UNDERLINE)
                    .unwrap_or(Underline::Single)
            };
            !(doc.is(*child, W, "u") && underline == Some(kind()))
        })
        .collect();
    doc.set_children(rpr, children);
}

#[cfg(test)]
mod tests;