easydoc 0.1.0

A Rust library for easy DOC/DOCX document operations — read, write, template fill, Markdown conversion, and streaming event processing
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
//! Integration tests for the new `EasyDoc` facade methods:
//! - `read_events` (SAX streaming read)
//! - `view_as` (`ViewMode` rendering)

use easydoc::prelude::*;
use easydoc::{ContentCollector, EasyDoc, ViewMode};
use tempfile::TempDir;

// ============================================================================
// Helper: build a small DOCX with heading + paragraph + table
// ============================================================================

/// Helper struct for table writing in tests.
#[derive(Debug, Clone)]
struct Item {
    name: String,
    qty: String,
}

impl DocxRow for Item {
    fn schema() -> &'static [easydoc::TableColumn] {
        static SCHEMA: std::sync::LazyLock<Vec<easydoc::TableColumn>> =
            std::sync::LazyLock::new(|| {
                vec![
                    easydoc::TableColumn::new("Name", "name", 0),
                    easydoc::TableColumn::new("Qty", "qty", 1),
                ]
            });
        &SCHEMA
    }
    fn from_row(_row: &easydoc::RowData) -> easydoc::Result<Self> {
        unimplemented!("not needed for write test")
    }
    fn from_row_with_converters(
        _row: &easydoc::RowData,
        _registry: &easydoc::ConverterRegistry,
    ) -> easydoc::Result<Self> {
        unimplemented!("not needed for write test")
    }
    fn to_row(&self) -> easydoc::Result<Vec<easydoc::CellData>> {
        Ok(vec![
            easydoc::CellData::new(self.name.clone()),
            easydoc::CellData::new(self.qty.clone()),
        ])
    }
    fn to_row_with_converters(
        &self,
        _registry: &easydoc::ConverterRegistry,
    ) -> easydoc::Result<Vec<easydoc::CellData>> {
        self.to_row()
    }
}

fn build_test_docx(dir: &std::path::Path) -> std::path::PathBuf {
    let path = dir.join("test_facade.docx");

    let items = vec![
        Item {
            name: "Widget".into(),
            qty: "10".into(),
        },
        Item {
            name: "Gadget".into(),
            qty: "5".into(),
        },
    ];

    EasyDoc::document(&path)
        .add_heading("Test Document", HeadingLevel::H1)
        .add_paragraph(Paragraph::new().add_text("This is a test paragraph."))
        .add_heading("Details", HeadingLevel::H2)
        .add_paragraph(Paragraph::new().add_text("Another paragraph with details."))
        .add_table(easydoc::Table::from_data(&items))
        .save()
        .expect("save should succeed");

    path
}

// ============================================================================
// Test: read_events via SAX streaming
// ============================================================================

#[test]
fn test_read_events_heading_paragraph_table() {
    let dir = TempDir::new().expect("tempdir");
    let path = build_test_docx(dir.path());

    let mut collector = ContentCollector::new();
    EasyDoc::read_events(&path, &mut collector).expect("read_events should succeed");
    let content = collector.into_content();

    // Should have: H1 heading, paragraph, H2 heading, paragraph, table
    assert!(
        content.blocks.len() >= 4,
        "expected at least 4 blocks, got {}",
        content.blocks.len()
    );

    // First block: H1 heading
    match &content.blocks[0] {
        DocumentBlock::Heading { level, runs } => {
            assert_eq!(*level, 1, "first heading should be level 1");
            let text: String = runs.iter().map(|r| r.text.as_str()).collect();
            assert!(
                text.contains("Test Document"),
                "heading text should contain 'Test Document', got: {text}"
            );
        }
        other => panic!("expected Heading as first block, got: {other:?}"),
    }

    // Second block: paragraph
    match &content.blocks[1] {
        DocumentBlock::Paragraph(runs) => {
            let text: String = runs.iter().map(|r| r.text.as_str()).collect();
            assert!(
                text.contains("test paragraph"),
                "paragraph text should contain 'test paragraph', got: {text}"
            );
        }
        other => panic!("expected Paragraph as second block, got: {other:?}"),
    }

    // Third block: H2 heading
    match &content.blocks[2] {
        DocumentBlock::Heading { level, runs } => {
            assert_eq!(*level, 2, "second heading should be level 2");
            let text: String = runs.iter().map(|r| r.text.as_str()).collect();
            assert!(
                text.contains("Details"),
                "heading text should contain 'Details', got: {text}"
            );
        }
        other => panic!("expected Heading as third block, got: {other:?}"),
    }

    // Find the table block
    let table_block = content
        .blocks
        .iter()
        .find(|b| matches!(b, DocumentBlock::Table(_)));
    assert!(table_block.is_some(), "should contain a Table block");

    if let Some(DocumentBlock::Table(table)) = table_block {
        assert!(
            table.rows.len() >= 2,
            "table should have at least 2 rows, got {}",
            table.rows.len()
        );
    }
}

