Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,10 @@ impl MDBook {
let mut index = File::create(themedir.join("index.hbs"))?;
index.write_all(theme::INDEX)?;

// toc.hbs
let mut toc = File::create(themedir.join("toc.hbs"))?;
toc.write_all(theme::TOC)?;

// book.css
let mut css = File::create(themedir.join("book.css"))?;
css.write_all(theme::CSS)?;
Expand Down
182 changes: 140 additions & 42 deletions src/renderer/html_handlebars/hbs_renderer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use renderer::html_handlebars::helpers;
use renderer::html_handlebars::toc_json;
use preprocess;
use renderer::Renderer;
use book::MDBook;
Expand All @@ -23,6 +24,12 @@ use serde_json;
#[derive(Default)]
pub struct HtmlHandlebars;

fn register_hbs_helpers(handlebars: &mut Handlebars) {
handlebars.register_helper("link", Box::new(helpers::toc::link));
handlebars.register_helper("previous", Box::new(helpers::navigation::previous));
handlebars.register_helper("next", Box::new(helpers::navigation::next));
}

impl HtmlHandlebars {
pub fn new() -> Self {
HtmlHandlebars
Expand Down Expand Up @@ -215,12 +222,6 @@ impl HtmlHandlebars {
json!(utils::fs::path_to_root(Path::new("print.md"))));
}

fn register_hbs_helpers(&self, handlebars: &mut Handlebars) {
handlebars.register_helper("toc", Box::new(helpers::toc::RenderToc));
handlebars.register_helper("previous", Box::new(helpers::navigation::previous));
handlebars.register_helper("next", Box::new(helpers::navigation::next));
}

/// Copy across any additional CSS and JavaScript files which the book
/// has been configured to use.
fn copy_additional_css_and_js(&self, book: &MDBook) -> Result<()> {
Expand Down Expand Up @@ -255,9 +256,10 @@ impl Renderer for HtmlHandlebars {

debug!("[*]: Register handlebars template");
handlebars.register_template_string("index", String::from_utf8(theme.index.clone())?)?;
handlebars.register_template_string("toc", String::from_utf8(theme.toc.clone())?)?;

debug!("[*]: Register handlebars helpers");
self.register_hbs_helpers(&mut handlebars);
register_hbs_helpers(&mut handlebars);

let mut data = make_data(book, &book.config)?;

Expand Down Expand Up @@ -315,6 +317,56 @@ impl Renderer for HtmlHandlebars {
}
}

fn make_chapter(
item: &Chapter,
section: Option<String>,
previous: Option<&mut BTreeMap<String, String>>)
-> Result<BTreeMap<String, String>> {
let mut chapter = BTreeMap::new();

if let Some(section) = section {
chapter.insert("section".to_owned(), section);
}

chapter.insert("name".to_owned(), item.name.to_owned());

let path = item.path.to_str().chain_err(|| "Could not convert path to str")?;
chapter.insert("path".to_owned(), path.to_owned());

previous.map(|previous| {
previous.insert("next_path".to_owned(), path.to_owned());
if let Some(previous_path) = previous.get("path") {
chapter.insert("previous_path".to_owned(), previous_path.to_owned());
}
});

Ok(chapter)
}

fn make_chapters(book: &MDBook) -> Result<Vec<BTreeMap<String, String>>> {
let mut chapters: Vec<BTreeMap<String, String>> = vec![];

for item in book.iter() {
let chapter = match *item {
BookItem::Affix(ref ch) => {
make_chapter(ch, None, chapters.last_mut())?
}
BookItem::Chapter(ref s, ref ch) => {
make_chapter(ch, Some(s.to_owned()), chapters.last_mut())?
}
BookItem::Spacer => {
let mut chapter = BTreeMap::new();
chapter.insert("spacer".to_owned(), "_spacer_".to_owned());
chapter
}
};

chapters.push(chapter);
};

Ok(chapters)
}

fn make_data(book: &MDBook, config: &Config) -> Result<serde_json::Map<String, serde_json::Value>> {
debug!("[fn]: make_data");
let html = config.html_config().unwrap_or_default();
Expand Down Expand Up @@ -381,41 +433,8 @@ fn make_data(book: &MDBook, config: &Config) -> Result<serde_json::Map<String, s
json!("theme-tomorrow_night.js"));
}

let mut chapters = vec![];

for item in book.iter() {
// Create the data to inject in the template
let mut chapter = BTreeMap::new();

match *item {
BookItem::Affix(ref ch) => {
chapter.insert("name".to_owned(), json!(ch.name));
let path = ch.path.to_str().ok_or_else(|| {
io::Error::new(io::ErrorKind::Other,
"Could not convert path \
to str")
})?;
chapter.insert("path".to_owned(), json!(path));
}
BookItem::Chapter(ref s, ref ch) => {
chapter.insert("section".to_owned(), json!(s));
chapter.insert("name".to_owned(), json!(ch.name));
let path = ch.path.to_str().ok_or_else(|| {
io::Error::new(io::ErrorKind::Other,
"Could not convert path \
to str")
})?;
chapter.insert("path".to_owned(), json!(path));
}
BookItem::Spacer => {
chapter.insert("spacer".to_owned(), json!("_spacer_"));
}
}

chapters.push(chapter);
}

data.insert("chapters".to_owned(), json!(chapters));
let chapters = make_chapters(book)?;
data.insert("toc".to_owned(), toc_json::make_toc_tree(chapters.as_slice())?);

debug!("[*]: JSON constructed");
Ok(data)
Expand Down Expand Up @@ -671,4 +690,83 @@ mod tests {
assert_eq!(id_from_content("## Method-call expressions"),
"method-call-expressions");
}

#[test]
fn toc_html() {
let template =
"{{#with toc}}
{{> toc}}
{{/with}}";

let toc = json!({
"children": [
{
"name": "Introduction",
"section": "1.",
"link": "intro.html",
"next": {
"link": "start.html"
},
"children": [
{
"name": "Getting started",
"section": "1.1.",
"link": "start.html",
"previous": {
"link": "intro.html"
},
"next": {
"link": "indepth.html"
}
}
]
},
{
"name": "In depth",
"section": "2.",
"link": "indepth.html",
"previous": {
"link": "start.html"
}
}
]
});

let expected = r#"
<li>
<a href="intro.html">
<strong>1.</strong>
Introduction
</a>
</li>
<ul class="section">
<li>
<a class="active" href="start.html">
<strong>1.1.</strong>
Getting started
</a>
</li>
</ul>
<li>
<a href="indepth.html">
<strong>2.</strong>
In depth
</a>
</li>
"#;

let mut handlebars = Handlebars::new();
let data = json!({
"toc": toc,
"path": "start.html"
});

register_hbs_helpers(&mut handlebars);
handlebars.register_template_string("toc", String::from_utf8(theme::TOC.to_owned()).unwrap()).unwrap();

let rendered = handlebars.template_render(template, &data).unwrap();

assert!(rendered.split_whitespace().eq(expected.split_whitespace()),
"rendered:\n{}\nexpected:\n{}", rendered, expected);
}
}
Loading