rusdox 0.1.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
use serde::{Deserialize, Serialize};

use crate::run::Run;

const MAX_LIST_LEVEL: u8 = 8;
const DEFAULT_BULLET_LIST_ID: u32 = 1;
const DEFAULT_NUMBERED_LIST_ID: u32 = 2;

/// Paragraph alignment options.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ParagraphAlignment {
    /// Left aligned text.
    Left,
    /// Center aligned text.
    Center,
    /// Right aligned text.
    Right,
    /// Justified text.
    Justified,
    /// Preserve or emit a custom OOXML value.
    Custom(String),
}

impl ParagraphAlignment {
    pub(crate) fn from_xml(value: &str) -> Self {
        match value {
            "left" => Self::Left,
            "center" => Self::Center,
            "right" => Self::Right,
            "both" | "justify" => Self::Justified,
            other => Self::Custom(other.to_string()),
        }
    }

    pub(crate) fn as_xml_value(&self) -> &str {
        match self {
            Self::Left => "left",
            Self::Center => "center",
            Self::Right => "right",
            Self::Justified => "both",
            Self::Custom(value) => value.as_str(),
        }
    }
}

/// Semantic paragraph list kinds supported by the DOCX writer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ParagraphListKind {
    /// Bulleted list formatting.
    Bullet,
    /// Decimal numbered list formatting.
    Decimal,
}

impl ParagraphListKind {
    pub(crate) fn from_number_format(value: &str) -> Option<Self> {
        match value {
            "bullet" => Some(Self::Bullet),
            "decimal" => Some(Self::Decimal),
            _ => None,
        }
    }

    pub(crate) fn as_number_format(self) -> &'static str {
        match self {
            Self::Bullet => "bullet",
            Self::Decimal => "decimal",
        }
    }
}

/// Semantic DOCX numbering metadata for a paragraph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParagraphList {
    kind: ParagraphListKind,
    level: u8,
    id: u32,
}

impl ParagraphList {
    /// Creates a top-level bullet list item using the default shared list id.
    pub fn bullet() -> Self {
        Self::bullet_with_id(DEFAULT_BULLET_LIST_ID)
    }

    /// Creates a top-level bullet list item with an explicit list id.
    pub fn bullet_with_id(id: u32) -> Self {
        Self {
            kind: ParagraphListKind::Bullet,
            level: 0,
            id: sanitize_list_id(id),
        }
    }

    /// Creates a top-level decimal numbered list item using the default shared list id.
    pub fn numbered() -> Self {
        Self::numbered_with_id(DEFAULT_NUMBERED_LIST_ID)
    }

    /// Creates a top-level decimal numbered list item with an explicit list id.
    pub fn numbered_with_id(id: u32) -> Self {
        Self {
            kind: ParagraphListKind::Decimal,
            level: 0,
            id: sanitize_list_id(id),
        }
    }

    /// Returns the list kind.
    pub fn kind(&self) -> ParagraphListKind {
        self.kind
    }

    /// Returns the nesting level.
    pub fn level(&self) -> u8 {
        self.level
    }

    /// Returns the logical list id.
    pub fn id(&self) -> u32 {
        self.id
    }

    /// Sets the nesting level, clamped to the OOXML-supported range `0..=8`.
    pub fn with_level(mut self, level: u8) -> Self {
        self.level = level.min(MAX_LIST_LEVEL);
        self
    }

    pub(crate) fn from_parts(kind: ParagraphListKind, id: u32, level: u8) -> Self {
        Self {
            kind,
            level: level.min(MAX_LIST_LEVEL),
            id: sanitize_list_id(id),
        }
    }
}

fn sanitize_list_id(id: u32) -> u32 {
    id.max(1)
}

