blackline_docx/
comment.rs1use serde::Serialize;
4
5use blackline_core::ns;
6use blackline_core::package::Package;
7use blackline_core::rels::{Relationship, Relationships};
8use blackline_core::textutil::find_normalized;
9use blackline_core::time::utc_now_iso;
10use blackline_core::xml::{max_numeric_id, XmlDocument, XmlNode};
11
12use crate::body::visible_text;
13use crate::error::DocxError;
14use crate::style::build_run;
15
16const COMMENTS_PART: &str = "word/comments.xml";
17
18#[derive(Debug, Clone, Serialize)]
21pub struct CommentThread {
22 pub id: String,
24 pub author: String,
26 pub date: String,
28 pub text: String,
30}
31
32pub fn list_comments(pkg: &Package) -> Result<Vec<CommentThread>, DocxError> {
34 if !pkg.has_part(COMMENTS_PART) {
35 return Ok(Vec::new());
36 }
37 let doc = pkg.part_xml(COMMENTS_PART)?;
38 let mut out = Vec::new();
39 for c in doc.root.find_all("comment") {
40 out.push(CommentThread {
41 id: c.get_attr("id").unwrap_or("").to_string(),
42 author: c.get_attr("author").unwrap_or("").to_string(),
43 date: c.get_attr("date").unwrap_or("").to_string(),
44 text: visible_text(c),
45 });
46 }
47 Ok(out)
48}
49
50pub fn insert_comment(
53 pkg: &mut Package,
54 para: &mut XmlNode,
55 anchor: &str,
56 text: &str,
57 author: &str,
58) -> Result<String, DocxError> {
59 insert_comment_dated(pkg, para, anchor, text, author, None)
60}
61
62pub fn insert_comment_dated(
64 pkg: &mut Package,
65 para: &mut XmlNode,
66 anchor: &str,
67 text: &str,
68 author: &str,
69 date: Option<&str>,
70) -> Result<String, DocxError> {
71 let date = date
72 .map(str::trim)
73 .filter(|s| !s.is_empty())
74 .map(str::to_string)
75 .unwrap_or_else(utc_now_iso);
76 let next_id = next_comment_id(pkg, para)?;
77 let id = next_id.to_string();
78
79 wrap_anchor(para, anchor, &id)?;
81
82 let mut comments = if pkg.has_part(COMMENTS_PART) {
84 pkg.part_xml(COMMENTS_PART)?
85 } else {
86 empty_comments()
87 };
88 comments.root = comments
89 .root
90 .with_child(comment_element(&id, author, &date, text));
91 pkg.set_part_xml(COMMENTS_PART, &comments);
92
93 let mut rels = pkg.rels_for("word/document.xml")?;
94 if rels.by_type(ns::rel::COMMENTS).is_none() {
95 rels.add(Relationship::internal(
96 rels.next_id(),
97 ns::rel::COMMENTS,
98 "comments.xml",
99 ));
100 pkg.set_rels_for("word/document.xml", &rels);
101 }
102 let mut ct = pkg.content_types()?;
103 ct.ensure_override(COMMENTS_PART, ns::content::COMMENTS);
104 pkg.set_content_types(&ct);
105 Ok(id)
106}
107
108pub fn delete_comment(
110 pkg: &mut Package,
111 doc_root: &mut XmlNode,
112 id: &str,
113) -> Result<bool, DocxError> {
114 strip_markers(doc_root, id);
115 if !pkg.has_part(COMMENTS_PART) {
116 return Ok(false);
117 }
118 let mut comments = pkg.part_xml(COMMENTS_PART)?;
119 let before = comments.root.children().len();
120 comments
121 .root
122 .children_mut()
123 .retain(|c| !(c.is_element_with_local_name("comment") && c.get_attr("id") == Some(id)));
124 let removed = comments.root.children().len() < before;
125 pkg.set_part_xml(COMMENTS_PART, &comments);
126 Ok(removed)
127}
128
129fn empty_comments() -> XmlDocument {
130 XmlDocument::new(
131 XmlNode::w("comments")
132 .with_attr("xmlns:w", ns::W)
133 .with_attr("xmlns:r", ns::R),
134 )
135}
136
137fn comment_element(id: &str, author: &str, date: &str, text: &str) -> XmlNode {
138 XmlNode::w("comment")
139 .with_attr("w:id", id)
140 .with_attr("w:author", author)
141 .with_attr("w:date", date)
142 .with_attr("w:initials", initials(author))
143 .with_child(XmlNode::w("p").with_child(build_run(text, None)))
144}
145
146fn initials(author: &str) -> String {
147 author
148 .split_whitespace()
149 .filter_map(|w| w.chars().next())
150 .collect::<String>()
151 .chars()
152 .take(4)
153 .collect()
154}
155
156fn next_comment_id(pkg: &Package, para: &XmlNode) -> Result<usize, DocxError> {
157 let mut max = max_numeric_id(para);
158 if pkg.has_part(COMMENTS_PART) {
159 let doc = pkg.part_xml(COMMENTS_PART)?;
160 max = max.max(max_numeric_id(&doc.root));
161 }
162 Ok(max + 1)
163}
164
165fn wrap_anchor(para: &mut XmlNode, anchor: &str, id: &str) -> Result<(), DocxError> {
166 let text = visible_text(para);
167 let needle = if anchor.is_empty() {
168 text.as_str()
169 } else {
170 anchor
171 };
172 let Some(_) = find_normalized(&text, needle) else {
173 return Err(DocxError::invalid(format!(
174 "comment anchor {needle:?} not found in paragraph"
175 )));
176 };
177 let start = XmlNode::w("commentRangeStart").with_attr("w:id", id);
181 let end = XmlNode::w("commentRangeEnd").with_attr("w:id", id);
182 let reference = XmlNode::w("r").with_child(
183 XmlNode::w("rPr")
184 .with_child(XmlNode::w("rStyle").with_attr("w:val", "CommentReference"))
185 .with_child(XmlNode::w("annotationRef")),
186 );
187 let kids = para.children_mut();
189 let insert_at = if kids
190 .first()
191 .is_some_and(|c| c.is_element_with_local_name("pPr"))
192 {
193 1
194 } else {
195 0
196 };
197 kids.insert(insert_at, start);
198 kids.push(end);
199 kids.push(XmlNode::w("r").with_child(XmlNode::w("commentReference").with_attr("w:id", id)));
200 let _ = reference;
201 Ok(())
202}
203
204fn strip_markers(root: &mut XmlNode, id: &str) {
205 if let Some(kids) = root.try_children_mut() {
206 kids.retain(|c| {
207 let is_marker = c.is_element_with_local_name("commentRangeStart")
208 || c.is_element_with_local_name("commentRangeEnd")
209 || c.is_element_with_local_name("commentReference");
210 !(is_marker && c.get_attr("id") == Some(id))
211 });
212 for kid in kids.iter_mut() {
214 if kid.is_element_with_local_name("r") {
215 let has_ref = kid.children().iter().any(|c| {
216 c.is_element_with_local_name("commentReference") && c.get_attr("id") == Some(id)
217 });
218 if has_ref {
219 kid.children_mut().retain(|c| {
221 !(c.is_element_with_local_name("commentReference")
222 && c.get_attr("id") == Some(id))
223 });
224 }
225 }
226 strip_markers(kid, id);
227 }
228 kids.retain(|c| {
229 !(c.is_element_with_local_name("r")
230 && c.find_child("t").is_none()
231 && c.find_child("delText").is_none()
232 && c.find_child("commentReference").is_none()
233 && c.find_child("drawing").is_none())
234 });
235 }
236}
237
238#[allow(dead_code)]
240fn _rels(_: Relationships) {}