pter 0.1.0

Plain Text Email Renderer — convert HTML email bodies into readable markdown
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
use scraper::ElementRef;

/// Determine whether a `<table>` element is a data table or a layout table.
///
/// Email HTML overwhelmingly uses tables for layout. A table is considered
/// a **data table** if it has structural indicators of tabular data:
/// - Contains `<th>` elements
/// - Has a `<caption>` child
/// - Has `role="grid"` or `role="table"`
/// - Has multiple rows where multiple cells contain substantive text
///
/// Everything else is treated as a layout table and unwrapped.
pub fn is_data_table(table: ElementRef) -> bool {
    let el = table.value();

    // role attribute
    if let Some(role) = el.attr("role") {
        if role == "grid" || role == "table" {
            return true;
        }
        // role="presentation" is an explicit layout signal
        if role == "presentation" || role == "none" {
            return false;
        }
    }

    let mut has_th = false;
    let mut has_caption = false;
    let mut multi_cell_rows = 0u32;

    for descendant in table.descendants() {
        if let Some(el_ref) = ElementRef::wrap(descendant) {
            match el_ref.value().name() {
                "th" => has_th = true,
                "caption" => has_caption = true,
                "tr" => {
                    let cell_count = el_ref
                        .children()
                        .filter_map(ElementRef::wrap)
                        .filter(|c| {
                            let name = c.value().name();
                            (name == "td" || name == "th") && has_substantive_text(*c)
                        })
                        .count();
                    if cell_count > 1 {
                        multi_cell_rows += 1;
                    }
                }
                _ => {}
            }
        }
    }

    if has_th || has_caption {
        return true;
    }

    // Multiple rows with multiple substantive cells = data table
    multi_cell_rows >= 2
}

/// Check if an element contains meaningful text (not just whitespace/nbsp).
fn has_substantive_text(el: ElementRef) -> bool {
    let text = el.text().collect::<String>();
    let trimmed = text.trim().replace('\u{a0}', ""); // strip &nbsp;
    trimmed.len() > 1 // more than a single character
}

/// Extract rows and cells from a data table for markdown rendering.
///
/// Returns (headers, rows) where each is a Vec of cell text strings.
/// If no `<thead>`/`<th>` row exists, the first row is used as headers.
pub fn extract_table_data(table: ElementRef) -> (Vec<String>, Vec<Vec<String>>) {
    let mut headers: Vec<String> = Vec::new();
    let mut rows: Vec<Vec<String>> = Vec::new();

    // Look for thead/th first
    for descendant in table.children().filter_map(ElementRef::wrap) {
        let name = descendant.value().name();
        if name == "thead" {
            for tr in descendant.children().filter_map(ElementRef::wrap) {
                if tr.value().name() == "tr" {
                    headers = extract_cells(tr);
                    break; // first row of thead
                }
            }
        } else if name == "tbody" || name == "tr" {
            let trs: Box<dyn Iterator<Item = ElementRef>> = if name == "tbody" {
                Box::new(
                    descendant
                        .children()
                        .filter_map(ElementRef::wrap)
                        .filter(|e| e.value().name() == "tr"),
                )
            } else {
                Box::new(std::iter::once(descendant))
            };

            for tr in trs {
                let cells = extract_cells(tr);
                if !cells.is_empty() {
                    // If we haven't found headers yet and this row has <th> cells,
                    // treat it as the header row
                    if headers.is_empty() && has_th_cells(tr) {
                        headers = cells;
                    } else {
                        rows.push(cells);
                    }
                }
            }
        }
    }

    // If still no headers, promote first data row
    if headers.is_empty() && !rows.is_empty() {
        headers = rows.remove(0);
    }

    (headers, rows)
}

fn extract_cells(tr: ElementRef) -> Vec<String> {
    tr.children()
        .filter_map(ElementRef::wrap)
        .filter(|e| {
            let n = e.value().name();
            n == "td" || n == "th"
        })
        .map(|cell| {
            let text = cell.text().collect::<String>();
            text.split_whitespace().collect::<Vec<_>>().join(" ")
        })
        .collect()
}

fn has_th_cells(tr: ElementRef) -> bool {
    tr.children()
        .filter_map(ElementRef::wrap)
        .any(|e| e.value().name() == "th")
}

