Skip to main content

sheetkit_xml/
table.rs

1//! Table XML schema structures.
2//!
3//! Represents `xl/tables/table{N}.xml` in the OOXML package.
4//! Tables define structured data ranges with named columns, auto-filters,
5//! and optional styles.
6//!
7//! The serde `Deserialize` implementation captures every unprefixed
8//! `CT_Table` / `CT_TableColumn` attribute plus the column formulas.
9//! [`parse_table_xml`] additionally preserves prefixed attributes and
10//! opaque children (`sortState`, `extLst`, `xmlColumnPr`, auto-filter
11//! criteria) and records the source text so unchanged parts can be written
12//! back verbatim via [`TableXml::unchanged_source`].
13
14use std::collections::{BTreeMap, BTreeSet};
15use std::sync::Arc;
16
17use quick_xml::events::{BytesStart, Event};
18use quick_xml::Reader;
19use serde::ser::{SerializeMap, SerializeStruct};
20use serde::{Deserialize, Serialize, Serializer};
21
22use crate::namespaces;
23
24/// Prefixed root attributes that are re-emitted on serialization, as
25/// `(attribute name, serde field key)` pairs.
26const ROOT_EXTRA_ATTRIBUTES: &[(&str, &str)] = &[
27    ("xmlns:mc", "@xmlns:mc"),
28    ("xmlns:x14ac", "@xmlns:x14ac"),
29    ("xmlns:xr", "@xmlns:xr"),
30    ("xmlns:xr3", "@xmlns:xr3"),
31    ("mc:Ignorable", "@mc:Ignorable"),
32    ("xr:uid", "@xr:uid"),
33];
34
35fn default_spreadsheet_ns() -> String {
36    namespaces::SPREADSHEET_ML.to_string()
37}
38
39/// Root element for a table definition part (`xl/tables/table{N}.xml`).
40#[derive(Debug, Clone, PartialEq, Deserialize)]
41#[serde(rename = "table")]
42pub struct TableXml {
43    #[serde(rename = "@xmlns", default = "default_spreadsheet_ns")]
44    pub xmlns: String,
45
46    #[serde(rename = "@id")]
47    pub id: u32,
48
49    #[serde(rename = "@name")]
50    pub name: String,
51
52    #[serde(rename = "@displayName")]
53    pub display_name: String,
54
55    #[serde(rename = "@comment", default)]
56    pub comment: Option<String>,
57
58    #[serde(rename = "@ref")]
59    pub reference: String,
60
61    #[serde(rename = "@tableType", default)]
62    pub table_type: Option<String>,
63
64    #[serde(rename = "@headerRowCount", default)]
65    pub header_row_count: Option<u32>,
66
67    #[serde(rename = "@insertRow", default)]
68    pub insert_row: Option<bool>,
69
70    #[serde(rename = "@insertRowShift", default)]
71    pub insert_row_shift: Option<bool>,
72
73    #[serde(rename = "@totalsRowCount", default)]
74    pub totals_row_count: Option<u32>,
75
76    #[serde(rename = "@totalsRowShown", default)]
77    pub totals_row_shown: Option<bool>,
78
79    #[serde(rename = "@published", default)]
80    pub published: Option<bool>,
81
82    #[serde(rename = "@headerRowDxfId", default)]
83    pub header_row_dxf_id: Option<u32>,
84
85    #[serde(rename = "@dataDxfId", default)]
86    pub data_dxf_id: Option<u32>,
87
88    #[serde(rename = "@totalsRowDxfId", default)]
89    pub totals_row_dxf_id: Option<u32>,
90
91    #[serde(rename = "@headerRowBorderDxfId", default)]
92    pub header_row_border_dxf_id: Option<u32>,
93
94    #[serde(rename = "@tableBorderDxfId", default)]
95    pub table_border_dxf_id: Option<u32>,
96
97    #[serde(rename = "@totalsRowBorderDxfId", default)]
98    pub totals_row_border_dxf_id: Option<u32>,
99
100    #[serde(rename = "@headerRowCellStyle", default)]
101    pub header_row_cell_style: Option<String>,
102
103    #[serde(rename = "@dataCellStyle", default)]
104    pub data_cell_style: Option<String>,
105
106    #[serde(rename = "@totalsRowCellStyle", default)]
107    pub totals_row_cell_style: Option<String>,
108
109    #[serde(rename = "@connectionId", default)]
110    pub connection_id: Option<u32>,
111
112    /// Prefixed root attributes (namespace declarations, `mc:Ignorable`,
113    /// `xr:uid`). Only names listed in the serializer allow-list are written.
114    #[serde(skip)]
115    pub extra_attributes: Vec<(String, String)>,
116
117    #[serde(rename = "autoFilter", default)]
118    pub auto_filter: Option<TableAutoFilter>,
119
120    /// Opaque `sortState` element, preserved verbatim.
121    #[serde(skip)]
122    pub sort_state: Option<XmlFragment>,
123
124    #[serde(rename = "tableColumns")]
125    pub table_columns: TableColumnsXml,
126
127    #[serde(rename = "tableStyleInfo", default)]
128    pub table_style_info: Option<TableStyleInfoXml>,
129
130    /// Opaque `extLst` element, preserved verbatim.
131    #[serde(skip)]
132    pub ext_lst: Option<XmlFragment>,
133
134    /// Original part text captured by [`parse_table_xml`].
135    #[serde(skip)]
136    pub source: TableSource,
137}
138
139/// Auto-filter reference within a table definition.
140#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
141pub struct TableAutoFilter {
142    #[serde(rename = "@ref")]
143    pub reference: String,
144
145    /// Filter criteria children (`filterColumn`, `sortState`, `extLst`),
146    /// preserved verbatim.
147    #[serde(skip)]
148    pub children: Vec<XmlFragment>,
149}
150
151/// Container for table column definitions.
152#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
153pub struct TableColumnsXml {
154    #[serde(rename = "@count")]
155    pub count: u32,
156
157    #[serde(rename = "tableColumn", default)]
158    pub columns: Vec<TableColumnXml>,
159}
160
161/// A single column within a table definition (`CT_TableColumn`).
162#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
163pub struct TableColumnXml {
164    #[serde(rename = "@id")]
165    pub id: u32,
166
167    #[serde(rename = "@uniqueName", default)]
168    pub unique_name: Option<String>,
169
170    #[serde(rename = "@name")]
171    pub name: String,
172
173    #[serde(rename = "@totalsRowFunction", default)]
174    pub totals_row_function: Option<String>,
175
176    #[serde(rename = "@totalsRowLabel", default)]
177    pub totals_row_label: Option<String>,
178
179    #[serde(rename = "@queryTableFieldId", default)]
180    pub query_table_field_id: Option<u32>,
181
182    #[serde(rename = "@headerRowDxfId", default)]
183    pub header_row_dxf_id: Option<u32>,
184
185    #[serde(rename = "@dataDxfId", default)]
186    pub data_dxf_id: Option<u32>,
187
188    #[serde(rename = "@totalsRowDxfId", default)]
189    pub totals_row_dxf_id: Option<u32>,
190
191    #[serde(rename = "@headerRowCellStyle", default)]
192    pub header_row_cell_style: Option<String>,
193
194    #[serde(rename = "@dataCellStyle", default)]
195    pub data_cell_style: Option<String>,
196
197    #[serde(rename = "@totalsRowCellStyle", default)]
198    pub totals_row_cell_style: Option<String>,
199
200    /// Prefixed attributes such as `xr3:uid`, with any namespace
201    /// declarations they need.
202    #[serde(skip)]
203    pub extra_attributes: Vec<(String, String)>,
204
205    #[serde(rename = "calculatedColumnFormula", default)]
206    pub calculated_column_formula: Option<TableFormula>,
207
208    #[serde(rename = "totalsRowFormula", default)]
209    pub totals_row_formula: Option<TableFormula>,
210
211    /// Opaque `xmlColumnPr` element, preserved verbatim.
212    #[serde(skip)]
213    pub xml_column_pr: Option<XmlFragment>,
214
215    /// Opaque `extLst` element, preserved verbatim.
216    #[serde(skip)]
217    pub ext_lst: Option<XmlFragment>,
218}
219
220/// A table column formula (`CT_TableFormula`).
221#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
222pub struct TableFormula {
223    #[serde(rename = "@array", default, skip_serializing_if = "Option::is_none")]
224    pub array: Option<bool>,
225
226    #[serde(rename = "$text", default)]
227    pub formula: String,
228}
229
230/// Style information for a table.
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
232pub struct TableStyleInfoXml {
233    #[serde(rename = "@name", skip_serializing_if = "Option::is_none")]
234    pub name: Option<String>,
235
236    #[serde(rename = "@showFirstColumn", skip_serializing_if = "Option::is_none")]
237    pub show_first_column: Option<bool>,
238
239    #[serde(rename = "@showLastColumn", skip_serializing_if = "Option::is_none")]
240    pub show_last_column: Option<bool>,
241
242    #[serde(rename = "@showRowStripes", skip_serializing_if = "Option::is_none")]
243    pub show_row_stripes: Option<bool>,
244
245    #[serde(rename = "@showColumnStripes", skip_serializing_if = "Option::is_none")]
246    pub show_column_stripes: Option<bool>,
247}
248
249/// A generic XML element preserved with its qualified names intact.
250///
251/// When serialized, the element name comes from the enclosing field or,
252/// for auto-filter children, from [`XmlFragment::name`].
253#[derive(Debug, Clone, PartialEq, Default)]
254pub struct XmlFragment {
255    pub name: String,
256    pub attributes: Vec<(String, String)>,
257    pub children: Vec<XmlFragmentChild>,
258}
259
260/// Content of an [`XmlFragment`].
261#[derive(Debug, Clone, PartialEq)]
262pub enum XmlFragmentChild {
263    Element(XmlFragment),
264    Text(String),
265}
266
267/// Original table part text and the parsed state it corresponds to.
268///
269/// Equality always holds so that it never affects `TableXml` comparisons.
270#[derive(Clone, Default)]
271pub struct TableSource(Option<Arc<(String, TableXml)>>);
272
273impl PartialEq for TableSource {
274    fn eq(&self, _other: &Self) -> bool {
275        true
276    }
277}
278
279impl std::fmt::Debug for TableSource {
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281        f.debug_tuple("TableSource")
282            .field(&self.0.as_ref().map(|s| s.0.len()))
283            .finish()
284    }
285}
286
287impl TableXml {
288    /// Return the original part text when the table has not been modified
289    /// since [`parse_table_xml`] produced it; `None` otherwise.
290    pub fn unchanged_source(&self) -> Option<&str> {
291        let snapshot = self.source.0.as_ref()?;
292        (self == &snapshot.1).then_some(snapshot.0.as_str())
293    }
294}
295
296impl Default for TableXml {
297    fn default() -> Self {
298        Self {
299            xmlns: namespaces::SPREADSHEET_ML.to_string(),
300            id: 1,
301            name: "Table1".to_string(),
302            display_name: "Table1".to_string(),
303            comment: None,
304            reference: "A1:A1".to_string(),
305            table_type: None,
306            header_row_count: None,
307            insert_row: None,
308            insert_row_shift: None,
309            totals_row_count: None,
310            totals_row_shown: None,
311            published: None,
312            header_row_dxf_id: None,
313            data_dxf_id: None,
314            totals_row_dxf_id: None,
315            header_row_border_dxf_id: None,
316            table_border_dxf_id: None,
317            totals_row_border_dxf_id: None,
318            header_row_cell_style: None,
319            data_cell_style: None,
320            totals_row_cell_style: None,
321            connection_id: None,
322            extra_attributes: Vec::new(),
323            auto_filter: None,
324            sort_state: None,
325            table_columns: TableColumnsXml {
326                count: 1,
327                columns: vec![TableColumnXml {
328                    id: 1,
329                    name: "Column1".to_string(),
330                    ..Default::default()
331                }],
332            },
333            table_style_info: None,
334            ext_lst: None,
335            source: TableSource::default(),
336        }
337    }
338}
339
340macro_rules! opt_field {
341    ($state:expr, $key:literal, $value:expr) => {
342        if let Some(value) = $value.as_ref() {
343            $state.serialize_field($key, value)?;
344        }
345    };
346}
347
348macro_rules! opt_entry {
349    ($state:expr, $key:literal, $value:expr) => {
350        if let Some(value) = $value.as_ref() {
351            $state.serialize_entry($key, value)?;
352        }
353    };
354}
355
356impl Serialize for TableXml {
357    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
358        let mut state = serializer.serialize_struct("table", 32)?;
359        state.serialize_field("@xmlns", &self.xmlns)?;
360        for (attr_name, key) in ROOT_EXTRA_ATTRIBUTES {
361            if let Some((_, value)) = self.extra_attributes.iter().find(|(n, _)| n == attr_name) {
362                state.serialize_field(key, value)?;
363            }
364        }
365        state.serialize_field("@id", &self.id)?;
366        state.serialize_field("@name", &self.name)?;
367        state.serialize_field("@displayName", &self.display_name)?;
368        opt_field!(state, "@comment", self.comment);
369        state.serialize_field("@ref", &self.reference)?;
370        opt_field!(state, "@tableType", self.table_type);
371        opt_field!(state, "@headerRowCount", self.header_row_count);
372        opt_field!(state, "@insertRow", self.insert_row);
373        opt_field!(state, "@insertRowShift", self.insert_row_shift);
374        opt_field!(state, "@totalsRowCount", self.totals_row_count);
375        opt_field!(state, "@totalsRowShown", self.totals_row_shown);
376        opt_field!(state, "@published", self.published);
377        opt_field!(state, "@headerRowDxfId", self.header_row_dxf_id);
378        opt_field!(state, "@dataDxfId", self.data_dxf_id);
379        opt_field!(state, "@totalsRowDxfId", self.totals_row_dxf_id);
380        opt_field!(
381            state,
382            "@headerRowBorderDxfId",
383            self.header_row_border_dxf_id
384        );
385        opt_field!(state, "@tableBorderDxfId", self.table_border_dxf_id);
386        opt_field!(
387            state,
388            "@totalsRowBorderDxfId",
389            self.totals_row_border_dxf_id
390        );
391        opt_field!(state, "@headerRowCellStyle", self.header_row_cell_style);
392        opt_field!(state, "@dataCellStyle", self.data_cell_style);
393        opt_field!(state, "@totalsRowCellStyle", self.totals_row_cell_style);
394        opt_field!(state, "@connectionId", self.connection_id);
395        opt_field!(state, "autoFilter", self.auto_filter);
396        opt_field!(state, "sortState", self.sort_state);
397        state.serialize_field("tableColumns", &self.table_columns)?;
398        opt_field!(state, "tableStyleInfo", self.table_style_info);
399        opt_field!(state, "extLst", self.ext_lst);
400        state.end()
401    }
402}
403
404impl Serialize for TableAutoFilter {
405    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
406        let mut map = serializer.serialize_map(None)?;
407        map.serialize_entry("@ref", &self.reference)?;
408        for child in &self.children {
409            map.serialize_entry(&child.name, child)?;
410        }
411        map.end()
412    }
413}
414
415impl Serialize for TableColumnXml {
416    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
417        let mut map = serializer.serialize_map(None)?;
418        map.serialize_entry("@id", &self.id)?;
419        for (name, value) in &self.extra_attributes {
420            map.serialize_entry(&format!("@{name}"), value)?;
421        }
422        opt_entry!(map, "@uniqueName", self.unique_name);
423        map.serialize_entry("@name", &self.name)?;
424        opt_entry!(map, "@totalsRowFunction", self.totals_row_function);
425        opt_entry!(map, "@totalsRowLabel", self.totals_row_label);
426        opt_entry!(map, "@queryTableFieldId", self.query_table_field_id);
427        opt_entry!(map, "@headerRowDxfId", self.header_row_dxf_id);
428        opt_entry!(map, "@dataDxfId", self.data_dxf_id);
429        opt_entry!(map, "@totalsRowDxfId", self.totals_row_dxf_id);
430        opt_entry!(map, "@headerRowCellStyle", self.header_row_cell_style);
431        opt_entry!(map, "@dataCellStyle", self.data_cell_style);
432        opt_entry!(map, "@totalsRowCellStyle", self.totals_row_cell_style);
433        opt_entry!(
434            map,
435            "calculatedColumnFormula",
436            self.calculated_column_formula
437        );
438        opt_entry!(map, "totalsRowFormula", self.totals_row_formula);
439        opt_entry!(map, "xmlColumnPr", self.xml_column_pr);
440        opt_entry!(map, "extLst", self.ext_lst);
441        map.end()
442    }
443}
444
445impl Serialize for XmlFragment {
446    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
447        let mut map = serializer.serialize_map(None)?;
448        for (name, value) in &self.attributes {
449            map.serialize_entry(&format!("@{name}"), value)?;
450        }
451        for child in &self.children {
452            match child {
453                XmlFragmentChild::Element(element) => {
454                    map.serialize_entry(&element.name, element)?
455                }
456                XmlFragmentChild::Text(text) => map.serialize_entry("$text", text)?,
457            }
458        }
459        map.end()
460    }
461}
462
463#[derive(Default)]
464struct ColumnExtras {
465    attributes: Vec<(String, String)>,
466    xml_column_pr: Option<XmlFragment>,
467    ext_lst: Option<XmlFragment>,
468}
469
470#[derive(Default)]
471struct TableExtras {
472    root_attributes: Vec<(String, String)>,
473    sort_state: Option<XmlFragment>,
474    ext_lst: Option<XmlFragment>,
475    auto_filter_children: Vec<XmlFragment>,
476    columns: Vec<ColumnExtras>,
477}
478
479fn local_name(name: &[u8]) -> &[u8] {
480    match name.iter().rposition(|b| *b == b':') {
481        Some(pos) => &name[pos + 1..],
482        None => name,
483    }
484}
485
486fn read_attributes(
487    start: &BytesStart<'_>,
488    prefixed_only: bool,
489) -> Result<Vec<(String, String)>, quick_xml::DeError> {
490    let mut attributes = Vec::new();
491    for attribute in start.attributes() {
492        let attribute = attribute?;
493        let key = String::from_utf8_lossy(attribute.key.as_ref()).into_owned();
494        if prefixed_only && !key.contains(':') {
495            continue;
496        }
497        attributes.push((key, attribute.unescape_value()?.into_owned()));
498    }
499    Ok(attributes)
500}
501
502/// Read a complete element starting at `start` into an [`XmlFragment`].
503fn capture_fragment(
504    reader: &mut Reader<&[u8]>,
505    start: &BytesStart<'_>,
506    empty: bool,
507) -> Result<XmlFragment, quick_xml::DeError> {
508    let mut fragment = XmlFragment {
509        name: String::from_utf8_lossy(start.name().as_ref()).into_owned(),
510        attributes: read_attributes(start, false)?,
511        children: Vec::new(),
512    };
513    if empty {
514        return Ok(fragment);
515    }
516    loop {
517        match reader.read_event()? {
518            Event::Start(child) => {
519                let child = child.into_owned();
520                let element = capture_fragment(reader, &child, false)?;
521                fragment.children.push(XmlFragmentChild::Element(element));
522            }
523            Event::Empty(child) => {
524                let element = capture_fragment(reader, &child, true)?;
525                fragment.children.push(XmlFragmentChild::Element(element));
526            }
527            Event::Text(text) => {
528                let text = text.unescape()?;
529                if !text.trim().is_empty() {
530                    fragment
531                        .children
532                        .push(XmlFragmentChild::Text(text.into_owned()));
533                }
534            }
535            Event::CData(data) => {
536                let text = String::from_utf8_lossy(&data.into_inner()).into_owned();
537                fragment.children.push(XmlFragmentChild::Text(text));
538            }
539            Event::End(_) => return Ok(fragment),
540            Event::Eof => {
541                return Err(quick_xml::DeError::UnexpectedEof);
542            }
543            _ => {}
544        }
545    }
546}
547
548fn collect_table_extras(xml: &str) -> Result<TableExtras, quick_xml::DeError> {
549    let mut reader = Reader::from_str(xml);
550    let mut extras = TableExtras::default();
551    let mut stack: Vec<Vec<u8>> = Vec::new();
552
553    loop {
554        let (start, empty) = match reader.read_event()? {
555            Event::Start(start) => (start.into_owned(), false),
556            Event::Empty(start) => (start.into_owned(), true),
557            Event::End(_) => {
558                stack.pop();
559                continue;
560            }
561            Event::Eof => break,
562            _ => continue,
563        };
564        let name = local_name(start.name().as_ref()).to_vec();
565        let parent: Vec<&[u8]> = stack.iter().map(Vec::as_slice).collect();
566        match (parent.as_slice(), name.as_slice()) {
567            ([], _) => {
568                extras.root_attributes = read_attributes(&start, true)?;
569            }
570            ([b"table"], b"sortState") => {
571                extras.sort_state = Some(capture_fragment(&mut reader, &start, empty)?);
572                continue;
573            }
574            ([b"table"], b"extLst") => {
575                extras.ext_lst = Some(capture_fragment(&mut reader, &start, empty)?);
576                continue;
577            }
578            ([b"table", b"autoFilter"], _) => {
579                let fragment = capture_fragment(&mut reader, &start, empty)?;
580                extras.auto_filter_children.push(fragment);
581                continue;
582            }
583            ([b"table", b"tableColumns"], b"tableColumn") => {
584                extras.columns.push(ColumnExtras {
585                    attributes: read_attributes(&start, true)?,
586                    ..Default::default()
587                });
588            }
589            ([b"table", b"tableColumns", b"tableColumn"], b"xmlColumnPr" | b"extLst") => {
590                let fragment = capture_fragment(&mut reader, &start, empty)?;
591                if let Some(column) = extras.columns.last_mut() {
592                    if name == b"xmlColumnPr" {
593                        column.xml_column_pr = Some(fragment);
594                    } else {
595                        column.ext_lst = Some(fragment);
596                    }
597                }
598                continue;
599            }
600            _ => {}
601        }
602        if !empty {
603            stack.push(name);
604        }
605    }
606    Ok(extras)
607}
608
609fn name_prefix(name: &str) -> Option<&str> {
610    name.split_once(':')
611        .map(|(prefix, _)| prefix)
612        .filter(|prefix| *prefix != "xmlns" && *prefix != "xml")
613}
614
615fn collect_fragment_prefixes(
616    fragment: &XmlFragment,
617    used: &mut BTreeSet<String>,
618    declared: &mut BTreeSet<String>,
619) {
620    if let Some(prefix) = name_prefix(&fragment.name) {
621        used.insert(prefix.to_string());
622    }
623    for (name, _) in &fragment.attributes {
624        if let Some(prefix) = name.strip_prefix("xmlns:") {
625            declared.insert(prefix.to_string());
626        } else if let Some(prefix) = name_prefix(name) {
627            used.insert(prefix.to_string());
628        }
629    }
630    for child in &fragment.children {
631        if let XmlFragmentChild::Element(element) = child {
632            collect_fragment_prefixes(element, used, declared);
633        }
634    }
635}
636
637/// Namespace declarations needed by `used` prefixes that are neither
638/// declared locally nor emitted on the table root.
639fn missing_declarations(
640    used: &BTreeSet<String>,
641    declared: &BTreeSet<String>,
642    root_namespaces: &BTreeMap<String, String>,
643    root_emitted: &BTreeSet<String>,
644) -> Vec<(String, String)> {
645    used.iter()
646        .filter(|prefix| !declared.contains(*prefix) && !root_emitted.contains(*prefix))
647        .filter_map(|prefix| {
648            root_namespaces
649                .get(prefix)
650                .map(|uri| (format!("xmlns:{prefix}"), uri.clone()))
651        })
652        .collect()
653}
654
655fn localize_fragment(
656    fragment: &mut XmlFragment,
657    root_namespaces: &BTreeMap<String, String>,
658    root_emitted: &BTreeSet<String>,
659) {
660    let mut used = BTreeSet::new();
661    let mut declared = BTreeSet::new();
662    collect_fragment_prefixes(fragment, &mut used, &mut declared);
663    let missing = missing_declarations(&used, &declared, root_namespaces, root_emitted);
664    fragment.attributes.extend(missing);
665}
666
667/// Keep allow-listed root attributes whose namespace prefixes are themselves
668/// preserved; returns the kept attributes and the prefixes they declare.
669fn filter_root_attributes(
670    attributes: &[(String, String)],
671) -> (Vec<(String, String)>, BTreeSet<String>) {
672    let allowed: Vec<&(String, String)> = attributes
673        .iter()
674        .filter(|(name, _)| ROOT_EXTRA_ATTRIBUTES.iter().any(|(n, _)| n == name))
675        .collect();
676    let declared: BTreeSet<String> = allowed
677        .iter()
678        .filter_map(|(name, _)| name.strip_prefix("xmlns:").map(str::to_string))
679        .collect();
680    let kept = allowed
681        .into_iter()
682        .filter(|(name, value)| {
683            if name.starts_with("xmlns:") {
684                return true;
685            }
686            let Some(prefix) = name_prefix(name) else {
687                return false;
688            };
689            if !declared.contains(prefix) {
690                return false;
691            }
692            name != "mc:Ignorable"
693                || value
694                    .split_whitespace()
695                    .all(|ignored| declared.contains(ignored))
696        })
697        .cloned()
698        .collect();
699    (kept, declared)
700}
701
702/// Parse a table part, preserving content that the serde schema does not
703/// model and recording the source text for verbatim write-back.
704pub fn parse_table_xml(xml: &str) -> Result<TableXml, quick_xml::DeError> {
705    let mut table: TableXml = quick_xml::de::from_str(xml)?;
706    let extras = collect_table_extras(xml)?;
707
708    let root_namespaces: BTreeMap<String, String> = extras
709        .root_attributes
710        .iter()
711        .filter_map(|(name, value)| {
712            name.strip_prefix("xmlns:")
713                .map(|prefix| (prefix.to_string(), value.clone()))
714        })
715        .collect();
716    let (root_kept, root_emitted) = filter_root_attributes(&extras.root_attributes);
717    table.extra_attributes = root_kept;
718
719    let localize = |fragment: Option<XmlFragment>| {
720        fragment.map(|mut fragment| {
721            localize_fragment(&mut fragment, &root_namespaces, &root_emitted);
722            fragment
723        })
724    };
725    table.sort_state = localize(extras.sort_state);
726    table.ext_lst = localize(extras.ext_lst);
727    if let Some(auto_filter) = table.auto_filter.as_mut() {
728        auto_filter.children = extras
729            .auto_filter_children
730            .into_iter()
731            .filter_map(|fragment| localize(Some(fragment)))
732            .collect();
733    }
734    for (column, column_extras) in table.table_columns.columns.iter_mut().zip(extras.columns) {
735        let used: BTreeSet<String> = column_extras
736            .attributes
737            .iter()
738            .filter_map(|(name, _)| name_prefix(name).map(str::to_string))
739            .collect();
740        let declared: BTreeSet<String> = column_extras
741            .attributes
742            .iter()
743            .filter_map(|(name, _)| name.strip_prefix("xmlns:").map(str::to_string))
744            .collect();
745        let mut attributes = column_extras.attributes;
746        attributes.extend(missing_declarations(
747            &used,
748            &declared,
749            &root_namespaces,
750            &root_emitted,
751        ));
752        column.extra_attributes = attributes;
753        column.xml_column_pr = localize(column_extras.xml_column_pr);
754        column.ext_lst = localize(column_extras.ext_lst);
755    }
756
757    let snapshot = table.clone();
758    table.source = TableSource(Some(Arc::new((xml.to_string(), snapshot))));
759    Ok(table)
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765
766    #[test]
767    fn test_table_xml_default() {
768        let table = TableXml::default();
769        assert_eq!(table.xmlns, namespaces::SPREADSHEET_ML);
770        assert_eq!(table.name, "Table1");
771        assert_eq!(table.display_name, "Table1");
772        assert_eq!(table.reference, "A1:A1");
773        assert_eq!(table.table_columns.count, 1);
774        assert_eq!(table.table_columns.columns.len(), 1);
775    }
776
777    #[test]
778    fn test_table_xml_serialize_roundtrip() {
779        let table = TableXml {
780            xmlns: namespaces::SPREADSHEET_ML.to_string(),
781            id: 1,
782            name: "SalesTable".to_string(),
783            display_name: "SalesTable".to_string(),
784            reference: "A1:D10".to_string(),
785            totals_row_count: None,
786            totals_row_shown: None,
787            header_row_count: None,
788            auto_filter: Some(TableAutoFilter {
789                reference: "A1:D10".to_string(),
790                ..Default::default()
791            }),
792            table_columns: TableColumnsXml {
793                count: 4,
794                columns: vec![
795                    TableColumnXml {
796                        id: 1,
797                        name: "Name".to_string(),
798                        totals_row_function: None,
799                        totals_row_label: None,
800                        ..Default::default()
801                    },
802                    TableColumnXml {
803                        id: 2,
804                        name: "Region".to_string(),
805                        totals_row_function: None,
806                        totals_row_label: None,
807                        ..Default::default()
808                    },
809                    TableColumnXml {
810                        id: 3,
811                        name: "Sales".to_string(),
812                        totals_row_function: None,
813                        totals_row_label: None,
814                        ..Default::default()
815                    },
816                    TableColumnXml {
817                        id: 4,
818                        name: "Profit".to_string(),
819                        totals_row_function: None,
820                        totals_row_label: None,
821                        ..Default::default()
822                    },
823                ],
824            },
825            table_style_info: Some(TableStyleInfoXml {
826                name: Some("TableStyleMedium2".to_string()),
827                show_first_column: Some(false),
828                show_last_column: Some(false),
829                show_row_stripes: Some(true),
830                show_column_stripes: Some(false),
831            }),
832            ..Default::default()
833        };
834
835        let xml = quick_xml::se::to_string(&table).unwrap();
836        assert!(xml.contains("SalesTable"));
837        assert!(xml.contains("A1:D10"));
838        assert!(xml.contains("autoFilter"));
839        assert!(xml.contains("TableStyleMedium2"));
840
841        let parsed: TableXml = quick_xml::de::from_str(&xml).unwrap();
842        assert_eq!(parsed.name, "SalesTable");
843        assert_eq!(parsed.display_name, "SalesTable");
844        assert_eq!(parsed.reference, "A1:D10");
845        assert_eq!(parsed.table_columns.count, 4);
846        assert_eq!(parsed.table_columns.columns.len(), 4);
847        assert_eq!(parsed.table_columns.columns[0].name, "Name");
848        assert!(parsed.auto_filter.is_some());
849        assert_eq!(parsed.auto_filter.unwrap().reference, "A1:D10");
850        let style = parsed.table_style_info.unwrap();
851        assert_eq!(style.name, Some("TableStyleMedium2".to_string()));
852        assert_eq!(style.show_row_stripes, Some(true));
853    }
854
855    #[test]
856    fn test_table_xml_without_optional_fields() {
857        let table = TableXml {
858            xmlns: namespaces::SPREADSHEET_ML.to_string(),
859            id: 2,
860            name: "Table2".to_string(),
861            display_name: "Table2".to_string(),
862            reference: "B1:C5".to_string(),
863            totals_row_count: None,
864            totals_row_shown: None,
865            header_row_count: None,
866            auto_filter: None,
867            table_columns: TableColumnsXml {
868                count: 2,
869                columns: vec![
870                    TableColumnXml {
871                        id: 1,
872                        name: "Col1".to_string(),
873                        totals_row_function: None,
874                        totals_row_label: None,
875                        ..Default::default()
876                    },
877                    TableColumnXml {
878                        id: 2,
879                        name: "Col2".to_string(),
880                        totals_row_function: None,
881                        totals_row_label: None,
882                        ..Default::default()
883                    },
884                ],
885            },
886            table_style_info: None,
887            ..Default::default()
888        };
889
890        let xml = quick_xml::se::to_string(&table).unwrap();
891        assert!(!xml.contains("autoFilter"));
892        assert!(!xml.contains("tableStyleInfo"));
893
894        let parsed: TableXml = quick_xml::de::from_str(&xml).unwrap();
895        assert_eq!(parsed.id, 2);
896        assert!(parsed.auto_filter.is_none());
897        assert!(parsed.table_style_info.is_none());
898    }
899
900    #[test]
901    fn test_table_xml_with_totals_row() {
902        let table = TableXml {
903            xmlns: namespaces::SPREADSHEET_ML.to_string(),
904            id: 3,
905            name: "Table3".to_string(),
906            display_name: "Table3".to_string(),
907            reference: "A1:B5".to_string(),
908            totals_row_count: Some(1),
909            totals_row_shown: Some(true),
910            header_row_count: None,
911            auto_filter: None,
912            table_columns: TableColumnsXml {
913                count: 2,
914                columns: vec![
915                    TableColumnXml {
916                        id: 1,
917                        name: "Label".to_string(),
918                        totals_row_function: None,
919                        totals_row_label: Some("Total".to_string()),
920                        ..Default::default()
921                    },
922                    TableColumnXml {
923                        id: 2,
924                        name: "Amount".to_string(),
925                        totals_row_function: Some("sum".to_string()),
926                        totals_row_label: None,
927                        ..Default::default()
928                    },
929                ],
930            },
931            table_style_info: None,
932            ..Default::default()
933        };
934
935        let xml = quick_xml::se::to_string(&table).unwrap();
936        assert!(xml.contains("totalsRowCount"));
937        assert!(xml.contains("totalsRowFunction"));
938        assert!(xml.contains("totalsRowLabel"));
939
940        let parsed: TableXml = quick_xml::de::from_str(&xml).unwrap();
941        assert_eq!(parsed.totals_row_count, Some(1));
942        assert_eq!(
943            parsed.table_columns.columns[0].totals_row_label,
944            Some("Total".to_string())
945        );
946        assert_eq!(
947            parsed.table_columns.columns[1].totals_row_function,
948            Some("sum".to_string())
949        );
950    }
951
952    #[test]
953    fn test_parse_real_excel_table_xml() {
954        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
955<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
956       id="1" name="Table1" displayName="Table1" ref="A1:C4">
957  <autoFilter ref="A1:C4"/>
958  <tableColumns count="3">
959    <tableColumn id="1" name="Name"/>
960    <tableColumn id="2" name="City"/>
961    <tableColumn id="3" name="Score"/>
962  </tableColumns>
963  <tableStyleInfo name="TableStyleMedium9" showFirstColumn="0" showLastColumn="0"
964                  showRowStripes="1" showColumnStripes="0"/>
965</table>"#;
966
967        let parsed: TableXml = quick_xml::de::from_str(xml).unwrap();
968        assert_eq!(parsed.id, 1);
969        assert_eq!(parsed.name, "Table1");
970        assert_eq!(parsed.display_name, "Table1");
971        assert_eq!(parsed.reference, "A1:C4");
972        assert!(parsed.auto_filter.is_some());
973        assert_eq!(parsed.auto_filter.unwrap().reference, "A1:C4");
974        assert_eq!(parsed.table_columns.count, 3);
975        assert_eq!(parsed.table_columns.columns[0].name, "Name");
976        assert_eq!(parsed.table_columns.columns[1].name, "City");
977        assert_eq!(parsed.table_columns.columns[2].name, "Score");
978        let style = parsed.table_style_info.unwrap();
979        assert_eq!(style.name, Some("TableStyleMedium9".to_string()));
980        assert_eq!(style.show_first_column, Some(false));
981        assert_eq!(style.show_row_stripes, Some(true));
982    }
983
984    const RICH_TABLE_XML: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
985<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="xr xr3" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:xr3="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" id="1" xr:uid="{00000000-0000-0000-0000-000000000001}" name="Calc" displayName="Calc" ref="A1:C4" totalsRowCount="1" dataDxfId="3" tableType="worksheet"><autoFilter ref="A1:C3"><filterColumn colId="0"><filters><filter val="a&amp;b"/></filters></filterColumn></autoFilter><sortState ref="A2:C3"><sortCondition descending="1" ref="B2:B3"/></sortState><tableColumns count="3"><tableColumn id="1" xr3:uid="{00000000-0000-0000-0000-000000000002}" name="Label" totalsRowLabel="Total" dataDxfId="2"/><tableColumn id="2" name="Value" totalsRowFunction="custom"><calculatedColumnFormula>1+1</calculatedColumnFormula><totalsRowFormula array="1">SUM(Calc[Value])&gt;0</totalsRowFormula></tableColumn><tableColumn id="3" uniqueName="u3" name="Map" queryTableFieldId="4"><xmlColumnPr mapId="1" xpath="/root/item" xmlDataType="string"/></tableColumn></tableColumns><tableStyleInfo name="TableStyleMedium2" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/><extLst><ext uri="{504A1905-F514-4f6f-8877-14C23A59335A}"><x14:table altText="Alt &lt;text&gt;"/></ext></extLst></table>"#;
986
987    #[test]
988    fn test_serde_preserves_column_formulas_and_attributes() {
989        let parsed: TableXml = quick_xml::de::from_str(RICH_TABLE_XML).unwrap();
990        let value = &parsed.table_columns.columns[1];
991        assert_eq!(
992            value.calculated_column_formula.as_ref().unwrap().formula,
993            "1+1"
994        );
995        let totals = value.totals_row_formula.as_ref().unwrap();
996        assert_eq!(totals.formula, "SUM(Calc[Value])>0");
997        assert_eq!(totals.array, Some(true));
998        assert_eq!(parsed.table_type.as_deref(), Some("worksheet"));
999        assert_eq!(parsed.data_dxf_id, Some(3));
1000        assert_eq!(parsed.table_columns.columns[0].data_dxf_id, Some(2));
1001        assert_eq!(
1002            parsed.table_columns.columns[2].query_table_field_id,
1003            Some(4)
1004        );
1005
1006        let xml = quick_xml::se::to_string(&parsed).unwrap();
1007        let reparsed: TableXml = quick_xml::de::from_str(&xml).unwrap();
1008        assert_eq!(reparsed, parsed);
1009    }
1010
1011    #[test]
1012    fn test_parse_table_xml_preserves_opaque_content_through_serialize() {
1013        let parsed = parse_table_xml(RICH_TABLE_XML).unwrap();
1014        assert_eq!(parsed.unchanged_source(), Some(RICH_TABLE_XML));
1015
1016        let xml = quick_xml::se::to_string(&parsed).unwrap();
1017        for needle in [
1018            r#"mc:Ignorable="xr xr3""#,
1019            r#"xr:uid="{00000000-0000-0000-0000-000000000001}""#,
1020            r#"xr3:uid="{00000000-0000-0000-0000-000000000002}""#,
1021            r#"<filter val="a&amp;b"/>"#,
1022            r#"<sortState ref="A2:C3"><sortCondition descending="1" ref="B2:B3"/></sortState>"#,
1023            "<calculatedColumnFormula>1+1</calculatedColumnFormula>",
1024            r#"<xmlColumnPr mapId="1" xpath="/root/item" xmlDataType="string"/>"#,
1025            r#"<x14:table altText="Alt &lt;text&gt;""#,
1026            r#"xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main""#,
1027        ] {
1028            assert!(xml.contains(needle), "missing {needle} in {xml}");
1029        }
1030
1031        let reparsed = parse_table_xml(&xml).unwrap();
1032        assert_eq!(reparsed.table_columns, parsed.table_columns);
1033        assert_eq!(reparsed.sort_state, parsed.sort_state);
1034        assert_eq!(reparsed.auto_filter, parsed.auto_filter);
1035        assert_eq!(
1036            reparsed.ext_lst.as_ref().unwrap().children,
1037            parsed.ext_lst.as_ref().unwrap().children
1038        );
1039    }
1040
1041    #[test]
1042    fn test_unchanged_source_cleared_by_mutation() {
1043        let mut parsed = parse_table_xml(RICH_TABLE_XML).unwrap();
1044        parsed.reference = "A1:C5".to_string();
1045        assert!(parsed.unchanged_source().is_none());
1046    }
1047
1048    #[test]
1049    fn test_root_ignorable_dropped_when_prefix_not_preserved() {
1050        let xml = r#"<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:zz="urn:zz" mc:Ignorable="zz" id="1" name="T" displayName="T" ref="A1:A2"><tableColumns count="1"><tableColumn id="1" zz:tag="x" name="A"/></tableColumns></table>"#;
1051        let parsed = parse_table_xml(xml).unwrap();
1052        let out = quick_xml::se::to_string(&parsed).unwrap();
1053        assert!(!out.contains("mc:Ignorable"));
1054        assert!(out.contains(r#"xmlns:zz="urn:zz""#), "{out}");
1055        assert!(out.contains(r#"zz:tag="x""#));
1056        quick_xml::de::from_str::<TableXml>(&out).unwrap();
1057    }
1058}