Skip to content

Commit c71891c

Browse files
committed
Make print page (print.html) links link to anchors on the print page
Let all the anchors id on the print page to have a path id prefix to help locate. e.g. bar/foo.md#abc -> #bar-foo-abc Also append a dummy div to the start of the original page to make sure that original page links without an anchor can also be located. Fix to remove all the `./` in the normalized path id so that for "./foo/bar.html#abc" we still get "#foo-bar-abc" Add support for redirect link anchors in print page so that anchors can also be redirected, also handle URL redirect links on print page Handle all the elements id to add a path prefix, also make path id to all be the lower case Fix for print page footnote links by adding the path id prefix Signed-off-by: Hollow Man <[email protected]>
1 parent 92e5082 commit c71891c

File tree

3 files changed

+374
-69
lines changed

3 files changed

+374
-69
lines changed

src/renderer/html_handlebars/hbs_renderer.rs

+80-7
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,11 @@ impl HtmlHandlebars {
5959

6060
let content = utils::render_markdown(&ch.content, ctx.html_config.smart_punctuation());
6161

62-
let fixed_content = utils::render_markdown_with_path(
62+
let printed_item = utils::render_markdown_with_path_and_redirects(
6363
&ch.content,
6464
ctx.html_config.smart_punctuation(),
6565
Some(path),
66+
&ctx.html_config.redirect,
6667
);
6768
if !ctx.is_index && ctx.html_config.print.page_break {
6869
// Add page break between chapters
@@ -71,7 +72,25 @@ impl HtmlHandlebars {
7172
print_content
7273
.push_str(r#"<div style="break-before: page; page-break-before: always;"></div>"#);
7374
}
74-
print_content.push_str(&fixed_content);
75+
let print_page_id = {
76+
let mut base = path.display().to_string();
77+
if base.ends_with(".md") {
78+
base.truncate(base.len() - 3);
79+
}
80+
&base
81+
.replace("/", "-")
82+
.replace("\\", "-")
83+
.to_ascii_lowercase()
84+
};
85+
86+
// We have to build header links in advance so that we can know the ranges
87+
// for the headers in one page.
88+
// Insert a dummy div to make sure that we can locate the specific page.
89+
print_content.push_str(&(format!(r#"<div id="{print_page_id}"></div>"#)));
90+
print_content.push_str(&build_header_links(
91+
&build_print_element_id(&printed_item, &print_page_id),
92+
Some(print_page_id),
93+
));
7594

7695
// Update the context with data for this file
7796
let ctx_path = path
@@ -216,7 +235,23 @@ impl HtmlHandlebars {
216235
code_config: &Code,
217236
edition: Option<RustEdition>,
218237
) -> String {
219-
let rendered = build_header_links(&rendered);
238+
let rendered = build_header_links(&rendered, None);
239+
let rendered = self.post_process_common(rendered, &playground_config, code_config, edition);
240+
241+
rendered
242+
}
243+
244+
/// Applies some post-processing to the HTML to apply some adjustments.
245+
///
246+
/// This common function is used for both normal chapters (via
247+
/// `post_process`) and the combined print page.
248+
fn post_process_common(
249+
&self,
250+
rendered: String,
251+
playground_config: &Playground,
252+
code_config: &Code,
253+
edition: Option<RustEdition>,
254+
) -> String {
220255
let rendered = fix_code_blocks(&rendered);
221256
let rendered = add_playground_pre(&rendered, playground_config, edition);
222257
let rendered = hide_lines(&rendered, code_config);
@@ -465,7 +500,7 @@ impl Renderer for HtmlHandlebars {
465500
debug!("Render template");
466501
let rendered = handlebars.render("index", &data)?;
467502

468-
let rendered = self.post_process(
503+
let rendered = self.post_process_common(
469504
rendered,
470505
&html_config.playground,
471506
&html_config.code,
@@ -661,9 +696,34 @@ fn make_data(
661696
Ok(data)
662697
}
663698

699+
/// Go through the rendered print page HTML,
700+
/// add path id prefix to all the elements id as well as footnote links.
701+
fn build_print_element_id(html: &str, print_page_id: &str) -> String {
702+
static ALL_ID: Lazy<Regex> = Lazy::new(|| Regex::new(r#"(<[^>]*?id=")([^"]+?)""#).unwrap());
703+
static FOOTNOTE_ID: Lazy<Regex> = Lazy::new(|| {
704+
Regex::new(
705+
r##"(<sup [^>]*?class="footnote-reference"[^>]*?>[^<]*?<a [^>]*?href="#)([^"]+?)""##,
706+
)
707+
.unwrap()
708+
});
709+
710+
let temp_html = ALL_ID.replace_all(html, |caps: &Captures<'_>| {
711+
format!("{}{}-{}\"", &caps[1], print_page_id, &caps[2])
712+
});
713+
714+
FOOTNOTE_ID
715+
.replace_all(&temp_html, |caps: &Captures<'_>| {
716+
format!("{}{}-{}\"", &caps[1], print_page_id, &caps[2])
717+
})
718+
.into_owned()
719+
}
720+
664721
/// Goes through the rendered HTML, making sure all header tags have
665722
/// an anchor respectively so people can link to sections directly.
666-
fn build_header_links(html: &str) -> String {
723+
///
724+
/// `print_page_id` should be set to the print page ID prefix when adjusting the
725+
/// print page.
726+
fn build_header_links(html: &str, print_page_id: Option<&str>) -> String {
667727
static BUILD_HEADER_LINKS: Lazy<Regex> = Lazy::new(|| {
668728
Regex::new(r#"<h(\d)(?: id="([^"]+)")?(?: class="([^"]+)")?>(.*?)</h\d>"#).unwrap()
669729
});
@@ -692,21 +752,34 @@ fn build_header_links(html: &str) -> String {
692752
caps.get(2).map(|x| x.as_str().to_string()),
693753
caps.get(3).map(|x| x.as_str().to_string()),
694754
&mut id_counter,
755+
print_page_id,
695756
)
696757
})
697758
.into_owned()
698759
}
699760

700761
/// Insert a single link into a header, making sure each link gets its own
701762
/// unique ID by appending an auto-incremented number (if necessary).
763+
///
764+
/// For `print.html`, we will add a path id prefix.
702765
fn insert_link_into_header(
703766
level: usize,
704767
content: &str,
705768
id: Option<String>,
706769
classes: Option<String>,
707770
id_counter: &mut HashMap<String, usize>,
771+
print_page_id: Option<&str>,
708772
) -> String {
709-
let id = id.unwrap_or_else(|| utils::unique_id_from_content(content, id_counter));
773+
let id = if let Some(print_page_id) = print_page_id {
774+
let content_id = {
775+
#[allow(deprecated)]
776+
utils::id_from_content(content)
777+
};
778+
let with_prefix = format!("{} {}", print_page_id, content_id);
779+
id.unwrap_or_else(|| utils::unique_id_from_content(&with_prefix, id_counter))
780+
} else {
781+
id.unwrap_or_else(|| utils::unique_id_from_content(content, id_counter))
782+
};
710783
let classes = classes
711784
.map(|s| format!(" class=\"{s}\""))
712785
.unwrap_or_default();
@@ -983,7 +1056,7 @@ mod tests {
9831056
];
9841057

9851058
for (src, should_be) in inputs {
986-
let got = build_header_links(src);
1059+
let got = build_header_links(src, None);
9871060
assert_eq!(got, should_be);
9881061
}
9891062
}

0 commit comments

Comments
 (0)