text-document-io 1.7.0

Import/export for text-document: plain text, Markdown, HTML, LaTeX, DOCX
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
// Generated by Qleany v1.4.8 from feature_use_case.tera
use crate::ExportHtmlDto;
use anyhow::{Result, anyhow};
use common::database::QueryUnitOfWork;
use common::database::rope_helpers::block_content_via_store;
use common::entities::{
    Alignment, Block, Document, Frame, List, ListStyle, Root, Table, TableCell, TextDirection,
};
use common::format_runs::InlineContent;
use common::types::{EntityId, ROOT_ENTITY_ID};
use std::collections::HashSet;

pub trait ExportHtmlUnitOfWorkFactoryTrait: Send + Sync {
    fn create(&self) -> Box<dyn ExportHtmlUnitOfWorkTrait>;
}

#[macros::uow_action(entity = "Root", action = "GetRO")]
#[macros::uow_action(entity = "Root", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Document", action = "GetRO")]
#[macros::uow_action(entity = "Document", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Frame", action = "GetRO")]
#[macros::uow_action(entity = "Frame", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Block", action = "GetRO")]
#[macros::uow_action(entity = "Block", action = "GetMultiRO")]
#[macros::uow_action(entity = "Block", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "List", action = "GetRO")]
#[macros::uow_action(entity = "Table", action = "GetRO")]
#[macros::uow_action(entity = "Table", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "TableCell", action = "GetMultiRO")]
pub trait ExportHtmlUnitOfWorkTrait: QueryUnitOfWork {}

pub struct ExportHtmlUseCase {
    uow_factory: Box<dyn ExportHtmlUnitOfWorkFactoryTrait>,
}

impl ExportHtmlUseCase {
    pub fn new(uow_factory: Box<dyn ExportHtmlUnitOfWorkFactoryTrait>) -> Self {
        ExportHtmlUseCase { uow_factory }
    }

    pub fn execute(&mut self) -> Result<ExportHtmlDto> {
        let uow = self.uow_factory.create();
        uow.begin_transaction()?;

        // Step 1: Get Root and Document
        let root = uow
            .get_root(&ROOT_ENTITY_ID)?
            .ok_or_else(|| anyhow!("Root entity not found"))?;

        let doc_ids = uow.get_root_relationship(
            &root.id,
            &common::direct_access::root::RootRelationshipField::Document,
        )?;
        let doc_id = *doc_ids
            .first()
            .ok_or_else(|| anyhow!("Root has no associated Document"))?;

        let frame_ids = uow.get_document_relationship(
            &doc_id,
            &common::direct_access::document::DocumentRelationshipField::Frames,
        )?;

        // Collect all cell frame IDs so we can skip them in the main loop
        let table_ids = uow.get_document_relationship(
            &doc_id,
            &common::direct_access::document::DocumentRelationshipField::Tables,
        )?;
        let mut cell_frame_ids: HashSet<EntityId> = HashSet::new();
        for tid in &table_ids {
            let cell_ids = uow.get_table_relationship(
                tid,
                &common::direct_access::table::TableRelationshipField::Cells,
            )?;
            let cells_opt = uow.get_table_cell_multi(&cell_ids)?;
            for cell in cells_opt.into_iter().flatten() {
                if let Some(cf_id) = cell.cell_frame {
                    cell_frame_ids.insert(cf_id);
                }
            }
        }

        let mut body_parts: Vec<String> = Vec::new();

        for frame_id in &frame_ids {
            // Skip cell frames — they're rendered as part of their table
            if cell_frame_ids.contains(frame_id) {
                continue;
            }
            // Skip sub-frames (parent_frame != None) — recursively rendered
            // by their parent's render_frame_html walk; rendering at the
            // top level again would duplicate their content.
            if let Some(f) = uow.get_frame(frame_id)?
                && f.parent_frame.is_some()
            {
                continue;
            }

            let frame_html = self.render_frame_html(&*uow, frame_id, &cell_frame_ids)?;
            if !frame_html.is_empty() {
                body_parts.push(frame_html);
            }
        }

        uow.end_transaction()?;

        let html_text = format!(
            "<html><head><meta charset=\"utf-8\"></head><body>{}</body></html>",
            body_parts.join("")
        );

        Ok(ExportHtmlDto { html_text })
    }

