mdbook/crates/mdbook-html/src/utils.rs

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

136 lines
4.5 KiB
Rust
Raw Permalink Normal View History

//! Utilities for processing HTML.
use std::collections::HashSet;
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 std::path::{Component, Path, PathBuf};
/// Utility function to normalize path elements like `..`.
pub(crate) fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(Component::RootDir);
}
Component::CurDir => {}
Component::ParentDir => {
if ret.ends_with(Component::ParentDir) {
ret.push(Component::ParentDir);
} else {
let popped = ret.pop();
if !popped && !ret.has_root() {
ret.push(Component::ParentDir);
}
}
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
/// Helper trait for converting a [`Path`] to a string suitable for an HTML path.
pub(crate) trait ToUrlPath {
fn to_url_path(&self) -> String;
}
impl ToUrlPath for Path {
fn to_url_path(&self) -> String {
// We're generally assuming that all paths we deal with are utf-8.
// The replace here is to handle Windows paths.
self.to_str().unwrap().replace('\\', "/")
}
}
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
/// Make sure an HTML id is unique.
///
/// Keeps a set of all previously returned IDs; if the requested id is already
/// used, numeric suffixes (-1, -2, ...) are tried until an unused one is found.
pub(crate) fn unique_id(id: &str, used: &mut HashSet<String>) -> String {
if used.insert(id.to_string()) {
return id.to_string();
}
// This ID is already in use. Generate one that is not by appending a
// numeric suffix.
let mut counter: u32 = 1;
loop {
let candidate = format!("{id}-{counter}");
if used.insert(candidate.clone()) {
return candidate;
}
counter += 1;
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
}
}
/// Generates an HTML id from the given text.
pub(crate) fn id_from_content(content: &str) -> String {
// This is intended to be close to how header ID generation is done in
// other sites and tools, but is not 100% the same. Not all sites and
// tools use the same algorithm. See these for more information:
//
// - https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#section-links
// - https://docs.gitlab.com/user/markdown/#heading-ids-and-links
// - https://pandoc.org/MANUAL.html#extension-auto_identifiers
// - https://kramdown.gettalong.org/converter/html#auto-ids
// - https://docs.rs/comrak/latest/comrak/options/struct.Extension.html#structfield.header_ids
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
content
.trim()
.to_lowercase()
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
.chars()
.filter_map(|ch| {
if ch.is_alphanumeric() || ch == '_' || ch == '-' {
Some(ch)
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
} else if ch.is_whitespace() {
Some('-')
} else {
None
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_generates_unique_ids() {
let mut id_counter = Default::default();
assert_eq!(unique_id("", &mut id_counter), "");
assert_eq!(unique_id("Über", &mut id_counter), "Über");
assert_eq!(unique_id("Über", &mut id_counter), "Über-1");
assert_eq!(unique_id("Über", &mut id_counter), "Über-2");
}
#[test]
fn it_normalizes_ids() {
assert_eq!(
id_from_content("`--passes`: add more rustdoc passes"),
"--passes-add-more-rustdoc-passes"
);
assert_eq!(
id_from_content("Method-call 🐙 expressions \u{1f47c}"),
"method-call--expressions-"
);
assert_eq!(id_from_content("_-_12345"), "_-_12345");
assert_eq!(id_from_content("12345"), "12345");
assert_eq!(id_from_content("中文"), "中文");
assert_eq!(id_from_content("にほんご"), "にほんご");
assert_eq!(id_from_content("한국어"), "한국어");
assert_eq!(id_from_content(""), "");
assert_eq!(id_from_content("中文標題 CJK title"), "中文標題-cjk-title");
assert_eq!(id_from_content("Über"), "über");
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
}
}