rusdox 1.0.0

Generate DOCX and PDF from YAML at Rust speed.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::paragraph::Paragraph;

/// A supported border style.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum BorderStyle {
    /// No visible border.
    None,
    /// A single line border.
    Single,
    /// A double line border.
    Double,
    /// A dotted border.
    Dotted,
    /// A dashed border.
    Dashed,
    /// Preserve or emit a custom OOXML border value.
    Custom(String),
}

impl BorderStyle {
    pub(crate) fn from_xml(value: &str) -> Self {
        match value {
            "nil" | "none" => Self::None,
            "single" => Self::Single,
            "double" => Self::Double,
            "dotted" => Self::Dotted,
            "dashed" => Self::Dashed,
            other => Self::Custom(other.to_string()),
        }
    }

    pub(crate) fn as_xml_value(&self) -> &str {
        match self {
            Self::None => "nil",
            Self::Single => "single",
            Self::Double => "double",
            Self::Dotted => "dotted",
            Self::Dashed => "dashed",
            Self::Custom(value) => value.as_str(),
        }
    }
}

/// A single table or cell border.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Border {
    /// The border style.
    pub style: BorderStyle,
    /// Optional line size in eighths of a point.
    pub size: Option<u16>,
    /// Optional hexadecimal RGB color value.
    pub color: Option<String>,
}

impl Border {
    /// Creates a border with the provided style.
    pub fn new(style: BorderStyle) -> Self {
        Self {
            style,
            size: None,
            color: None,
        }
    }

    /// Sets the border size.
    pub fn size(mut self, size: u16) -> Self {
        self.size = Some(size);
        self
    }

    /// Sets the border color.
    pub fn color(mut self, color: impl Into<String>) -> Self {
        self.color = Some(color.into());
        self
    }
}

/// Border collection for tables and table cells.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct TableBorders {
    /// Top border.
    pub top: Option<Border>,
    /// Bottom border.
    pub bottom: Option<Border>,
    /// Left border.
    pub left: Option<Border>,
    /// Right border.
    pub right: Option<Border>,
    /// Horizontal internal border.
    pub inside_horizontal: Option<Border>,
    /// Vertical internal border.
    pub inside_vertical: Option<Border>,
}

impl TableBorders {
    /// Creates an empty border set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the top border.
    pub fn top(mut self, border: Border) -> Self {
        self.top = Some(border);
        self
    }

    /// Sets the bottom border.
    pub fn bottom(mut self, border: Border) -> Self {
        self.bottom = Some(border);
        self
    }

    /// Sets the left border.
    pub fn left(mut self, border: Border) -> Self {
        self.left = Some(border);
        self
    }

    /// Sets the right border.
    pub fn right(mut self, border: Border) -> Self {
        self.right = Some(border);
        self
    }

    /// Sets the internal horizontal border.
    pub fn inside_horizontal(mut self, border: Border) -> Self {
        self.inside_horizontal = Some(border);
        self
    }

    /// Sets the internal vertical border.
    pub fn inside_vertical(mut self, border: Border) -> Self {
        self.inside_vertical = Some(border);
        self
    }

    pub(crate) fn has_serialized_content(&self) -> bool {
        self.top.is_some()
            || self.bottom.is_some()
            || self.left.is_some()
            || self.right.is_some()
            || self.inside_horizontal.is_some()
            || self.inside_vertical.is_some()
    }
}

/// Properties attached to a table.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TableProperties {
    /// Optional named table style id.
    pub style_id: Option<String>,
    /// Optional table width in DXA units.
    pub width: Option<u32>,
    /// Optional table borders.
    pub borders: Option<TableBorders>,
}

/// Properties attached to a table cell.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TableCellProperties {
    /// Optional cell width in DXA units.
    pub width: Option<u32>,
    /// Optional grid span.
    pub grid_span: Option<u32>,
    /// Optional cell borders.
    pub borders: Option<TableBorders>,
    /// Optional cell background color in hexadecimal RGB form.
    pub background_color: Option<String>,
}

/// A table cell containing one or more paragraphs.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TableCell {
    paragraphs: Vec<Paragraph>,
    nested_tables: Vec<Table>,
    properties: TableCellProperties,
}

impl TableCell {
    /// Creates an empty cell.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a paragraph using a builder-style API.
    pub fn add_paragraph(mut self, paragraph: Paragraph) -> Self {
        self.paragraphs.push(paragraph);
        self
    }