    /// Render a frame's content as HTML, walking its `child_order` to interleave
    /// blocks and sub-frames (blockquotes). Falls back to sorted blocks when
    /// `child_order` is empty.
    fn render_frame_html(
        &self,
        uow: &dyn ExportHtmlUnitOfWorkTrait,
        frame_id: &EntityId,
        cell_frame_ids: &HashSet<EntityId>,
    ) -> Result<String> {
        let frame = uow
            .get_frame(frame_id)?
            .ok_or_else(|| anyhow!("Frame not found"))?;

        // Table anchor frame — render the table instead of blocks
        if let Some(table_id) = frame.table {
            return self.render_table_html(uow, &table_id);
        }

        // If child_order is populated, use it to interleave blocks and sub-frames
        if !frame.child_order.is_empty() {
            return self.render_frame_by_child_order(uow, &frame, cell_frame_ids);
        }

        // Fallback: render all blocks in document_position order (original behaviour)
        let block_ids = uow.get_frame_relationship(
            frame_id,
            &common::direct_access::frame::FrameRelationshipField::Blocks,
        )?;

        if block_ids.is_empty() {
            return Ok(String::new());
        }

        let blocks_opt = uow.get_block_multi(&block_ids)?;
        let mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
        blocks.sort_by_key(|b| b.document_position);

        self.render_blocks_html(uow, &blocks)
    }

    /// Walk `child_order` entries: positive values are block IDs, negative values
    /// are negated sub-frame IDs.
    fn render_frame_by_child_order(
        &self,
        uow: &dyn ExportHtmlUnitOfWorkTrait,
        frame: &Frame,
        cell_frame_ids: &HashSet<EntityId>,
    ) -> Result<String> {
        let mut parts: Vec<String> = Vec::new();
        // Accumulate consecutive blocks so we can group list items
        let mut pending_blocks: Vec<Block> = Vec::new();

        for &entry in &frame.child_order {
            if entry > 0 {
                // Positive: block ID
                let block_id = entry as u64;
                if let Some(block) = uow.get_block(&block_id)? {
                    pending_blocks.push(block);
                }
            } else {
                // Negative: negated sub-frame ID
                // First, flush any accumulated blocks
                if !pending_blocks.is_empty() {
                    let html = self.render_blocks_html(uow, &pending_blocks)?;
                    if !html.is_empty() {
                        parts.push(html);
                    }
                    pending_blocks.clear();
                }

                let sub_frame_id = (-entry) as u64;

                // Skip cell frames
                if cell_frame_ids.contains(&sub_frame_id) {
                    continue;
                }

                let sub_frame = uow.get_frame(&sub_frame_id)?;
                if let Some(ref sf) = sub_frame {
                    if sf.fmt_is_blockquote == Some(true) {
                        // Recursively render the blockquote frame content
                        let inner = self.render_frame_html(uow, &sub_frame_id, cell_frame_ids)?;
                        if !inner.is_empty() {
                            parts.push(format!("<blockquote>{}</blockquote>", inner));
                        }
                    } else {
                        // Non-blockquote sub-frame: render normally
                        let inner = self.render_frame_html(uow, &sub_frame_id, cell_frame_ids)?;
                        if !inner.is_empty() {
                            parts.push(inner);
                        }
                    }
                }
            }
        }

        // Flush remaining blocks
        if !pending_blocks.is_empty() {
            let html = self.render_blocks_html(uow, &pending_blocks)?;
            if !html.is_empty() {
                parts.push(html);
            }
        }

        Ok(parts.join(""))
    }

