f-office-docx 0.3.0

DOCX model and Word's layout rules.
Documentation
//! Comments (`word/comments.xml`), which Word prints in balloons beside the page.

use std::collections::{HashMap, HashSet};

use f_office_xml::{Document, NodeId};

use crate::body::{Block, read_story};
use crate::ns::{W, W14, W15};
use crate::reader::PartReader;

/// One comment.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Comment {
    /// The author's initials (`w:initials`), which the balloon's label shows.
    pub initials: String,
    /// The text of the comment.
    pub blocks: Vec<Block>,
    /// The ID (`w14:paraId`) of the comment's last paragraph, which names the comment in the
    /// part that links replies.
    pub para_id: Option<String>,
    /// The ID of the comment that this one replies to.
    pub parent: Option<String>,
    /// Whether Word shows no balloon for the comment: a mark of its range lies outside a
    /// paragraph, or it replies to such a comment. It still takes its number.
    pub hidden: bool,
}

/// The comments of a document by ID.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Comments {
    /// The comments by `w:id`.
    pub by_id: HashMap<String, Comment>,
    /// Whether the body holds a deleted table cell (`w:cellDel`), which shows a balloon of its
    /// own.
    pub deleted_cells: bool,
}

impl Comments {
    /// Reads the comments part (`w:comments`).
    pub(crate) fn read(reader: &mut PartReader, root: NodeId) -> Self {
        let doc = reader.doc;
        let mut by_id = HashMap::new();
        for node in doc
            .child_elements(root)
            .filter(|n| doc.is(*n, W, "comment"))
        {
            let Some(id) = doc.attribute(node, Some(W), "id") else {
                continue;
            };
            let initials = doc.attribute(node, Some(W), "initials").unwrap_or("");
            let para_id = doc
                .child_elements(node)
                .filter(|n| doc.is(*n, W, "p"))
                .last()
                .and_then(|p| doc.attribute(p, Some(W14), "paraId"))
                .map(str::to_owned);
            let comment = Comment {
                initials: initials.to_owned(),
                blocks: read_story(reader, node),
                para_id,
                parent: None,
                hidden: false,
            };
            by_id.insert(id.to_owned(), comment);
        }
        Self {
            by_id,
            deleted_cells: false,
        }
    }

    /// Links replies to the comments that they answer, from the part that names each comment's
    /// last paragraph and its parent's (`w15:commentsEx`).
    pub fn link_replies(&mut self, parents: &HashMap<String, String>) {
        let ids: HashMap<String, String> = self
            .by_id
            .iter()
            .filter_map(|(id, c)| c.para_id.clone().map(|p| (p, id.clone())))
            .collect();
        for comment in self.by_id.values_mut() {
            let parent = comment.para_id.as_ref().and_then(|p| parents.get(p));
            comment.parent = parent.and_then(|p| ids.get(p)).cloned();
        }
    }

    /// Hides the comments with these IDs, and the replies to them.
    pub fn hide(&mut self, ids: &HashSet<String>) {
        for (id, comment) in &mut self.by_id {
            let parent = comment.parent.as_ref().is_some_and(|p| ids.contains(p));
            comment.hidden = ids.contains(id) || parent;
        }
    }
}

/// The IDs of the comments whose range ends (`w:commentRangeEnd`) outside a paragraph, such
/// as between a table and the paragraph after it. Word writes this mark inside a paragraph,
/// and shows no balloon for such a comment. A range that starts outside a paragraph still
/// shows.
pub fn marked_outside_paragraphs(doc: &Document, node: NodeId) -> HashSet<String> {
    let mut out = HashSet::new();
    walk_marks(doc, node, &mut None, &mut out);
    out
}

/// Whether the tree below `node` holds a deleted table cell (`w:cellDel`).
pub fn holds_deleted_cells(doc: &Document, node: NodeId) -> bool {
    doc.child_elements(node)
        .any(|child| doc.is(child, W, "cellDel") || holds_deleted_cells(doc, child))
}

/// What a walk has seen of the paragraph that it is in.
#[derive(Default)]
struct Seen {
    /// Whether the paragraph has text before the current node.
    text: bool,
    /// The comments whose range starts in the paragraph.
    starts: HashSet<String>,
}

/// Walks the marks below `node`. `seen` is `None` outside a paragraph.
fn walk_marks(doc: &Document, node: NodeId, seen: &mut Option<Seen>, out: &mut HashSet<String>) {
    for child in doc.child_elements(node) {
        if seen.is_none() && doc.is(child, W, "p") {
            walk_marks(doc, child, &mut Some(Seen::default()), out);
            continue;
        }
        let id = || doc.attribute(child, Some(W), "id").map(str::to_owned);
        if doc.is(child, W, "commentRangeStart")
            && let Some(paragraph) = seen.as_mut()
        {
            paragraph.starts.extend(id());
        }
        // A range that ends before the text of a paragraph, and started before it, ends
        // between paragraphs too.
        if doc.is(child, W, "commentRangeEnd") {
            let ends_outside = match seen {
                None => true,
                Some(paragraph) => {
                    !paragraph.text && id().is_some_and(|id| !paragraph.starts.contains(&id))
                }
            };
            if ends_outside {
                out.extend(id());
            }
        }
        if let Some(paragraph) = seen.as_mut()
            && (doc.is(child, W, "t") || doc.is(child, W, "delText"))
            && doc
                .children(child)
                .iter()
                .filter_map(|c| doc.text(*c))
                .any(|t| !t.is_empty())
        {
            paragraph.text = true;
        }
        walk_marks(doc, child, seen, out);
    }
}

