Skip to main content

sheetkit_core/
comment.rs

1//! Comment management utilities.
2//!
3//! Provides functions for adding, querying, and removing cell comments.
4
5use sheetkit_xml::comments::{Authors, Comment, CommentList, CommentRun, CommentText, Comments};
6use sheetkit_xml::namespaces;
7
8/// Configuration for a cell comment.
9#[derive(Debug, Clone, PartialEq)]
10pub struct CommentConfig {
11    /// The cell reference (e.g. "A1").
12    pub cell: String,
13    /// The author of the comment.
14    pub author: String,
15    /// The plain text of the comment.
16    pub text: String,
17}
18
19/// Add a comment to a sheet's comments collection.
20///
21/// If `comments` is `None`, a new `Comments` structure is created.
22pub fn add_comment(comments: &mut Option<Comments>, config: &CommentConfig) {
23    add_comment_with_existing(comments, config, true);
24}
25
26/// Add a comment, scanning for an existing comment on the same cell only
27/// when `may_exist` is true. Callers that already searched the cell pass the
28/// search result to avoid a second full scan.
29pub(crate) fn add_comment_with_existing(
30    comments: &mut Option<Comments>,
31    config: &CommentConfig,
32    may_exist: bool,
33) {
34    let c = comments.get_or_insert_with(|| Comments {
35        xmlns: namespaces::SPREADSHEET_ML.to_string(),
36        authors: Authors {
37            authors: Vec::new(),
38        },
39        comment_list: CommentList {
40            comments: Vec::new(),
41        },
42    });
43
44    // Find or add the author.
45    let author_id = match c.authors.authors.iter().position(|a| a == &config.author) {
46        Some(idx) => idx as u32,
47        None => {
48            c.authors.authors.push(config.author.clone());
49            (c.authors.authors.len() - 1) as u32
50        }
51    };
52
53    // Remove existing comment on the same cell if any.
54    if may_exist {
55        c.comment_list
56            .comments
57            .retain(|comment| comment.r#ref != config.cell);
58    }
59
60    // Add the new comment.
61    c.comment_list.comments.push(Comment {
62        r#ref: config.cell.clone(),
63        author_id,
64        text: CommentText {
65            runs: vec![CommentRun {
66                rpr: None,
67                t: config.text.clone(),
68            }],
69        },
70    });
71}
72
73/// Get the comment for a specific cell.
74///
75/// Returns `None` if there is no comment on the cell.
76pub fn get_comment(comments: &Option<Comments>, cell: &str) -> Option<CommentConfig> {
77    let index = find_comment_index(comments, cell)?;
78    comment_config_at(comments, index)
79}
80
81/// Index of the first comment on `cell`, if any.
82pub(crate) fn find_comment_index(comments: &Option<Comments>, cell: &str) -> Option<usize> {
83    comments
84        .as_ref()?
85        .comment_list
86        .comments
87        .iter()
88        .position(|cm| cm.r#ref == cell)
89}
90
91/// Build the configuration of the comment at `index`.
92pub(crate) fn comment_config_at(
93    comments: &Option<Comments>,
94    index: usize,
95) -> Option<CommentConfig> {
96    let c = comments.as_ref()?;
97    let comment = c.comment_list.comments.get(index)?;
98
99    let author = c
100        .authors
101        .authors
102        .get(comment.author_id as usize)
103        .cloned()
104        .unwrap_or_default();
105
106    let text = comment
107        .text
108        .runs
109        .iter()
110        .map(|r| r.t.as_str())
111        .collect::<Vec<_>>()
112        .join("");
113
114    Some(CommentConfig {
115        cell: comment.r#ref.clone(),
116        author,
117        text,
118    })
119}
120
121/// Remove a comment from a specific cell.
122///
123/// Returns `true` if a comment was found and removed.
124pub fn remove_comment(comments: &mut Option<Comments>, cell: &str) -> bool {
125    if let Some(ref mut c) = comments {
126        let before = c.comment_list.comments.len();
127        c.comment_list
128            .comments
129            .retain(|comment| comment.r#ref != cell);
130        let removed = c.comment_list.comments.len() < before;
131
132        // Clean up if no comments remain.
133        if c.comment_list.comments.is_empty() {
134            *comments = None;
135        }
136
137        removed
138    } else {
139        false
140    }
141}
142
143/// Get all comments from a sheet's comments collection.
144pub fn get_all_comments(comments: &Option<Comments>) -> Vec<CommentConfig> {
145    match comments.as_ref() {
146        Some(c) => c
147            .comment_list
148            .comments
149            .iter()
150            .map(|comment| {
151                let author = c
152                    .authors
153                    .authors
154                    .get(comment.author_id as usize)
155                    .cloned()
156                    .unwrap_or_default();
157                let text = comment
158                    .text
159                    .runs
160                    .iter()
161                    .map(|r| r.t.as_str())
162                    .collect::<Vec<_>>()
163                    .join("");
164                CommentConfig {
165                    cell: comment.r#ref.clone(),
166                    author,
167                    text,
168                }
169            })
170            .collect(),
171        None => Vec::new(),
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn test_add_comment() {
181        let mut comments = None;
182        let config = CommentConfig {
183            cell: "A1".to_string(),
184            author: "Alice".to_string(),
185            text: "Hello comment".to_string(),
186        };
187        add_comment(&mut comments, &config);
188
189        assert!(comments.is_some());
190        let c = comments.as_ref().unwrap();
191        assert_eq!(c.authors.authors.len(), 1);
192        assert_eq!(c.authors.authors[0], "Alice");
193        assert_eq!(c.comment_list.comments.len(), 1);
194        assert_eq!(c.comment_list.comments[0].r#ref, "A1");
195    }
196
197    #[test]
198    fn test_get_comment() {
199        let mut comments = None;
200        let config = CommentConfig {
201            cell: "A1".to_string(),
202            author: "Alice".to_string(),
203            text: "Test comment".to_string(),
204        };
205        add_comment(&mut comments, &config);
206
207        let result = get_comment(&comments, "A1");
208        assert!(result.is_some());
209        let c = result.unwrap();
210        assert_eq!(c.cell, "A1");
211        assert_eq!(c.author, "Alice");
212        assert_eq!(c.text, "Test comment");
213    }
214
215    #[test]
216    fn test_get_comment_nonexistent() {
217        let comments: Option<Comments> = None;
218        assert!(get_comment(&comments, "A1").is_none());
219    }
220
221    #[test]
222    fn test_get_comment_wrong_cell() {
223        let mut comments = None;
224        let config = CommentConfig {
225            cell: "A1".to_string(),
226            author: "Alice".to_string(),
227            text: "Test".to_string(),
228        };
229        add_comment(&mut comments, &config);
230        assert!(get_comment(&comments, "B1").is_none());
231    }
232
233    #[test]
234    fn test_remove_comment() {
235        let mut comments = None;
236        let config = CommentConfig {
237            cell: "A1".to_string(),
238            author: "Alice".to_string(),
239            text: "Test".to_string(),
240        };
241        add_comment(&mut comments, &config);
242        assert!(remove_comment(&mut comments, "A1"));
243        assert!(comments.is_none());
244    }
245
246    #[test]
247    fn test_remove_nonexistent_comment() {
248        let mut comments: Option<Comments> = None;
249        assert!(!remove_comment(&mut comments, "A1"));
250    }
251
252    #[test]
253    fn test_multiple_comments_different_cells() {
254        let mut comments = None;
255        add_comment(
256            &mut comments,
257            &CommentConfig {
258                cell: "A1".to_string(),
259                author: "Alice".to_string(),
260                text: "Comment 1".to_string(),
261            },
262        );
263        add_comment(
264            &mut comments,
265            &CommentConfig {
266                cell: "B2".to_string(),
267                author: "Bob".to_string(),
268                text: "Comment 2".to_string(),
269            },
270        );
271        add_comment(
272            &mut comments,
273            &CommentConfig {
274                cell: "C3".to_string(),
275                author: "Alice".to_string(),
276                text: "Comment 3".to_string(),
277            },
278        );
279
280        let all = get_all_comments(&comments);
281        assert_eq!(all.len(), 3);
282
283        // Verify authors are deduplicated
284        let c = comments.as_ref().unwrap();
285        assert_eq!(c.authors.authors.len(), 2); // Alice and Bob
286
287        // Verify individual lookups
288        let c1 = get_comment(&comments, "A1").unwrap();
289        assert_eq!(c1.text, "Comment 1");
290        assert_eq!(c1.author, "Alice");
291
292        let c2 = get_comment(&comments, "B2").unwrap();
293        assert_eq!(c2.text, "Comment 2");
294        assert_eq!(c2.author, "Bob");
295    }
296
297    #[test]
298    fn test_overwrite_comment_on_same_cell() {
299        let mut comments = None;
300        add_comment(
301            &mut comments,
302            &CommentConfig {
303                cell: "A1".to_string(),
304                author: "Alice".to_string(),
305                text: "Original".to_string(),
306            },
307        );
308        add_comment(
309            &mut comments,
310            &CommentConfig {
311                cell: "A1".to_string(),
312                author: "Bob".to_string(),
313                text: "Updated".to_string(),
314            },
315        );
316
317        let all = get_all_comments(&comments);
318        assert_eq!(all.len(), 1);
319        assert_eq!(all[0].text, "Updated");
320        assert_eq!(all[0].author, "Bob");
321    }
322
323    #[test]
324    fn test_remove_one_of_multiple_comments() {
325        let mut comments = None;
326        add_comment(
327            &mut comments,
328            &CommentConfig {
329                cell: "A1".to_string(),
330                author: "Alice".to_string(),
331                text: "First".to_string(),
332            },
333        );
334        add_comment(
335            &mut comments,
336            &CommentConfig {
337                cell: "B2".to_string(),
338                author: "Bob".to_string(),
339                text: "Second".to_string(),
340            },
341        );
342
343        assert!(remove_comment(&mut comments, "A1"));
344        assert!(comments.is_some()); // Still has B2
345
346        let all = get_all_comments(&comments);
347        assert_eq!(all.len(), 1);
348        assert_eq!(all[0].cell, "B2");
349    }
350
351    #[test]
352    fn test_get_all_comments_empty() {
353        let comments: Option<Comments> = None;
354        let all = get_all_comments(&comments);
355        assert!(all.is_empty());
356    }
357
358    #[test]
359    fn test_comments_xml_roundtrip() {
360        let mut comments = None;
361        add_comment(
362            &mut comments,
363            &CommentConfig {
364                cell: "A1".to_string(),
365                author: "Author".to_string(),
366                text: "A test comment".to_string(),
367            },
368        );
369
370        let c = comments.as_ref().unwrap();
371        let xml = quick_xml::se::to_string(c).unwrap();
372        let parsed: Comments = quick_xml::de::from_str(&xml).unwrap();
373
374        assert_eq!(parsed.authors.authors.len(), 1);
375        assert_eq!(parsed.comment_list.comments.len(), 1);
376        assert_eq!(parsed.comment_list.comments[0].r#ref, "A1");
377        assert_eq!(
378            parsed.comment_list.comments[0].text.runs[0].t,
379            "A test comment"
380        );
381    }
382}