Skip to main content

sheetkit_xml/
slicer.rs

1//! Slicer XML schema structures.
2//!
3//! Represents `xl/slicers/slicer{N}.xml` and `xl/slicerCaches/slicerCache{N}.xml`
4//! in the OOXML package. These are Office 2010+ extensions for visual filter controls.
5//!
6//! The slicer cache XML uses namespace-prefixed elements (`x15:tableSlicerCache`)
7//! which cannot round-trip through serde. The `SlicerCacheDefinition` is therefore
8//! serialized manually during workbook save.
9
10use serde::{Deserialize, Serialize};
11
12/// Root element for a slicer definition part (`xl/slicers/slicer{N}.xml`).
13///
14/// Contains one or more slicer definitions that describe visual filter controls
15/// linked to table or pivot table columns.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17#[serde(rename = "slicers")]
18pub struct SlicerDefinitions {
19    #[serde(rename = "@xmlns", default = "default_slicer_ns")]
20    pub xmlns: String,
21
22    #[serde(rename = "@xmlns:mc", skip_serializing_if = "Option::is_none")]
23    pub xmlns_mc: Option<String>,
24
25    #[serde(rename = "slicer", default)]
26    pub slicers: Vec<SlicerDefinition>,
27}
28
29/// A single slicer definition within the slicers part.
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31pub struct SlicerDefinition {
32    #[serde(rename = "@name")]
33    pub name: String,
34
35    #[serde(rename = "@cache")]
36    pub cache: String,
37
38    #[serde(rename = "@caption", skip_serializing_if = "Option::is_none")]
39    pub caption: Option<String>,
40
41    #[serde(rename = "@startItem", skip_serializing_if = "Option::is_none")]
42    pub start_item: Option<u32>,
43
44    #[serde(rename = "@columnCount", skip_serializing_if = "Option::is_none")]
45    pub column_count: Option<u32>,
46
47    #[serde(rename = "@showCaption", skip_serializing_if = "Option::is_none")]
48    pub show_caption: Option<bool>,
49
50    #[serde(rename = "@style", skip_serializing_if = "Option::is_none")]
51    pub style: Option<String>,
52
53    #[serde(rename = "@lockedPosition", skip_serializing_if = "Option::is_none")]
54    pub locked_position: Option<bool>,
55
56    #[serde(rename = "@rowHeight")]
57    pub row_height: u32,
58}
59
60/// In-memory representation of a slicer cache definition.
61///
62/// Serialized manually (not via serde) because the XML uses namespace-prefixed
63/// child elements (`x15:tableSlicerCache`) that serde cannot handle.
64#[derive(Debug, Clone, PartialEq)]
65pub struct SlicerCacheDefinition {
66    pub name: String,
67    pub source_name: String,
68    pub table_slicer_cache: Option<TableSlicerCache>,
69}
70
71/// Tabular slicer cache linking the slicer to a table column.
72#[derive(Debug, Clone, PartialEq)]
73pub struct TableSlicerCache {
74    pub table_id: u32,
75    pub column: u32,
76}
77
78/// Serialize a `SlicerCacheDefinition` to XML manually.
79///
80/// Produces the full `slicerCacheDefinition` element with proper namespace
81/// prefixes for the table slicer cache extension.
82pub fn serialize_slicer_cache(def: &SlicerCacheDefinition) -> String {
83    use std::fmt::Write;
84
85    let ns_x14 = crate::namespaces::SLICER_2009;
86    let ns_x15 = crate::namespaces::SLICER_2010;
87    let ns_mc = crate::namespaces::MC;
88
89    let mut xml = String::new();
90    let _ = write!(
91        xml,
92        "<slicerCacheDefinition \
93         xmlns=\"{ns_x14}\" \
94         xmlns:mc=\"{ns_mc}\" \
95         name=\"{}\" \
96         sourceName=\"{}\"",
97        escape_xml_attr(&def.name),
98        escape_xml_attr(&def.source_name),
99    );
100
101    if let Some(ref tsc) = def.table_slicer_cache {
102        let _ = write!(xml, ">");
103        let _ = write!(
104            xml,
105            "<extLst>\
106             <ext xmlns:x15=\"{ns_x15}\" \
107             uri=\"{{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}}\">\
108             <x15:tableSlicerCache tableId=\"{}\" column=\"{}\"/>\
109             </ext>\
110             </extLst>",
111            tsc.table_id, tsc.column,
112        );
113        let _ = write!(xml, "</slicerCacheDefinition>");
114    } else {
115        let _ = write!(xml, "/>");
116    }
117
118    xml
119}
120
121/// Parse a `SlicerCacheDefinition` from XML.
122///
123/// Uses namespace-aware event parsing, so element prefixes are irrelevant and
124/// attribute values are entity-decoded with either quote style. The root must
125/// be a `slicerCacheDefinition` element with unprefixed `name` and
126/// `sourceName` attributes. The first `tableSlicerCache` element that is not
127/// bound to a foreign namespace supplies the table link. Returns `None` for
128/// malformed XML or a missing required attribute.
129pub fn parse_slicer_cache(xml: &str) -> Option<SlicerCacheDefinition> {
130    use quick_xml::events::Event;
131    use quick_xml::name::{Namespace, ResolveResult};
132    use quick_xml::NsReader;
133
134    let x15 = Namespace(crate::namespaces::SLICER_2010.as_bytes());
135    let mut reader = NsReader::from_str(xml);
136    let mut root: Option<(String, String)> = None;
137    let mut table_slicer_cache = None;
138
139    loop {
140        let (ns, event) = reader.read_resolved_event().ok()?;
141        let element = match event {
142            Event::Start(e) | Event::Empty(e) => e,
143            Event::Eof => break,
144            _ => continue,
145        };
146        let local = element.local_name();
147        if root.is_none() {
148            if local.as_ref() != b"slicerCacheDefinition" {
149                return None;
150            }
151            let name = unprefixed_attr(&element, b"name")?;
152            let source_name = unprefixed_attr(&element, b"sourceName")?;
153            root = Some((name, source_name));
154            continue;
155        }
156        let in_x15_or_unbound = match ns {
157            ResolveResult::Bound(bound) => bound == x15,
158            ResolveResult::Unbound | ResolveResult::Unknown(_) => true,
159        };
160        if table_slicer_cache.is_none()
161            && local.as_ref() == b"tableSlicerCache"
162            && in_x15_or_unbound
163        {
164            let number =
165                |key: &[u8]| -> Option<u32> { unprefixed_attr(&element, key)?.trim().parse().ok() };
166            if let (Some(table_id), Some(column)) = (number(b"tableId"), number(b"column")) {
167                table_slicer_cache = Some(TableSlicerCache { table_id, column });
168            }
169        }
170    }
171
172    let (name, source_name) = root?;
173    Some(SlicerCacheDefinition {
174        name,
175        source_name,
176        table_slicer_cache,
177    })
178}
179
180/// Look up an unprefixed attribute by name and entity-decode its value.
181///
182/// Returns `None` when the attribute is absent or its value contains an
183/// invalid entity reference.
184fn unprefixed_attr(element: &quick_xml::events::BytesStart<'_>, key: &[u8]) -> Option<String> {
185    let attr = element
186        .attributes()
187        .flatten()
188        .find(|attr| attr.key.as_ref() == key)?;
189    attr.unescape_value().ok().map(|v| v.into_owned())
190}
191
192/// Escape special characters for use in XML attribute values.
193fn escape_xml_attr(s: &str) -> String {
194    s.replace('&', "&amp;")
195        .replace('<', "&lt;")
196        .replace('>', "&gt;")
197        .replace('"', "&quot;")
198}
199
200fn default_slicer_ns() -> String {
201    crate::namespaces::SLICER_2009.to_string()
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn test_slicer_definition_roundtrip() {
210        let defs = SlicerDefinitions {
211            xmlns: "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main".to_string(),
212            xmlns_mc: None,
213            slicers: vec![SlicerDefinition {
214                name: "Slicer_Category".to_string(),
215                cache: "Slicer_Category".to_string(),
216                caption: Some("Category".to_string()),
217                start_item: None,
218                column_count: None,
219                show_caption: Some(true),
220                style: Some("SlicerStyleLight1".to_string()),
221                locked_position: None,
222                row_height: 241300,
223            }],
224        };
225
226        let xml = quick_xml::se::to_string(&defs).unwrap();
227        assert!(xml.contains("Slicer_Category"));
228        assert!(xml.contains("SlicerStyleLight1"));
229
230        let parsed: SlicerDefinitions = quick_xml::de::from_str(&xml).unwrap();
231        assert_eq!(parsed.slicers.len(), 1);
232        assert_eq!(parsed.slicers[0].name, "Slicer_Category");
233        assert_eq!(parsed.slicers[0].row_height, 241300);
234    }
235
236    #[test]
237    fn test_slicer_cache_serialize_and_parse() {
238        let cache = SlicerCacheDefinition {
239            name: "Slicer_Category".to_string(),
240            source_name: "Category".to_string(),
241            table_slicer_cache: Some(TableSlicerCache {
242                table_id: 1,
243                column: 2,
244            }),
245        };
246
247        let xml = serialize_slicer_cache(&cache);
248        assert!(xml.contains("Slicer_Category"));
249        assert!(xml.contains("sourceName=\"Category\""));
250        assert!(xml.contains("x15:tableSlicerCache"));
251        assert!(xml.contains("tableId=\"1\""));
252        assert!(xml.contains("column=\"2\""));
253
254        let parsed = parse_slicer_cache(&xml).unwrap();
255        assert_eq!(parsed.name, "Slicer_Category");
256        assert_eq!(parsed.source_name, "Category");
257        let tsc = parsed.table_slicer_cache.unwrap();
258        assert_eq!(tsc.table_id, 1);
259        assert_eq!(tsc.column, 2);
260    }
261
262    #[test]
263    fn test_slicer_definition_minimal() {
264        let def = SlicerDefinition {
265            name: "S1".to_string(),
266            cache: "S1".to_string(),
267            caption: None,
268            start_item: None,
269            column_count: None,
270            show_caption: None,
271            style: None,
272            locked_position: None,
273            row_height: 241300,
274        };
275
276        let xml = quick_xml::se::to_string(&def).unwrap();
277        assert!(!xml.contains("caption="));
278        assert!(!xml.contains("style="));
279        assert!(xml.contains("rowHeight=\"241300\""));
280    }
281
282    #[test]
283    fn test_multiple_slicers_in_definitions() {
284        let defs = SlicerDefinitions {
285            xmlns: "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main".to_string(),
286            xmlns_mc: None,
287            slicers: vec![
288                SlicerDefinition {
289                    name: "Slicer_A".to_string(),
290                    cache: "Slicer_A".to_string(),
291                    caption: Some("Column A".to_string()),
292                    start_item: None,
293                    column_count: Some(2),
294                    show_caption: Some(true),
295                    style: Some("SlicerStyleDark1".to_string()),
296                    locked_position: None,
297                    row_height: 241300,
298                },
299                SlicerDefinition {
300                    name: "Slicer_B".to_string(),
301                    cache: "Slicer_B".to_string(),
302                    caption: Some("Column B".to_string()),
303                    start_item: None,
304                    column_count: None,
305                    show_caption: Some(false),
306                    style: None,
307                    locked_position: Some(true),
308                    row_height: 241300,
309                },
310            ],
311        };
312
313        let xml = quick_xml::se::to_string(&defs).unwrap();
314        let parsed: SlicerDefinitions = quick_xml::de::from_str(&xml).unwrap();
315        assert_eq!(parsed.slicers.len(), 2);
316        assert_eq!(parsed.slicers[0].name, "Slicer_A");
317        assert_eq!(parsed.slicers[1].name, "Slicer_B");
318    }
319
320    #[test]
321    fn test_slicer_cache_without_table_cache() {
322        let cache = SlicerCacheDefinition {
323            name: "Slicer_X".to_string(),
324            source_name: "ColumnX".to_string(),
325            table_slicer_cache: None,
326        };
327
328        let xml = serialize_slicer_cache(&cache);
329        assert!(!xml.contains("tableSlicerCache"));
330        assert!(xml.contains("Slicer_X"));
331
332        let parsed = parse_slicer_cache(&xml).unwrap();
333        assert_eq!(parsed.name, "Slicer_X");
334        assert!(parsed.table_slicer_cache.is_none());
335    }
336
337    #[test]
338    fn test_slicer_cache_escapes_special_chars() {
339        let cache = SlicerCacheDefinition {
340            name: "Slicer_A&B".to_string(),
341            source_name: "Col<1>".to_string(),
342            table_slicer_cache: None,
343        };
344
345        let xml = serialize_slicer_cache(&cache);
346        assert!(xml.contains("Slicer_A&amp;B"));
347        assert!(xml.contains("Col&lt;1&gt;"));
348    }
349
350    #[test]
351    fn test_slicer_cache_special_chars_roundtrip_multi_cycle() {
352        let cache = SlicerCacheDefinition {
353            name: "Slicer_A&B".to_string(),
354            source_name: "A&B <c> \"d\" 'e'".to_string(),
355            table_slicer_cache: Some(TableSlicerCache {
356                table_id: 3,
357                column: 4,
358            }),
359        };
360
361        let mut current = cache.clone();
362        for _ in 0..3 {
363            let xml = serialize_slicer_cache(&current);
364            current = parse_slicer_cache(&xml).unwrap();
365            assert_eq!(current, cache);
366        }
367    }
368
369    #[test]
370    fn test_parse_slicer_cache_single_quoted_attributes() {
371        let xml = r#"<slicerCacheDefinition xmlns='http://schemas.microsoft.com/office/spreadsheetml/2009/9/main' name='Slicer_Q' sourceName='Col &amp; Q'><extLst><ext uri='{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}' xmlns:x15='http://schemas.microsoft.com/office/spreadsheetml/2010/11/main'><x15:tableSlicerCache tableId='5' column='6'/></ext></extLst></slicerCacheDefinition>"#;
372
373        let parsed = parse_slicer_cache(xml).unwrap();
374        assert_eq!(parsed.name, "Slicer_Q");
375        assert_eq!(parsed.source_name, "Col & Q");
376        assert_eq!(
377            parsed.table_slicer_cache,
378            Some(TableSlicerCache {
379                table_id: 5,
380                column: 6
381            })
382        );
383    }
384
385    #[test]
386    fn test_parse_slicer_cache_alternate_namespace_prefix() {
387        let xml = r#"<sc:slicerCacheDefinition xmlns:sc="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" sourceName="Region"
388    name="Slicer_Region"><sc:extLst><sc:ext uri="{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}" xmlns:t="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"><t:tableSlicerCache column="2" tableId="9"/></sc:ext></sc:extLst></sc:slicerCacheDefinition>"#;
389
390        let parsed = parse_slicer_cache(xml).unwrap();
391        assert_eq!(parsed.name, "Slicer_Region");
392        assert_eq!(parsed.source_name, "Region");
393        assert_eq!(
394            parsed.table_slicer_cache,
395            Some(TableSlicerCache {
396                table_id: 9,
397                column: 2
398            })
399        );
400    }
401
402    #[test]
403    fn test_parse_slicer_cache_ignores_lookalike_attributes() {
404        // `xname` and a prefixed `p:name` must not satisfy the `name` lookup,
405        // and an element in a foreign namespace is not a table slicer cache.
406        let xml = r#"<slicerCacheDefinition xmlns="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:p="urn:other" xname="wrong" p:name="wrong" name="right" sourceName="S"><extLst><ext xmlns:o="urn:other"><o:tableSlicerCache tableId="1" column="1"/></ext></extLst></slicerCacheDefinition>"#;
407
408        let parsed = parse_slicer_cache(xml).unwrap();
409        assert_eq!(parsed.name, "right");
410        assert!(parsed.table_slicer_cache.is_none());
411    }
412
413    #[test]
414    fn test_parse_slicer_cache_rejects_malformed_input() {
415        assert!(parse_slicer_cache("").is_none());
416        assert!(parse_slicer_cache("<slicerCacheDefinition sourceName=\"S\"/>").is_none());
417        assert!(parse_slicer_cache("<other name=\"N\" sourceName=\"S\"/>").is_none());
418        assert!(
419            parse_slicer_cache("<slicerCacheDefinition name=\"a&bogus;\" sourceName=\"S\"/>")
420                .is_none()
421        );
422    }
423}