typlite/writer/docx/
writer.rs

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
640
641
642
643
644
//! DOCX document writer implementation

use base64::Engine;
use cmark_writer::ast::{ListItem, Node};
use docx_rs::*;
use ecow::EcoString;
use std::fs;
use std::io::Cursor;

use crate::common::{FigureNode, FormatWriter};
use crate::Result;

use super::image_processor::DocxImageProcessor;
use super::numbering::DocxNumbering;
use super::styles::DocxStyles;

/// DOCX writer that generates DOCX directly from AST (without intermediate representation)
pub struct DocxWriter {
    styles: DocxStyles,
    numbering: DocxNumbering,
    list_level: usize,
    list_numbering_count: usize,
    image_processor: DocxImageProcessor,
}

impl Default for DocxWriter {
    fn default() -> Self {
        Self::new()
    }
}

impl DocxWriter {
    pub fn new() -> Self {
        Self {
            styles: DocxStyles::new(),
            numbering: DocxNumbering::new(),
            list_level: 0,
            list_numbering_count: 0,
            image_processor: DocxImageProcessor::new(),
        }
    }

    /// Process image node
    fn process_image(&self, docx: Docx, url: &str, alt_nodes: &[Node]) -> Result<Docx> {
        // Build alt text
        let alt_text = if !alt_nodes.is_empty() {
            let mut text = String::new();
            for node in alt_nodes {
                if let Node::Text(content) = node {
                    text.push_str(content);
                }
            }
            Some(text)
        } else {
            None
        };

        // Try reading image file
        if let Ok(img_data) = fs::read(url) {
            Ok(self
                .image_processor
                .process_image_data(docx, &img_data, alt_text.as_deref(), None))
        } else {
            let placeholder = format!("[Image not found: {}]", url);
            let para = Paragraph::new().add_run(Run::new().add_text(placeholder));
            Ok(docx.add_paragraph(para))
        }
    }

    /// Process figure node (image with caption)
    fn process_figure(&mut self, mut docx: Docx, figure_node: &FigureNode) -> Result<Docx> {
        // First handle the figure body (typically an image)
        match &*figure_node.body {
            Node::Paragraph(content) => {
                for node in content {
                    if let Node::Image {
                        url,
                        title: _,
                        alt: _,
                    } = node
                    {
                        // Process the image
                        if let Ok(img_data) = fs::read(url) {
                            let alt_text = figure_node.caption.clone();
                            // Add the image with caption
                            docx = self.image_processor.process_image_data(
                                docx,
                                &img_data,
                                Some(&alt_text),
                                None,
                            );

                            // Add caption as a separate paragraph with Caption style
                            if !figure_node.caption.is_empty() {
                                let caption_text = format!("Figure: {}", figure_node.caption);
                                let caption_para = Paragraph::new()
                                    .style("Caption")
                                    .add_run(Run::new().add_text(caption_text));
                                docx = docx.add_paragraph(caption_para);
                            }
                        } else {
                            // Image not found, show placeholder
                            let placeholder = format!("[Image not found: {}]", url);
                            let para = Paragraph::new().add_run(Run::new().add_text(placeholder));
                            docx = docx.add_paragraph(para);

                            // Still add caption
                            if !figure_node.caption.is_empty() {
                                let caption_para = Paragraph::new()
                                    .style("Caption")
                                    .add_run(Run::new().add_text(&figure_node.caption));
                                docx = docx.add_paragraph(caption_para);
                            }
                        }
                    } else {
                        // Handle non-image content
                        let mut para = Paragraph::new();
                        let run = Run::new();
                        let run = self.process_inline_to_run(run, node)?;
                        if !run.children.is_empty() {
                            para = para.add_run(run);
                            docx = docx.add_paragraph(para);
                        }

                        // Add caption as a separate paragraph
                        if !figure_node.caption.is_empty() {
                            let caption_para = Paragraph::new()
                                .style("Caption")
                                .add_run(Run::new().add_text(&figure_node.caption));
                            docx = docx.add_paragraph(caption_para);
                        }
                    }
                }
            }
            // Handle other content types within figure
            _ => {
                // Process the content using standard node processing
                docx = self.process_node(docx, &figure_node.body)?;

                // Add caption as a separate paragraph
                if !figure_node.caption.is_empty() {
                    let caption_para = Paragraph::new()
                        .style("Caption")
                        .add_run(Run::new().add_text(&figure_node.caption));
                    docx = docx.add_paragraph(caption_para);
                }
            }
        }

        Ok(docx)
    }

