fix manual header links

This commit is contained in:
Mylloon 2024-12-15 19:47:37 +01:00
parent 519236a561
commit 2df93e5c99
Signed by: Anri
GPG key ID: A82D63DFF8D1317F

View file

@ -59,19 +59,7 @@ pub fn get_options(path: Option<FilePath>, metadata_type: MType) -> ComrakOption
.autolink(true)
.tasklist(true)
.superscript(true)
.header_ids(match path {
Some(ref fp) => {
format!(
"{}-",
fp.path
.get(..fp.path.len() - 3)
.unwrap_or_default()
.replace([' ', '/'], "-")
.to_lowercase()
)
}
None => String::new(),
})
.header_ids(path_to_hid(path.as_ref()))
.footnotes(true)
.description_lists(true)
.front_matter_delimiter("---".into())
@ -151,6 +139,23 @@ pub fn get_options(path: Option<FilePath>, metadata_type: MType) -> ComrakOption
}
}
/// Transform the path to something usable for header IDs
fn path_to_hid(path: Option<&FilePath>) -> String {
match path {
Some(fp) => {
format!(
"{}-",
fp.path
.get(..fp.path.len() - 3)
.unwrap_or_default()
.replace([' ', '/'], "-")
.to_lowercase()
)
}
None => String::new(),
}
}
/// Resize images if needed
fn custom_img_size(html: &str) -> String {
rewrite_str(
@ -199,7 +204,7 @@ fn custom_img_size(html: &str) -> String {
.unwrap()
}
fn fix_headers_ids(html: &str) -> String {
fn fix_headers_ids(html: &str, path: Option<&FilePath>) -> String {
rewrite_str(
html,
RewriteStrSettings {
@ -208,11 +213,15 @@ fn fix_headers_ids(html: &str) -> String {
element_content_handlers: vec![element!(
"a:not(.footnote-ref):not(.footnote-backref)[href^='#']",
|el| {
// TODO: Link without IDs are link manually created to a header
// Currently, this breaks them
if let Some(id) = el.get_attribute("id") {
/// Remove the first character of a string
fn remove_anchor(s: &str) -> &str {
s.chars().next().map(|c| &s[c.len_utf8()..]).unwrap()
}
let id = el.get_attribute("id").unwrap_or(
path_to_hid(path) + remove_anchor(&el.get_attribute("href").unwrap()),
);
el.set_attribute("href", &format!("#{id}")).unwrap();
};
Ok(())
}
)],
@ -340,7 +349,7 @@ pub fn read_md(
(html_content, children_metadata) =
fix_images_and_integration(path, &html_content, metadata_type, recursive);
html_content = custom_img_size(&html_content);
html_content = fix_headers_ids(&html_content);
html_content = fix_headers_ids(&html_content, Some(path));
(html_content, mail_obfsucated) = mail_obfuscation(&html_content);
let mut final_metadata = Metadata {