adocers-html 0.2.0

Render an AsciiDoc document to HTML, following Asciidoctor's HTML5 converter
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
//! Table rendering.

use std::fmt::Write as _;

use asciidoc_parser::blocks::{
    Block,
    ColumnStyle,
    Frame,
    Grid,
    HorizontalAlignment,
    IsBlock,
    Stripes,
    TableBlock,
    TableCell,
    TableCellContent,
    TableColumn,
    TableRow,
    VerticalAlignment,
};

use crate::{
    Renderer,
    html::escape_attr,
};

impl<'src> Renderer<'src> {
    /// Render a `|===` table.
    pub(super) fn table_block(&mut self, block: &'src Block<'src>, table: &'src TableBlock<'src>) {
        let mut classes = vec!["tableblock".to_string()];
        classes.push(frame_class(table.frame()));
        classes.push(grid_class(table.grid()));

        if let Some(stripes) = stripes_class(table.stripes()) {
            classes.push(stripes);
        }

        // A `[width=NN%]` narrower than the page says how wide the table is
        // outright, which leaves nothing for either sizing class to say: it
        // overrides autowidth as well as the default of filling the page.
        let width = table.width().filter(|&width| width < 100);

        if width.is_none() {
            classes.push(
                if table.is_autowidth() {
                    "fit-content"
                } else {
                    "stretch"
                }
                .to_string(),
            );
        }

        if let Some(float) = block
            .attrlist()
            .and_then(|attrlist| attrlist.named_attribute("float"))
            .map(asciidoc_parser::attributes::ElementAttribute::value)
            .filter(|float| !float.is_empty())
        {
            classes.push(float.to_string());
        }

        // The block's own roles come last, after every class the table's own
        // shape called for.
        classes.extend(block.roles().into_iter().map(str::to_string));

        let mut open = String::from("<table");

        if let Some(id) = block.id() {
            let _ = write!(open, " id=\"{}\"", escape_attr(id));
        }

        let _ = write!(open, " class=\"{}\"", escape_attr(&classes.join(" ")));

        if let Some(width) = width {
            let _ = write!(open, " style=\"width: {width}%;\"");
        }

        open.push('>');
        self.out.line(&open);

        if let Some(title) = block.title() {
            let caption = block.caption().unwrap_or_default();
            self.out.line(&format!(
                "<caption class=\"title\">{caption}{title}</caption>"
            ));
        }

        self.colgroup(table);

        if let Some(header) = table.header_row() {
            self.out.line("<thead>");
            self.row(header, table.columns(), true);
            self.out.line("</thead>");
        }

        let body = table.body_rows();
        if !body.is_empty() {
            self.out.line("<tbody>");

            for row in body {
                self.row(row, table.columns(), false);
            }

            self.out.line("</tbody>");
        }

        if let Some(footer) = table.footer_row() {
            self.out.line("<tfoot>");
            self.row(footer, table.columns(), false);
            self.out.line("</tfoot>");
        }

        self.out.close("table");
    }

    /// Emit the `<colgroup>` that fixes the relative column widths.
    fn colgroup(&mut self, table: &'src TableBlock<'src>) {
        let columns = table.columns();

        if columns.is_empty() {
            return;
        }

        self.out.line("<colgroup>");

        // With autowidth there is nothing to distribute: the browser measures
        // the content itself.
        let total: usize = columns.iter().map(TableColumn::width).sum();

        // A single `~` column stops the row being a proportion of anything: the
        // measured columns then stand for the percentage they were written as,
        // and the rest is the browser's to divide.
        let mixed = columns.iter().any(TableColumn::is_autowidth);

        let mut shares: Vec<Option<u64>> = columns
            .iter()
            .map(|column| {
                if table.is_autowidth() || total == 0 || column.is_autowidth() {
                    None
                } else if mixed {
                    Some(percentage(column.width(), 100))
                } else {
                    Some(percentage(column.width(), total))
                }
            })
            .collect();

        // Rounding each share on its own leaves the row a hair short of, or
        // over, the full width. The last measured column absorbs the
        // difference, so the widths always add up to exactly 100% — which is
        // only meaningful when every column was measured.
        if !mixed {
            balance(&mut shares);
        }

        for share in shares {
            match share {
                None => self.out.line("<col>"),
                Some(share) => self
                    .out
                    .line(&format!("<col style=\"width: {}%;\">", trim_percent(share))),
            }
        }

        self.out.close("colgroup");
    }