    /// Process inline element and add to Run
    fn process_inline_to_run(&self, mut run: Run, node: &Node) -> Result<Run> {
        match node {
            Node::Text(text) => {
                run = run.add_text(text);
            }
            Node::Strong(content) => {
                run = run.style("Strong");
                for child in content {
                    run = self.process_inline_to_run(run, child)?;
                }
            }
            Node::Emphasis(content) => {
                run = run.style("Emphasis");
                for child in content {
                    run = self.process_inline_to_run(run, child)?;
                }
            }
            Node::Strikethrough(content) => {
                run = run.strike();
                for child in content {
                    run = self.process_inline_to_run(run, child)?;
                }
            }
            Node::Link {
                url: _,
                title: _,
                content,
            } => {
                // Hyperlinks need to be processed at paragraph level, only handle content here
                run = run.style("Hyperlink");
                for child in content {
                    run = self.process_inline_to_run(run, child)?;
                }
            }
            Node::Image {
                url,
                title: _,
                alt: _,
            } => {
                if let Ok(img_data) = fs::read(url) {
                    run = self.image_processor.process_inline_image(run, &img_data)?;
                } else {
                    run = run.add_text(format!("[Image not found: {}]", url));
                }
            }
            Node::HtmlElement(element) => {
                // Handle special HTML elements
                if element.tag == "mark" {
                    run = run.style("Highlight");
                    for child in &element.children {
                        run = self.process_inline_to_run(run, child)?;
                    }
                } else if element.tag == "img" && element.self_closing {
                    let is_typst_block = element
                        .attributes
                        .iter()
                        .any(|a| a.name == "alt" && a.value == "typst-block");

                    let src = element
                        .attributes
                        .iter()
                        .find(|a| a.name == "src")
                        .map(|a| a.value.as_str())
                        .unwrap_or("");

                    if src.starts_with("data:image/") {
                        run = self.image_processor.process_data_url_image(
                            run,
                            src,
                            is_typst_block,
                        )?;
                    }
                } else {
                    // Standard element content processing
                    for child in &element.children {
                        run = self.process_inline_to_run(run, child)?;
                    }
                }
            }
            Node::InlineCode(code) => {
                run = run.style("CodeInline").add_text(code);
            }
            Node::HardBreak => {
                run = run.add_break(BreakType::TextWrapping);
            }
            Node::SoftBreak => {
                run = run.add_text(" ");
            }
            // Other inline element types
            _ => {}
        }

        Ok(run)
    }

    /// Process paragraph and add to document
    fn process_paragraph(
        &self,
        mut docx: Docx,
        content: &[Node],
        style: Option<&str>,
    ) -> Result<Docx> {
        let mut para = Paragraph::new();

        // Apply style
        if let Some(style_name) = style {
            para = para.style(style_name);
        }

        // Extract all link nodes
        let mut links = Vec::new();
        for (i, node) in content.iter().enumerate() {
            if let Node::Link {
                url,
                title: _,
                content: _,
            } = node
            {
                links.push((i, url.clone()));
            }
        }

        // If no links, process paragraph normally
        if links.is_empty() {
            // Process paragraph content
            for node in content {
                let run = Run::new();
                let run = self.process_inline_to_run(run, node)?;
                if !run.children.is_empty() {
                    para = para.add_run(run);
                }
            }
        } else {
            // If links exist, we need to process in segments
            let mut last_idx = 0;
            for (idx, url) in links {
                // Process content before the link
                for item in content.iter().take(idx).skip(last_idx) {
                    let run = Run::new();
                    let run = self.process_inline_to_run(run, item)?;
                    if !run.children.is_empty() {
                        para = para.add_run(run);
                    }
                }

                // Process link
                if let Node::Link {
                    url: _,
                    title: _,
                    content: link_content,
                } = &content[idx]
                {
                    let mut hyperlink_run = Run::new().style("Hyperlink");
                    for child in link_content {
                        hyperlink_run = self.process_inline_to_run(hyperlink_run, child)?;
                    }

                    // Create and add hyperlink
                    if !hyperlink_run.children.is_empty() {
                        let hyperlink =
                            Hyperlink::new(&url, HyperlinkType::External).add_run(hyperlink_run);
                        para = para.add_hyperlink(hyperlink);
                    }
                }

                last_idx = idx + 1;
            }

            // Process content after the last link
            for item in content.iter().skip(last_idx) {
                let run = Run::new();
                let run = self.process_inline_to_run(run, item)?;
                if !run.children.is_empty() {
                    para = para.add_run(run);
                }
            }
        }

        // Only add when paragraph has content
        if !para.children.is_empty() {
            docx = docx.add_paragraph(para);
        }

        Ok(docx)
    }

