text-document-io 1.4.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
// Generated by Qleany v1.4.8 from feature_use_case.tera
use crate::ExportMarkdownDto;
use anyhow::{Result, anyhow};
use common::database::QueryUnitOfWork;
use common::entities::{
    Block, Document, Frame, InlineContent, InlineElement, List, ListStyle, Root, Table, TableCell,
};
use common::types::{EntityId, ROOT_ENTITY_ID};
use std::collections::HashSet;

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

#[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 = "GetMultiRO")]
#[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 = "InlineElement", action = "GetMultiRO")]
#[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 ExportMarkdownUnitOfWorkTrait: QueryUnitOfWork {}

pub struct ExportMarkdownUseCase {
    uow_factory: Box<dyn ExportMarkdownUnitOfWorkFactoryTrait>,
}

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

    pub fn execute(&mut self) -> Result<ExportMarkdownDto> {
        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 output_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;
            }

            // Check if this is a table anchor frame
            let frame = uow.get_frame(frame_id)?;
            if let Some(ref f) = frame
                && let Some(table_id) = f.table
            {
                let table_md = self.render_table_markdown(&*uow, &table_id)?;
                if !output_parts.is_empty() {
                    output_parts.push("\n\n".to_string());
                }
                output_parts.push(table_md);
                continue;
            }

            if let Some(ref f) = frame {
                let frame_lines = self.render_frame_content(&*uow, f, &cell_frame_ids, "")?;
                for line in frame_lines {
                    if !output_parts.is_empty() {
                        output_parts.push("\n\n".to_string());
                    }
                    output_parts.push(line);
                }
            }
        }

        uow.end_transaction()?;

        let markdown_text = output_parts.concat();

        Ok(ExportMarkdownDto { markdown_text })
    }

    /// Render the content of a frame by walking its `child_order`.
    /// Positive entries are block IDs, negative entries are negated sub-frame IDs.
    /// `quote_prefix` is prepended to every output line (e.g. "> " for blockquotes).
    /// Returns a vec of block-level strings (each is one rendered block or sub-frame output).
    fn render_frame_content(
        &self,
        uow: &dyn ExportMarkdownUnitOfWorkTrait,
        frame: &Frame,
        cell_frame_ids: &HashSet<EntityId>,
        quote_prefix: &str,
    ) -> Result<Vec<String>> {
        let mut result: Vec<String> = Vec::new();
        let mut prev_was_list = false;
        let mut ordered_list_counter: i64 = 0;
        let mut current_list_id: Option<EntityId> = None;

        // If child_order is empty, fall back to iterating blocks directly
        let use_child_order = !frame.child_order.is_empty();

        if use_child_order {
            for &entry in &frame.child_order {
                if entry > 0 {
                    // Positive: block ID
                    let block_id = entry as EntityId;
                    let block = uow.get_block(&block_id)?;
                    if let Some(ref b) = block {
                        let (line, is_list_item) = self.render_block_line(
                            uow,
                            b,
                            quote_prefix,
                            &mut ordered_list_counter,
                            &mut current_list_id,
                        )?;
                        if !result.is_empty() {
                            if is_list_item && prev_was_list {
                                result.push("\n".to_string());
                            } else {
                                result.push("\n\n".to_string());
                            }
                        }
                        result.push(line);
                        prev_was_list = is_list_item;
                    }
                } else {
                    // Negative: negated sub-frame ID
                    let sub_frame_id = (-entry) as EntityId;
                    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 {
                        // Check if sub-frame is a table anchor
                        if let Some(table_id) = sf.table {
                            let table_md = self.render_table_markdown(uow, &table_id)?;
                            let prefixed = if !quote_prefix.is_empty() {
                                prefix_lines(&table_md, quote_prefix)
                            } else {
                                table_md
                            };
                            if !result.is_empty() {
                                result.push("\n\n".to_string());
                            }
                            result.push(prefixed);
                            prev_was_list = false;
                            current_list_id = None;
                            ordered_list_counter = 0;
                            continue;
                        }

                        // Blockquote sub-frame
                        let sub_prefix = if sf.fmt_is_blockquote == Some(true) {
                            format!("{}> ", quote_prefix)
                        } else {
                            quote_prefix.to_string()
                        };

                        let sub_lines =
                            self.render_frame_content(uow, sf, cell_frame_ids, &sub_prefix)?;
                        for sub_line in sub_lines {
                            if !result.is_empty() {
                                result.push("\n\n".to_string());
                            }
                            result.push(sub_line);
                        }
                        prev_was_list = false;
                        current_list_id = None;
                        ordered_list_counter = 0;
                    }
                }
            }
        } else {
            // Fallback: iterate blocks from the Blocks relationship
            let block_ids = uow.get_frame_relationship(
                &frame.id,
                &common::direct_access::frame::FrameRelationshipField::Blocks,
            )?;

            if block_ids.is_empty() {
                return Ok(result);
            }

            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);

            for block in &blocks {
                let (line, is_list_item) = self.render_block_line(
                    uow,
                    block,
                    quote_prefix,
                    &mut ordered_list_counter,
                    &mut current_list_id,
                )?;
                if !result.is_empty() {
                    if is_list_item && prev_was_list {
                        result.push("\n".to_string());
                    } else {
                        result.push("\n\n".to_string());
                    }
                }
                result.push(line);
                prev_was_list = is_list_item;
            }
        }

        Ok(result)
    }

    /// Render a single block into a markdown line string.
    /// Returns (rendered_line, is_list_item).
    fn render_block_line(
        &self,
        uow: &dyn ExportMarkdownUnitOfWorkTrait,
        block: &Block,
        quote_prefix: &str,
        ordered_list_counter: &mut i64,
        current_list_id: &mut Option<EntityId>,
    ) -> Result<(String, bool)> {
        // Check if this is a code block
        if block.fmt_is_code_block == Some(true) {
            let lang = block.fmt_code_language.as_deref().unwrap_or("");
            let element_ids = uow.get_block_relationship(
                &block.id,
                &common::direct_access::block::BlockRelationshipField::Elements,
            )?;
            let elements_opt = uow.get_inline_element_multi(&element_ids)?;
            let elements: Vec<InlineElement> = elements_opt.into_iter().flatten().collect();

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

            let code_block = if quote_prefix.is_empty() {
                format!("```{}\n{}\n```", lang, raw_text)
            } else {
                let mut lines = Vec::new();
                lines.push(format!("{}```{}", quote_prefix, lang));
                for line in raw_text.lines() {
                    lines.push(format!("{}{}", quote_prefix, line));
                }
                // Handle the case where raw_text is empty or ends without newline
                if raw_text.is_empty() {
                    lines.push(quote_prefix.to_string());
                }
                lines.push(format!("{}```", quote_prefix));
                lines.join("\n")
            };

            *current_list_id = None;
            *ordered_list_counter = 0;
            return Ok((code_block, false));
        }

        // Get inline elements
        let element_ids = uow.get_block_relationship(
            &block.id,
            &common::direct_access::block::BlockRelationshipField::Elements,
        )?;

        let elements_opt = uow.get_inline_element_multi(&element_ids)?;
        let elements: Vec<InlineElement> = elements_opt.into_iter().flatten().collect();

        // Check if block has a list
        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
        };

        let is_list_item = list.is_some();

        // Build inline markdown text
        let inline_md = self.render_inline_elements(&elements)?;

        // Build the block line
        let block_line = if let Some(level) = block.fmt_heading_level {
            let prefix = "#".repeat(level as usize);
            format!("{}{} {}", quote_prefix, prefix, inline_md)
        } else if let Some(ref list_entity) = list {
            let indent_prefix = "  ".repeat(list_entity.indent as usize);
            match list_entity.style {
                ListStyle::Decimal
                | ListStyle::LowerAlpha
                | ListStyle::UpperAlpha
                | ListStyle::LowerRoman
                | ListStyle::UpperRoman => {
                    let this_list_id = list_ids.first().copied();
                    if this_list_id != *current_list_id {
                        *ordered_list_counter = 1;
                        *current_list_id = this_list_id;
                    } else {
                        *ordered_list_counter += 1;
                    }
                    format!(
                        "{}{}{}. {}",
                        quote_prefix, indent_prefix, ordered_list_counter, inline_md
                    )
                }
                _ => format!("{}{}- {}", quote_prefix, indent_prefix, inline_md),
            }
        } else {
            *current_list_id = None;
            *ordered_list_counter = 0;
            format!("{}{}", quote_prefix, inline_md)
        };

        Ok((block_line, is_list_item))
    }

    /// Render inline elements into markdown text with formatting.
    fn render_inline_elements(&self, elements: &[InlineElement]) -> Result<String> {
        let mut inline_md = String::new();
        for elem in elements {
            let is_code = elem.fmt_font_family.as_deref() == Some("monospace");
            let text = match &elem.content {
                InlineContent::Text(t) => {
                    if is_code {
                        t.clone()
                    } else {
                        escape_markdown(t)
                    }
                }
                InlineContent::Image { name, .. } => {
                    format!("![{}]({})", name, name)
                }
                InlineContent::Empty => String::new(),
            };

            if text.is_empty() {
                continue;
            }

            let mut formatted = text.clone();

            // Apply formatting (innermost first)
            if elem.fmt_font_family.as_deref() == Some("monospace") {
                formatted = format!("`{}`", formatted);
            }
            if elem.fmt_font_strikeout == Some(true) {
                formatted = format!("~~{}~~", formatted);
            }
            if elem.fmt_font_bold == Some(true) && elem.fmt_font_italic == Some(true) {
                formatted = format!("***{}***", formatted);
            } else if elem.fmt_font_bold == Some(true) {
                formatted = format!("**{}**", formatted);
            } else if elem.fmt_font_italic == Some(true) {
                formatted = format!("*{}*", formatted);
            }
            if let Some(ref href) = elem.fmt_anchor_href {
                formatted = format!("[{}]({})", formatted, href);
            }

            inline_md.push_str(&formatted);
        }
        Ok(inline_md)
    }

    fn render_table_markdown(
        &self,
        uow: &dyn ExportMarkdownUnitOfWorkTrait,
        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)));

        let rows = table.rows as usize;
        let cols = table.columns as usize;

        // Build a grid of cell content strings
        let mut grid: Vec<Vec<String>> = vec![vec![String::new(); cols]; rows];

        for cell in &cells {
            let r = cell.row as usize;
            let c = cell.column as usize;
            if r >= rows || c >= cols {
                continue;
            }

            let mut cell_text = String::new();
            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 mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
                blocks.sort_by_key(|b| b.document_position);

                let mut parts: Vec<String> = Vec::new();
                for block in &blocks {
                    let inline_md = self.render_inline_markdown(uow, block)?;
                    if !inline_md.is_empty() {
                        parts.push(inline_md);
                    }
                }
                cell_text = parts.join(" ");
            }

            grid[r][c] = cell_text;
        }

        // Render as pipe-delimited markdown table
        let mut md = String::new();

        for (r, row) in grid.iter().enumerate() {
            md.push('|');
            for cell_text in row {
                md.push(' ');
                md.push_str(cell_text);
                md.push_str(" |");
            }
            md.push('\n');

            // Add separator after header row
            if r == 0 {
                md.push('|');
                for _ in 0..cols {
                    md.push_str("---|");
                }
                md.push('\n');
            }
        }

        // Remove trailing newline
        if md.ends_with('\n') {
            md.pop();
        }

        Ok(md)
    }

    fn render_inline_markdown(
        &self,
        uow: &dyn ExportMarkdownUnitOfWorkTrait,
        block: &Block,
    ) -> Result<String> {
        let element_ids = uow.get_block_relationship(
            &block.id,
            &common::direct_access::block::BlockRelationshipField::Elements,
        )?;

        let elements_opt = uow.get_inline_element_multi(&element_ids)?;
        let elements: Vec<InlineElement> = elements_opt.into_iter().flatten().collect();

        self.render_inline_elements(&elements)
    }
}

/// Prefix every line of `text` with `prefix`.
fn prefix_lines(text: &str, prefix: &str) -> String {
    text.lines()
        .map(|line| format!("{}{}", prefix, line))
        .collect::<Vec<_>>()
        .join("\n")
}

fn escape_markdown(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '\\' | '*' | '_' | '{' | '}' | '[' | ']' | '(' | ')' | '#' | '+' | '-' | '.' | '!'
            | '|' | '~' | '>' => {
                result.push('\\');
                result.push(c);
            }
            _ => result.push(c),
        }
    }
    result
}