    /// Appends a paragraph in place.
    pub fn push_paragraph(&mut self, paragraph: Paragraph) -> &mut Self {
        self.paragraphs.push(paragraph);
        self
    }

    /// Returns immutable access to cell paragraphs.
    pub fn paragraphs(&self) -> std::slice::Iter<'_, Paragraph> {
        self.paragraphs.iter()
    }

    /// Returns mutable access to cell paragraphs.
    pub fn paragraphs_mut(&mut self) -> std::slice::IterMut<'_, Paragraph> {
        self.paragraphs.iter_mut()
    }

    /// Appends a nested table after the cell paragraphs.
    pub fn add_table(mut self, table: Table) -> Self {
        self.nested_tables.push(table);
        self
    }

    /// Returns nested tables in document order.
    pub fn nested_tables(&self) -> std::slice::Iter<'_, Table> {
        self.nested_tables.iter()
    }

    /// Sets the cell width in DXA units.
    pub fn width(mut self, width: u32) -> Self {
        self.properties.width = Some(width);
        self
    }

    /// Sets the cell grid span.
    pub fn grid_span(mut self, grid_span: u32) -> Self {
        self.properties.grid_span = Some(grid_span);
        self
    }

    /// Applies cell borders.
    pub fn borders(mut self, borders: TableBorders) -> Self {
        self.properties.borders = Some(borders);
        self
    }

    /// Applies a background color to the cell.
    pub fn background(mut self, color: impl Into<String>) -> Self {
        self.properties.background_color = Some(color.into());
        self
    }

    /// Returns the cell properties.
    pub fn properties(&self) -> &TableCellProperties {
        &self.properties
    }

    /// Returns mutable access to cell properties.
    pub fn properties_mut(&mut self) -> &mut TableCellProperties {
        &mut self.properties
    }

    /// Extracts plain text from all cell paragraphs.
    pub fn text(&self) -> String {
        let mut parts = self
            .paragraphs
            .iter()
            .map(Paragraph::text)
            .collect::<Vec<_>>();
        parts.extend(self.nested_tables.iter().map(Table::text));
        parts.join("\n")
    }

    pub(crate) fn from_parts(
        paragraphs: Vec<Paragraph>,
        nested_tables: Vec<Table>,
        properties: TableCellProperties,
    ) -> Self {
        Self {
            paragraphs,
            nested_tables,
            properties,
        }
    }
}

/// A row in a table.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableRowProperties {
    /// Whether the row should repeat as a header on subsequent pages.
    pub repeat_as_header: bool,
    /// Whether the row may split across pages.
    pub allow_split_across_pages: bool,
}

impl Default for TableRowProperties {
    fn default() -> Self {
        Self {
            repeat_as_header: false,
            allow_split_across_pages: true,
        }
    }
}

impl TableRowProperties {
    pub(crate) fn has_serialized_content(&self) -> bool {
        self.repeat_as_header || !self.allow_split_across_pages
    }
}

/// A row in a table.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TableRow {
    cells: Vec<TableCell>,
    properties: TableRowProperties,
}

impl TableRow {
    /// Creates an empty row.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a cell using a builder-style API.
    pub fn add_cell(mut self, cell: TableCell) -> Self {
        self.cells.push(cell);
        self
    }

    /// Appends a cell in place.
    pub fn push_cell(&mut self, cell: TableCell) -> &mut Self {
        self.cells.push(cell);
        self
    }

    /// Marks the row as a repeating header row.
    pub fn repeat_as_header(mut self) -> Self {
        self.properties.repeat_as_header = true;
        self
    }

    /// Controls whether the row may split across pages.
    pub fn allow_split_across_pages(mut self, allow: bool) -> Self {
        self.properties.allow_split_across_pages = allow;
        self
    }

    /// Returns immutable access to row cells.
    pub fn cells(&self) -> std::slice::Iter<'_, TableCell> {
        self.cells.iter()
    }

    /// Returns mutable access to row cells.
    pub fn cells_mut(&mut self) -> std::slice::IterMut<'_, TableCell> {
        self.cells.iter_mut()
    }

    /// Returns the row properties.
    pub fn properties(&self) -> &TableRowProperties {
        &self.properties
    }

    /// Returns mutable access to row properties.
    pub fn properties_mut(&mut self) -> &mut TableRowProperties {
        &mut self.properties
    }

    pub(crate) fn from_parts(cells: Vec<TableCell>, properties: TableRowProperties) -> Self {
        Self { cells, properties }
    }
}