    /// Render a slice of blocks as HTML, grouping consecutive list items and
    /// handling code blocks, headings, and paragraphs.
    fn render_blocks_html(
        &self,
        uow: &dyn ExportHtmlUnitOfWorkTrait,
        blocks: &[Block],
    ) -> Result<String> {
        let mut parts: Vec<String> = Vec::new();
        let mut i = 0;

        while i < blocks.len() {
            let block = &blocks[i];

            // --- Code block ---
            if block.fmt_is_code_block == Some(true) {
                let block_text = block_content_via_store(block, &uow.store());
                let elements = common::format_runs_query::inline_segments_for_block(
                    &uow.store(),
                    block.id,
                    &block_text,
                );

                // Concatenate raw text without inline formatting
                let mut raw_text = String::new();
                for elem in &elements {
                    match &elem.content {
                        InlineContent::Text(t) => raw_text.push_str(t),
                        InlineContent::Image { .. } | InlineContent::Empty => {}
                    }
                }

                let escaped = escape_html(&raw_text);

                let code_open = if let Some(ref lang) = block.fmt_code_language {
                    if !lang.is_empty() {
                        format!("<code class=\"language-{}\">", escape_html(lang))
                    } else {
                        "<code>".to_string()
                    }
                } else {
                    "<code>".to_string()
                };

                parts.push(format!("<pre>{}{}</code></pre>", code_open, escaped));
                i += 1;
                continue;
            }

            // --- List items ---
            let list_ids = uow.get_block_relationship(
                &block.id,
                &common::direct_access::block::BlockRelationshipField::List,
            )?;
            let list = if let Some(list_id) = list_ids.first() {
                uow.get_list(list_id)?
            } else {
                None
            };

            if let Some(ref list_entity) = list {
                let is_ordered = matches!(
                    list_entity.style,
                    ListStyle::Decimal
                        | ListStyle::LowerAlpha
                        | ListStyle::UpperAlpha
                        | ListStyle::LowerRoman
                        | ListStyle::UpperRoman
                );
                let list_tag = if is_ordered { "ol" } else { "ul" };
                let mut list_items = Vec::new();

                while i < blocks.len() {
                    let b = &blocks[i];
                    let b_list_ids = uow.get_block_relationship(
                        &b.id,
                        &common::direct_access::block::BlockRelationshipField::List,
                    )?;
                    let b_list = if let Some(lid) = b_list_ids.first() {
                        uow.get_list(lid)?
                    } else {
                        None
                    };

                    if b_list.is_some() {
                        let inline_html = self.render_inline_html(uow, b)?;
                        list_items.push(format!("<li>{}</li>", inline_html));
                        i += 1;
                    } else {
                        break;
                    }
                }

                parts.push(format!(
                    "<{}>{}</{}>",
                    list_tag,
                    list_items.join(""),
                    list_tag
                ));
            } else {
                // --- Normal block (paragraph / heading) ---
                let inline_html = self.render_inline_html(uow, block)?;

                let mut styles: Vec<String> = Vec::new();
                match block.fmt_alignment {
                    Some(Alignment::Left) => styles.push("text-align: left".into()),
                    Some(Alignment::Right) => styles.push("text-align: right".into()),
                    Some(Alignment::Center) => styles.push("text-align: center".into()),
                    Some(Alignment::Justify) => styles.push("text-align: justify".into()),
                    None => {}
                }
                if let Some(lh) = block.fmt_line_height {
                    styles.push(format!("line-height: {}", lh as f64 / 1000.0));
                }
                if block.fmt_non_breakable_lines == Some(true) {
                    styles.push("white-space: pre".into());
                }
                if block.fmt_direction == Some(TextDirection::RightToLeft) {
                    styles.push("direction: rtl".into());
                }
                if let Some(ref c) = block.fmt_background_color {
                    styles.push(format!("background-color: {}", c));
                }
                let style_attr = if styles.is_empty() {
                    String::new()
                } else {
                    format!(" style=\"{}\"", styles.join("; "))
                };

                if let Some(level) = block.fmt_heading_level {
                    let level = level.clamp(1, 6);
                    parts.push(format!(
                        "<h{}{}>{}</h{}>",
                        level, style_attr, inline_html, level
                    ));
                } else {
                    parts.push(format!("<p{}>{}</p>", style_attr, inline_html));
                }
                i += 1;
            }
        }

        Ok(parts.join(""))
    }