    /// Emit one `<tr>`.
    fn row(&mut self, row: &'src TableRow<'src>, columns: &'src [TableColumn], is_header: bool) {
        self.out.line("<tr>");

        for (index, cell) in row.cells().iter().enumerate() {
            self.cell(cell, columns.get(index), is_header);
        }

        self.out.line("</tr>");
    }

    /// Emit one `<td>` or `<th>`.
    ///
    /// A cell inherits its alignment from its column unless it overrides it,
    /// and a cell whose style is `h` becomes a header cell wherever it appears.
    fn cell(
        &mut self,
        cell: &'src TableCell<'src>,
        column: Option<&'src TableColumn>,
        is_header: bool,
    ) {
        let style = cell.style();
        let header = is_header || style == ColumnStyle::Header;
        let tag = if header { "th" } else { "td" };

        let mut open = format!(
            "<{tag} class=\"tableblock halign-{} valign-{}\"",
            halign(cell.h_align(), column),
            valign(cell.v_align(), column)
        );

        if cell.colspan() > 1 {
            let _ = write!(open, " colspan=\"{}\"", cell.colspan());
        }

        if cell.rowspan() > 1 {
            let _ = write!(open, " rowspan=\"{}\"", cell.rowspan());
        }

        open.push('>');
        self.out.raw(&open);

        self.cell_content(cell, is_header);

        self.out.line(&format!("</{tag}>"));
    }

    /// Emit the inside of a cell, in whichever of the six cell styles applies.
    ///
    /// `in_header_row` is not the same question as whether the cell is a
    /// `<th>`: a cell in the header row carries its text bare, while an
    /// `h`-styled cell in the body is a `<th>` that still wraps its text
    /// like every other cell.
    fn cell_content(&mut self, cell: &'src TableCell<'src>, in_header_row: bool) {
        match cell.content() {
            TableCellContent::Simple(content) => {
                let rendered = content.rendered_html();

                // An empty cell stays empty rather than holding an empty
                // paragraph. A literal one is the exception: its `<pre>` is a
                // visible box, and the row would jump without it.
                if rendered.is_empty() && cell.style() != ColumnStyle::Literal {
                    return;
                }

                if in_header_row {
                    self.out.raw(rendered);
                    return;
                }

                // A literal cell is one box however many blank lines are in it;
                // every other style breaks into a paragraph apiece, the way the
                // same text would outside a table.
                if cell.style() == ColumnStyle::Literal {
                    self.out.raw(&format!(
                        "<div class=\"literal\"><pre>{rendered}</pre></div>"
                    ));
                    return;
                }

                let (open, close) = match cell.style() {
                    ColumnStyle::Emphasis => ("<em>", "</em>"),
                    ColumnStyle::Strong => ("<strong>", "</strong>"),
                    ColumnStyle::Monospace => ("<code>", "</code>"),
                    _ => ("", ""),
                };

                let wrapped: Vec<String> = paragraphs(rendered)
                    .into_iter()
                    .map(|paragraph| {
                        format!("<p class=\"tableblock\">{open}{paragraph}{close}</p>")
                    })
                    .collect();

                // Joined rather than each on its own line: the last one is
                // followed directly by the closing `</td>`.
                self.out.raw(&wrapped.join("\n"));
            }

            // An AsciiDoc cell is a document in its own right; its blocks
            // render exactly as they would at the top level. The wrapper hugs
            // them, opening on the `<td>`'s line and closing on the last
            // block's, so the cell reads as one run of markup.
            TableCellContent::AsciiDoc(nested) => {
                self.out.raw("<div class=\"content\">");
                self.blocks(nested.blocks().iter());
                self.out.unline();
                self.out.raw("</div>");
            }
        }
    }
}

