Skip to main content

jubarte_doc/
comments.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Comment threads: list every comment with its thread position and the
6//! text it is anchored to, and write the comment part family whole.
7//!
8//! Word keeps one comment across up to five parts. `word/comments.xml`
9//! holds the `w:comment` definitions; each comment paragraph carries a
10//! `w14:paraId`, and the paraId of a comment's last paragraph is its key in
11//! the other parts. `commentsExtended.xml` (`w15:commentEx`) records the
12//! thread (`w15:paraIdParent`) and resolution (`w15:done`);
13//! `commentsIds.xml` maps the key to a `w16cid:durableId`;
14//! `commentsExtensible.xml` carries the UTC date by durable id; and
15//! `people.xml` lists the authors. `CommentFamily` loads all of them and
16//! writes them back consistent: every comment paragraph has a paraId, and
17//! each extended part has exactly one row per comment.
18//!
19//! Word threads are one level deep: a reply to a reply hangs off the
20//! thread's first comment.
21
22use std::collections::{BTreeMap, HashMap, HashSet};
23use std::fmt;
24
25use serde::{Deserialize, Serialize};
26
27use crate::comparer::comments::FAMILY;
28use crate::inspect::{Opened, project_paragraph};
29use crate::namespaces::{MC, W, W14, W15};
30use crate::opc::PartFs;
31use crate::xmllinq::{Dom, NodeId, XName, XNamespace};
32
33const CID: &str = "http://schemas.microsoft.com/office/word/2016/wordml/cid";
34const CEX: &str = "http://schemas.microsoft.com/office/word/2018/wordml/cex";
35const PEOPLE_REL: &str = "http://schemas.microsoft.com/office/2011/relationships/people";
36/// Characters of context kept on either side of an anchor.
37const CONTEXT: usize = 80;
38/// Bytes of anchor text one listing may hold (#2067). Every comment copies
39/// its whole range exactly, since `edit -p cN.text` resolves inside it, so
40/// thousands of comments on one long range would copy it thousands of times.
41/// Past this a listing refuses with `INPUT_LIMIT`, as a part past
42/// [`crate::admission::InputLimits::max_part_bytes`] does, instead of
43/// holding a truncated anchor.
44const ANCHOR_BYTE_BUDGET: usize = 64 * 1024 * 1024;
45/// First sentinel code point used to locate range markers in a projection
46/// (supplementary private use area B, which no Word symbol font uses).
47const SENTINEL: u32 = 0x10_0000;
48
49/// One comment with its thread position and where it sits.
50#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub struct CommentRecord {
52    /// `w:id` of the comment.
53    pub id: u32,
54    /// The id the view and `jubarte comments` print: `c{id}`.
55    #[serde(default, rename = "ref")]
56    pub r#ref: String,
57    /// `w:author`.
58    pub author: String,
59    /// `w:initials`.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub initials: Option<String>,
62    /// The linked UTC instant, written in the author's local offset when both
63    /// times record a whole-minute difference within ±14:00; otherwise `Z`.
64    /// Without a valid `w16cex:dateUtc`, `w:date` as stored.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub date: Option<String>,
67    /// Comment text, paragraphs (and line breaks) joined by `\n`.
68    pub text: String,
69    /// `w:id` of the comment this one replies to.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub parent: Option<u32>,
72    /// `w15:done`: the thread is resolved.
73    pub done: bool,
74    /// Story and paragraph id of the range start (`p12`), or of the
75    /// reference when the comment has no range.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub paragraph: Option<String>,
78    /// Story and paragraph id of the range end (`p14`) when the range
79    /// ends in a later paragraph than it starts; `None` otherwise.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub last_paragraph: Option<String>,
82    /// The anchored text, exact; paragraphs joined by `\n`.
83    pub anchor_text: String,
84    /// Up to 80 characters before the anchor in its first paragraph.
85    pub before: String,
86    /// Up to 80 characters after the anchor in its last paragraph.
87    pub after: String,
88}
89
90/// Why comments could not be listed.
91#[derive(Debug)]
92pub enum CommentError {
93    /// Refused before parsing by [`crate::admission`].
94    Admission(crate::admission::AdmissionError),
95    /// The package or one of its parts could not be read.
96    Package(String),
97}
98
99impl CommentError {
100    /// Stable error code, as the edit API reports it: the admission code, or
101    /// `INVALID_DOCUMENT` for an unreadable package.
102    pub fn code(&self) -> &'static str {
103        match self {
104            CommentError::Admission(refused) => refused.code(),
105            CommentError::Package(_) => "INVALID_DOCUMENT",
106        }
107    }
108}
109
110impl fmt::Display for CommentError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            CommentError::Admission(refused) => write!(f, "{}", refused.message),
114            CommentError::Package(m) => write!(f, "invalid package: {m}"),
115        }
116    }
117}
118
119impl std::error::Error for CommentError {}
120
121impl From<crate::inspect::InspectError> for CommentError {
122    fn from(error: crate::inspect::InspectError) -> Self {
123        match error {
124            crate::inspect::InspectError::Admission(refused) => CommentError::Admission(refused),
125            other => CommentError::Package(other.to_string()),
126        }
127    }
128}
129
130/// Every comment in `comments.xml` order, with its thread, resolution and
131/// anchor. Backs `jubarte comments`. A document without comments lists none.
132/// Nothing is written.
133///
134/// # Errors
135///
136/// [`CommentError::Admission`] when the bytes are refused before parsing;
137/// [`CommentError::Package`] when the package or one of its parts cannot be
138/// read.
139pub fn list_comments(docx: &[u8]) -> Result<Vec<CommentRecord>, CommentError> {
140    comments_in(&mut Opened::open(docx)?)
141}
142
143/// [`list_comments`] under `limits`, for a command that already admitted
144/// the same bytes at that budget.
145pub(crate) fn list_comments_within(
146    docx: &[u8],
147    limits: crate::admission::InputLimits,
148) -> Result<Vec<CommentRecord>, CommentError> {
149    comments_in(&mut Opened::open_within(docx, limits)?)
150}
151
152/// [`list_comments`] of a package already open. The scan marks up the
153/// body's DOM, so read what else `opened` holds first.
154pub(crate) fn comments_in(opened: &mut Opened) -> Result<Vec<CommentRecord>, CommentError> {
155    comments_within_budget(opened, ANCHOR_BYTE_BUDGET)
156}
157
158/// [`comments_in`] with `budget` bytes of anchor text for the listing.
159fn comments_within_budget(
160    opened: &mut Opened,
161    budget: usize,
162) -> Result<Vec<CommentRecord>, CommentError> {
163    let family = CommentFamily::load(&opened.pkg, &opened.main).map_err(CommentError::Package)?;
164    if family.is_empty() {
165        return Ok(Vec::new());
166    }
167    let mut anchors = Anchors {
168        budget,
169        ..Anchors::default()
170    };
171    anchors.scan("body", &mut opened.dom, opened.body, true);
172    for (id, _, part) in opened.story_parts() {
173        let (mut dom, _, root) = crate::inspect::parse_part(&opened.pkg, &part)?;
174        anchors.scan(&id, &mut dom, root, false);
175    }
176    family
177        .order()
178        .into_iter()
179        .map(|id| {
180            let mut record = family.record(id);
181            anchors.fill(&mut record)?;
182            Ok(record)
183        })
184        .collect()
185}
186
187/// `jubarte comments`' listing: one line per comment, `c{id}\t{paragraph}
188/// \t{author}\t{text}\ton {anchor}[\treply to c{parent}][\tresolved]`
189/// (`-` for an absent paragraph; text and anchor quoted, their first 60 and
190/// 40 characters), then `{n} comment(s)`.
191pub fn comments_text(comments: &[CommentRecord]) -> String {
192    let mut out = String::new();
193    for c in comments {
194        let text: String = c.text.chars().take(60).collect();
195        let anchor: String = c.anchor_text.chars().take(40).collect();
196        let paragraph = c
197            .paragraph
198            .as_deref()
199            .map_or_else(|| "-".to_string(), crate::ids::short_paragraph);
200        let thread = c
201            .parent
202            .map(|p| format!("\treply to c{p}"))
203            .unwrap_or_default();
204        let done = if c.done { "\tresolved" } else { "" };
205        out.push_str(&format!(
206            "c{}\t{paragraph}\t{}\t{text:?}\ton {anchor:?}{thread}{done}\n",
207            c.id, c.author
208        ));
209    }
210    out.push_str(&format!("{} comment(s)\n", comments.len()));
211    out
212}
213
214/// Filter a listing: `author` keeps that author's comments (exact match);
215/// `latest` keeps one comment per thread, the newest by `date` (later in the
216/// listing on a tie), threads in the order their first comment appears.
217pub fn select_comments(
218    records: Vec<CommentRecord>,
219    author: Option<&str>,
220    latest: bool,
221) -> Vec<CommentRecord> {
222    let parents: HashMap<u32, Option<u32>> = records.iter().map(|r| (r.id, r.parent)).collect();
223    let root_of = |mut id: u32| {
224        let mut seen = HashSet::new();
225        while let Some(Some(parent)) = parents.get(&id) {
226            if !seen.insert(id) {
227                break;
228            }
229            id = *parent;
230        }
231        id
232    };
233    let kept = records
234        .into_iter()
235        .filter(|r| author.is_none_or(|a| r.author == a));
236    if !latest {
237        return kept.collect();
238    }
239    let mut threads: Vec<(u32, CommentRecord)> = Vec::new();
240    for record in kept {
241        let root = root_of(record.id);
242        match threads.iter_mut().find(|(r, _)| *r == root) {
243            Some((_, best)) => {
244                if record
245                    .date
246                    .as_deref()
247                    .and_then(crate::util::datetime::timestamp_order_key)
248                    >= best
249                        .date
250                        .as_deref()
251                        .and_then(crate::util::datetime::timestamp_order_key)
252                {
253                    *best = record;
254                }
255            }
256            None => threads.push((root, record)),
257        }
258    }
259    threads.into_iter().map(|(_, record)| record).collect()
260}
261
262/// Where each comment's markers sit, story by story.
263#[derive(Default)]
264struct Anchors {
265    /// `(story id, paragraph texts)`, sentinels removed.
266    stories: Vec<(String, Vec<String>)>,
267    /// Comment id → (story, paragraph, byte offset) of the range start.
268    starts: HashMap<String, (usize, usize, usize)>,
269    ends: HashMap<String, (usize, usize, usize)>,
270    /// Comment id → (story, paragraph) of the reference.
271    references: HashMap<String, (usize, usize)>,
272    /// Bytes of anchor text this listing may still own.
273    budget: usize,
274}
275
276impl Anchors {
277    /// Locate every marker of one story. Sentinel runs are inserted before
278    /// in-paragraph range markers so the projection reports their offsets;
279    /// the DOM is a throwaway copy.
280    fn scan(&mut self, story_id: &str, dom: &mut Dom, root: NodeId, body: bool) {
281        let story = self.stories.len();
282        let paragraphs = if body {
283            crate::inspect::body_paragraph_nodes(dom, root)
284        } else {
285            crate::inspect::story_paragraph_nodes(dom, root)
286        };
287        let index: HashMap<NodeId, usize> = paragraphs
288            .iter()
289            .enumerate()
290            .map(|(i, &p)| (p, i))
291            .collect();
292        let order: HashMap<NodeId, usize> = dom
293            .descendants(root, None)
294            .into_iter()
295            .enumerate()
296            .map(|(i, n)| (n, i))
297            .collect();
298        let paragraph_of = |dom: &Dom, node: NodeId| {
299            dom.ancestors(node, Some(&W::p()))
300                .into_iter()
301                .find_map(|p| index.get(&p).copied())
302        };
303        // (sentinel char, comment id, is start) per paragraph.
304        let mut sentinels: HashMap<char, (String, bool)> = HashMap::new();
305        let mut block: Vec<(String, bool, usize)> = Vec::new();
306        let mut next = SENTINEL;
307        for local in ["commentRangeStart", "commentRangeEnd", "commentReference"] {
308            for marker in dom.descendants(root, Some(&W::name(local))) {
309                let Some(id) = dom.attribute(marker, &W::id()).map(str::to_string) else {
310                    continue;
311                };
312                let para = paragraph_of(dom, marker);
313                if local == "commentReference" {
314                    if let Some(para) = para {
315                        self.references.entry(id).or_insert((story, para));
316                    }
317                    continue;
318                }
319                let start = local == "commentRangeStart";
320                match para {
321                    Some(_) => {
322                        let Some(sentinel) = char::from_u32(next) else {
323                            continue;
324                        };
325                        next += 1;
326                        let run = dom.new_element(W::r());
327                        let t = dom.new_element(W::t());
328                        dom.add_text(t, &sentinel.to_string());
329                        dom.add(run, t);
330                        dom.add_before_self(marker, run);
331                        sentinels.insert(sentinel, (id, start));
332                    }
333                    None => {
334                        // A block-level marker: the range starts at the next
335                        // paragraph or ends with the previous one.
336                        let at = order.get(&marker).copied().unwrap_or(0);
337                        let neighbour = if start {
338                            paragraphs.iter().position(|p| order[p] > at)
339                        } else {
340                            paragraphs.iter().rposition(|p| order[p] < at)
341                        };
342                        if let Some(para) = neighbour {
343                            block.push((id, start, para));
344                        }
345                    }
346                }
347            }
348        }
349        let mut texts = Vec::with_capacity(paragraphs.len());
350        for (para, &node) in paragraphs.iter().enumerate() {
351            let projection = project_paragraph(dom, node);
352            let mut text = String::with_capacity(projection.text.len());
353            for c in projection.text.chars() {
354                match sentinels.get(&c) {
355                    Some((id, true)) => {
356                        self.starts
357                            .entry(id.clone())
358                            .or_insert((story, para, text.len()));
359                    }
360                    Some((id, false)) => {
361                        self.ends
362                            .entry(id.clone())
363                            .or_insert((story, para, text.len()));
364                    }
365                    None => text.push(c),
366                }
367            }
368            texts.push(text);
369        }
370        for (id, start, para) in block {
371            if start {
372                self.starts.entry(id).or_insert((story, para, 0));
373            } else {
374                let end = texts[para].len();
375                self.ends.entry(id).or_insert((story, para, end));
376            }
377        }
378        self.stories.push((story_id.to_string(), texts));
379    }
380
381    /// Writes `record`'s anchor, exact, and charges it to the listing's
382    /// budget; refuses with `INPUT_LIMIT` once the anchors pass it.
383    fn fill(&mut self, record: &mut CommentRecord) -> Result<(), CommentError> {
384        self.write_anchor(record);
385        let held = record.anchor_text.len();
386        if held > self.budget {
387            return Err(CommentError::Admission(
388                crate::admission::AdmissionError::new(
389                    crate::admission::AdmissionErrorKind::InputLimit,
390                    format!(
391                        "comment anchors pass the {} bytes one listing may hold: c{} \
392                         covers {held} bytes with {} left",
393                        ANCHOR_BYTE_BUDGET, record.id, self.budget
394                    ),
395                ),
396            ));
397        }
398        self.budget -= held;
399        Ok(())
400    }
401
402    fn write_anchor(&self, record: &mut CommentRecord) {
403        let id = record.id.to_string();
404        let start = self.starts.get(&id).copied();
405        let end = self.ends.get(&id).copied();
406        let paragraph_id =
407            |story: usize, para: usize| crate::ids::paragraph_id(&self.stories[story].0, para);
408        match (start, end) {
409            (Some((story, first, s)), Some((end_story, last, e))) if story != end_story => {
410                // A range cannot cross parts in OOXML, so this malformed
411                // input is still recorded as a range: both endpoints are
412                // real marks and neither may be dropped.
413                record.paragraph = Some(paragraph_id(story, first));
414                record.last_paragraph = Some(paragraph_id(end_story, last));
415                record.anchor_text = self.stories[story].1[first][s..].to_string();
416                record.before = tail(&self.stories[story].1[first][..s], CONTEXT);
417                record.after = self.stories[end_story].1[last][e..]
418                    .chars()
419                    .take(CONTEXT)
420                    .collect();
421            }
422            (Some((story, first, s)), Some((end_story, last, e))) if story == end_story => {
423                // A malformed input may name the end before the start; the
424                // range still spans its paragraphs, start to end.
425                let (first, s, last, e) = if (first, s) <= (last, e) {
426                    (first, s, last, e)
427                } else {
428                    (last, e, first, s)
429                };
430                let texts = &self.stories[story].1;
431                record.paragraph = Some(paragraph_id(story, first));
432                record.last_paragraph = (last > first).then(|| paragraph_id(story, last));
433                if first == last {
434                    record.anchor_text = texts[first][s..e].to_string();
435                } else {
436                    let mut anchor = texts[first][s..].to_string();
437                    for text in &texts[first + 1..last] {
438                        anchor.push('\n');
439                        anchor.push_str(text);
440                    }
441                    anchor.push('\n');
442                    anchor.push_str(&texts[last][..e]);
443                    record.anchor_text = anchor;
444                }
445                record.before = tail(&texts[first][..s], CONTEXT);
446                record.after = texts[last][e..].chars().take(CONTEXT).collect();
447            }
448            _ => {
449                if let Some(&(story, para)) = self.references.get(&id) {
450                    record.paragraph = Some(paragraph_id(story, para));
451                }
452            }
453        }
454    }
455}
456
457/// The last `n` characters of `text`.
458fn tail(text: &str, n: usize) -> String {
459    let count = text.chars().count();
460    text.chars().skip(count.saturating_sub(n)).collect()
461}
462
463/// A new comment for [`CommentFamily::add`].
464#[doc(hidden)]
465pub struct NewComment<'a> {
466    #[doc(hidden)]
467    pub id: u32,
468    #[doc(hidden)]
469    pub author: &'a str,
470    #[doc(hidden)]
471    pub date: &'a str,
472    #[doc(hidden)]
473    pub initials: &'a str,
474    /// `\n` starts a new line (a `w:br`), as the edit plan writes comments.
475    #[doc(hidden)]
476    pub text: &'a str,
477    /// The comment replied to; the reply joins that comment's thread.
478    #[doc(hidden)]
479    pub parent: Option<u32>,
480}
481
482/// One parsed part of the family.
483struct Part {
484    name: String,
485    doc: NodeId,
486    root: NodeId,
487}
488
489/// What the extended parts say about one comment.
490struct Meta {
491    node: NodeId,
492    parent: Option<u32>,
493    done: bool,
494    ext_row: Option<NodeId>,
495    id_row: Option<NodeId>,
496    cex_row: Option<NodeId>,
497}
498
499/// The comment part family of one package, loaded for reading and editing
500/// (module docs).
501#[doc(hidden)]
502pub struct CommentFamily {
503    dom: Dom,
504    /// comments, commentsExtended, commentsIds, commentsExtensible.
505    parts: [Option<Part>; 4],
506    meta: BTreeMap<u32, Meta>,
507    /// Authors of removed comments, for pruning `people.xml`.
508    removed_authors: HashSet<String>,
509    /// Authors of added comments, for `people.xml` when it exists.
510    added_authors: Vec<String>,
511}
512
513impl CommentFamily {
514    /// Load the family the main part `main` relates to.
515    #[doc(hidden)]
516    pub fn load(pkg: &PartFs, main: &str) -> Result<Self, String> {
517        let mut dom = Dom::new();
518        let mut parts: [Option<Part>; 4] = [None, None, None, None];
519        for (k, (_, _, rel_type)) in FAMILY.iter().enumerate() {
520            let Some(name) = related_part(pkg, main, rel_type) else {
521                continue;
522            };
523            let xml = pkg
524                .part_string(&name)
525                .ok_or_else(|| format!("missing part {name}"))?;
526            crate::xmllinq::parse::validate_xml(&xml).map_err(|e| format!("{name}: {e}"))?;
527            let doc = dom.parse_xdocument(&xml);
528            let root = dom
529                .root(doc)
530                .ok_or_else(|| format!("{name}: missing XML root"))?;
531            parts[k] = Some(Part { name, doc, root });
532        }
533        let mut family = Self {
534            dom,
535            parts,
536            meta: BTreeMap::new(),
537            removed_authors: HashSet::new(),
538            added_authors: Vec::new(),
539        };
540        family.read_meta();
541        Ok(family)
542    }
543
544    fn read_meta(&mut self) {
545        let Some(comments) = &self.parts[0] else {
546            return;
547        };
548        let dom = &self.dom;
549        let rows = |k: usize, row: XName, key: XName| -> HashMap<String, NodeId> {
550            self.parts[k].as_ref().map_or_else(HashMap::new, |part| {
551                dom.descendants(part.root, Some(&row))
552                    .into_iter()
553                    .filter_map(|r| dom.attribute(r, &key).map(|v| (v.to_string(), r)))
554                    .collect()
555            })
556        };
557        let ext = rows(1, W15::name("commentEx"), W15::name("paraId"));
558        let ids = rows(2, XName::get("commentId", CID), XName::get("paraId", CID));
559        let cex = rows(
560            3,
561            XName::get("commentExtensible", CEX),
562            XName::get("durableId", CEX),
563        );
564        let mut by_para: HashMap<String, u32> = HashMap::new();
565        let mut parent_para: Vec<(u32, String)> = Vec::new();
566        for node in dom.elements(comments.root, Some(&W::comment())) {
567            let Some(id) = dom
568                .attribute(node, &W::id())
569                .and_then(|v| v.parse::<u32>().ok())
570            else {
571                continue;
572            };
573            let last = last_para_id(dom, node);
574            let ext_row = last.as_ref().and_then(|p| ext.get(p)).copied();
575            let id_row = last.as_ref().and_then(|p| ids.get(p)).copied();
576            let cex_row = id_row
577                .and_then(|r| dom.attribute(r, &XName::get("durableId", CID)))
578                .and_then(|d| cex.get(d))
579                .copied();
580            let done = ext_row
581                .and_then(|r| dom.attribute(r, &W15::name("done")))
582                .is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
583            if let Some(parent) = ext_row.and_then(|r| dom.attribute(r, &W15::name("paraIdParent")))
584            {
585                parent_para.push((id, parent.to_string()));
586            }
587            if let Some(last) = last {
588                by_para.insert(last, id);
589            }
590            self.meta.insert(
591                id,
592                Meta {
593                    node,
594                    parent: None,
595                    done,
596                    ext_row,
597                    id_row,
598                    cex_row,
599                },
600            );
601        }
602        for (id, parent) in parent_para {
603            let parent = by_para.get(&parent).copied().filter(|&p| p != id);
604            if let Some(meta) = self.meta.get_mut(&id) {
605                meta.parent = parent;
606            }
607        }
608    }
609
610    /// No comment is defined.
611    #[doc(hidden)]
612    pub fn is_empty(&self) -> bool {
613        self.meta.is_empty()
614    }
615
616    /// Whether comment `id` is defined.
617    #[doc(hidden)]
618    pub fn contains(&self, id: u32) -> bool {
619        self.meta.contains_key(&id)
620    }
621
622    /// The `w:author` comment `id` is recorded under, when it names one.
623    #[doc(hidden)]
624    pub fn author(&self, id: u32) -> Option<&str> {
625        let meta = self.meta.get(&id)?;
626        self.dom.attribute(meta.node, &W::author())
627    }
628
629    /// Comment ids in `comments.xml` order.
630    #[doc(hidden)]
631    pub fn order(&self) -> Vec<u32> {
632        let Some(comments) = &self.parts[0] else {
633            return Vec::new();
634        };
635        self.dom
636            .elements(comments.root, Some(&W::comment()))
637            .into_iter()
638            .filter_map(|c| {
639                self.dom
640                    .attribute(c, &W::id())
641                    .and_then(|v| v.parse::<u32>().ok())
642            })
643            .filter(|id| self.meta.contains_key(id))
644            .collect()
645    }
646
647    /// The first comment of `id`'s thread.
648    #[doc(hidden)]
649    pub fn thread_root(&self, mut id: u32) -> u32 {
650        let mut seen = HashSet::new();
651        while let Some(parent) = self.meta.get(&id).and_then(|m| m.parent) {
652            if !seen.insert(id) {
653                break;
654            }
655            id = parent;
656        }
657        id
658    }
659
660    /// `id` and every comment that replies to it, directly or not.
661    #[doc(hidden)]
662    pub fn with_replies(&self, id: u32) -> Vec<u32> {
663        let mut out = vec![id];
664        let mut i = 0;
665        while i < out.len() {
666            let current = out[i];
667            for (&child, meta) in &self.meta {
668                if meta.parent == Some(current) && !out.contains(&child) {
669                    out.push(child);
670                }
671            }
672            i += 1;
673        }
674        out
675    }
676
677    fn record(&self, id: u32) -> CommentRecord {
678        let meta = &self.meta[&id];
679        let attr = |name: &str| {
680            self.dom
681                .attribute(meta.node, &W::name(name))
682                .map(str::to_string)
683        };
684        CommentRecord {
685            id,
686            r#ref: format!("c{id}"),
687            author: attr("author").unwrap_or_default(),
688            initials: attr("initials"),
689            date: self.reported_date(id),
690            text: comment_text(&self.dom, meta.node),
691            parent: meta.parent,
692            done: meta.done,
693            paragraph: None,
694            last_paragraph: None,
695            anchor_text: String::new(),
696            before: String::new(),
697            after: String::new(),
698        }
699    }
700
701    /// The comment instant, sharing the revision reader's offset and fallback rule.
702    #[doc(hidden)]
703    pub fn reported_date(&self, id: u32) -> Option<String> {
704        let meta = self.meta.get(&id)?;
705        crate::util::datetime::reported_date(
706            self.dom.attribute(meta.node, &W::date()),
707            meta.cex_row
708                .and_then(|row| self.dom.attribute(row, &XName::get("dateUtc", CEX))),
709        )
710    }
711
712    /// Add a comment; a reply goes right after the last comment of its
713    /// thread and hangs off the thread's first comment.
714    #[doc(hidden)]
715    pub fn add(&mut self, new: &NewComment<'_>) {
716        let root = self.comments_root();
717        let dom = &mut self.dom;
718        let comment = dom.new_element(W::comment());
719        dom.set_attribute_value(comment, &W::id(), Some(&new.id.to_string()));
720        dom.set_attribute_value(comment, &W::author(), Some(new.author));
721        dom.set_attribute_value(comment, &W::date(), Some(new.date));
722        dom.set_attribute_value(comment, &W::name("initials"), Some(new.initials));
723        let p = dom.new_element(W::p());
724        fill_comment_paragraph(dom, p, new.text);
725        dom.add(comment, p);
726        let parent = new.parent.map(|p| self.thread_root(p));
727        let after = parent.and_then(|thread| {
728            self.order()
729                .into_iter()
730                .rev()
731                .find(|&c| self.thread_root(c) == thread)
732                .map(|c| self.meta[&c].node)
733        });
734        match after {
735            Some(node) => self.dom.add_after_self(node, comment),
736            None => self.dom.add(root, comment),
737        }
738        self.meta.insert(
739            new.id,
740            Meta {
741                node: comment,
742                parent,
743                done: false,
744                ext_row: None,
745                id_row: None,
746                cex_row: None,
747            },
748        );
749        if !self.added_authors.iter().any(|a| a == new.author) {
750            self.added_authors.push(new.author.to_string());
751        }
752    }
753
754    /// The root of `comments.xml`, created when the family has none.
755    fn comments_root(&mut self) -> NodeId {
756        if let Some(part) = &self.parts[0] {
757            return part.root;
758        }
759        let doc = self.dom.parse_xdocument(&format!(
760            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:comments xmlns:w="{}" xmlns:r="{}"/>"#,
761            W::URI,
762            crate::namespaces::R::URI
763        ));
764        let root = self.dom.root(doc).expect("root");
765        self.parts[0] = Some(Part {
766            name: FAMILY[0].0.to_string(),
767            doc,
768            root,
769        });
770        root
771    }
772
773    /// The comments part's name: the one the main part relates to, or the
774    /// name [`Self::store`] gives a new one.
775    pub(crate) fn part_name(&self) -> String {
776        self.parts[0]
777            .as_ref()
778            .map_or_else(|| FAMILY[0].0.to_string(), |p| p.name.clone())
779    }
780
781    /// Comment `id`'s thread parent, resolution and UTC date
782    /// (`w16cex:dateUtc`), when `id` is defined.
783    #[doc(hidden)]
784    pub fn thread_state(&self, id: u32) -> Option<(Option<u32>, bool, Option<String>)> {
785        let meta = self.meta.get(&id)?;
786        let date = meta
787            .cex_row
788            .and_then(|row| self.dom.attribute(row, &XName::get("dateUtc", CEX)))
789            .map(str::to_string);
790        Some((meta.parent, meta.done, date))
791    }
792
793    /// Set a linked UTC date before storing the existing comment family.
794    #[doc(hidden)]
795    pub fn set_date_utc(&mut self, id: u32, date: &str) {
796        let Some(meta) = self.meta.get_mut(&id) else {
797            return;
798        };
799        let row = *meta
800            .cex_row
801            .get_or_insert_with(|| self.dom.new_element(XName::get("commentExtensible", CEX)));
802        self.dom
803            .set_attribute_value(row, &XName::get("dateUtc", CEX), Some(date));
804    }
805
806    /// Add a comment copied whole from another package (its formatting,
807    /// line breaks and links stay): `xml` is its `w:comment` element with
808    /// the namespaces it uses declared on it. It takes id `id`, loses its
809    /// paragraphs' paraIds ([`Self::store`] stamps fresh ones, unique in the
810    /// package), and keeps `done` and `date_utc`; it replies to `parent`
811    /// when this family holds `parent`.
812    pub(crate) fn adopt(
813        &mut self,
814        xml: &str,
815        id: u32,
816        parent: Option<u32>,
817        done: bool,
818        date_utc: Option<&str>,
819    ) {
820        let root = self.comments_root();
821        let dom = &mut self.dom;
822        let wrapper = dom.parse_xdocument(&format!("<fragment>{xml}</fragment>"));
823        let Some(comment) = dom
824            .root(wrapper)
825            .and_then(|w| dom.elements(w, Some(&W::comment())).first().copied())
826        else {
827            return;
828        };
829        dom.remove(comment);
830        dom.set_attribute_value(comment, &W::id(), Some(&id.to_string()));
831        for p in dom.descendants(comment, Some(&W::p())) {
832            dom.set_attribute_value(p, &W14::name("paraId"), None);
833            dom.set_attribute_value(p, &W14::name("textId"), None);
834        }
835        dom.add(root, comment);
836        let cex_row = date_utc.map(|date| {
837            let row = dom.new_element(XName::get("commentExtensible", CEX));
838            dom.set_attribute_value(row, &XName::get("dateUtc", CEX), Some(date));
839            row
840        });
841        if let Some(author) = dom.attribute(comment, &W::author()).map(str::to_string)
842            && !self.added_authors.contains(&author)
843        {
844            self.added_authors.push(author);
845        }
846        let parent = parent.filter(|p| self.meta.contains_key(p));
847        self.meta.insert(
848            id,
849            Meta {
850                node: comment,
851                parent,
852                done,
853                ext_row: None,
854                id_row: None,
855                cex_row,
856            },
857        );
858    }
859
860    /// Replace a comment's text. Its last paragraph stays (with its paraId,
861    /// the comment's key in the extended parts); the others go.
862    #[doc(hidden)]
863    pub fn set_text(&mut self, id: u32, text: &str) {
864        let Some(meta) = self.meta.get(&id) else {
865            return;
866        };
867        let comment = meta.node;
868        let dom = &mut self.dom;
869        let keep = dom
870            .descendants(comment, Some(&W::p()))
871            .last()
872            .copied()
873            .unwrap_or_else(|| dom.new_element(W::p()));
874        for child in dom.nodes(comment) {
875            dom.remove(child);
876        }
877        for child in dom.nodes(keep) {
878            if !dom.name_is(child, &W::p_pr()) {
879                dom.remove(child);
880            }
881        }
882        fill_comment_paragraph(dom, keep, text);
883        dom.add(comment, keep);
884    }
885
886    /// Set comment `id`'s thread: the comment it replies to (it hangs off
887    /// that comment's thread root, Word threads being one level deep) and
888    /// whether it is resolved. A parent the family lacks is ignored.
889    #[doc(hidden)]
890    pub fn set_thread(&mut self, id: u32, parent: Option<u32>, done: bool) {
891        let parent = parent
892            .filter(|p| *p != id && self.meta.contains_key(p))
893            .map(|p| self.thread_root(p));
894        if let Some(meta) = self.meta.get_mut(&id) {
895            meta.parent = parent.filter(|&p| p != id);
896            meta.done = done;
897        }
898    }
899
900    /// Mark `id` and its replies resolved (or open again).
901    #[doc(hidden)]
902    pub fn set_done(&mut self, id: u32, done: bool) {
903        for c in self.with_replies(id) {
904            if let Some(meta) = self.meta.get_mut(&c) {
905                meta.done = done;
906            }
907        }
908    }
909
910    /// Remove `id` and its replies; the removed ids.
911    #[doc(hidden)]
912    pub fn remove(&mut self, id: u32) -> Vec<u32> {
913        let removed = self.with_replies(id);
914        for c in &removed {
915            if let Some(meta) = self.meta.remove(c) {
916                if let Some(author) = self.dom.attribute(meta.node, &W::author()) {
917                    self.removed_authors.insert(author.to_string());
918                }
919                self.dom.remove(meta.node);
920            }
921        }
922        removed
923    }
924
925    /// Write the family back into `pkg`: every part present and consistent,
926    /// or none of them when no comment is left; `people.xml` follows.
927    #[doc(hidden)]
928    pub fn store(mut self, pkg: &mut PartFs, main: &str) {
929        let remaining_authors: HashSet<String> = self
930            .meta
931            .values()
932            .filter_map(|m| self.dom.attribute(m.node, &W::author()).map(str::to_string))
933            .collect();
934        if self.meta.is_empty() {
935            for (k, (part, _, rel_type)) in FAMILY.iter().enumerate() {
936                let name = self.parts[k]
937                    .as_ref()
938                    .map_or_else(|| (*part).to_string(), |p| p.name.clone());
939                pkg.remove_part(&name);
940                pkg.remove_content_type_override(&format!("/{name}"));
941                pkg.remove_relationships_by_type(main, rel_type);
942            }
943            self.store_people(pkg, main, &remaining_authors);
944            return;
945        }
946        self.stamp_para_ids(pkg);
947        let order = self.order();
948        let last: HashMap<u32, String> = order
949            .iter()
950            .filter_map(|&id| last_para_id(&self.dom, self.meta[&id].node).map(|p| (id, p)))
951            .collect();
952        // commentsExtended.
953        let ext_root = self.ensure_part(1, |mc| {
954            format!(
955                r#"<w15:commentsEx xmlns:w15="{}" xmlns:mc="{mc}" mc:Ignorable="w15"/>"#,
956                W15::URI
957            )
958        });
959        clear_rows(&mut self.dom, ext_root, &W15::name("commentEx"));
960        for &id in &order {
961            let meta = &self.meta[&id];
962            let row = meta
963                .ext_row
964                .unwrap_or_else(|| self.dom.new_element(W15::name("commentEx")));
965            let parent = meta.parent.and_then(|p| last.get(&p)).cloned();
966            let done = if meta.done { "1" } else { "0" };
967            self.dom.set_attribute_value(
968                row,
969                &W15::name("paraId"),
970                last.get(&id).map(String::as_str),
971            );
972            self.dom
973                .set_attribute_value(row, &W15::name("paraIdParent"), parent.as_deref());
974            self.dom
975                .set_attribute_value(row, &W15::name("done"), Some(done));
976            self.dom.add(ext_root, row);
977        }
978        // commentsIds and commentsExtensible.
979        let ids_root = self.ensure_part(2, |mc| {
980            format!(
981                r#"<w16cid:commentsIds xmlns:w16cid="{CID}" xmlns:mc="{mc}" mc:Ignorable="w16cid"/>"#
982            )
983        });
984        let cex_root = self.ensure_part(3, |mc| {
985            format!(
986                r#"<w16cex:commentsExtensible xmlns:w16cex="{CEX}" xmlns:mc="{mc}" mc:Ignorable="w16cex"/>"#
987            )
988        });
989        clear_rows(&mut self.dom, ids_root, &XName::get("commentId", CID));
990        clear_rows(
991            &mut self.dom,
992            cex_root,
993            &XName::get("commentExtensible", CEX),
994        );
995        let durable_key = XName::get("durableId", CID);
996        // Existing durable ids stay (first holder wins); the rest are new.
997        let mut durables: HashSet<String> = HashSet::new();
998        let kept: HashMap<u32, String> = order
999            .iter()
1000            .filter_map(|&id| {
1001                let d = self.meta[&id]
1002                    .id_row
1003                    .and_then(|r| self.dom.attribute(r, &durable_key))?
1004                    .to_ascii_uppercase();
1005                (is_hex8(&d) && durables.insert(d.clone())).then_some((id, d))
1006            })
1007            .collect();
1008        for &id in &order {
1009            let meta = &self.meta[&id];
1010            let para = last.get(&id).cloned().unwrap_or_default();
1011            let durable = kept.get(&id).cloned().unwrap_or_else(|| {
1012                let seed = u32::from_str_radix(&para, 16).unwrap_or(id) ^ 0x2D5A_1C3B;
1013                allocate_hex8(&mut durables, seed)
1014            });
1015            let row = meta
1016                .id_row
1017                .unwrap_or_else(|| self.dom.new_element(XName::get("commentId", CID)));
1018            self.dom
1019                .set_attribute_value(row, &XName::get("paraId", CID), Some(&para));
1020            self.dom
1021                .set_attribute_value(row, &durable_key, Some(&durable));
1022            self.dom.add(ids_root, row);
1023            let row = meta
1024                .cex_row
1025                .unwrap_or_else(|| self.dom.new_element(XName::get("commentExtensible", CEX)));
1026            self.dom
1027                .set_attribute_value(row, &XName::get("durableId", CEX), Some(&durable));
1028            let date_key = XName::get("dateUtc", CEX);
1029            if self.dom.attribute(row, &date_key).is_none()
1030                && let Some(date) = self
1031                    .dom
1032                    .attribute(meta.node, &W::date())
1033                    .map(str::to_string)
1034            {
1035                self.dom.set_attribute_value(row, &date_key, Some(&date));
1036            }
1037            self.dom.add(cex_root, row);
1038        }
1039        for (k, (part, content_type, rel_type)) in FAMILY.iter().enumerate() {
1040            let Some(p) = &self.parts[k] else { continue };
1041            let xml = self.dom.serialize_document(p.doc);
1042            pkg.set_part(&p.name, xml.into_bytes());
1043            if related_part(pkg, main, rel_type).is_none() {
1044                let target = crate::opc::relative_rel_target(main, part);
1045                pkg.add_document_relationship(main, rel_type, &target);
1046                pkg.add_content_type_override(&format!("/{part}"), content_type);
1047            }
1048        }
1049        self.store_people(pkg, main, &remaining_authors);
1050    }
1051
1052    /// Create part `k` from `xml(mc namespace)` when missing; its root.
1053    fn ensure_part(&mut self, k: usize, xml: impl Fn(&str) -> String) -> NodeId {
1054        if let Some(part) = &self.parts[k] {
1055            return part.root;
1056        }
1057        let doc = self.dom.parse_xdocument(&format!(
1058            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>{}"#,
1059            xml(MC::URI)
1060        ));
1061        let root = self.dom.root(doc).expect("root");
1062        self.parts[k] = Some(Part {
1063            name: FAMILY[k].0.to_string(),
1064            doc,
1065            root,
1066        });
1067        root
1068    }
1069
1070    /// Give every comment paragraph without one a `w14:paraId` unique in the
1071    /// package, and declare `w14` on the comments root.
1072    fn stamp_para_ids(&mut self, pkg: &PartFs) {
1073        let Some(comments) = &self.parts[0] else {
1074            return;
1075        };
1076        let root = comments.root;
1077        let comments_name = comments.name.clone();
1078        let key = W14::name("paraId");
1079        let mut used = package_para_ids(pkg, &comments_name);
1080        for p in self.dom.descendants(root, Some(&W::p())) {
1081            if let Some(v) = self.dom.attribute(p, &key) {
1082                used.insert(v.to_ascii_uppercase());
1083            }
1084        }
1085        for (id, meta) in &self.meta {
1086            for (index, p) in self
1087                .dom
1088                .descendants(meta.node, Some(&W::p()))
1089                .into_iter()
1090                .enumerate()
1091            {
1092                if self.dom.attribute(p, &key).is_some() {
1093                    continue;
1094                }
1095                let seed = 0x1000_0000u32
1096                    .wrapping_add(id.wrapping_mul(0x11))
1097                    .wrapping_add((index as u32).wrapping_mul(0x100));
1098                let para = allocate_hex8(&mut used, seed);
1099                self.dom.set_attribute_value(p, &key, Some(&para));
1100            }
1101        }
1102        declare_ignorable(&mut self.dom, root, "w14", W14::URI);
1103    }
1104
1105    /// Drop `people.xml` rows of removed authors who no longer comment, and
1106    /// add new authors, when the part exists; never create it.
1107    fn store_people(&self, pkg: &mut PartFs, main: &str, remaining: &HashSet<String>) {
1108        let Some(name) = related_part(pkg, main, PEOPLE_REL) else {
1109            return;
1110        };
1111        let Some(xml) = pkg.part_string(&name) else {
1112            return;
1113        };
1114        let mut dom = Dom::new();
1115        let doc = dom.parse_xdocument(&xml);
1116        let Some(root) = dom.root(doc) else { return };
1117        let author_key = W15::name("author");
1118        let mut changed = false;
1119        let mut present: HashSet<String> = HashSet::new();
1120        for person in dom.descendants(root, Some(&W15::name("person"))) {
1121            let author = dom.attribute(person, &author_key).unwrap_or("").to_string();
1122            if self.removed_authors.contains(&author) && !remaining.contains(&author) {
1123                dom.remove(person);
1124                changed = true;
1125            } else {
1126                present.insert(author);
1127            }
1128        }
1129        for author in &self.added_authors {
1130            if present.contains(author) || !remaining.contains(author) {
1131                continue;
1132            }
1133            let person = dom.new_element(W15::name("person"));
1134            dom.set_attribute_value(person, &author_key, Some(author));
1135            let presence = dom.new_element(W15::name("presenceInfo"));
1136            dom.set_attribute_value(presence, &W15::name("providerId"), Some("None"));
1137            dom.set_attribute_value(presence, &W15::name("userId"), Some(author));
1138            dom.add(person, presence);
1139            dom.add(root, person);
1140            present.insert(author.clone());
1141            changed = true;
1142        }
1143        if !changed {
1144            return;
1145        }
1146        if dom.descendants(root, Some(&W15::name("person"))).is_empty() {
1147            pkg.remove_part(&name);
1148            pkg.remove_content_type_override(&format!("/{name}"));
1149            pkg.remove_relationships_by_type(main, PEOPLE_REL);
1150        } else {
1151            pkg.set_part(&name, dom.serialize_document(doc).into_bytes());
1152        }
1153    }
1154}
1155
1156/// The part the main part relates to with exactly `rel_type`.
1157fn related_part(pkg: &PartFs, main: &str, rel_type: &str) -> Option<String> {
1158    pkg.read_rels_for(main)?
1159        .items
1160        .iter()
1161        .find(|r| r.rel_type == rel_type && r.target_mode.as_deref() != Some("External"))
1162        .map(|r| pkg.resolve_rel_target(main, &r.target))
1163        .filter(|name| pkg.part_string(name).is_some())
1164}
1165
1166/// `w14:paraId` of a comment's last paragraph.
1167fn last_para_id(dom: &Dom, comment: NodeId) -> Option<String> {
1168    let last = dom.descendants(comment, Some(&W::p())).last().copied()?;
1169    dom.attribute(last, &W14::name("paraId"))
1170        .map(str::to_string)
1171}
1172
1173/// A comment's text: `w:t` as is, breaks and paragraphs as `\n`, tabs as
1174/// `\t`.
1175fn comment_text(dom: &Dom, comment: NodeId) -> String {
1176    let mut out = String::new();
1177    for (i, p) in dom
1178        .descendants(comment, Some(&W::p()))
1179        .into_iter()
1180        .enumerate()
1181    {
1182        if i > 0 {
1183            out.push('\n');
1184        }
1185        for node in dom.descendants(p, None) {
1186            let Some(name) = dom.name(node).filter(|n| n.namespace_name() == W::URI) else {
1187                continue;
1188            };
1189            match name.local_name() {
1190                "t" => out.push_str(&dom.value(node)),
1191                "br" | "cr" => out.push('\n'),
1192                "tab" if !dom.ancestors(node, Some(&W::p_pr())).is_empty() => {}
1193                "tab" => out.push('\t'),
1194                _ => {}
1195            }
1196        }
1197    }
1198    out
1199}
1200
1201/// The annotation-reference run, then one run per line of `text`, a
1202/// `w:br` before every line after the first.
1203fn fill_comment_paragraph(dom: &mut Dom, p: NodeId, text: &str) {
1204    let ref_run = dom.new_element(W::r());
1205    let annotation = dom.new_element(W::name("annotationRef"));
1206    dom.add(ref_run, annotation);
1207    dom.add(p, ref_run);
1208    for (i, line) in text.split('\n').enumerate() {
1209        let run = dom.new_element(W::r());
1210        if i > 0 {
1211            let br = dom.new_element(W::name("br"));
1212            dom.add(run, br);
1213        }
1214        let t = dom.new_element(W::t());
1215        dom.set_attribute_value(t, &XNamespace::xml().name("space"), Some("preserve"));
1216        dom.add_text(t, line);
1217        dom.add(run, t);
1218        dom.add(p, run);
1219    }
1220}
1221
1222fn clear_rows(dom: &mut Dom, root: NodeId, row: &XName) {
1223    for node in dom.elements(root, Some(row)) {
1224        dom.remove(node);
1225    }
1226}
1227
1228fn is_hex8(value: &str) -> bool {
1229    value.len() == 8 && value.bytes().all(|b| b.is_ascii_hexdigit())
1230}
1231
1232/// A paraId (or durable id) below `0x80000000`, nonzero, not in `used`, from `seed` on.
1233fn allocate_hex8(used: &mut HashSet<String>, seed: u32) -> String {
1234    let mut next = seed & 0x7FFF_FFFF;
1235    loop {
1236        if next == 0 {
1237            next = 1;
1238        }
1239        let candidate = format!("{next:08X}");
1240        if used.insert(candidate.clone()) {
1241            return candidate;
1242        }
1243        next = (next + 1) & 0x7FFF_FFFF;
1244    }
1245}
1246
1247/// Every `paraId="XXXXXXXX"` value in the package's XML parts other than
1248/// `skip`, uppercased: Word wants paraIds unique across the document.
1249fn package_para_ids(pkg: &PartFs, skip: &str) -> HashSet<String> {
1250    let mut used = HashSet::new();
1251    for name in pkg.parts() {
1252        if name == skip || !name.ends_with(".xml") {
1253            continue;
1254        }
1255        let Some(xml) = pkg.part_string(&name) else {
1256            continue;
1257        };
1258        let mut rest = xml.as_str();
1259        while let Some(at) = rest.find("paraId=\"") {
1260            rest = &rest[at + 8..];
1261            if let Some(value) = rest.get(..8)
1262                && is_hex8(value)
1263            {
1264                used.insert(value.to_ascii_uppercase());
1265            }
1266        }
1267    }
1268    used
1269}
1270
1271/// Declare `prefix` on `root` and list it in `mc:Ignorable`, declaring `mc`
1272/// too, unless already done.
1273fn declare_ignorable(dom: &mut Dom, root: NodeId, prefix: &str, uri: &str) {
1274    let xmlns = XNamespace::xmlns();
1275    if dom.attribute(root, &xmlns.name(prefix)).is_none() {
1276        dom.set_attribute_value(root, &xmlns.name(prefix), Some(uri));
1277    }
1278    if dom.attribute(root, &xmlns.name("mc")).is_none() {
1279        dom.set_attribute_value(root, &xmlns.name("mc"), Some(MC::URI));
1280    }
1281    let key = MC::name("Ignorable");
1282    let current = dom.attribute(root, &key).unwrap_or("").to_string();
1283    if !current.split_whitespace().any(|p| p == prefix) {
1284        let value = if current.trim().is_empty() {
1285            prefix.to_string()
1286        } else {
1287            format!("{} {prefix}", current.trim())
1288        };
1289        dom.set_attribute_value(root, &key, Some(&value));
1290    }
1291}
1292
1293#[cfg(test)]
1294#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1295mod tests {
1296    use super::*;
1297
1298    #[test]
1299    fn para_ids_stay_below_the_word_bound_and_skip_used_ones() {
1300        let mut used = HashSet::new();
1301        used.insert("10000000".to_string());
1302        assert_eq!(allocate_hex8(&mut used, 0x1000_0000), "10000001");
1303        assert_eq!(allocate_hex8(&mut used, 0xFFFF_FFFF), "7FFFFFFF");
1304        assert_eq!(allocate_hex8(&mut used, 0x8000_0000), "00000001");
1305    }
1306
1307    #[test]
1308    fn tail_counts_characters_not_bytes() {
1309        assert_eq!(tail("ação", 2), "ão");
1310        assert_eq!(tail("ab", 5), "ab");
1311    }
1312
1313    #[test]
1314    fn ignorable_prefixes_are_appended_once() {
1315        let mut dom = Dom::new();
1316        let doc = dom.parse_xdocument(&format!(
1317            r#"<w:comments xmlns:w="{}" xmlns:mc="{}" mc:Ignorable="w15"/>"#,
1318            W::URI,
1319            MC::URI
1320        ));
1321        let root = dom.root(doc).unwrap();
1322        declare_ignorable(&mut dom, root, "w14", W14::URI);
1323        declare_ignorable(&mut dom, root, "w14", W14::URI);
1324        assert_eq!(dom.attribute(root, &MC::name("Ignorable")), Some("w15 w14"));
1325    }
1326}
1327
1328#[cfg(test)]
1329#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1330mod people_and_text_boundary_tests {
1331    use super::*;
1332
1333    fn pkg() -> PartFs {
1334        PartFs::open(include_bytes!(
1335            "../../../tests/fixtures/redline/original.docx"
1336        ))
1337        .unwrap()
1338    }
1339
1340    fn people(pkg: &mut PartFs, xml: &str) {
1341        pkg.set_part("word/people.xml", xml.as_bytes().to_vec());
1342        pkg.add_content_type_override(
1343            "/word/people.xml",
1344            "application/vnd.openxmlformats-officedocument.wordprocessingml.people+xml",
1345        );
1346        pkg.add_document_relationship("word/document.xml", PEOPLE_REL, "people.xml");
1347    }
1348
1349    #[test]
1350    fn people_updates_preserve_existing_presence_and_add_each_remaining_author_once() {
1351        let mut pkg = pkg();
1352        people(
1353            &mut pkg,
1354            &format!(
1355                r#"<w15:people xmlns:w15="{}"><w15:person w15:author="Alice"/><w15:person w15:author="Bob"><w15:presenceInfo w15:providerId="Existing"/></w15:person></w15:people>"#,
1356                W15::URI
1357            ),
1358        );
1359        let mut family = CommentFamily::load(&pkg, "word/document.xml").unwrap();
1360        family.removed_authors.insert("Alice".into());
1361        family.added_authors = vec!["Bob".into(), "Carol".into(), "Carol".into(), "Gone".into()];
1362        family.store_people(
1363            &mut pkg,
1364            "word/document.xml",
1365            &HashSet::from(["Bob".into(), "Carol".into()]),
1366        );
1367        let output = pkg.part_string("word/people.xml").unwrap();
1368        let mut dom = Dom::new();
1369        let doc = dom.parse_xdocument(&output);
1370        let root = dom.root(doc).unwrap();
1371        let authors = dom
1372            .descendants(root, Some(&W15::name("person")))
1373            .into_iter()
1374            .map(|n| dom.attribute(n, &W15::name("author")).unwrap())
1375            .collect::<Vec<_>>();
1376        assert_eq!(authors, ["Bob", "Carol"]);
1377        let providers = dom
1378            .descendants(root, Some(&W15::name("presenceInfo")))
1379            .into_iter()
1380            .map(|n| dom.attribute(n, &W15::name("providerId")).unwrap())
1381            .collect::<Vec<_>>();
1382        assert_eq!(providers, ["Existing", "None"]);
1383    }
1384
1385    #[test]
1386    fn removing_the_last_person_removes_its_part_type_and_relationship() {
1387        let mut pkg = pkg();
1388        people(
1389            &mut pkg,
1390            &format!(
1391                r#"<w15:people xmlns:w15="{}"><w15:person w15:author="Alice"/></w15:people>"#,
1392                W15::URI
1393            ),
1394        );
1395        let mut family = CommentFamily::load(&pkg, "word/document.xml").unwrap();
1396        family.removed_authors.insert("Alice".into());
1397        family.store_people(&mut pkg, "word/document.xml", &HashSet::new());
1398        assert!(pkg.part_bytes("word/people.xml").is_none());
1399        assert!(
1400            !pkg.read_rels_for("word/document.xml")
1401                .unwrap()
1402                .items
1403                .iter()
1404                .any(|rel| rel.rel_type == PEOPLE_REL)
1405        );
1406    }
1407
1408    #[test]
1409    fn unchanged_people_are_byte_identical_and_new_authors_do_not_create_a_people_part() {
1410        let mut pkg = pkg();
1411        let family = CommentFamily::load(&pkg, "word/document.xml").unwrap();
1412        family.store_people(
1413            &mut pkg,
1414            "word/document.xml",
1415            &HashSet::from(["Alice".into()]),
1416        );
1417        assert!(pkg.part_bytes("word/people.xml").is_none());
1418        let input = format!(
1419            r#"<w15:people xmlns:w15="{}"><w15:person w15:author="Alice"/></w15:people>"#,
1420            W15::URI
1421        );
1422        people(&mut pkg, &input);
1423        let mut family = CommentFamily::load(&pkg, "word/document.xml").unwrap();
1424        family.removed_authors.insert("Alice".into());
1425        family.store_people(
1426            &mut pkg,
1427            "word/document.xml",
1428            &HashSet::from(["Alice".into()]),
1429        );
1430        assert_eq!(pkg.part_string("word/people.xml").unwrap(), input);
1431        pkg.set_part("word/people.xml", Vec::new());
1432        family.store_people(&mut pkg, "word/document.xml", &HashSet::new());
1433        assert_eq!(pkg.part_bytes("word/people.xml"), Some([].as_slice()));
1434    }
1435
1436    #[test]
1437    fn comment_projection_ignores_tab_stops_and_foreign_elements_but_keeps_breaks() {
1438        let mut dom = Dom::new();
1439        let doc = dom.parse_xdocument(&format!(r#"<w:comment xmlns:w="{}" xmlns:x="urn:foreign"><w:p><w:pPr><w:tabs><w:tab/></w:tabs></w:pPr><w:r><w:t>one</w:t><w:tab/><w:t>two</w:t><w:br/><w:cr/><x:t>foreign</x:t></w:r></w:p><w:p><w:r><w:t>three</w:t></w:r></w:p></w:comment>"#, W::URI));
1440        let root = dom.root(doc).unwrap();
1441        assert_eq!(comment_text(&dom, root), "one\ttwo\n\n\nthree");
1442        assert!(last_para_id(&dom, root).is_none());
1443        let p = *dom.descendants(root, Some(&W::p())).last().unwrap();
1444        dom.set_attribute_value(p, &W14::name("paraId"), Some("12345678"));
1445        assert_eq!(last_para_id(&dom, root).as_deref(), Some("12345678"));
1446    }
1447
1448    #[test]
1449    fn adopted_comments_preserve_text_and_drop_old_paragraph_ids() {
1450        let pkg = pkg();
1451        let mut family = CommentFamily::load(&pkg, "word/document.xml").unwrap();
1452        family.adopt("<not-a-comment/>", 7, None, false, None);
1453        assert!(family.meta.is_empty());
1454        let input = format!(
1455            r#"<w:comment xmlns:w="{}" xmlns:w14="{}" w:id="99" w:author="Alice"><w:p w14:paraId="11111111" w14:textId="22222222"><w:r><w:t>copied</w:t></w:r></w:p></w:comment>"#,
1456            W::URI,
1457            W14::URI
1458        );
1459        family.adopt(&input, 7, Some(123), true, Some("2026-01-02T03:04:05Z"));
1460        let meta = &family.meta[&7];
1461        assert_eq!(comment_text(&family.dom, meta.node), "copied");
1462        assert_eq!(family.dom.attribute(meta.node, &W::id()), Some("7"));
1463        assert!(last_para_id(&family.dom, meta.node).is_none());
1464        assert_eq!(
1465            family.thread_state(7),
1466            Some((None, true, Some("2026-01-02T03:04:05Z".into())))
1467        );
1468        assert_eq!(family.thread_state(123), None);
1469        family.adopt(&input, 8, Some(7), false, None);
1470        assert_eq!(family.thread_state(8), Some((Some(7), false, None)));
1471        assert_eq!(family.added_authors, ["Alice"]);
1472    }
1473}
1474
1475#[cfg(test)]
1476#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1477mod public_memory_anchor_boundary_tests {
1478    use super::*;
1479
1480    fn package(body: &str) -> PartFs {
1481        let mut pkg = PartFs::open(include_bytes!(
1482            "../../../tests/fixtures/redline/original.docx"
1483        ))
1484        .unwrap();
1485        pkg.set_part("word/document.xml",format!("<w:document xmlns:w='{}'><w:body>{body}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>",W::URI).into_bytes());
1486        pkg
1487    }
1488    fn snapshot(pkg: &PartFs) -> Vec<(String, Vec<u8>)> {
1489        let mut parts = pkg.parts();
1490        parts.sort();
1491        parts
1492            .into_iter()
1493            .map(|name| {
1494                let bytes = pkg.part_bytes(&name).unwrap().to_vec();
1495                (name, bytes)
1496            })
1497            .collect()
1498    }
1499
1500    fn paragraph(text: &str) -> String {
1501        format!(
1502            "<w:p><w:pPr><w:spacing w:after='80'/></w:pPr><w:r><w:rPr><w:b/><w:color w:val='123456'/></w:rPr><w:t>{text}</w:t></w:r></w:p>"
1503        )
1504    }
1505    #[test]
1506    fn block_and_point_comments_preserve_exact_unicode_anchor_context_and_package() {
1507        let first = paragraph("First ação");
1508        let middle = paragraph("Middle café");
1509        let last = paragraph("Last τέλος");
1510        let cases = [
1511            (
1512                format!(
1513                    "<w:commentRangeStart w:id='7'/>{first}{middle}{last}<w:commentRangeEnd w:id='7'/>"
1514                ),
1515                "First ação\nMiddle café\nLast τέλος",
1516                "",
1517                "",
1518                "p0",
1519            ),
1520            (
1521                format!(
1522                    "{first}<w:commentRangeStart w:id='7'/>{middle}<w:commentRangeEnd w:id='7'/>{last}"
1523                ),
1524                "Middle café",
1525                "",
1526                "",
1527                "p1",
1528            ),
1529            (
1530                format!(
1531                    "{first}<w:p><w:pPr><w:spacing w:after='80'/></w:pPr><w:r><w:t>Before </w:t></w:r><w:commentRangeStart w:id='7'/><w:r><w:t>ação</w:t></w:r></w:p>{middle}<w:p><w:r><w:t>τέλος</w:t></w:r><w:commentRangeEnd w:id='7'/><w:r><w:t xml:space='preserve'> after</w:t></w:r></w:p>"
1532                ),
1533                "ação\nMiddle café\nτέλος",
1534                "Before ",
1535                " after",
1536                "p1",
1537            ),
1538            (
1539                format!(
1540                    "{first}<w:p><w:r><w:t>Point location</w:t></w:r><w:r><w:rPr><w:rStyle w:val='CommentReference'/></w:rPr><w:commentReference w:id='7'/></w:r></w:p>{last}"
1541                ),
1542                "",
1543                "",
1544                "",
1545                "p1",
1546            ),
1547        ];
1548        for (body, anchor, before, after, paragraph) in cases {
1549            let mut pkg = package(&body);
1550            pkg.set_part("word/comments.xml",format!("<w:comments xmlns:w='{}'><w:comment w:id='7' w:author='Source reviewer' w:initials='SR' w:date='2025-02-03T04:05:06Z'><w:p><w:r><w:t>Review ação</w:t></w:r></w:p><w:p><w:r><w:t>Second line</w:t></w:r></w:p></w:comment></w:comments>",W::URI).into_bytes());
1551            pkg.add_content_type_override(
1552                "/word/comments.xml",
1553                "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",
1554            );
1555            pkg.add_document_relationship(
1556                "word/document.xml",
1557                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
1558                "comments.xml",
1559            );
1560            let source = snapshot(&pkg);
1561            let bytes = pkg.to_zip().unwrap();
1562            // A range over several paragraphs names its last one too.
1563            let start: usize = paragraph["p".len()..].parse().unwrap();
1564            let lines = anchor.matches('\n').count();
1565            let last_paragraph = (lines > 0).then(|| format!("p{}", start + lines));
1566            let expected = vec![CommentRecord {
1567                id: 7,
1568                r#ref: "c7".into(),
1569                author: "Source reviewer".into(),
1570                initials: Some("SR".into()),
1571                date: Some("2025-02-03T04:05:06Z".into()),
1572                text: "Review ação\nSecond line".into(),
1573                parent: None,
1574                done: false,
1575                paragraph: Some(paragraph.into()),
1576                last_paragraph,
1577                anchor_text: anchor.into(),
1578                before: before.into(),
1579                after: after.into(),
1580            }];
1581            assert_eq!(list_comments(&bytes).unwrap(), expected);
1582            assert_eq!(
1583                list_comments(&bytes).unwrap(),
1584                expected,
1585                "repeat must have identical anchor and author records"
1586            );
1587            assert_eq!(
1588                snapshot(&PartFs::open(&bytes).unwrap()),
1589                source,
1590                "listing retains all source properties, relationships and comment history bytes"
1591            );
1592        }
1593    }
1594    #[test]
1595    fn reversed_ranges_record_both_endpoints() {
1596        let body = format!(
1597            "<w:p><w:r><w:t>AA</w:t></w:r><w:commentRangeEnd w:id='7'/><w:r><w:t>BB</w:t></w:r></w:p>{}<w:p><w:r><w:t>CC</w:t></w:r><w:commentRangeStart w:id='7'/><w:r><w:t>DD</w:t></w:r></w:p>",
1598            paragraph("middle")
1599        );
1600        let mut pkg = package(&body);
1601        pkg.set_part("word/comments.xml",format!("<w:comments xmlns:w='{}'><w:comment w:id='7' w:author='Source reviewer' w:initials='SR' w:date='2025-02-03T04:05:06Z'><w:p><w:r><w:t>Review</w:t></w:r></w:p></w:comment></w:comments>",W::URI).into_bytes());
1602        pkg.add_content_type_override(
1603            "/word/comments.xml",
1604            "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",
1605        );
1606        pkg.add_document_relationship(
1607            "word/document.xml",
1608            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
1609            "comments.xml",
1610        );
1611        let bytes = pkg.to_zip().unwrap();
1612        let record = &list_comments(&bytes).unwrap()[0];
1613        assert_eq!(record.paragraph.as_deref(), Some("p0"));
1614        assert_eq!(record.last_paragraph.as_deref(), Some("p2"));
1615        assert_eq!(record.anchor_text, "BB\nmiddle\nCC");
1616        assert_eq!(record.before, "AA");
1617        assert_eq!(record.after, "DD");
1618    }
1619    #[test]
1620    fn latest_thread_selection_preserves_complete_winning_source_records_and_thread_order() {
1621        let record = |id, parent, author: &str, date: &str| CommentRecord {
1622            id,
1623            r#ref: format!("c{id}"),
1624            parent,
1625            author: author.into(),
1626            initials: Some("SR".into()),
1627            date: Some(date.into()),
1628            text: format!("Source comment {id}"),
1629            done: false,
1630            paragraph: Some(format!("p{id}")),
1631            last_paragraph: None,
1632            anchor_text: format!("Owned anchor {id}"),
1633            before: "before".into(),
1634            after: "after".into(),
1635        };
1636        let records = vec![
1637            record(1, None, "Alice", "2025-02-03T00:00:00Z"),
1638            record(2, Some(1), "Bob", "2025-02-05T00:00:00Z"),
1639            record(3, Some(2), "Alice", "2025-02-04T00:00:00Z"),
1640            record(4, None, "Bob", "2025-02-02T00:00:00Z"),
1641            record(5, Some(4), "Bob", "2025-02-02T00:00:00Z"),
1642        ];
1643        assert_eq!(
1644            select_comments(records.clone(), None, true),
1645            vec![records[1].clone(), records[4].clone()]
1646        );
1647        assert_eq!(
1648            select_comments(records.clone(), Some("Alice"), true),
1649            vec![records[2].clone()]
1650        );
1651        assert_eq!(
1652            select_comments(records.clone(), Some("Nobody"), true),
1653            Vec::new()
1654        );
1655        assert_eq!(select_comments(records.clone(), None, false), records);
1656    }
1657
1658    /// `count` comments on one paragraph of `text`.
1659    fn comments_on_one_range(text: &str, count: usize) -> Vec<u8> {
1660        let mut body = String::new();
1661        for id in 1..=count {
1662            body.push_str(&format!("<w:commentRangeStart w:id='{id}'/>"));
1663        }
1664        body.push_str(&paragraph(text));
1665        for id in 1..=count {
1666            body.push_str(&format!("<w:commentRangeEnd w:id='{id}'/>"));
1667        }
1668        let mut comments = format!("<w:comments xmlns:w='{}'>", W::URI);
1669        for id in 1..=count {
1670            comments.push_str(&format!(
1671                "<w:comment w:id='{id}' w:author='A' w:date='2025-01-01T00:00:00Z'><w:p><w:r><w:t>n</w:t></w:r></w:p></w:comment>"
1672            ));
1673        }
1674        comments.push_str("</w:comments>");
1675        let mut pkg = package(&body);
1676        pkg.set_part("word/comments.xml", comments.into_bytes());
1677        pkg.add_content_type_override(
1678            "/word/comments.xml",
1679            "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",
1680        );
1681        pkg.add_document_relationship(
1682            "word/document.xml",
1683            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
1684            "comments.xml",
1685        );
1686        pkg.to_zip().unwrap()
1687    }
1688
1689    /// Four comments on one 80 KB range: 320 KB of anchors in all, past the
1690    /// 256 KiB a listing once kept, and each one is still the exact text it
1691    /// covers.
1692    #[test]
1693    fn many_comments_on_one_range_keep_exact_anchors() {
1694        const BUDGET: usize = 256 * 1024;
1695        let text = "A".repeat(80_000);
1696        let count = 4;
1697        let listed = list_comments(&comments_on_one_range(&text, count)).unwrap();
1698        assert_eq!(listed.len(), count);
1699        // `edit -p cN.text` resolves inside this text, and inspect, WASM
1700        // and Python print it: every anchor stays exact.
1701        for comment in &listed {
1702            assert_eq!(comment.anchor_text, text, "c{}", comment.id);
1703        }
1704        assert!(count * text.len() > BUDGET);
1705    }
1706
1707    /// Past its budget a listing refuses with `INPUT_LIMIT` and names the
1708    /// comment that passed it, rather than hold a truncated anchor.
1709    #[test]
1710    fn anchors_past_the_budget_refuse_with_input_limit() {
1711        let text = "A".repeat(80_000);
1712        let bytes = comments_on_one_range(&text, 4);
1713        let mut opened = Opened::open(&bytes).unwrap();
1714        let refused = comments_within_budget(&mut opened, 200_000).unwrap_err();
1715        assert_eq!(refused.code(), "INPUT_LIMIT");
1716        assert!(
1717            refused
1718                .to_string()
1719                .contains("c3 covers 80000 bytes with 40000 left"),
1720            "{refused}"
1721        );
1722        let mut opened = Opened::open(&bytes).unwrap();
1723        assert_eq!(
1724            comments_within_budget(&mut opened, 320_000).unwrap().len(),
1725            4
1726        );
1727    }
1728}
1729
1730#[cfg(test)]
1731#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1732mod authored_thread_reference_contract_tests {
1733    use super::*;
1734
1735    fn family(parents: [Option<usize>; 3]) -> (PartFs, CommentFamily) {
1736        let mut pkg = PartFs::open(include_bytes!(
1737            "../../../tests/fixtures/redline/original.docx"
1738        ))
1739        .unwrap();
1740        let comments = (0..3).map(|i| format!("<w:comment w:id='{i}' w:author='Owner{i}' w:date='2025-01-0{}T00:00:00Z'><w:p w14:paraId='{:08X}'><w:pPr><w:spacing w:after='{}'/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>Comment owner {i}</w:t></w:r></w:p></w:comment>",i+1,i+1,80+i)).collect::<String>();
1741        let extended = parents
1742            .iter()
1743            .enumerate()
1744            .map(|(i, parent)| {
1745                format!(
1746                    "<w15:commentEx w15:paraId='{:08X}'{} w15:done='0'/>",
1747                    i + 1,
1748                    parent
1749                        .map(|p| format!(" w15:paraIdParent='{:08X}'", p + 1))
1750                        .unwrap_or_default()
1751                )
1752            })
1753            .collect::<String>();
1754        for (index, xml) in [
1755            (
1756                0,
1757                format!(
1758                    "<w:comments xmlns:w='{}' xmlns:w14='{}'>{comments}</w:comments>",
1759                    W::URI,
1760                    W14::URI
1761                ),
1762            ),
1763            (
1764                1,
1765                format!(
1766                    "<w15:commentsEx xmlns:w15='{}'>{extended}</w15:commentsEx>",
1767                    W15::URI
1768                ),
1769            ),
1770        ] {
1771            let (part, content_type, rel_type) = FAMILY[index];
1772            pkg.set_part(&format!("word/{part}"), xml.into_bytes());
1773            pkg.add_content_type_override(&format!("/word/{part}"), content_type);
1774            pkg.add_document_relationship("word/document.xml", rel_type, part);
1775        }
1776        let family = CommentFamily::load(&pkg, "word/document.xml").unwrap();
1777        (pkg, family)
1778    }
1779
1780    #[test]
1781    fn cyclic_and_missing_parent_metadata_terminate_without_discarding_comment_owners() {
1782        for (parents, roots, replies) in [
1783            ([Some(1), Some(0), None], [0, 1, 2], vec![0, 1]),
1784            ([Some(1), Some(2), Some(0)], [0, 1, 2], vec![0, 2, 1]),
1785            ([Some(2), Some(2), None], [2, 2, 2], vec![0]),
1786            ([Some(0), Some(3), None], [0, 1, 2], vec![0]),
1787        ] {
1788            let (pkg, family) = family(parents);
1789            let source = pkg.to_zip().unwrap();
1790            let records = list_comments(&source).unwrap();
1791            assert_eq!(records.len(), 3);
1792            for i in 0..3 {
1793                assert_eq!(family.thread_root(i), roots[i as usize]);
1794                assert_eq!(records[i as usize].author, format!("Owner{i}"));
1795                assert_eq!(records[i as usize].text, format!("Comment owner {i}"));
1796                let expected = parents[i as usize]
1797                    .filter(|&p| p < 3 && p != i as usize)
1798                    .map(|p| p as u32);
1799                assert_eq!(records[i as usize].parent, expected);
1800            }
1801            assert_eq!(family.with_replies(0), replies);
1802            let selected = select_comments(records.clone(), None, true);
1803            if roots == [2, 2, 2] {
1804                assert_eq!(selected, vec![records[2].clone()]);
1805            } else {
1806                assert_eq!(selected, records);
1807            }
1808            assert_eq!(pkg.to_zip().unwrap(), source);
1809        }
1810    }
1811
1812    #[test]
1813    fn paragraph_id_scan_reserves_only_complete_hex_ids_from_other_xml_parts() {
1814        let mut pkg = PartFs::open(include_bytes!(
1815            "../../../tests/fixtures/redline/original.docx"
1816        ))
1817        .unwrap();
1818        pkg.set_part("word/document.xml",b"<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'><w:body/></w:document>".to_vec());
1819        pkg.set_part(
1820            "word/owned.xml",
1821            b"<root paraId=\"abcdef12\"><node paraId=\"NOTHEX12\"/><node paraId=\"short\"/></root>"
1822                .to_vec(),
1823        );
1824        pkg.set_part("word/skipped.xml", b"<root paraId=\"13579024\"/>".to_vec());
1825        pkg.set_part("word/image.bin", b"paraId=\"12345678\"".to_vec());
1826        pkg.set_part("word/non_utf8.xml", vec![255, 254]);
1827        let frozen = pkg.to_zip().unwrap();
1828        let used = package_para_ids(&pkg, "word/skipped.xml");
1829        assert_eq!(used, HashSet::from(["ABCDEF12".to_string()]));
1830        assert_eq!(pkg.to_zip().unwrap(), frozen);
1831    }
1832}
1833
1834#[cfg(test)]
1835#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1836mod family_edit_tests {
1837    use super::*;
1838
1839    fn received() -> (PartFs, String) {
1840        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1841            .join("../../tests/fixtures/agent-view/received.docx");
1842        let pkg = PartFs::open(&std::fs::read(path).unwrap()).unwrap();
1843        (pkg, "word/document.xml".to_string())
1844    }
1845
1846    /// Edits name an id; one the family lacks changes nothing, and a parent
1847    /// it lacks (or the comment itself) leaves the comment a thread root.
1848    #[test]
1849    fn edits_to_absent_comments_change_nothing() {
1850        let (mut pkg, main) = received();
1851        let mut family = CommentFamily::load(&pkg, &main).unwrap();
1852        let before: Vec<_> = [5, 6, 11].map(|id| family.record(id)).into();
1853        family.set_text(999, "nobody");
1854        family.set_thread(999, Some(5), true);
1855        family.set_done(999, true);
1856        assert_eq!(family.remove(999), [999]);
1857        family.set_thread(11, Some(11), false);
1858        family.set_thread(6, Some(404), false);
1859        assert_eq!(family.record(11).parent, None);
1860        assert_eq!(family.record(6).parent, None);
1861        assert_eq!(family.record(5), before[0]);
1862        // A real edit keeps the paragraph's properties and its id.
1863        family.set_text(5, "Reworded.");
1864        let edited = family.record(5);
1865        assert_eq!(edited.text, "Reworded.");
1866        assert_eq!(edited.last_paragraph, before[0].last_paragraph);
1867        family.store(&mut pkg, &main);
1868        let xml = pkg.part_string("word/comments.xml").unwrap();
1869        let five = &xml[xml.find("w:id=\"5\"").unwrap()..];
1870        let five = &five[..five.find("</w:comment>").unwrap()];
1871        assert!(
1872            five.contains("CommentText") && five.contains("Reworded."),
1873            "{five}"
1874        );
1875        assert!(!xml.contains("statutory cap"), "{xml}");
1876    }
1877
1878    /// Only full eight-digit hex values count as used paraIds, even when a
1879    /// part ends right after the attribute opens.
1880    #[test]
1881    fn truncated_para_ids_are_not_counted() {
1882        let (mut pkg, _) = received();
1883        let base = package_para_ids(&pkg, "");
1884        pkg.set_part(
1885            "word/extra.xml",
1886            b"<x a=\"1\" paraId=\"abcdef01\"/><x paraId=\"zz\"/>paraId=\"12".to_vec(),
1887        );
1888        let used = package_para_ids(&pkg, "");
1889        assert_eq!(used.len(), base.len() + 1);
1890        assert!(used.contains("ABCDEF01"));
1891        assert_eq!(package_para_ids(&pkg, "word/extra.xml"), base);
1892    }
1893}