Skip to main content

sheetkit_xml/
comments.rs

1//! Comments XML schema structures.
2//!
3//! Represents `xl/comments{N}.xml` in the OOXML package.
4
5use serde::{Deserialize, Deserializer, Serialize};
6
7use crate::namespaces;
8
9/// Comments root element.
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11#[serde(rename = "comments")]
12pub struct Comments {
13    #[serde(rename = "@xmlns", default = "crate::default_spreadsheet_ml_ns")]
14    pub xmlns: String,
15
16    #[serde(rename = "authors")]
17    pub authors: Authors,
18
19    #[serde(rename = "commentList")]
20    pub comment_list: CommentList,
21}
22
23/// Authors container.
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25pub struct Authors {
26    #[serde(rename = "author", default)]
27    pub authors: Vec<String>,
28}
29
30/// Comment list container.
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub struct CommentList {
33    #[serde(rename = "comment", default)]
34    pub comments: Vec<Comment>,
35}
36
37/// Individual comment.
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct Comment {
40    #[serde(rename = "@ref")]
41    pub r#ref: String,
42
43    #[serde(rename = "@authorId")]
44    pub author_id: u32,
45
46    #[serde(rename = "text")]
47    pub text: CommentText,
48}
49
50/// Comment text content.
51#[derive(Debug, Clone, PartialEq, Serialize)]
52pub struct CommentText {
53    #[serde(rename = "r", default)]
54    pub runs: Vec<CommentRun>,
55}
56
57impl<'de> Deserialize<'de> for CommentText {
58    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
59    where
60        D: Deserializer<'de>,
61    {
62        let elements = CommentTextElements::deserialize(deserializer)?;
63        Ok(Self {
64            runs: elements
65                .content
66                .into_iter()
67                .map(|element| match element {
68                    CommentTextElement::Run(run) => run,
69                    CommentTextElement::DirectText(t) => CommentRun {
70                        rpr: None,
71                        t: t.value,
72                    },
73                })
74                .collect(),
75        })
76    }
77}
78
79#[derive(Deserialize)]
80struct CommentTextElements {
81    #[serde(rename = "$value", default)]
82    content: Vec<CommentTextElement>,
83}
84
85#[derive(Deserialize)]
86enum CommentTextElement {
87    #[serde(rename = "r")]
88    Run(CommentRun),
89    #[serde(rename = "t")]
90    DirectText(CommentTextValue),
91}
92
93#[derive(Deserialize)]
94struct CommentTextValue {
95    #[serde(rename = "$value", default)]
96    value: String,
97}
98
99/// A text run within a comment.
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101pub struct CommentRun {
102    #[serde(rename = "rPr", skip_serializing_if = "Option::is_none")]
103    pub rpr: Option<CommentRunProperties>,
104
105    #[serde(rename = "t")]
106    pub t: String,
107}
108
109/// Run properties for comment text formatting.
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub struct CommentRunProperties {
112    #[serde(rename = "b", skip_serializing_if = "Option::is_none")]
113    pub b: Option<BoldFlag>,
114
115    #[serde(rename = "sz", skip_serializing_if = "Option::is_none")]
116    pub sz: Option<FontSize>,
117}
118
119/// Bold flag element.
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121pub struct BoldFlag;
122
123/// Font size element.
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125pub struct FontSize {
126    #[serde(rename = "@val")]
127    pub val: f64,
128}
129
130impl Default for Comments {
131    fn default() -> Self {
132        Self {
133            xmlns: namespaces::SPREADSHEET_ML.to_string(),
134            authors: Authors {
135                authors: Vec::new(),
136            },
137            comment_list: CommentList {
138                comments: Vec::new(),
139            },
140        }
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn test_comments_default() {
150        let comments = Comments::default();
151        assert_eq!(comments.xmlns, namespaces::SPREADSHEET_ML);
152        assert!(comments.authors.authors.is_empty());
153        assert!(comments.comment_list.comments.is_empty());
154    }
155
156    #[test]
157    fn test_comments_roundtrip() {
158        let comments = Comments {
159            xmlns: namespaces::SPREADSHEET_ML.to_string(),
160            authors: Authors {
161                authors: vec!["Author1".to_string()],
162            },
163            comment_list: CommentList {
164                comments: vec![Comment {
165                    r#ref: "A1".to_string(),
166                    author_id: 0,
167                    text: CommentText {
168                        runs: vec![CommentRun {
169                            rpr: None,
170                            t: "This is a comment".to_string(),
171                        }],
172                    },
173                }],
174            },
175        };
176
177        let xml = quick_xml::se::to_string(&comments).unwrap();
178        assert!(xml.contains("A1"));
179        assert!(xml.contains("This is a comment"));
180        assert!(xml.contains("Author1"));
181
182        let parsed: Comments = quick_xml::de::from_str(&xml).unwrap();
183        assert_eq!(parsed.authors.authors.len(), 1);
184        assert_eq!(parsed.comment_list.comments.len(), 1);
185        assert_eq!(parsed.comment_list.comments[0].r#ref, "A1");
186        assert_eq!(parsed.comment_list.comments[0].author_id, 0);
187        assert_eq!(
188            parsed.comment_list.comments[0].text.runs[0].t,
189            "This is a comment"
190        );
191    }
192
193    #[test]
194    fn test_comment_text_deserializes_direct_rich_and_mixed_text_in_order() {
195        let xml = r#"
196<comments xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
197  <authors><author>Author</author></authors>
198  <commentList>
199    <comment ref="A1" authorId="0"><text><t>plain text &amp; more</t></text></comment>
200    <comment ref="A2" authorId="0"><text><r><rPr><b/></rPr><t>rich text</t></r></text></comment>
201    <comment ref="A3" authorId="0"><text><t>first part</t><r><t>middle part</t></r><t>last part</t></text></comment>
202  </commentList>
203</comments>"#;
204
205        let parsed: Comments = quick_xml::de::from_str(xml).unwrap();
206        let direct = &parsed.comment_list.comments[0].text;
207        assert_eq!(
208            direct
209                .runs
210                .iter()
211                .map(|run| run.t.as_str())
212                .collect::<String>(),
213            "plain text & more"
214        );
215        assert!(direct.runs[0].rpr.is_none());
216
217        let rich = &parsed.comment_list.comments[1].text;
218        assert_eq!(rich.runs[0].t, "rich text");
219        assert!(rich.runs[0].rpr.is_some());
220
221        let mixed = &parsed.comment_list.comments[2].text;
222        assert_eq!(
223            mixed
224                .runs
225                .iter()
226                .map(|run| run.t.as_str())
227                .collect::<String>(),
228            "first partmiddle partlast part"
229        );
230
231        let serialized = quick_xml::se::to_string(&parsed).unwrap();
232        assert_eq!(serialized.matches("plain text &amp; more").count(), 1);
233        assert_eq!(serialized.matches("rich text").count(), 1);
234        assert_eq!(serialized.matches("first part").count(), 1);
235        let reparsed: Comments = quick_xml::de::from_str(&serialized).unwrap();
236        assert_eq!(reparsed, parsed);
237    }
238}