/// A block-level text container made up of one or more runs.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Paragraph {
    runs: Vec<Run>,
    style_id: Option<String>,
    list: Option<ParagraphList>,
    alignment: Option<ParagraphAlignment>,
    spacing_before: Option<u32>,
    spacing_after: Option<u32>,
    keep_next: bool,
    page_break_before: bool,
}

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

    /// Adds a run using a builder-style API.
    pub fn add_run(mut self, run: Run) -> Self {
        self.runs.push(run);
        self
    }

    /// Appends a run in place.
    pub fn push_run(&mut self, run: Run) -> &mut Self {
        self.runs.push(run);
        self
    }

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

    /// Returns mutable access to the paragraph runs.
    pub fn runs_mut(&mut self) -> std::slice::IterMut<'_, Run> {
        self.runs.iter_mut()
    }

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

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

    /// Sets the named paragraph style in place.
    pub fn set_style(&mut self, style_id: impl Into<String>) -> &mut Self {
        self.style_id = Some(style_id.into());
        self
    }

    /// Returns the semantic list metadata, if present.
    pub fn list(&self) -> Option<&ParagraphList> {
        self.list.as_ref()
    }

    /// Sets semantic list metadata in a builder-friendly way.
    pub fn with_list(mut self, list: ParagraphList) -> Self {
        self.list = Some(list);
        self
    }

    /// Sets semantic list metadata in place.
    pub fn set_list(&mut self, list: ParagraphList) -> &mut Self {
        self.list = Some(list);
        self
    }

    /// Removes semantic list metadata in place.
    pub fn clear_list(&mut self) -> &mut Self {
        self.list = None;
        self
    }

    /// Returns the paragraph alignment, if present.
    pub fn alignment(&self) -> Option<&ParagraphAlignment> {
        self.alignment.as_ref()
    }

    /// Sets paragraph alignment in a builder-friendly way.
    pub fn with_alignment(mut self, alignment: ParagraphAlignment) -> Self {
        self.alignment = Some(alignment);
        self
    }

    /// Sets paragraph alignment in place.
    pub fn set_alignment(&mut self, alignment: ParagraphAlignment) -> &mut Self {
        self.alignment = Some(alignment);
        self
    }

    /// Returns the concatenated plain text of all runs.
    pub fn text(&self) -> String {
        self.runs.iter().map(Run::text).collect()
    }

    /// Sets spacing before the paragraph in twips.
    pub fn spacing_before(mut self, twips: u32) -> Self {
        self.spacing_before = Some(twips);
        self
    }

    /// Sets spacing after the paragraph in twips.
    pub fn spacing_after(mut self, twips: u32) -> Self {
        self.spacing_after = Some(twips);
        self
    }

    /// Forces the paragraph to start on a new page.
    pub fn page_break_before(mut self) -> Self {
        self.page_break_before = true;
        self
    }

    /// Keeps the paragraph on the same page as the following block when possible.
    pub fn keep_next(mut self) -> Self {
        self.keep_next = true;
        self
    }

    /// Returns spacing before the paragraph, if present.
    pub fn spacing_before_value(&self) -> Option<u32> {
        self.spacing_before
    }

    /// Returns spacing after the paragraph, if present.
    pub fn spacing_after_value(&self) -> Option<u32> {
        self.spacing_after
    }

    /// Returns whether the paragraph starts on a new page.
    pub fn has_page_break_before(&self) -> bool {
        self.page_break_before
    }

    /// Returns whether the paragraph should stay with the following block.
    pub fn has_keep_next(&self) -> bool {
        self.keep_next
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn from_parts(
        runs: Vec<Run>,
        style_id: Option<String>,
        list: Option<ParagraphList>,
        alignment: Option<ParagraphAlignment>,
        spacing_before: Option<u32>,
        spacing_after: Option<u32>,
        keep_next: bool,
        page_break_before: bool,
    ) -> Self {
        Self {
            runs,
            style_id,
            list,
            alignment,
            spacing_before,
            spacing_after,
            keep_next,
            page_break_before,
        }
    }

    pub(crate) fn has_properties(&self) -> bool {
        self.list.is_some()
            || self.style_id.is_some()
            || self.alignment.is_some()
            || self.spacing_before.is_some()
            || self.spacing_after.is_some()
            || self.keep_next
            || self.page_break_before
    }
}

#[cfg(test)]
mod tests {
    use super::{Paragraph, ParagraphAlignment, ParagraphList, ParagraphListKind};
    use crate::Run;

