Skip to main content

sheetkit_xml/
relationships.rs

1//! Relationships XML schema structures.
2//!
3//! Used in `_rels/.rels`, `xl/_rels/workbook.xml.rels`, and other relationship files.
4
5use serde::{Deserialize, Serialize};
6
7use crate::namespaces;
8
9/// Relationships root element.
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11#[serde(rename = "Relationships")]
12pub struct Relationships {
13    #[serde(rename = "@xmlns", default = "default_package_relationships_ns")]
14    pub xmlns: String,
15
16    #[serde(rename = "Relationship", default)]
17    pub relationships: Vec<Relationship>,
18}
19
20/// Individual relationship entry.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct Relationship {
23    #[serde(rename = "@Id")]
24    pub id: String,
25
26    #[serde(rename = "@Type")]
27    pub rel_type: String,
28
29    #[serde(rename = "@Target")]
30    pub target: String,
31
32    #[serde(rename = "@TargetMode", skip_serializing_if = "Option::is_none")]
33    pub target_mode: Option<String>,
34}
35
36/// Creates the package-level relationships (`_rels/.rels`).
37///
38/// Contains relationships from the package root to the workbook, core
39/// properties, and extended properties parts.
40pub fn package_rels() -> Relationships {
41    Relationships {
42        xmlns: namespaces::PACKAGE_RELATIONSHIPS.to_string(),
43        relationships: vec![
44            Relationship {
45                id: "rId1".to_string(),
46                rel_type: rel_types::OFFICE_DOCUMENT.to_string(),
47                target: "xl/workbook.xml".to_string(),
48                target_mode: None,
49            },
50            Relationship {
51                id: "rId2".to_string(),
52                rel_type: rel_types::CORE_PROPERTIES.to_string(),
53                target: "docProps/core.xml".to_string(),
54                target_mode: None,
55            },
56            Relationship {
57                id: "rId3".to_string(),
58                rel_type: rel_types::EXTENDED_PROPERTIES.to_string(),
59                target: "docProps/app.xml".to_string(),
60                target_mode: None,
61            },
62        ],
63    }
64}
65
66/// Creates the workbook-level relationships (`xl/_rels/workbook.xml.rels`).
67///
68/// Contains relationships to worksheets, styles, and shared strings.
69pub fn workbook_rels() -> Relationships {
70    Relationships {
71        xmlns: namespaces::PACKAGE_RELATIONSHIPS.to_string(),
72        relationships: vec![
73            Relationship {
74                id: "rId1".to_string(),
75                rel_type: rel_types::WORKSHEET.to_string(),
76                target: "worksheets/sheet1.xml".to_string(),
77                target_mode: None,
78            },
79            Relationship {
80                id: "rId2".to_string(),
81                rel_type: rel_types::STYLES.to_string(),
82                target: "styles.xml".to_string(),
83                target_mode: None,
84            },
85            Relationship {
86                id: "rId3".to_string(),
87                rel_type: rel_types::SHARED_STRINGS.to_string(),
88                target: "sharedStrings.xml".to_string(),
89                target_mode: None,
90            },
91        ],
92    }
93}
94
95/// Relationship type URI constants.
96pub mod rel_types {
97    // Package level
98    pub const OFFICE_DOCUMENT: &str =
99        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
100    pub const CORE_PROPERTIES: &str =
101        "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
102    pub const EXTENDED_PROPERTIES: &str =
103        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
104
105    // Workbook level
106    pub const WORKSHEET: &str =
107        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet";
108    pub const SHARED_STRINGS: &str =
109        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
110    pub const STYLES: &str =
111        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
112    pub const THEME: &str =
113        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
114    pub const CHARTSHEET: &str =
115        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet";
116    pub const CALC_CHAIN: &str =
117        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/calcChain";
118    pub const EXTERNAL_LINK: &str =
119        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink";
120    pub const PIVOT_CACHE_DEF: &str =
121        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition";
122    pub const PIVOT_TABLE: &str =
123        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable";
124    pub const PIVOT_CACHE_RECORDS: &str =
125        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheRecords";
126
127    // Worksheet level
128    pub const COMMENTS: &str =
129        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
130    pub const DRAWING: &str =
131        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing";
132    pub const TABLE: &str =
133        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/table";
134    pub const HYPERLINK: &str =
135        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
136    pub const PRINTER_SETTINGS: &str =
137        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings";
138
139    pub const VML_DRAWING: &str =
140        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing";
141    pub const CONTROL_PROPERTIES: &str =
142        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp";
143
144    // Drawing level
145    pub const CHART: &str =
146        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";
147    pub const IMAGE: &str =
148        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
149
150    // Custom properties
151    pub const CUSTOM_PROPERTIES: &str =
152        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties";
153
154    // Slicers
155    pub const SLICER: &str = "http://schemas.microsoft.com/office/2007/relationships/slicer";
156    pub const SLICER_CACHE: &str =
157        "http://schemas.microsoft.com/office/2007/relationships/slicerCache";
158}
159
160fn default_package_relationships_ns() -> String {
161    crate::namespaces::PACKAGE_RELATIONSHIPS.to_string()
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn test_package_rels_factory() {
170        let rels = package_rels();
171        assert_eq!(rels.xmlns, namespaces::PACKAGE_RELATIONSHIPS);
172        assert_eq!(rels.relationships.len(), 3);
173
174        // Office document relationship
175        assert_eq!(rels.relationships[0].id, "rId1");
176        assert_eq!(rels.relationships[0].rel_type, rel_types::OFFICE_DOCUMENT);
177        assert_eq!(rels.relationships[0].target, "xl/workbook.xml");
178        assert!(rels.relationships[0].target_mode.is_none());
179
180        // Core properties relationship
181        assert_eq!(rels.relationships[1].id, "rId2");
182        assert_eq!(rels.relationships[1].rel_type, rel_types::CORE_PROPERTIES);
183        assert_eq!(rels.relationships[1].target, "docProps/core.xml");
184
185        // Extended properties relationship
186        assert_eq!(rels.relationships[2].id, "rId3");
187        assert_eq!(
188            rels.relationships[2].rel_type,
189            rel_types::EXTENDED_PROPERTIES
190        );
191        assert_eq!(rels.relationships[2].target, "docProps/app.xml");
192    }
193
194    #[test]
195    fn test_workbook_rels_factory() {
196        let rels = workbook_rels();
197        assert_eq!(rels.xmlns, namespaces::PACKAGE_RELATIONSHIPS);
198        assert_eq!(rels.relationships.len(), 3);
199
200        // Verify worksheet relationship
201        assert_eq!(rels.relationships[0].id, "rId1");
202        assert_eq!(rels.relationships[0].rel_type, rel_types::WORKSHEET);
203        assert_eq!(rels.relationships[0].target, "worksheets/sheet1.xml");
204
205        // Verify styles relationship
206        assert_eq!(rels.relationships[1].id, "rId2");
207        assert_eq!(rels.relationships[1].rel_type, rel_types::STYLES);
208        assert_eq!(rels.relationships[1].target, "styles.xml");
209
210        // Verify shared strings relationship
211        assert_eq!(rels.relationships[2].id, "rId3");
212        assert_eq!(rels.relationships[2].rel_type, rel_types::SHARED_STRINGS);
213        assert_eq!(rels.relationships[2].target, "sharedStrings.xml");
214    }
215
216    #[test]
217    fn test_relationships_roundtrip() {
218        let rels = package_rels();
219        let xml = quick_xml::se::to_string(&rels).unwrap();
220        let parsed: Relationships = quick_xml::de::from_str(&xml).unwrap();
221        assert_eq!(rels.xmlns, parsed.xmlns);
222        assert_eq!(rels.relationships.len(), parsed.relationships.len());
223        assert_eq!(rels.relationships[0].id, parsed.relationships[0].id);
224        assert_eq!(
225            rels.relationships[0].rel_type,
226            parsed.relationships[0].rel_type
227        );
228        assert_eq!(rels.relationships[0].target, parsed.relationships[0].target);
229    }
230
231    #[test]
232    fn test_workbook_rels_roundtrip() {
233        let rels = workbook_rels();
234        let xml = quick_xml::se::to_string(&rels).unwrap();
235        let parsed: Relationships = quick_xml::de::from_str(&xml).unwrap();
236        assert_eq!(rels.relationships.len(), parsed.relationships.len());
237        for (orig, parsed) in rels.relationships.iter().zip(parsed.relationships.iter()) {
238            assert_eq!(orig.id, parsed.id);
239            assert_eq!(orig.rel_type, parsed.rel_type);
240            assert_eq!(orig.target, parsed.target);
241        }
242    }
243
244    #[test]
245    fn test_relationship_with_target_mode() {
246        let rel = Relationship {
247            id: "rId1".to_string(),
248            rel_type: rel_types::HYPERLINK.to_string(),
249            target: "https://example.com".to_string(),
250            target_mode: Some("External".to_string()),
251        };
252        let xml = quick_xml::se::to_string(&rel).unwrap();
253        assert!(xml.contains("TargetMode=\"External\""));
254
255        let parsed: Relationship = quick_xml::de::from_str(&xml).unwrap();
256        assert_eq!(parsed.target_mode, Some("External".to_string()));
257    }
258
259    #[test]
260    fn test_relationship_without_target_mode_omits_attr() {
261        let rel = Relationship {
262            id: "rId1".to_string(),
263            rel_type: rel_types::WORKSHEET.to_string(),
264            target: "worksheets/sheet1.xml".to_string(),
265            target_mode: None,
266        };
267        let xml = quick_xml::se::to_string(&rel).unwrap();
268        assert!(!xml.contains("TargetMode"));
269    }
270
271    #[test]
272    fn test_parse_real_excel_rels() {
273        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
274<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
275  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
276</Relationships>"#;
277
278        let parsed: Relationships = quick_xml::de::from_str(xml).unwrap();
279        assert_eq!(parsed.xmlns, namespaces::PACKAGE_RELATIONSHIPS);
280        assert_eq!(parsed.relationships.len(), 1);
281        assert_eq!(parsed.relationships[0].id, "rId1");
282        assert_eq!(parsed.relationships[0].target, "xl/workbook.xml");
283    }
284
285    #[test]
286    fn test_parse_real_excel_workbook_rels() {
287        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
288<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
289  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
290  <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
291  <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>
292</Relationships>"#;
293
294        let parsed: Relationships = quick_xml::de::from_str(xml).unwrap();
295        assert_eq!(parsed.relationships.len(), 3);
296        assert_eq!(parsed.relationships[0].rel_type, rel_types::WORKSHEET);
297        assert_eq!(parsed.relationships[1].rel_type, rel_types::STYLES);
298        assert_eq!(parsed.relationships[2].rel_type, rel_types::SHARED_STRINGS);
299    }
300
301    #[test]
302    fn test_serialize_structure() {
303        let rels = package_rels();
304        let xml = quick_xml::se::to_string(&rels).unwrap();
305        assert!(xml.contains("<Relationships"));
306        assert!(xml.contains("<Relationship"));
307        assert!(xml.contains("Id="));
308        assert!(xml.contains("Type="));
309        assert!(xml.contains("Target="));
310    }
311
312    #[test]
313    fn test_empty_relationships() {
314        let rels = Relationships {
315            xmlns: namespaces::PACKAGE_RELATIONSHIPS.to_string(),
316            relationships: vec![],
317        };
318        let xml = quick_xml::se::to_string(&rels).unwrap();
319        let parsed: Relationships = quick_xml::de::from_str(&xml).unwrap();
320        assert!(parsed.relationships.is_empty());
321    }
322}