Skip to main content

bpaf/buffer/
html.rs

1use crate::{
2    buffer::{
3        splitter::{split, Chunk},
4        Block, Skip, Style, Token,
5    },
6    Doc, OptionParser,
7};
8
9#[cfg(feature = "docgen")]
10use crate::{
11    buffer::{extract_sections, Info, Meta},
12    meta_help::render_help,
13    Parser,
14};
15
16#[inline(never)]
17#[cfg(feature = "docgen")]
18fn collect_html(app: String, meta: &Meta, info: &Info) -> Doc {
19    let mut sections = Vec::new();
20    let root = meta;
21    let mut path = vec![app];
22    extract_sections(root, info, &mut path, &mut sections);
23
24    let mut buf = Doc::default();
25
26    if sections.len() > 1 {
27        buf.token(Token::BlockStart(Block::Block));
28        buf.token(Token::BlockStart(Block::Header));
29        buf.text("Command summary");
30        buf.token(Token::BlockEnd(Block::Header));
31        buf.token(Token::BlockEnd(Block::Block));
32
33        // TODO - this defines forward references to sections which are rendered differently
34        // between html and markdown and never used in console...
35        for section in &sections {
36            buf.token(Token::BlockStart(Block::ItemBody));
37            buf.text(&format!(
38                "* [`{}`↴](#{})",
39                section.path.join(" "),
40                section.path.join("-").to_lowercase().replace(' ', "-"),
41            ));
42            buf.token(Token::BlockEnd(Block::ItemBody));
43        }
44    }
45
46    for section in sections {
47        buf.token(Token::BlockStart(Block::Header));
48        buf.text(&section.path.join(" ").to_string());
49        buf.token(Token::BlockEnd(Block::Header));
50
51        let b = render_help(
52            &section.path,
53            section.info,
54            section.meta,
55            &section.info.meta(),
56        );
57        buf.doc(&b);
58    }
59    buf
60}
61
62impl<T> OptionParser<T> {
63    /// Render command line documentation for the app into html/markdown mix
64    #[cfg(feature = "docgen")]
65    pub fn render_html(&self, app: impl Into<String>) -> String {
66        collect_html(app.into(), &self.inner.meta(), &self.info).render_html(true, false)
67    }
68
69    /// Render command line documentation for the app into Markdown
70    #[cfg(feature = "docgen")]
71    pub fn render_markdown(&self, app: impl Into<String>) -> String {
72        collect_html(app.into(), &self.inner.meta(), &self.info).render_markdown(true)
73    }
74}
75
76#[derive(Copy, Clone, Default)]
77pub(crate) struct Styles {
78    mono: bool,
79    bold: bool,
80    italic: bool,
81}
82impl From<Style> for Styles {
83    fn from(f: Style) -> Self {
84        match f {
85            Style::Literal => Styles {
86                bold: true,
87                mono: true,
88                italic: false,
89            },
90            Style::Metavar => Styles {
91                bold: false,
92                mono: true,
93                italic: true,
94            },
95            Style::Text => Styles {
96                bold: false,
97                mono: false,
98                italic: false,
99            },
100            Style::Emphasis | Style::Invalid => Styles {
101                mono: false,
102                bold: true,
103                italic: false,
104            },
105        }
106    }
107}
108
109fn change_style(res: &mut String, cur: &mut Styles, new: Styles) {
110    if cur.italic {
111        res.push_str("</i>");
112    }
113    if cur.bold {
114        res.push_str("</b>");
115    }
116    if cur.mono {
117        res.push_str("</tt>");
118    }
119    if new.mono {
120        res.push_str("<tt>");
121    }
122    if new.bold {
123        res.push_str("<b>");
124    }
125    if new.italic {
126        res.push_str("<i>");
127    }
128    *cur = new;
129}
130
131fn change_to_markdown_style(res: &mut String, cur: &mut Styles, new: Styles) {
132    if cur.mono {
133        res.push('`');
134    }
135
136    if cur.bold {
137        res.push_str("**");
138    }
139    if cur.italic {
140        res.push('_');
141    }
142    if new.italic {
143        res.push('_');
144    }
145    if new.bold {
146        res.push_str("**");
147    }
148    if new.mono {
149        res.push('`');
150    }
151    *cur = new;
152}
153
154/// Make it so new text is separated by an empty line
155fn blank_html_line(res: &mut String) {
156    if !(res.is_empty() || res.ends_with("<br>\n")) {
157        res.push_str("<br>\n");
158    }
159}
160
161/// Make it so new text is separated by an empty line
162fn blank_markdown_line(res: &mut String) {
163    if !(res.is_empty() || res.ends_with("\n\n")) {
164        res.push_str("\n\n");
165    }
166}
167
168/// Make it so new text is separated by an empty line
169fn new_markdown_line(res: &mut String) {
170    if !(res.is_empty() || res.ends_with('\n')) {
171        res.push('\n');
172    }
173}
174
175const CSS: &str = "
176<style>
177div.bpaf-doc {
178    padding: 14px;
179    background-color:var(--code-block-background-color);
180    font-family: \"Source Code Pro\", monospace;
181    margin-bottom: 0.75em;
182}
183div.bpaf-doc dt { margin-left: 1em; }
184div.bpaf-doc dd { margin-left: 3em; }
185div.bpaf-doc dl { margin-top: 0; padding-left: 1em; }
186div.bpaf-doc  { padding-left: 1em; }
187</style>";
188
189impl Doc {
190    #[doc(hidden)]
191    /// Render doc into html page, used by documentation sample generator
192    #[must_use]
193    pub fn render_html(&self, full: bool, include_css: bool) -> String {
194        let mut res = String::new();
195        let mut byte_pos = 0;
196        let mut cur_style = Styles::default();
197
198        // skip tracks text paragraphs, paragraphs starting from the section
199        // one are only shown when full is set to true
200        let mut skip = Skip::default();
201
202        // stack keeps track of the AST tree, mostly to be able to tell
203        // if we are rendering definition list or item list
204        let mut stack = Vec::new();
205
206        for token in self.tokens.iter().copied() {
207            match token {
208                Token::Text { bytes, style } => {
209                    let input = &self.payload[byte_pos..byte_pos + bytes];
210                    byte_pos += bytes;
211
212                    if skip.enabled() {
213                        continue;
214                    }
215
216                    change_style(&mut res, &mut cur_style, Styles::from(style));
217
218                    for chunk in split(input) {
219                        match chunk {
220                            Chunk::Raw(input, _) => {
221                                let input = input.replace('<', "&lt;").replace('>', "&gt;");
222                                res.push_str(&input);
223                            }
224                            Chunk::Paragraph => {
225                                if full {
226                                    res.push_str("<br>\n");
227                                } else {
228                                    skip.enable();
229                                    break;
230                                }
231                            }
232                            Chunk::LineBreak => res.push_str("<br>\n"),
233                        }
234                    }
235                }
236                Token::BlockStart(b) => {
237                    change_style(&mut res, &mut cur_style, Styles::default());
238                    match b {
239                        Block::Header => {
240                            blank_html_line(&mut res);
241                            res.push_str("# ");
242                        }
243                        Block::Section2 => {
244                            res.push_str("<div>\n");
245                        }
246                        Block::ItemTerm => res.push_str("<dt>"),
247                        Block::ItemBody => {
248                            if stack.last().copied() == Some(Block::DefinitionList) {
249                                res.push_str("<dd>");
250                            } else {
251                                res.push_str("<li>");
252                            }
253                        }
254                        Block::DefinitionList => {
255                            res.push_str("<dl>");
256                        }
257                        Block::Block => {
258                            res.push_str("<p>");
259                        }
260                        Block::Meta => todo!(),
261                        Block::Section3 | Block::Section4 => {
262                            res.push_str("<div style='padding-left: 0.5em'>")
263                        }
264                        Block::Mono | Block::TermRef => {}
265                        Block::InlineBlock => {
266                            skip.push();
267                        }
268                    }
269                    stack.push(b);
270                }
271                Token::BlockEnd(b) => {
272                    change_style(&mut res, &mut cur_style, Styles::default());
273                    stack.pop();
274                    match b {
275                        Block::Header => {
276                            blank_html_line(&mut res);
277                        }
278                        Block::Section2 => {
279                            res.push_str("</div>");
280                        }
281
282                        Block::InlineBlock => {
283                            skip.pop();
284                        }
285                        Block::ItemTerm => res.push_str("</dt>\n"),
286                        Block::ItemBody => {
287                            if stack.last().copied() == Some(Block::DefinitionList) {
288                                res.push_str("</dd>\n");
289                            } else {
290                                res.push_str("</li>\n");
291                            }
292                        }
293                        Block::DefinitionList => res.push_str("</dl>\n"),
294                        Block::Block => {
295                            res.push_str("</p>");
296                        }
297                        Block::Mono | Block::TermRef => {}
298                        Block::Section3 | Block::Section4 => res.push_str("</div>"),
299                        Block::Meta => todo!(),
300                    }
301                }
302            }
303        }
304        change_style(&mut res, &mut cur_style, Styles::default());
305        if include_css {
306            res.push_str(CSS);
307        }
308        res
309    }
310
311    /// Render doc into markdown document, used by documentation sample generator
312    #[must_use]
313    pub fn render_markdown(&self, full: bool) -> String {
314        let mut res = String::new();
315        let mut byte_pos = 0;
316        let mut cur_style = Styles::default();
317
318        let mut skip = Skip::default();
319        let mut empty_term = false;
320        let mut mono = 0;
321        let mut def_list = false;
322        let mut code_block = false;
323        let mut app_name_seen = false;
324        for (ix, token) in self.tokens.iter().copied().enumerate() {
325            match token {
326                Token::Text { bytes, style } => {
327                    let input = &self.payload[byte_pos..byte_pos + bytes];
328                    byte_pos += bytes;
329                    if skip.enabled() {
330                        continue;
331                    }
332
333                    change_to_markdown_style(&mut res, &mut cur_style, Styles::from(style));
334
335                    for chunk in split(input) {
336                        match chunk {
337                            Chunk::Raw(input, w) => {
338                                if w == Chunk::TICKED_CODE {
339                                    new_markdown_line(&mut res);
340                                    res.push_str("  ");
341                                    res.push_str(input);
342                                    res.push('\n');
343                                } else if w == Chunk::CODE {
344                                    if !code_block {
345                                        res.push_str("\n\n  ```text\n");
346                                    }
347                                    code_block = true;
348                                    res.push_str("  ");
349                                    res.push_str(input);
350                                    res.push('\n');
351                                } else {
352                                    if code_block {
353                                        res.push_str("\n  ```\n");
354                                        code_block = false;
355                                    }
356                                    if mono > 0 {
357                                        let input = input.replace('[', "\\[").replace(']', "\\]");
358                                        res.push_str(&input);
359                                    } else {
360                                        res.push_str(input);
361                                    }
362                                }
363                            }
364                            Chunk::Paragraph => {
365                                if full {
366                                    res.push_str("\n\n");
367                                    if def_list {
368                                        res.push_str("  ");
369                                    }
370                                } else {
371                                    skip.enable();
372                                    break;
373                                }
374                            }
375                            Chunk::LineBreak => res.push('\n'),
376                        }
377                    }
378
379                    if code_block {
380                        res.push_str("  ```\n");
381                        code_block = false;
382                    }
383                }
384                Token::BlockStart(b) => {
385                    change_to_markdown_style(&mut res, &mut cur_style, Styles::default());
386                    match b {
387                        Block::Header => {
388                            blank_markdown_line(&mut res);
389                            if app_name_seen {
390                                res.push_str("## ");
391                            } else {
392                                res.push_str("# ");
393                                app_name_seen = true;
394                            }
395                        }
396                        Block::Section2 => {
397                            res.push_str("");
398                        }
399                        Block::ItemTerm | Block::Section4 => {
400                            new_markdown_line(&mut res);
401                            empty_term = matches!(
402                                self.tokens.get(ix + 1),
403                                Some(Token::BlockEnd(Block::ItemTerm))
404                            );
405                            res.push_str(if empty_term { "  " } else { "- " });
406                        }
407                        Block::ItemBody => {
408                            if def_list {
409                                res.push_str(if empty_term { " " } else { " &mdash; " });
410                            }
411                            new_markdown_line(&mut res);
412                            res.push_str("  ");
413                        }
414                        Block::DefinitionList => {
415                            def_list = true;
416                            res.push_str("");
417                        }
418                        Block::Block => {
419                            res.push('\n');
420                        }
421                        Block::Meta => todo!(),
422                        Block::Mono => {
423                            mono += 1;
424                        }
425                        Block::Section3 => res.push_str("### "),
426                        Block::TermRef => {}
427                        Block::InlineBlock => {
428                            skip.push();
429                        }
430                    }
431                }
432                Token::BlockEnd(b) => {
433                    change_to_markdown_style(&mut res, &mut cur_style, Styles::default());
434                    match b {
435                        Block::Header
436                        | Block::Block
437                        | Block::Section3
438                        | Block::Section2
439                        | Block::Section4 => {
440                            res.push('\n');
441                        }
442
443                        Block::InlineBlock => {
444                            skip.pop();
445                        }
446                        Block::ItemTerm | Block::TermRef => {}
447                        Block::ItemBody => {
448                            if def_list {
449                                res.push('\n');
450                            }
451                        }
452                        Block::DefinitionList => {
453                            def_list = false;
454                            res.push('\n');
455                        }
456                        Block::Mono => {
457                            mono -= 1;
458                        }
459                        Block::Meta => todo!(),
460                    }
461                }
462            }
463        }
464        change_to_markdown_style(&mut res, &mut cur_style, Styles::default());
465        res
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472
473    #[test]
474    fn transitions_are_okay() {
475        let mut doc = Doc::default();
476
477        doc.emphasis("Usage: "); // bold
478        doc.literal("my_program"); // bold + tt
479
480        let r = doc.render_html(true, false);
481
482        assert_eq!(r, "<b>Usage: </b><tt><b>my_program</b></tt>")
483    }
484}