/// Render a data table as a GFM markdown table.
pub fn render_markdown_table(headers: &[String], rows: &[Vec<String>]) -> String {
    if headers.is_empty() {
        return String::new();
    }

    let col_count = headers.len();
    let mut out = String::new();

    // Header row
    out.push('|');
    for h in headers {
        out.push(' ');
        out.push_str(h);
        out.push_str(" |");
    }
    out.push('\n');

    // Separator row
    out.push('|');
    for _ in 0..col_count {
        out.push_str(" --- |");
    }
    out.push('\n');

    // Data rows
    for row in rows {
        out.push('|');
        for i in 0..col_count {
            out.push(' ');
            if let Some(cell) = row.get(i) {
                out.push_str(cell);
            }
            out.push_str(" |");
        }
        out.push('\n');
    }

    // Remove trailing newline (caller handles spacing)
    out.trim_end().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use scraper::{Html, Selector};

    fn parse_table(html: &str) -> Html {
        Html::parse_document(html)
    }

    fn select_table(doc: &Html) -> ElementRef<'_> {
        let sel = Selector::parse("table").unwrap();
        doc.select(&sel).next().unwrap()
    }

    #[test]
    fn single_cell_is_layout() {
        let doc = parse_table("<table><tr><td>content</td></tr></table>");
        assert!(!is_data_table(select_table(&doc)));
    }

    #[test]
    fn table_with_th_is_data() {
        let doc = parse_table(
            "<table><tr><th>Name</th><th>Age</th></tr><tr><td>Alice</td><td>30</td></tr></table>",
        );
        assert!(is_data_table(select_table(&doc)));
    }

    #[test]
    fn table_with_caption_is_data() {
        let doc = parse_table(
            "<table><caption>Users</caption><tr><td>Alice</td><td>30</td></tr></table>",
        );
        assert!(is_data_table(select_table(&doc)));
    }

    #[test]
    fn role_presentation_is_layout() {
        let doc = parse_table(
            r#"<table role="presentation"><tr><td>layout</td><td>stuff</td></tr></table>"#,
        );
        assert!(!is_data_table(select_table(&doc)));
    }

    #[test]
    fn role_grid_is_data() {
        let doc =
            parse_table(r#"<table role="grid"><tr><td>Alice</td><td>30</td></tr></table>"#);
        assert!(is_data_table(select_table(&doc)));
    }

    #[test]
    fn multi_row_multi_cell_is_data() {
        let doc = parse_table(
            "<table>\
            <tr><td>Alice</td><td>Engineer</td></tr>\
            <tr><td>Bob</td><td>Designer</td></tr>\
            </table>",
        );
        assert!(is_data_table(select_table(&doc)));
    }

    #[test]
    fn spacer_cells_not_substantive() {
        let doc = parse_table(
            "<table><tr><td>content</td><td>&nbsp;</td></tr>\
            <tr><td>more</td><td> </td></tr></table>",
        );
        // Only one substantive cell per row
        assert!(!is_data_table(select_table(&doc)));
    }

    #[test]
    fn render_simple_table() {
        let headers = vec!["Name".into(), "Age".into()];
        let rows = vec![
            vec!["Alice".into(), "30".into()],
            vec!["Bob".into(), "25".into()],
        ];
        let md = render_markdown_table(&headers, &rows);
        assert_eq!(
            md,
            "| Name | Age |\n| --- | --- |\n| Alice | 30 |\n| Bob | 25 |"
        );
    }

    #[test]
    fn render_empty_headers() {
        let md = render_markdown_table(&[], &[]);
        assert_eq!(md, "");
    }

    #[test]
    fn extract_with_thead() {
        let doc = parse_table(
            "<table><thead><tr><th>A</th><th>B</th></tr></thead>\
            <tbody><tr><td>1</td><td>2</td></tr></tbody></table>",
        );
        let (h, r) = extract_table_data(select_table(&doc));
        assert_eq!(h, vec!["A", "B"]);
        assert_eq!(r, vec![vec!["1".to_string(), "2".to_string()]]);
    }

    #[test]
    fn extract_promotes_first_row() {
        let doc = parse_table(
            "<table><tr><td>Name</td><td>Val</td></tr>\
            <tr><td>X</td><td>Y</td></tr></table>",
        );
        let (h, r) = extract_table_data(select_table(&doc));
        assert_eq!(h, vec!["Name", "Val"]);
        assert_eq!(r, vec![vec!["X".to_string(), "Y".to_string()]]);
    }

    // -- Boundary tests for is_data_table role handling --

    #[test]
    fn role_none_is_layout() {
        // role="none" → explicit layout signal. Catches L22 `||` mutation
        // (presentation OR none); without the ||, "none" wouldn't short-circuit.
        let doc = parse_table(
            r#"<table role="none"><tr><th>X</th><th>Y</th></tr><tr><td>1</td><td>2</td></tr></table>"#,
        );
        // Even with <th>, the explicit role="none" should win.
        assert!(!is_data_table(select_table(&doc)));
    }

    #[test]
    fn role_table_is_data() {
        // role="table" → data. Catches L22 == "grid" mutating to != (which would
        // make grid not match) AND covers the parallel `|| role == "table"` arm.
        let doc =
            parse_table(r#"<table role="table"><tr><td>a</td></tr></table>"#);
        assert!(is_data_table(select_table(&doc)));
    }

    #[test]
    fn role_unknown_falls_through_to_structural() {
        // Unknown role → no early decision; structural rules apply.
        // Single-cell single-row layout table → not data.
        let doc =
            parse_table(r#"<table role="banner"><tr><td>only one cell</td></tr></table>"#);
        assert!(!is_data_table(select_table(&doc)));
    }

    #[test]
    fn role_presentation_overrides_structure() {
        // role="presentation" → layout, even with multiple substantive rows.
        // Catches L22 == "presentation" mutating to != (which would skip this check).
        let doc = parse_table(
            r#"<table role="presentation"><tr><td>Alice</td><td>Engineer</td></tr>\
            <tr><td>Bob</td><td>Designer</td></tr></table>"#,
        );
        assert!(!is_data_table(select_table(&doc)));
    }

    // -- Boundary tests for has_substantive_text > 1 --

    #[test]
    fn single_char_cells_not_substantive() {
        // Two rows of single-char cells → not substantive → not a data table.
        // Catches L66 `>` mutating to `>=`: with >=, single chars become substantive
        // and these two rows would qualify as a data table.
        let doc = parse_table(
            "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>",
        );
        assert!(!is_data_table(select_table(&doc)));
    }

    #[test]
    fn two_char_cells_are_substantive() {
        let doc = parse_table(
            "<table><tr><td>ab</td><td>cd</td></tr><tr><td>ef</td><td>gh</td></tr></table>",
        );
        assert!(is_data_table(select_table(&doc)));
    }

    // -- Boundary tests for extract_table_data tbody handling --

    #[test]
    fn extract_with_tbody_no_thead() {
        // Catches L87 `== "tbody"` mutating to != (which would skip tbody).
        let doc = parse_table(
            "<table><tbody><tr><td>Name</td><td>Val</td></tr><tr><td>X</td><td>Y</td></tr></tbody></table>",
        );
        let (h, r) = extract_table_data(select_table(&doc));
        // First tbody row promoted to headers; second row is data.
        assert_eq!(h, vec!["Name", "Val"]);
        assert_eq!(r, vec![vec!["X".to_string(), "Y".to_string()]]);
    }

    // -- Boundary tests for the headers-vs-th-row decision (L104 &&) --

    #[test]
    fn thead_present_blocks_later_th_row_promotion() {
        // Headers already set by thead. A later th-row should NOT overwrite them.
        // Catches L104 `&&` mutating to `||`: with ||, has_th_cells alone would
        // re-promote, clobbering the thead headers.
        let doc = parse_table(
            "<table><thead><tr><th>A</th><th>B</th></tr></thead>\
            <tbody><tr><th>X</th><th>Y</th></tr><tr><td>1</td><td>2</td></tr></tbody></table>",
        );
        let (h, r) = extract_table_data(select_table(&doc));
        assert_eq!(h, vec!["A", "B"], "thead headers must not be overwritten");
        // Both the th-row and the td-row become data rows.
        assert_eq!(r.len(), 2);
    }

    #[test]
    fn no_thead_th_row_promotes_to_headers() {
        // No thead, but a tr full of th cells → that tr's cells become headers.
        // Catches `has_th_cells -> bool` always-false mutation (which would
        // make this row become a data row instead).
        let doc = parse_table(
            "<table><tr><th>X</th><th>Y</th></tr><tr><td>1</td><td>2</td></tr></table>",
        );
        let (h, r) = extract_table_data(select_table(&doc));
        assert_eq!(h, vec!["X", "Y"]);
        assert_eq!(r, vec![vec!["1".to_string(), "2".to_string()]]);
    }

    #[test]
    fn all_td_rows_promote_first_to_headers() {
        // No th anywhere → has_th_cells is false for every row → first row promoted
        // by the `if headers.is_empty() && !rows.is_empty()` fallback.
        // Catches `has_th_cells -> bool` always-true mutation (which would promote
        // every row as headers, leaving rows empty after the first).
        let doc = parse_table(
            "<table><tr><td>Name</td><td>Val</td></tr><tr><td>X</td><td>Y</td></tr><tr><td>P</td><td>Q</td></tr></table>",
        );
        let (h, r) = extract_table_data(select_table(&doc));
        assert_eq!(h, vec!["Name", "Val"]);
        assert_eq!(r.len(), 2);
    }

    // -- Boundary test for has_th_cells (L139 == "th") --

    #[test]
    fn td_only_row_is_not_a_header_row() {
        // A tr with only <td> cells should NOT promote to headers when other
        // rows exist. Catches L139 `== "th"` mutating to `!=` (which would
        // match td cells and incorrectly treat every td row as a header row).
        let doc = parse_table(
            "<table><tr><td>data-1</td><td>data-2</td></tr>\
            <tr><td>data-3</td><td>data-4</td></tr>\
            <tr><td>data-5</td><td>data-6</td></tr></table>",
        );
        let (h, r) = extract_table_data(select_table(&doc));
        // First row is promoted (via the fallback at the end), leaving exactly two data rows.
        assert_eq!(h, vec!["data-1", "data-2"]);
        assert_eq!(r.len(), 2, "remaining rows should be data, not headers");
    }
}