/// The `frame-*` class for a table.
fn frame_class(frame: Frame) -> String {
    match frame {
        Frame::All => "frame-all",
        Frame::Ends => "frame-ends",
        Frame::Sides => "frame-sides",
        Frame::None => "frame-none",
    }
    .to_string()
}

/// The `grid-*` class for a table.
fn grid_class(grid: Grid) -> String {
    match grid {
        Grid::All => "grid-all",
        Grid::Rows => "grid-rows",
        Grid::Cols => "grid-cols",
        Grid::None => "grid-none",
    }
    .to_string()
}

/// The `stripes-*` class for a table, or `None` when it has no striping.
fn stripes_class(stripes: Stripes) -> Option<String> {
    match stripes {
        Stripes::None => None,
        Stripes::Even => Some("stripes-even".to_string()),
        Stripes::Odd => Some("stripes-odd".to_string()),
        Stripes::All => Some("stripes-all".to_string()),
        Stripes::Hover => Some("stripes-hover".to_string()),
    }
}

/// The effective horizontal alignment of a cell.
fn halign(cell: HorizontalAlignment, column: Option<&TableColumn>) -> &'static str {
    let alignment = if cell == HorizontalAlignment::Left {
        column.map_or(cell, TableColumn::h_align)
    } else {
        cell
    };

    match alignment {
        HorizontalAlignment::Center => "center",
        HorizontalAlignment::Right => "right",
        HorizontalAlignment::Left => "left",
    }
}

/// The effective vertical alignment of a cell.
fn valign(cell: VerticalAlignment, column: Option<&TableColumn>) -> &'static str {
    let alignment = if cell == VerticalAlignment::Top {
        column.map_or(cell, TableColumn::v_align)
    } else {
        cell
    };

    match alignment {
        VerticalAlignment::Middle => "middle",
        VerticalAlignment::Bottom => "bottom",
        VerticalAlignment::Top => "top",
    }
}

/// Split a cell's content into the paragraphs it was written as.
///
/// A blank line starts a new paragraph, exactly as it would outside a table; a
/// single newline is a soft wrap and stays where the author put it.
fn paragraphs(rendered: &str) -> Vec<String> {
    let mut paragraphs = Vec::new();
    let mut current: Vec<&str> = Vec::new();

    for line in rendered.lines() {
        if line.trim().is_empty() {
            if !current.is_empty() {
                paragraphs.push(current.join("\n"));
                current.clear();
            }
        } else {
            current.push(line);
        }
    }

    if !current.is_empty() {
        paragraphs.push(current.join("\n"));
    }

    paragraphs
}

/// A full column width: 100%, counted in the ten-thousandths of a percent that
/// [`percentage`] works in.
const FULL: u64 = 100 * 10_000;

/// One column's share of the total column width, in ten-thousandths of a
/// percent, rounded to nearest.
///
/// Percentages are carried as integers rather than floats so that a row of them
/// can be summed and [`balance`]d without rounding error creeping in.
fn percentage(width: usize, total: usize) -> u64 {
    let width = u64::try_from(width).unwrap_or(u64::MAX);
    let total = u64::try_from(total).unwrap_or(u64::MAX);

    if total == 0 {
        return 0;
    }

    // Saturating, because a nonsensically wide column should pin to the full
    // width rather than wrap around.
    let scaled = width.saturating_mul(FULL);

    // Truncated rather than rounded to nearest: Asciidoctor throws the last
    // digits away and lets `balance` hand the shortfall to the final column.
    scaled / total
}

/// Give the last measured column whatever the others' rounding left over, so
/// that the shares total exactly [`FULL`].
fn balance(shares: &mut [Option<u64>]) {
    let total: u64 = shares.iter().flatten().sum();

    let Some(last) = shares.iter_mut().flatten().next_back() else {
        return;
    };

    *last = last.saturating_add(FULL).saturating_sub(total);
}

/// Format a column width, dropping the trailing zeros a fixed precision leaves.
fn trim_percent(share: u64) -> String {
    let formatted = format!("{}.{:04}", share / 10_000, share % 10_000);
    let trimmed = formatted.trim_end_matches('0').trim_end_matches('.');

    trimmed.to_string()
}