/// Reads the part that links replies (`w15:commentsEx`): the parent paragraph ID of each
/// comment's last paragraph ID.
pub fn read_parents(doc: &Document, root: NodeId) -> HashMap<String, String> {
    doc.child_elements(root)
        .filter(|n| doc.is(*n, W15, "commentEx"))
        .filter_map(|n| {
            let id = doc.attribute(n, Some(W15), "paraId")?;
            let parent = doc.attribute(n, Some(W15), "paraIdParent")?;
            Some((id.to_owned(), parent.to_owned()))
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::{Comments, read_parents};
    use crate::reader::PartReader;
    use f_office_xml::{Document, Limits};

    fn parse(xml: &str) -> Document {
        Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
    }

    #[test]
    fn reads_comments_with_their_initials_and_text() {
        let xml = r#"<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:comment w:id="3" w:author="A" w:initials="AB"><w:p><w:r><w:t>Hi</w:t></w:r></w:p></w:comment><w:comment w:author="no id"/></w:comments>"#;
        let doc = parse(xml);
        let comments = Comments::read(&mut PartReader::new(&doc), doc.root().unwrap());
        assert_eq!(comments.by_id.len(), 1);
        let comment = &comments.by_id["3"];
        assert_eq!(comment.initials, "AB");
        assert_eq!(comment.blocks.len(), 1);
    }

    #[test]
    fn links_a_reply_to_its_comment_by_paragraph_ids() {
        let xml = r#"<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:comment w:id="0"><w:p w14:paraId="A1"/></w:comment><w:comment w:id="1"><w:p w14:paraId="B0"/><w:p w14:paraId="B1"/></w:comment></w:comments>"#;
        let doc = parse(xml);
        let mut comments = Comments::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let ex = r#"<w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml"><w15:commentEx w15:paraId="A1" w15:done="0"/><w15:commentEx w15:paraId="B1" w15:paraIdParent="A1"/></w15:commentsEx>"#;
        let ex = parse(ex);
        comments.link_replies(&read_parents(&ex, ex.root().unwrap()));
        assert_eq!(comments.by_id["1"].parent.as_deref(), Some("0"));
        assert_eq!(comments.by_id["0"].parent, None);
        // A mark outside a paragraph hides the comment and its reply.
        comments.hide(&["0".to_owned()].into_iter().collect());
        assert!(comments.by_id["0"].hidden && comments.by_id["1"].hidden);
    }

    #[test]
    fn finds_range_marks_outside_paragraphs() {
        let xml = r#"<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p><w:commentRangeStart w:id="1"/><w:r><w:t>a</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:commentRangeEnd w:id="2"/><w:p/></w:tc></w:tr></w:tbl><w:commentRangeStart w:id="4"/><w:commentRangeEnd w:id="3"/><w:p><w:hyperlink><w:r><w:t>b</w:t></w:r><w:commentRangeEnd w:id="1"/></w:hyperlink></w:p></w:body>"#;
        let doc = parse(xml);
        let marks = super::marked_outside_paragraphs(&doc, doc.root().unwrap());
        let mut ids: Vec<&String> = marks.iter().collect();
        ids.sort();
        assert_eq!(ids, ["2", "3"]);
    }

    #[test]
    fn counts_a_range_end_before_the_text_of_a_later_paragraph_as_outside() {
        // Range 5 covers a table and ends before the text of the next paragraph. Range 6 ends
        // after a space, and range 7 starts and ends before the text of its paragraph.
        let xml = r#"<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p><w:commentRangeStart w:id="5"/><w:commentRangeStart w:id="6"/><w:r><w:t>a</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>b</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:commentRangeEnd w:id="5"/><w:r><w:t>c</w:t></w:r></w:p><w:p><w:r><w:t xml:space="preserve"> </w:t></w:r><w:commentRangeEnd w:id="6"/></w:p><w:p><w:commentRangeStart w:id="7"/><w:commentRangeEnd w:id="7"/><w:r><w:t>d</w:t></w:r></w:p></w:body>"#;
        let doc = parse(xml);
        let marks = super::marked_outside_paragraphs(&doc, doc.root().unwrap());
        let ids: Vec<&String> = marks.iter().collect();
        assert_eq!(ids, ["5"]);
    }

    #[test]
    fn finds_deleted_table_cells() {
        let doc = parse(
            r#"<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:tbl><w:tr><w:tc><w:tcPr><w:cellDel w:id="1" w:author="A"/></w:tcPr><w:p/></w:tc></w:tr></w:tbl></w:body>"#,
        );
        assert!(super::holds_deleted_cells(&doc, doc.root().unwrap()));
        let plain = parse(
            r#"<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p/></w:body>"#,
        );
        assert!(!super::holds_deleted_cells(&plain, plain.root().unwrap()));
    }
}