    /// Process node and add to document
    fn process_node(&mut self, mut docx: Docx, node: &Node) -> Result<Docx> {
        match node {
            Node::Document(blocks) => {
                for block in blocks {
                    docx = self.process_node(docx, block)?;
                }
            }
            Node::Paragraph(content) => {
                docx = self.process_paragraph(docx, content, None)?;
            }
            Node::Heading {
                level,
                content,
                heading_type: _,
            } => {
                // Determine heading style name
                let style_name = match level {
                    1 => "Heading1",
                    2 => "Heading2",
                    3 => "Heading3",
                    4 => "Heading4",
                    5 => "Heading5",
                    _ => "Heading6",
                };

                docx = self.process_paragraph(docx, content, Some(style_name))?;
            }
            Node::BlockQuote(content) => {
                for block in content {
                    if let Node::Paragraph(inline) = block {
                        docx = self.process_paragraph(docx, inline, Some("Blockquote"))?;
                    } else {
                        docx = self.process_node(docx, block)?;
                    }
                }
            }
            Node::CodeBlock {
                language,
                content,
                block_type: _,
            } => {
                // Add language information
                if let Some(lang) = language {
                    if !lang.is_empty() {
                        let lang_para = Paragraph::new()
                            .style("CodeBlock")
                            .add_run(Run::new().add_text(lang));
                        docx = docx.add_paragraph(lang_para);
                    }
                }

                // Process code line by line, preserving line breaks
                let lines: Vec<&str> = content.split('\n').collect();
                for line in lines {
                    let code_para = Paragraph::new()
                        .style("CodeBlock")
                        .add_run(Run::new().add_text(line));
                    docx = docx.add_paragraph(code_para);
                }
            }
            Node::OrderedList { start: _, items } => {
                docx = self.process_ordered_list(docx, items)?;
            }
            Node::UnorderedList(items) => {
                docx = self.process_unordered_list(docx, items)?;
            }
            Node::Table {
                headers,
                rows,
                alignments: _,
            } => {
                docx = self.process_table(docx, headers, rows)?;
            }
            Node::Image { url, title: _, alt } => {
                docx = self.process_image(docx, url, alt)?;
            }
            Node::Custom(custom_node) => {
                if let Some(figure_node) = custom_node.as_any().downcast_ref::<FigureNode>() {
                    // Process figure node with special handling
                    docx = self.process_figure(docx, figure_node)?;
                } else if let Some(external_frame) = custom_node
                    .as_any()
                    .downcast_ref::<crate::common::ExternalFrameNode>(
                ) {
                    let data = base64::engine::general_purpose::STANDARD
                        .decode(&external_frame.svg_data)
                        .map_err(|e| format!("Failed to decode SVG data: {}", e))?;

                    docx = self.image_processor.process_image_data(
                        docx,
                        &data,
                        Some(&external_frame.alt_text),
                        None,
                    );
                } else {
                    // Fallback for unknown custom nodes - ignore or add placeholder
                    let placeholder = "[Unknown custom content]";
                    let para = Paragraph::new().add_run(Run::new().add_text(placeholder));
                    docx = docx.add_paragraph(para);
                }
            }
            Node::ThematicBreak => {
                // Add horizontal line as specially formatted paragraph
                let hr_para = Paragraph::new()
                    .style("HorizontalLine")
                    .add_run(Run::new().add_text(""));
                docx = docx.add_paragraph(hr_para);
            }
            // Inline elements should not be processed here individually
            _ => {}
        }

        Ok(docx)
    }

    /// Process ordered list
    fn process_ordered_list(&mut self, mut docx: Docx, items: &[ListItem]) -> Result<Docx> {
        // Enter deeper list level
        self.list_level += 1;
        let current_level = self.list_level - 1;

        // Create new ordered list numbering definition
        let (doc, num_id) = self.numbering.create_ordered_numbering(docx);
        docx = doc;

        // Process list items
        for item in items {
            if let ListItem::Ordered { content, .. } = item {
                docx = self.process_list_item_content(docx, content, num_id, current_level)?;
            }
        }

        // Exit list level
        self.list_level -= 1;
        Ok(docx)
    }