    #[test]
    fn alignment_round_trips_known_values() {
        let cases = [
            ("left", ParagraphAlignment::Left, "left"),
            ("center", ParagraphAlignment::Center, "center"),
            ("right", ParagraphAlignment::Right, "right"),
            ("both", ParagraphAlignment::Justified, "both"),
            ("justify", ParagraphAlignment::Justified, "both"),
        ];

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

    #[test]
    fn alignment_custom_value_is_preserved() {
        let parsed = ParagraphAlignment::from_xml("distribute");
        assert_eq!(parsed, ParagraphAlignment::Custom("distribute".to_string()));
        assert_eq!(parsed.as_xml_value(), "distribute");
    }

    #[test]
    fn add_and_push_run_preserve_order() {
        let mut paragraph = Paragraph::new().add_run(Run::from_text("A"));
        paragraph.push_run(Run::from_text("B"));
        paragraph.push_run(Run::from_text("C"));

        let texts: Vec<_> = paragraph.runs().map(Run::text).collect();
        assert_eq!(texts, vec!["A", "B", "C"]);
        assert_eq!(paragraph.text(), "ABC");
    }

    #[test]
    fn runs_mut_allows_in_place_run_updates() {
        let mut paragraph = Paragraph::new()
            .add_run(Run::from_text("Hello"))
            .add_run(Run::from_text("World"));

        for run in paragraph.runs_mut() {
            if run.text() == "World" {
                run.set_text("RusDox");
            }
        }

        assert_eq!(paragraph.text(), "HelloRusDox");
    }

    #[test]
    fn builder_sets_spacing_alignment_and_page_break() {
        let paragraph = Paragraph::new()
            .with_list(ParagraphList::bullet().with_level(2))
            .with_alignment(ParagraphAlignment::Center)
            .spacing_before(120)
            .spacing_after(240)
            .keep_next()
            .page_break_before()
            .add_run(Run::from_text("x"));

        assert_eq!(
            paragraph.list(),
            Some(&ParagraphList::bullet().with_level(2))
        );
        assert_eq!(paragraph.alignment(), Some(&ParagraphAlignment::Center));
        assert_eq!(paragraph.spacing_before_value(), Some(120));
        assert_eq!(paragraph.spacing_after_value(), Some(240));
        assert!(paragraph.has_keep_next());
        assert!(paragraph.has_page_break_before());
    }

    #[test]
    fn set_alignment_overwrites_existing_alignment() {
        let mut paragraph = Paragraph::new().with_alignment(ParagraphAlignment::Left);
        paragraph.set_alignment(ParagraphAlignment::Right);
        assert_eq!(paragraph.alignment(), Some(&ParagraphAlignment::Right));
    }

    #[test]
    fn has_properties_detects_any_non_default_property() {
        assert!(!Paragraph::new().has_properties());
        assert!(Paragraph::new()
            .with_list(ParagraphList::bullet())
            .has_properties());
        assert!(Paragraph::new()
            .with_alignment(ParagraphAlignment::Center)
            .has_properties());
        assert!(Paragraph::new().spacing_before(100).has_properties());
        assert!(Paragraph::new().spacing_after(100).has_properties());
        assert!(Paragraph::new().keep_next().has_properties());
        assert!(Paragraph::new().page_break_before().has_properties());
    }

    #[test]
    fn from_parts_constructs_full_paragraph_state() {
        let runs = vec![Run::from_text("one"), Run::from_text("two")];
        let paragraph = Paragraph::from_parts(
            runs,
            None,
            Some(ParagraphList::numbered_with_id(9).with_level(1)),
            Some(ParagraphAlignment::Justified),
            Some(160),
            Some(180),
            true,
            true,
        );

        assert_eq!(paragraph.text(), "onetwo");
        assert_eq!(
            paragraph.list(),
            Some(&ParagraphList::numbered_with_id(9).with_level(1))
        );
        assert_eq!(paragraph.alignment(), Some(&ParagraphAlignment::Justified));
        assert_eq!(paragraph.spacing_before_value(), Some(160));
        assert_eq!(paragraph.spacing_after_value(), Some(180));
        assert!(paragraph.has_keep_next());
        assert!(paragraph.has_page_break_before());
    }

    #[test]
    fn list_builders_clamp_invalid_ids_and_levels() {
        let bullet = ParagraphList::bullet_with_id(0).with_level(99);
        let numbered = ParagraphList::numbered_with_id(7).with_level(3);

        assert_eq!(bullet.kind(), ParagraphListKind::Bullet);
        assert_eq!(bullet.id(), 1);
        assert_eq!(bullet.level(), 8);
        assert_eq!(numbered.kind(), ParagraphListKind::Decimal);
        assert_eq!(numbered.id(), 7);
        assert_eq!(numbered.level(), 3);
    }

    #[test]
    fn clear_list_removes_semantic_numbering() {
        let mut paragraph = Paragraph::new().with_list(ParagraphList::bullet());
        assert!(paragraph.list().is_some());
        paragraph.clear_list();
        assert!(paragraph.list().is_none());
    }
}