#[test]
fn test_read_events_nonexistent_file() {
    let result = EasyDoc::read_events(
        "/nonexistent/path/to/file.docx",
        &mut ContentCollector::new(),
    );
    assert!(result.is_err(), "should fail for nonexistent file");
}

// ============================================================================
// Test: view_as with ViewMode::Plain
// ============================================================================

#[test]
fn test_view_as_plain() {
    let dir = TempDir::new().expect("tempdir");
    let path = build_test_docx(dir.path());

    let text = EasyDoc::view_as(&path, &ViewMode::Plain).expect("view_as Plain should succeed");

    assert!(
        text.contains("Test Document"),
        "plain view should contain heading text: {text}"
    );
    assert!(
        text.contains("test paragraph"),
        "plain view should contain paragraph text: {text}"
    );
    // Plain mode should NOT contain annotation markers
    assert!(
        !text.contains("[段落"),
        "plain view should not contain annotation markers: {text}"
    );
}

// ============================================================================
// Test: view_as with ViewMode::Annotated
// ============================================================================

#[test]
fn test_view_as_annotated() {
    let dir = TempDir::new().expect("tempdir");
    let path = build_test_docx(dir.path());

    let text =
        EasyDoc::view_as(&path, &ViewMode::Annotated).expect("view_as Annotated should succeed");

    assert!(
        text.contains("[标题1]") || text.contains("[标题 1]"),
        "annotated view should contain heading annotation: {text}"
    );
    assert!(
        text.contains("[段落") || text.contains("[表格"),
        "annotated view should contain structural annotations: {text}"
    );
}

// ============================================================================
// Test: view_as with ViewMode::Outline
// ============================================================================

#[test]
fn test_view_as_outline() {
    let dir = TempDir::new().expect("tempdir");
    let path = build_test_docx(dir.path());

    let text = EasyDoc::view_as(&path, &ViewMode::Outline { max_level: 3 })
        .expect("view_as Outline should succeed");

    // Outline should contain headings with Markdown-style # markers
    assert!(
        text.contains("# Test Document") || text.contains('#'),
        "outline view should contain heading markers: {text}"
    );
    // Outline should NOT contain paragraph text
    assert!(
        !text.contains("test paragraph"),
        "outline view should not contain paragraph body text: {text}"
    );
}

// ============================================================================
// Test: view_as with ViewMode::Stats
// ============================================================================

#[test]
fn test_view_as_stats() {
    let dir = TempDir::new().expect("tempdir");
    let path = build_test_docx(dir.path());

    let text = EasyDoc::view_as(&path, &ViewMode::Stats).expect("view_as Stats should succeed");

    // Stats mode should contain count information
    assert!(
        text.contains("段落数") || text.contains("段落"),
        "stats view should contain paragraph count: {text}"
    );
    assert!(
        text.contains("标题") || text.contains("heading"),
        "stats view should contain heading count: {text}"
    );
}

// ============================================================================
// Test: roundtrip — write → read_events → view_as
// ============================================================================