    /// Process unordered list
    fn process_unordered_list(&mut self, mut docx: Docx, items: &[ListItem]) -> Result<Docx> {
        // Enter deeper list level
        self.list_level += 1;
        let current_level = self.list_level - 1;

        // Create new unordered list numbering definition
        let (doc, num_id) = self.numbering.create_unordered_numbering(docx);
        docx = doc;

        // Process list items
        for item in items {
            if let ListItem::Unordered { content } = item {
                docx = self.process_list_item_content(docx, content, num_id, current_level)?;
            }
        }

        // Exit list level
        self.list_level -= 1;
        Ok(docx)
    }

    /// Helper function to process list item content
    fn process_list_item_content(
        &mut self,
        mut docx: Docx,
        content: &[Node],
        num_id: usize,
        level: usize,
    ) -> Result<Docx> {
        // If content is empty, add empty paragraph
        if content.is_empty() {
            let empty_para = Paragraph::new()
                .numbering(NumberingId::new(num_id), IndentLevel::new(level))
                .add_run(Run::new().add_text(""));
            return Ok(docx.add_paragraph(empty_para));
        }

        // Process content
        for block in content {
            match block {
                Node::Paragraph(inline) => {
                    let mut para = Paragraph::new()
                        .numbering(NumberingId::new(num_id), IndentLevel::new(level));

                    // Process paragraph content
                    for node in inline {
                        let run = Run::new();
                        let run = self.process_inline_to_run(run, node)?;
                        if !run.children.is_empty() {
                            para = para.add_run(run);
                        }
                    }

                    docx = docx.add_paragraph(para);
                }
                // Recursively process nested lists
                Node::OrderedList { start: _, items: _ } | Node::UnorderedList(_) => {
                    docx = self.process_node(docx, block)?;
                }
                _ => {
                    docx = self.process_node(docx, block)?;
                }
            }
        }

        Ok(docx)
    }

    /// Process table
    fn process_table(&self, mut docx: Docx, headers: &[Node], rows: &[Vec<Node>]) -> Result<Docx> {
        let mut table = Table::new(vec![]).style("Table");

        // Process table headers
        if !headers.is_empty() {
            let mut cells = Vec::new();

            for header_node in headers {
                let mut table_cell = TableCell::new();
                let mut para = Paragraph::new();

                let run = Run::new();
                let run = self.process_inline_to_run(run, header_node)?;
                if !run.children.is_empty() {
                    para = para.add_run(run);
                }

                if !para.children.is_empty() {
                    table_cell = table_cell.add_paragraph(para);
                }

                cells.push(table_cell);
            }

            if !cells.is_empty() {
                let header_row = TableRow::new(cells);
                table = table.add_row(header_row);
            }
        }

        // Process table rows
        for row in rows {
            let mut cells = Vec::new();

            for cell_node in row {
                let mut table_cell = TableCell::new();
                let mut para = Paragraph::new();

                let run = Run::new();
                let run = self.process_inline_to_run(run, cell_node)?;
                if !run.children.is_empty() {
                    para = para.add_run(run);
                }

                if !para.children.is_empty() {
                    table_cell = table_cell.add_paragraph(para);
                }

                cells.push(table_cell);
            }

            if !cells.is_empty() {
                let data_row = TableRow::new(cells);
                table = table.add_row(data_row);
            }
        }

        // Add table to document
        docx = docx.add_table(table);

        Ok(docx)
    }

    /// Generate DOCX document
    pub fn generate_docx(&mut self, doc: &Node) -> Result<Vec<u8>> {
        // Create DOCX document and initialize styles
        let mut docx = Docx::new();
        docx = self.styles.initialize_styles(docx);

        // Process document content
        docx = self.process_node(docx, doc)?;

        // Initialize numbering definitions
        docx = self.numbering.initialize_numbering(docx);

        // Build and pack document
        let docx_built = docx.build();
        let mut buffer = Vec::new();
        docx_built
            .pack(&mut Cursor::new(&mut buffer))
            .map_err(|e| format!("Failed to pack DOCX: {}", e))?;

        Ok(buffer)
    }
}

impl FormatWriter for DocxWriter {
    fn write_vec(&mut self, document: &Node) -> Result<Vec<u8>> {
        self.list_level = 0;
        self.list_numbering_count = 0;
        self.generate_docx(document)
    }

    fn write_eco(&mut self, _document: &Node, _output: &mut EcoString) -> Result<()> {
        Err("DOCX format does not support EcoString output".into())
    }
}