/// A document table.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Table {
    rows: Vec<TableRow>,
    properties: TableProperties,
}

impl Table {
    /// Creates an empty table.
    ///
    /// ```rust
    /// use rusdox::Table;
    ///
    /// let table = Table::new();
    /// assert!(table.rows().next().is_none());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a row using a builder-style API.
    pub fn add_row(mut self, row: TableRow) -> Self {
        self.rows.push(row);
        self
    }

    /// Appends a row in place.
    pub fn push_row(&mut self, row: TableRow) -> &mut Self {
        self.rows.push(row);
        self
    }

    /// Sets the table width in DXA units.
    pub fn width(mut self, width: u32) -> Self {
        self.properties.width = Some(width);
        self
    }

    /// Applies table borders.
    pub fn borders(mut self, borders: TableBorders) -> Self {
        self.properties.borders = Some(borders);
        self
    }

    /// Applies a named table style.
    pub fn style(mut self, style_id: impl Into<String>) -> Self {
        self.properties.style_id = Some(style_id.into());
        self
    }

    /// Returns immutable access to rows.
    pub fn rows(&self) -> std::slice::Iter<'_, TableRow> {
        self.rows.iter()
    }

    /// Returns mutable access to rows.
    pub fn rows_mut(&mut self) -> std::slice::IterMut<'_, TableRow> {
        self.rows.iter_mut()
    }

    /// Returns the table properties.
    pub fn properties(&self) -> &TableProperties {
        &self.properties
    }

    /// Returns mutable access to table properties.
    pub fn properties_mut(&mut self) -> &mut TableProperties {
        &mut self.properties
    }

    /// Returns the referenced named table style id, if present.
    pub fn style_id(&self) -> Option<&str> {
        self.properties.style_id.as_deref()
    }

    /// Extracts plain text from the table.
    pub fn text(&self) -> String {
        self.rows
            .iter()
            .map(|row| {
                row.cells()
                    .map(TableCell::text)
                    .collect::<Vec<_>>()
                    .join("\t")
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    pub(crate) fn from_parts(rows: Vec<TableRow>, properties: TableProperties) -> Self {
        Self { rows, properties }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Border, BorderStyle, Table, TableBorders, TableCell, TableCellProperties, TableProperties,
        TableRow, TableRowProperties,
    };
    use crate::{Paragraph, Run};

    #[test]
    fn border_style_round_trips_known_values() {
        let cases = [
            ("nil", BorderStyle::None, "nil"),
            ("none", BorderStyle::None, "nil"),
            ("single", BorderStyle::Single, "single"),
            ("double", BorderStyle::Double, "double"),
            ("dotted", BorderStyle::Dotted, "dotted"),
            ("dashed", BorderStyle::Dashed, "dashed"),
        ];

        for (xml, expected, roundtrip_xml) in cases {
            let parsed = BorderStyle::from_xml(xml);
            assert_eq!(parsed, expected);
            assert_eq!(parsed.as_xml_value(), roundtrip_xml);
        }
    }

    #[test]
    fn border_style_custom_value_is_preserved() {
        let parsed = BorderStyle::from_xml("thickThinLargeGap");
        assert_eq!(parsed, BorderStyle::Custom("thickThinLargeGap".to_string()));
        assert_eq!(parsed.as_xml_value(), "thickThinLargeGap");
    }

    #[test]
    fn border_builder_sets_size_and_color() {
        let border = Border::new(BorderStyle::Single).size(16).color("AABBCC");
        assert_eq!(border.style, BorderStyle::Single);
        assert_eq!(border.size, Some(16));
        assert_eq!(border.color.as_deref(), Some("AABBCC"));
    }

    #[test]
    fn table_borders_builder_and_serialization_flag() {
        let empty = TableBorders::new();
        assert!(!empty.has_serialized_content());

        let border = Border::new(BorderStyle::Single).size(8).color("111111");
        let filled = TableBorders::new()
            .top(border.clone())
            .bottom(border.clone())
            .left(border.clone())
            .right(border.clone())
            .inside_horizontal(border.clone())
            .inside_vertical(border);
        assert!(filled.has_serialized_content());
        assert!(filled.top.is_some());
        assert!(filled.bottom.is_some());
        assert!(filled.left.is_some());
        assert!(filled.right.is_some());
        assert!(filled.inside_horizontal.is_some());
        assert!(filled.inside_vertical.is_some());
    }

    #[test]
    fn table_cell_builder_sets_all_properties_and_text() {
        let borders = TableBorders::new().top(Border::new(BorderStyle::Single));
        let mut cell = TableCell::new()
            .width(1234)
            .grid_span(2)
            .borders(borders.clone())
            .background("DDEEFF")
            .add_paragraph(Paragraph::new().add_run(Run::from_text("A")))
            .add_paragraph(Paragraph::new().add_run(Run::from_text("B")));

        cell.push_paragraph(Paragraph::new().add_run(Run::from_text("C")));
        cell.properties_mut().width = Some(5678);

        assert_eq!(cell.properties().width, Some(5678));
        assert_eq!(cell.properties().grid_span, Some(2));
        assert_eq!(cell.properties().borders.as_ref(), Some(&borders));
        assert_eq!(
            cell.properties().background_color.as_deref(),
            Some("DDEEFF")
        );
        assert_eq!(cell.text(), "A\nB\nC");
    }

    #[test]
    fn table_row_builder_and_cells_mut_allow_changes() {
        let mut row = TableRow::new()
            .repeat_as_header()
            .allow_split_across_pages(false)
            .add_cell(TableCell::new().add_paragraph(Paragraph::new().add_run(Run::from_text("L"))))
            .add_cell(
                TableCell::new().add_paragraph(Paragraph::new().add_run(Run::from_text("R"))),
            );

        row.push_cell(
            TableCell::new().add_paragraph(Paragraph::new().add_run(Run::from_text("X"))),
        );

        for cell in row.cells_mut() {
            if cell.text() == "R" {
                cell.push_paragraph(Paragraph::new().add_run(Run::from_text("2")));
            }
        }

        let texts: Vec<_> = row.cells().map(TableCell::text).collect();
        assert_eq!(
            texts,
            vec!["L".to_string(), "R\n2".to_string(), "X".to_string()]
        );
        assert!(row.properties().repeat_as_header);
        assert!(!row.properties().allow_split_across_pages);
    }

    #[test]
    fn table_builder_sets_properties_and_formats_text_grid() {
        let borders = TableBorders::new().top(Border::new(BorderStyle::Single));
        let mut table = Table::new().width(9360).borders(borders.clone()).add_row(
            TableRow::new()
                .add_cell(
                    TableCell::new().add_paragraph(Paragraph::new().add_run(Run::from_text("H1"))),
                )
                .add_cell(
                    TableCell::new().add_paragraph(Paragraph::new().add_run(Run::from_text("H2"))),
                ),
        );

        table.push_row(
            TableRow::new()
                .add_cell(
                    TableCell::new().add_paragraph(Paragraph::new().add_run(Run::from_text("V1"))),
                )
                .add_cell(
                    TableCell::new().add_paragraph(Paragraph::new().add_run(Run::from_text("V2"))),
                ),
        );
        table.properties_mut().width = Some(9000);

        assert_eq!(table.properties().width, Some(9000));
        assert_eq!(table.properties().borders.as_ref(), Some(&borders));
        assert_eq!(table.text(), "H1\tH2\nV1\tV2");
    }

    #[test]
    fn from_parts_builders_preserve_exact_state() {
        let cell_properties = TableCellProperties {
            width: Some(1000),
            grid_span: Some(3),
            borders: Some(TableBorders::new().left(Border::new(BorderStyle::Double))),
            background_color: Some("ABCDEF".to_string()),
        };
        let cell = TableCell::from_parts(
            vec![Paragraph::new().add_run(Run::from_text("value"))],
            Vec::new(),
            cell_properties.clone(),
        );
        assert_eq!(cell.properties(), &cell_properties);

        let row_properties = TableRowProperties {
            repeat_as_header: true,
            allow_split_across_pages: false,
        };
        let row = TableRow::from_parts(vec![cell.clone()], row_properties.clone());
        assert_eq!(row.cells().count(), 1);
        assert_eq!(row.cells().next(), Some(&cell));
        assert_eq!(row.properties(), &row_properties);

        let table_properties = TableProperties {
            style_id: None,
            width: Some(7777),
            borders: Some(TableBorders::new().right(Border::new(BorderStyle::Dashed))),
        };
        let table = Table::from_parts(vec![row], table_properties.clone());
        assert_eq!(table.properties(), &table_properties);
        assert_eq!(table.rows().count(), 1);
    }
}