Skip to content

Commit

Permalink
feat(templ): post process inline sidebar
Browse files Browse the repository at this point in the history
  • Loading branch information
fiji-flo committed Jul 3, 2024
1 parent c9a7591 commit 648becb
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 24 deletions.
18 changes: 14 additions & 4 deletions crates/rari-doc/src/docs/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ use super::title::{page_title, transform_title};
use crate::baseline::get_baseline;
use crate::error::DocError;
use crate::html::modifier::add_missing_ids;
use crate::html::rewriter::post_process_html;
use crate::html::sections::{split_sections, BuildSection, BuildSectionType};
use crate::html::sidebar::build_sidebars;
use crate::html::rewriter::{post_process_html, post_process_inline_sidebar};
use crate::html::sections::{split_sections, BuildSection, BuildSectionType, Splitted};
use crate::html::sidebar::{build_sidebars, expand_details_and_mark_current_for_inline_sidebar};
use crate::specs::extract_specifications;
use crate::templ::render::{decode_ref, render};

Expand Down Expand Up @@ -144,7 +144,17 @@ pub fn build_content<T: PageLike>(doc: &T) -> Result<PageContent, DocError> {
let post_processed_html = post_process_html(&html, doc, false)?;
let mut fragment = Html::parse_fragment(&post_processed_html);
add_missing_ids(&mut fragment)?;
let (sections, summary, sidebar) = split_sections(&fragment).expect("DOOM");
expand_details_and_mark_current_for_inline_sidebar(&mut fragment, doc.url())?;
let Splitted {
sections,
summary,
sidebar,
} = split_sections(&fragment).expect("DOOM");
let sidebar = if let Some(sidebar) = sidebar {
Some(post_process_inline_sidebar(&sidebar)?)
} else {
None
};
let toc = make_toc(&sections, matches!(doc.page_type(), PageType::Curriculum));
let body = sections.into_iter().map(Into::into).collect();
Ok(PageContent {
Expand Down
6 changes: 6 additions & 0 deletions crates/rari-doc/src/helpers/subpages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,17 @@ fn title_natural_sorter(a: &Page, b: &Page) -> Ordering {
natural_compare_with_floats(a.title(), b.title())
}

fn slug_natural_sorter(a: &Page, b: &Page) -> Ordering {
natural_compare_with_floats(a.slug(), b.slug())
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum SubPagesSorter {
#[default]
Title,
Slug,
TitleNatural,
SlugNatural,
}

impl SubPagesSorter {
Expand All @@ -40,6 +45,7 @@ impl SubPagesSorter {
SubPagesSorter::Title => title_sorter,
SubPagesSorter::Slug => slug_sorter,
SubPagesSorter::TitleNatural => title_natural_sorter,
SubPagesSorter::SlugNatural => slug_natural_sorter,
}
}
}
Expand Down
18 changes: 17 additions & 1 deletion crates/rari-doc/src/html/rewriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::borrow::Cow;
use std::collections::HashSet;

use lol_html::html_content::ContentType;
use lol_html::{element, text, HtmlRewriter, Settings};
use lol_html::{element, rewrite_str, text, HtmlRewriter, RewriteStrSettings, Settings};
use rari_md::bq::NoteCard;
use rari_types::fm_types::PageType;
use rari_types::locale::Locale;
Expand All @@ -14,6 +14,22 @@ use crate::error::DocError;
use crate::redirects::resolve_redirect;
use crate::resolve::strip_locale_from_url;

pub fn post_process_inline_sidebar(input: &str) -> Result<String, DocError> {
let element_content_handlers = vec![element!("*[data-rewriter=em]", |el| {
el.prepend("<em>", ContentType::Html);
el.append("</em>", ContentType::Html);
el.remove_attribute("data-rewriter");
Ok(())
})];
Ok(rewrite_str(
input,
RewriteStrSettings {
element_content_handlers,
..Default::default()
},
)?)
}

pub fn post_process_html<T: PageLike>(
input: &str,
page: &T,
Expand Down
18 changes: 13 additions & 5 deletions crates/rari-doc/src/html/sections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@ pub struct BuildSection<'a> {
pub id: Option<String>,
}

pub fn split_sections(
html: &Html,
) -> Result<(Vec<BuildSection<'_>>, Option<String>, Option<String>), DocError> {
pub struct Splitted<'a> {
pub sections: Vec<BuildSection<'a>>,
pub summary: Option<String>,
pub sidebar: Option<String>,
}

pub fn split_sections(html: &Html) -> Result<Splitted, DocError> {
let root_children = html.root_element().children();
let raw_sections = root_children;
let summary_selector = Selector::parse("p").unwrap();
Expand Down Expand Up @@ -107,7 +111,7 @@ pub fn split_sections(
if let Some(section) = maybe_section.take() {
sections.push(section);
}
let html = ElementRef::wrap(current).unwrap().html();
let html = ElementRef::wrap(current).unwrap().inner_html();
sidebar = Some(html)
}
_ => {
Expand Down Expand Up @@ -233,5 +237,9 @@ pub fn split_sections(
if let Some(section) = last.take() {
sections.push(section);
}
Ok((sections, summary, sidebar))
Ok(Splitted {
sections,
summary,
sidebar,
})
}
26 changes: 19 additions & 7 deletions crates/rari-doc/src/html/sidebar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,19 @@ type SidebarCache = Arc<RwLock<HashMap<Locale, HashMap<String, String>>>>;

static SIDEBAR_CACHE: Lazy<SidebarCache> = Lazy::new(|| Arc::new(RwLock::new(HashMap::new())));

fn expand_details_to_for_current(mut html: Html, url: &str) -> Result<String, DocError> {
pub fn expand_details_and_mark_current_for_inline_sidebar(
html: &mut Html,
url: &str,
) -> Result<(), DocError> {
let a_selector = Selector::parse(&format!("#Quick_links a[href=\"{url}\"]")).unwrap();
expand_details_and_mark_current(html, a_selector)
}
fn expand_details_and_mark_current_for_sidebar(html: &mut Html, url: &str) -> Result<(), DocError> {
let a_selector = Selector::parse(&format!("a[href=\"{url}\"]")).unwrap();
expand_details_and_mark_current(html, a_selector)
}

fn expand_details_and_mark_current(html: &mut Html, a_selector: Selector) -> Result<(), DocError> {
let mut details = vec![];
let mut parent_id = None;
if let Some(a) = html.select(&a_selector).next() {
Expand All @@ -52,19 +63,20 @@ fn expand_details_to_for_current(mut html: Html, url: &str) -> Result<String, Do
}
}
if let Some(parent_id) = parent_id {
add_attribute(&mut html, parent_id, "data-rewriter", "em");
add_attribute(html, parent_id, "data-rewriter", "em");
}
for details in details {
add_attribute(&mut html, details, "open", "");
add_attribute(html, details, "open", "");
}

Ok(html.html())
Ok(())
}

fn postprocess_sidebar(ks_rendered_sidebar: &str, doc: &Doc) -> Result<String, DocError> {
let fragment = Html::parse_fragment(ks_rendered_sidebar);
let pre_processed_html = expand_details_to_for_current(fragment, &doc.meta.url)?;
let post_processed_html = post_process_html(&pre_processed_html, doc, true)?;
let mut fragment = Html::parse_fragment(ks_rendered_sidebar);

expand_details_and_mark_current_for_sidebar(&mut fragment, &doc.meta.url)?;
let post_processed_html = post_process_html(&fragment.html(), doc, true)?;
Ok::<_, DocError>(post_processed_html)
}

Expand Down
9 changes: 2 additions & 7 deletions crates/rari-doc/src/templ/macros/listsubpages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@ use crate::error::DocError;
use crate::helpers::subpages::{self, SubPagesSorter};

/// List sub pages
///
/// Parameters:
/// $0 Base url
/// $1 Title
/// $3 Page types
#[rari_f]
pub fn list_sub_pages(
url: Option<String>,
Expand All @@ -29,8 +24,8 @@ pub fn list_sub_pages(
url,
env.locale,
Some(depth.map(|d| d.as_int() as usize).unwrap_or(1)),
reverse.map(|r| r.as_bool()).unwrap_or_default(),
Some(SubPagesSorter::TitleNatural),
reverse.map(|r| r.as_int() != 0).unwrap_or_default(), // Yes the old marco checks for == 0 not === 0.
Some(SubPagesSorter::SlugNatural),
&[],
)?;
out.push_str(if ordered { "</ol>" } else { "</ul>" });
Expand Down

0 comments on commit 648becb

Please sign in to comment.