    fn render_table_html(
        &self,
        uow: &dyn ExportHtmlUnitOfWorkTrait,
        table_id: &EntityId,
    ) -> Result<String> {
        let table = uow
            .get_table(table_id)?
            .ok_or_else(|| anyhow!("Table not found"))?;

        let cell_ids = uow.get_table_relationship(
            table_id,
            &common::direct_access::table::TableRelationshipField::Cells,
        )?;
        let cells_opt = uow.get_table_cell_multi(&cell_ids)?;
        let mut cells: Vec<TableCell> = cells_opt.into_iter().flatten().collect();
        cells.sort_by(|a, b| a.row.cmp(&b.row).then(a.column.cmp(&b.column)));

        // Build a grid to track which cells are covered by spans
        let rows = table.rows as usize;
        let cols = table.columns as usize;
        let mut covered = vec![vec![false; cols]; rows];

        let mut html = String::from("<table");
        if let Some(border) = table.fmt_border {
            html.push_str(&format!(" border=\"{}\"", border));
        }
        html.push('>');

        for r in 0..rows {
            html.push_str("<tr>");
            for c in 0..cols {
                if covered[r][c] {
                    continue;
                }

                // Find the cell at this position
                let cell = cells
                    .iter()
                    .find(|cell| cell.row == r as i64 && cell.column == c as i64);

                if let Some(cell) = cell {
                    let mut td = String::from("<td");
                    if cell.row_span > 1 {
                        td.push_str(&format!(" rowspan=\"{}\"", cell.row_span));
                    }
                    if cell.column_span > 1 {
                        td.push_str(&format!(" colspan=\"{}\"", cell.column_span));
                    }
                    td.push('>');

                    // Render cell content from the cell's frame
                    if let Some(cf_id) = cell.cell_frame {
                        let block_ids = uow.get_frame_relationship(
                            &cf_id,
                            &common::direct_access::frame::FrameRelationshipField::Blocks,
                        )?;
                        let blocks_opt = uow.get_block_multi(&block_ids)?;
                        let blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();

                        let mut cell_parts: Vec<String> = Vec::new();
                        for block in &blocks {
                            let inline_html = self.render_inline_html(uow, block)?;
                            if !inline_html.is_empty() {
                                cell_parts.push(inline_html);
                            }
                        }
                        td.push_str(&cell_parts.join("<br/>"));
                    }

                    td.push_str("</td>");
                    html.push_str(&td);

                    // Mark spanned cells as covered
                    for sr in 0..cell.row_span as usize {
                        for sc in 0..cell.column_span as usize {
                            if sr == 0 && sc == 0 {
                                continue;
                            }
                            if r + sr < rows && c + sc < cols {
                                covered[r + sr][c + sc] = true;
                            }
                        }
                    }
                } else {
                    html.push_str("<td></td>");
                }
            }
            html.push_str("</tr>");
        }

        html.push_str("</table>");
        Ok(html)
    }

    fn render_inline_html(
        &self,
        uow: &dyn ExportHtmlUnitOfWorkTrait,
        block: &Block,
    ) -> Result<String> {
        let block_text = block_content_via_store(block, &uow.store());
        let elements = common::format_runs_query::inline_segments_for_block(
            &uow.store(),
            block.id,
            &block_text,
        );

        let mut html = String::new();

        for elem in &elements {
            let text = match &elem.content {
                InlineContent::Text(t) => escape_html(t),
                InlineContent::Image {
                    name,
                    width,
                    height,
                    ..
                } => {
                    format!(
                        "<img src=\"{}\" width=\"{}\" height=\"{}\" />",
                        escape_html(name),
                        width,
                        height
                    )
                }
                InlineContent::Empty => String::new(),
            };

            if text.is_empty() {
                continue;
            }

            // Check if this is an image tag (already formatted)
            if text.starts_with("<img ") {
                html.push_str(&text);
                continue;
            }

            let mut formatted = text;

            if elem.fmt_font_family.as_deref() == Some("monospace") {
                formatted = format!("<code>{}</code>", formatted);
            }
            if elem.fmt_font_bold == Some(true) {
                formatted = format!("<strong>{}</strong>", formatted);
            }
            if elem.fmt_font_italic == Some(true) {
                formatted = format!("<em>{}</em>", formatted);
            }
            if elem.fmt_font_underline == Some(true) {
                formatted = format!("<u>{}</u>", formatted);
            }
            if elem.fmt_font_strikeout == Some(true) {
                formatted = format!("<s>{}</s>", formatted);
            }
            if let Some(ref href) = elem.fmt_anchor_href {
                formatted = format!("<a href=\"{}\">{}</a>", escape_html(href), formatted);
            }

            html.push_str(&formatted);
        }

        Ok(html)
    }
}

fn escape_html(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
        // A raw CR in text content is normalised to LF by the HTML5 input
        // preprocessor on re-import (CR-from-`&#xD;` survives, literal CR
        // does not), which breaks serialiser idempotency. Emit it as a
        // numeric reference so it round-trips losslessly.
        .replace('\r', "&#13;")
}