#[test]
fn test_end_to_end_write_read_events_view() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("e2e.docx");

    // 1. Write a document
    EasyDoc::document(&path)
        .add_heading("Chapter 1", HeadingLevel::H1)
        .add_paragraph(Paragraph::new().add_text("Introduction text."))
        .add_heading("Section 1.1", HeadingLevel::H2)
        .add_paragraph(
            Paragraph::new()
                .add_text("Body with ")
                .add_run(easydoc::Run::new("bold").bold()),
        )
        .save()
        .expect("write should succeed");

    // 2. Read via SAX streaming
    let mut collector = ContentCollector::new();
    EasyDoc::read_events(&path, &mut collector).expect("read_events should succeed");
    let content = collector.into_content();

    assert!(
        content.blocks.len() >= 3,
        "should have at least 3 blocks, got {}",
        content.blocks.len()
    );

    // 3. Render as plain text
    let plain = EasyDoc::view_as(&path, &ViewMode::Plain).expect("view_as Plain should succeed");
    assert!(
        plain.contains("Chapter 1"),
        "plain should contain heading: {plain}"
    );
    assert!(
        plain.contains("Introduction text"),
        "plain should contain paragraph: {plain}"
    );

    // 4. Render as outline
    let outline = EasyDoc::view_as(&path, &ViewMode::Outline { max_level: 2 })
        .expect("view_as Outline should succeed");
    assert!(
        outline.contains("Chapter 1"),
        "outline should contain H1: {outline}"
    );
    assert!(
        outline.contains("Section 1.1"),
        "outline should contain H2: {outline}"
    );
}

// ============================================================================
// Test: re-exported types are accessible
// ============================================================================

#[test]
fn test_re_exported_types_accessible() {
    // Verify that DocxSaxReader, ViewMode, render_view are accessible
    // from the easydoc crate without depending on easydoc_reader directly.
    let _ = std::any::TypeId::of::<easydoc::DocxSaxReader<std::io::Cursor<Vec<u8>>>>();
    let _ = std::any::TypeId::of::<easydoc::ViewMode>();
    // render_view is a function, not a type — just verify it's callable
    let content = DocumentContent::default();
    let result = easydoc::render_view(&content, &ViewMode::Plain);
    assert!(
        result.is_ok(),
        "render_view should succeed on empty content"
    );
}

// ============================================================================
// Test: ContentCollector from prelude
// ============================================================================

#[test]
fn test_content_collector_from_prelude() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("collector_test.docx");

    EasyDoc::document(&path)
        .add_paragraph(Paragraph::new().add_text("Collector test."))
        .save()
        .expect("save should succeed");

    let mut collector = ContentCollector::new();
    EasyDoc::read_events(&path, &mut collector).expect("read_events should succeed");
    let content = collector.into_content();

    assert!(
        !content.blocks.is_empty(),
        "collector should have collected blocks"
    );
}

// ============================================================================
// Test: read_events with empty document
// ============================================================================

#[test]
fn test_read_events_empty_doc() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("empty.docx");

    // Create a minimal document (no content blocks)
    EasyDoc::document(&path)
        .save()
        .expect("save should succeed");

    let mut collector = ContentCollector::new();
    EasyDoc::read_events(&path, &mut collector).expect("read_events should succeed");
    let content = collector.into_content();

    // Empty document should produce no content blocks
    // (DocumentStart/DocumentEnd are consumed by ContentCollector without producing blocks)
    assert!(
        content.blocks.is_empty(),
        "empty document should produce no blocks, got {}",
        content.blocks.len()
    );
}

// ============================================================================
// Test: view_as with all four modes on the same document
// ============================================================================

#[test]
fn test_view_as_all_modes_consistent() {
    let dir = TempDir::new().expect("tempdir");
    let path = build_test_docx(dir.path());

    let modes = [
        ViewMode::Plain,
        ViewMode::Annotated,
        ViewMode::Outline { max_level: 3 },
        ViewMode::Stats,
    ];

    for mode in &modes {
        let result = EasyDoc::view_as(&path, mode);
        assert!(
            result.is_ok(),
            "view_as should succeed for mode {:?}: {:?}",
            mode,
            result.err()
        );
        let text = result.unwrap();
        assert!(
            !text.is_empty(),
            "view_as should return non-empty text for mode {mode:?}"
        );
    }
}