mdbook/crates/mdbook-html/src/html_handlebars/helpers/toc.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

185 lines
6.2 KiB
Rust
Raw Normal View History

use crate::utils::ToUrlPath;
2024-01-04 20:16:34 +08:00
use handlebars::{
Context, Handlebars, Helper, HelperDef, Output, RenderContext, RenderError, RenderErrorReason,
};
Add a new HTML rendering pipeline This rewrites the HTML rendering pipeline to use a tree data structure, and implements a custom HTML serializer. The intent is to make it easier to make changes and to manipulate the output. This should make some future changes much easier. This is a large change, but I'll try to briefly summarize what's changing: - All of the HTML rendering support has been moved out of mdbook-markdown into mdbook-html. For now, all of the API surface is private, though we may consider ways to safely expose it in the future. - Instead of using pulldown-cmark's html serializer, this takes the pulldown-cmark events and translates them into a tree data structure (using the ego-tree crate to define the tree). See `tree.rs`. - HTML in the markdown document is parsed using html5ever, and then lives inside the same tree data structure. See `tokenizer.rs`. - Transformations are then applied to the tree data structure. For example, adding header links or hiding code lines. - Serialization is a simple process of writing out the nodes to a string. See `serialize.rs`. - The search indexer works on the tree structure instead of re-rendering every chapter twice. See `html_handlebars/search.rs`. - The print page now takes a very different approach of taking the same tree structure built for rendering the chapters, and applies transformations to it. This avoid re-parsing everything again. See `print.rs`. - I changed the linking behavior so that links on the print page link to items on the print page instead of outside the print page. - There are a variety of small changes to how it serializes as can be seen in the changes to the tests. Some highlights: - Code blocks no longer have a second layer of `<pre>` tags wrapping it. - Fixed a minor issue where a rust code block with a specific edition was having the wrong classes when there was a default edition. - Drops the ammonia dependency, which significantly reduces the number of dependencies. It was only being used for a very minor task, and we can handle it much more easily now. - Drops `pretty_assertions`, they are no longer used (mostly being migrated to the testsuite). There's obviously a lot of risk trying to parse everything to such a low level, but I think the benefits are worth it. Also, the API isn't super ergonomic compared to say javascript (there are no selectors), but it works well enough so far. I have not run this through rigorous benchmarking, but it does have a very noticeable performance improvement, especially in a debug build. I expect in the future that we'll want to expose some kind of integration with extensions so they have access to this tree structure (or some kind of tree structure). Closes https://github.com/rust-lang/mdBook/issues/1736
2025-09-16 20:14:00 -07:00
use mdbook_core::utils::escape_html_attribute;
use std::path::Path;
use std::{cmp::Ordering, collections::BTreeMap};
// Handlebars helper to construct TOC
#[derive(Clone, Copy)]
pub(crate) struct RenderToc {
pub no_section_label: bool,
}
impl HelperDef for RenderToc {
2018-08-05 15:08:47 +08:00
fn call<'reg: 'rc, 'rc>(
&self,
2024-01-04 20:16:34 +08:00
_h: &Helper<'rc>,
2020-01-24 11:01:44 +08:00
_r: &'reg Handlebars<'_>,
ctx: &'rc Context,
2020-01-24 11:01:44 +08:00
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
2018-08-05 15:08:47 +08:00
) -> Result<(), RenderError> {
// get value from context data
// rc.get_path() is current json parent path, you should always use it like this
// param is the key of value you want to display
2019-07-13 00:11:05 +08:00
let chapters = rc.evaluate(ctx, "@root/chapters").and_then(|c| {
serde_json::value::from_value::<Vec<BTreeMap<String, String>>>(c.as_json().clone())
2024-01-04 20:16:34 +08:00
.map_err(|_| {
RenderErrorReason::Other("Could not decode the JSON data".to_owned()).into()
})
})?;
let fold_enable = rc
.evaluate(ctx, "@root/fold_enable")?
.as_json()
.as_bool()
2024-01-04 20:16:34 +08:00
.ok_or_else(|| {
RenderErrorReason::Other("Type error for `fold_enable`, bool expected".to_owned())
})?;
let fold_level = rc
.evaluate(ctx, "@root/fold_level")?
.as_json()
.as_u64()
2024-01-04 20:16:34 +08:00
.ok_or_else(|| {
RenderErrorReason::Other("Type error for `fold_level`, u64 expected".to_owned())
})?;
// If true, then this is the iframe and we need target="_parent"
let is_toc_html = rc
.evaluate(ctx, "@root/is_toc_html")?
.as_json()
.as_bool()
.unwrap_or(false);
2018-08-05 15:08:47 +08:00
out.write("<ol class=\"chapter\">")?;
let mut current_level = 1;
let mut first = true;
2017-06-13 20:53:25 +08:00
for item in chapters {
let level = item
.get("section")
.map(|s| s.matches('.').count())
.unwrap_or(1);
// Expand if folding is disabled, or if levels that are larger than this would not
// be folded.
let is_expanded = !fold_enable || level - 1 < (fold_level as usize);
match level.cmp(&current_level) {
Ordering::Greater => {
// There is an assumption that when descending, it can
// only go one level down at a time. This should be
// enforced by the nature of markdown lists and the
// summary parser.
assert_eq!(level, current_level + 1);
current_level += 1;
out.write("<ol class=\"section\">")?;
write_li_open_tag(out, is_expanded)?;
}
Ordering::Less => {
while level < current_level {
out.write("</li>")?;
out.write("</ol>")?;
current_level -= 1;
}
write_li_open_tag(out, is_expanded)?;
}
Ordering::Equal => {
if !first {
out.write("</li>")?;
}
write_li_open_tag(out, is_expanded)?;
}
}
first = false;
2020-03-20 21:18:07 -05:00
// Spacer
if item.contains_key("spacer") {
out.write("<li class=\"spacer\"></li>")?;
continue;
}
2020-03-20 21:18:07 -05:00
// Part title
if let Some(title) = item.get("part") {
out.write("<li class=\"part-title\">")?;
Add a new HTML rendering pipeline This rewrites the HTML rendering pipeline to use a tree data structure, and implements a custom HTML serializer. The intent is to make it easier to make changes and to manipulate the output. This should make some future changes much easier. This is a large change, but I'll try to briefly summarize what's changing: - All of the HTML rendering support has been moved out of mdbook-markdown into mdbook-html. For now, all of the API surface is private, though we may consider ways to safely expose it in the future. - Instead of using pulldown-cmark's html serializer, this takes the pulldown-cmark events and translates them into a tree data structure (using the ego-tree crate to define the tree). See `tree.rs`. - HTML in the markdown document is parsed using html5ever, and then lives inside the same tree data structure. See `tokenizer.rs`. - Transformations are then applied to the tree data structure. For example, adding header links or hiding code lines. - Serialization is a simple process of writing out the nodes to a string. See `serialize.rs`. - The search indexer works on the tree structure instead of re-rendering every chapter twice. See `html_handlebars/search.rs`. - The print page now takes a very different approach of taking the same tree structure built for rendering the chapters, and applies transformations to it. This avoid re-parsing everything again. See `print.rs`. - I changed the linking behavior so that links on the print page link to items on the print page instead of outside the print page. - There are a variety of small changes to how it serializes as can be seen in the changes to the tests. Some highlights: - Code blocks no longer have a second layer of `<pre>` tags wrapping it. - Fixed a minor issue where a rust code block with a specific edition was having the wrong classes when there was a default edition. - Drops the ammonia dependency, which significantly reduces the number of dependencies. It was only being used for a very minor task, and we can handle it much more easily now. - Drops `pretty_assertions`, they are no longer used (mostly being migrated to the testsuite). There's obviously a lot of risk trying to parse everything to such a low level, but I think the benefits are worth it. Also, the API isn't super ergonomic compared to say javascript (there are no selectors), but it works well enough so far. I have not run this through rigorous benchmarking, but it does have a very noticeable performance improvement, especially in a debug build. I expect in the future that we'll want to expose some kind of integration with extensions so they have access to this tree structure (or some kind of tree structure). Closes https://github.com/rust-lang/mdBook/issues/1736
2025-09-16 20:14:00 -07:00
out.write(&escape_html_attribute(title))?;
2020-03-20 21:18:07 -05:00
out.write("</li>")?;
continue;
}
out.write("<span class=\"chapter-link-wrapper\">")?;
// Link
let path_exists = match item.get("path") {
Some(path) if !path.is_empty() => {
out.write("<a href=\"")?;
let tmp = Path::new(path).with_extension("html").to_url_path();
// Add link
out.write(&tmp)?;
out.write(if is_toc_html {
"\" target=\"_parent\">"
} else {
"\">"
})?;
true
}
_ => {
out.write("<span>")?;
false
}
};
if !self.no_section_label {
// Section does not necessarily exist
if let Some(section) = item.get("section") {
2018-08-05 15:08:47 +08:00
out.write("<strong aria-hidden=\"true\">")?;
out.write(section)?;
2018-08-05 15:08:47 +08:00
out.write("</strong> ")?;
}
}
if let Some(name) = item.get("name") {
Add a new HTML rendering pipeline This rewrites the HTML rendering pipeline to use a tree data structure, and implements a custom HTML serializer. The intent is to make it easier to make changes and to manipulate the output. This should make some future changes much easier. This is a large change, but I'll try to briefly summarize what's changing: - All of the HTML rendering support has been moved out of mdbook-markdown into mdbook-html. For now, all of the API surface is private, though we may consider ways to safely expose it in the future. - Instead of using pulldown-cmark's html serializer, this takes the pulldown-cmark events and translates them into a tree data structure (using the ego-tree crate to define the tree). See `tree.rs`. - HTML in the markdown document is parsed using html5ever, and then lives inside the same tree data structure. See `tokenizer.rs`. - Transformations are then applied to the tree data structure. For example, adding header links or hiding code lines. - Serialization is a simple process of writing out the nodes to a string. See `serialize.rs`. - The search indexer works on the tree structure instead of re-rendering every chapter twice. See `html_handlebars/search.rs`. - The print page now takes a very different approach of taking the same tree structure built for rendering the chapters, and applies transformations to it. This avoid re-parsing everything again. See `print.rs`. - I changed the linking behavior so that links on the print page link to items on the print page instead of outside the print page. - There are a variety of small changes to how it serializes as can be seen in the changes to the tests. Some highlights: - Code blocks no longer have a second layer of `<pre>` tags wrapping it. - Fixed a minor issue where a rust code block with a specific edition was having the wrong classes when there was a default edition. - Drops the ammonia dependency, which significantly reduces the number of dependencies. It was only being used for a very minor task, and we can handle it much more easily now. - Drops `pretty_assertions`, they are no longer used (mostly being migrated to the testsuite). There's obviously a lot of risk trying to parse everything to such a low level, but I think the benefits are worth it. Also, the API isn't super ergonomic compared to say javascript (there are no selectors), but it works well enough so far. I have not run this through rigorous benchmarking, but it does have a very noticeable performance improvement, especially in a debug build. I expect in the future that we'll want to expose some kind of integration with extensions so they have access to this tree structure (or some kind of tree structure). Closes https://github.com/rust-lang/mdBook/issues/1736
2025-09-16 20:14:00 -07:00
out.write(&escape_html_attribute(name))?;
}
if path_exists {
2018-08-05 15:08:47 +08:00
out.write("</a>")?;
} else {
out.write("</span>")?;
}
// Render expand/collapse toggle
if let Some(flag) = item.get("has_sub_items") {
let has_sub_items = flag.parse::<bool>().unwrap_or_default();
if fold_enable && has_sub_items {
// The <div> here is to manage rotating the element when
// the chapter title is long and word-wraps.
out.write("<a class=\"chapter-fold-toggle\"><div>❱</div></a>")?;
}
}
out.write("</span>")?;
}
while current_level > 0 {
2018-08-05 15:08:47 +08:00
out.write("</li>")?;
out.write("</ol>")?;
current_level -= 1;
}
Ok(())
}
}
fn write_li_open_tag(out: &mut dyn Output, is_expanded: bool) -> Result<(), std::io::Error> {
2020-04-03 12:09:23 -07:00
let mut li = String::from("<li class=\"chapter-item ");
if is_expanded {
li.push_str("expanded ");
}
li.push_str("\">");
out.write(&li)
}