Skip to main content

sheetkit_core/
rich_text.rs

1//! Rich text run types and conversion utilities.
2//!
3//! A rich text value is a sequence of [`RichTextRun`] segments, each with its
4//! own formatting. These map to the `<r>` (run) elements inside `<si>` items
5//! in `xl/sharedStrings.xml`.
6
7use sheetkit_xml::shared_strings::{BoolVal, Color, FontName, FontSize, RPr, Si, R, T};
8
9/// A single formatted text segment within a rich text cell.
10#[derive(Debug, Clone, PartialEq)]
11pub struct RichTextRun {
12    /// The plain text content of this run.
13    pub text: String,
14    /// Font name (e.g., "Calibri").
15    pub font: Option<String>,
16    /// Font size in points.
17    pub size: Option<f64>,
18    /// Whether the text is bold.
19    pub bold: bool,
20    /// Whether the text is italic.
21    pub italic: bool,
22    /// Font color as an RGB hex string (e.g., "#FF0000").
23    pub color: Option<String>,
24}
25
26/// Convert a high-level [`RichTextRun`] into an XML `<r>` element.
27pub fn run_to_xml(run: &RichTextRun) -> R {
28    let has_formatting =
29        run.bold || run.italic || run.font.is_some() || run.size.is_some() || run.color.is_some();
30
31    let r_pr = if has_formatting {
32        Some(RPr {
33            r_font: run.font.as_ref().map(|val| FontName { val: val.clone() }),
34            family: None,
35            b: if run.bold {
36                Some(BoolVal { val: None })
37            } else {
38                None
39            },
40            i: if run.italic {
41                Some(BoolVal { val: None })
42            } else {
43                None
44            },
45            strike: None,
46            color: run.color.as_ref().map(|rgb| Color {
47                rgb: Some(rgb.clone()),
48                theme: None,
49                tint: None,
50            }),
51            sz: run.size.map(|val| FontSize { val }),
52            u: None,
53            vert_align: None,
54            scheme: None,
55        })
56    } else {
57        None
58    };
59
60    R {
61        r_pr,
62        t: T {
63            xml_space: if run.text.starts_with(' ')
64                || run.text.ends_with(' ')
65                || run.text.contains("  ")
66                || run.text.contains('\n')
67                || run.text.contains('\t')
68            {
69                Some("preserve".to_string())
70            } else {
71                None
72            },
73            value: run.text.clone(),
74        },
75    }
76}
77
78/// Convert an XML `<r>` element into a high-level [`RichTextRun`].
79pub fn xml_to_run(r: &R) -> RichTextRun {
80    let (font, size, bold, italic, color) = if let Some(ref rpr) = r.r_pr {
81        (
82            rpr.r_font.as_ref().map(|f| f.val.clone()),
83            rpr.sz.as_ref().map(|s| s.val),
84            rpr.b.is_some(),
85            rpr.i.is_some(),
86            rpr.color.as_ref().and_then(|c| c.rgb.clone()),
87        )
88    } else {
89        (None, None, false, false, None)
90    };
91
92    RichTextRun {
93        text: r.t.value.clone(),
94        font,
95        size,
96        bold,
97        italic,
98        color,
99    }
100}
101
102/// Convert a slice of [`RichTextRun`] into an XML `<si>` element (for the SST).
103pub fn runs_to_si(runs: &[RichTextRun]) -> Si {
104    Si {
105        t: None,
106        r: runs.iter().map(run_to_xml).collect(),
107    }
108}
109
110/// Extract plain text from a slice of rich text runs.
111pub fn rich_text_to_plain(runs: &[RichTextRun]) -> String {
112    runs.iter().map(|r| r.text.as_str()).collect()
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn test_rich_text_to_plain() {
121        let runs = vec![
122            RichTextRun {
123                text: "Hello ".to_string(),
124                font: None,
125                size: None,
126                bold: true,
127                italic: false,
128                color: None,
129            },
130            RichTextRun {
131                text: "World".to_string(),
132                font: None,
133                size: None,
134                bold: false,
135                italic: false,
136                color: None,
137            },
138        ];
139        assert_eq!(rich_text_to_plain(&runs), "Hello World");
140    }
141
142    #[test]
143    fn test_run_to_xml_plain() {
144        let run = RichTextRun {
145            text: "plain".to_string(),
146            font: None,
147            size: None,
148            bold: false,
149            italic: false,
150            color: None,
151        };
152        let xml_r = run_to_xml(&run);
153        assert!(xml_r.r_pr.is_none());
154        assert_eq!(xml_r.t.value, "plain");
155    }
156
157    #[test]
158    fn test_run_to_xml_bold() {
159        let run = RichTextRun {
160            text: "bold".to_string(),
161            font: None,
162            size: None,
163            bold: true,
164            italic: false,
165            color: None,
166        };
167        let xml_r = run_to_xml(&run);
168        assert!(xml_r.r_pr.is_some());
169        assert!(xml_r.r_pr.as_ref().unwrap().b.is_some());
170    }
171
172    #[test]
173    fn test_xml_to_run_roundtrip() {
174        let original = RichTextRun {
175            text: "test".to_string(),
176            font: Some("Arial".to_string()),
177            size: Some(12.0),
178            bold: true,
179            italic: true,
180            color: Some("#FF0000".to_string()),
181        };
182        let xml_r = run_to_xml(&original);
183        let back = xml_to_run(&xml_r);
184        assert_eq!(original, back);
185    }
186
187    #[test]
188    fn test_runs_to_si() {
189        let runs = vec![
190            RichTextRun {
191                text: "A".to_string(),
192                font: None,
193                size: None,
194                bold: true,
195                italic: false,
196                color: None,
197            },
198            RichTextRun {
199                text: "B".to_string(),
200                font: None,
201                size: None,
202                bold: false,
203                italic: false,
204                color: None,
205            },
206        ];
207        let si = runs_to_si(&runs);
208        assert!(si.t.is_none());
209        assert_eq!(si.r.len(), 2);
210    }
211
212    #[test]
213    fn test_xml_to_run_no_formatting() {
214        let r = R {
215            r_pr: None,
216            t: T {
217                xml_space: None,
218                value: "text".to_string(),
219            },
220        };
221        let run = xml_to_run(&r);
222        assert_eq!(run.text, "text");
223        assert!(!run.bold);
224        assert!(!run.italic);
225        assert!(run.font.is_none());
226        assert!(run.size.is_none());
227        assert!(run.color.is_none());
228    }
229
230    #[test]
231    fn test_space_preservation() {
232        let run = RichTextRun {
233            text: " leading space".to_string(),
234            font: None,
235            size: None,
236            bold: false,
237            italic: false,
238            color: None,
239        };
240        let xml_r = run_to_xml(&run);
241        assert_eq!(xml_r.t.xml_space, Some("preserve".to_string()));
242    }
243}