|
| 1 | +use super::error::RendererError; |
| 2 | +use super::CustomComponent; |
| 3 | +use crate::custom_component_renderer::error::Result; |
| 4 | +use lol_html::html_content::ContentType; |
| 5 | +use lol_html::{element, RewriteStrSettings}; |
| 6 | +use mdbook::renderer::RenderContext; |
| 7 | +use serde_json::to_value; |
| 8 | +use std::collections::HashMap; |
| 9 | +use std::fs; |
| 10 | +use std::io::{Read, Write}; |
| 11 | +use std::path::{Path, PathBuf}; |
| 12 | +use std::sync::Arc; |
| 13 | + |
| 14 | +pub struct RenderingContext<'a> { |
| 15 | + pub path: PathBuf, |
| 16 | + pub language: Option<String>, |
| 17 | + pub serialized_ctx: &'a serde_json::Value, |
| 18 | + pub ctx: &'a RenderContext, |
| 19 | +} |
| 20 | + |
| 21 | +impl<'a> RenderingContext<'a> { |
| 22 | + fn new( |
| 23 | + path: PathBuf, |
| 24 | + language: Option<String>, |
| 25 | + serialized_ctx: &'a serde_json::Value, |
| 26 | + ctx: &'a RenderContext, |
| 27 | + ) -> Result<Self> { |
| 28 | + Ok(RenderingContext { |
| 29 | + path, |
| 30 | + language, |
| 31 | + serialized_ctx, |
| 32 | + ctx, |
| 33 | + }) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +pub(crate) struct BookDirectoryRenderer { |
| 38 | + ctx: Arc<RenderContext>, |
| 39 | + serialized_ctx: serde_json::Value, |
| 40 | + components: Vec<CustomComponent>, |
| 41 | +} |
| 42 | + |
| 43 | +impl BookDirectoryRenderer { |
| 44 | + pub(crate) fn new(ctx: RenderContext) -> Result<BookDirectoryRenderer> { |
| 45 | + Ok(BookDirectoryRenderer { |
| 46 | + serialized_ctx: serde_json::to_value(&ctx)?, |
| 47 | + ctx: Arc::new(ctx), |
| 48 | + components: Vec::new(), |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + pub(crate) fn render_book(&mut self) -> Result<()> { |
| 53 | + let dest_dir = &self |
| 54 | + .ctx |
| 55 | + .destination |
| 56 | + .parent() |
| 57 | + .ok_or_else(|| { |
| 58 | + RendererError::InvalidPath(format!( |
| 59 | + "Destination directory {:?} has no parent", |
| 60 | + self.ctx.destination |
| 61 | + )) |
| 62 | + })? |
| 63 | + .to_owned(); |
| 64 | + if !dest_dir.is_dir() { |
| 65 | + return Err(RendererError::InvalidPath(format!( |
| 66 | + "{:?} is not a directory", |
| 67 | + dest_dir |
| 68 | + ))); |
| 69 | + } |
| 70 | + self.render_book_directory(&dest_dir) |
| 71 | + } |
| 72 | + |
| 73 | + fn create_get_context_function(&self) -> impl tera::Function { |
| 74 | + let ctx_rx = Arc::clone(&self.ctx); |
| 75 | + move |args: &HashMap<String, serde_json::value::Value>| -> tera::Result<tera::Value> { |
| 76 | + let key = args |
| 77 | + .get("key") |
| 78 | + .ok_or_else(|| tera::Error::from(format!("No key argument provided")))? |
| 79 | + .as_str() |
| 80 | + .ok_or_else(|| { |
| 81 | + tera::Error::from(format!("Key has invalid type, expected string")) |
| 82 | + })?; |
| 83 | + let value = ctx_rx |
| 84 | + .config |
| 85 | + .get(key) |
| 86 | + .ok_or_else(|| tera::Error::from(format!("Could not find key {key} in config")))?; |
| 87 | + let value = to_value(value)?; |
| 88 | + Ok(value) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + pub(crate) fn add_component(&mut self, mut component: CustomComponent) { |
| 93 | + component.register_function("get_context", self.create_get_context_function()); |
| 94 | + self.components.push(component); |
| 95 | + } |
| 96 | + |
| 97 | + fn render_components(&mut self, file_content: &str, path: &Path) -> Result<String> { |
| 98 | + let rendering_context = RenderingContext::new( |
| 99 | + path.to_owned(), |
| 100 | + self.ctx.config.book.language.clone(), |
| 101 | + &self.serialized_ctx, |
| 102 | + &self.ctx, |
| 103 | + )?; |
| 104 | + let custom_components_handlers = self |
| 105 | + .components |
| 106 | + .iter() |
| 107 | + .map(|component| { |
| 108 | + element!(component.component_name(), |el| { |
| 109 | + let rendered = component.render(&rendering_context)?; |
| 110 | + el.replace(&rendered, ContentType::Html); |
| 111 | + Ok(()) |
| 112 | + }) |
| 113 | + }) |
| 114 | + .collect(); |
| 115 | + let output = lol_html::rewrite_str( |
| 116 | + file_content, |
| 117 | + RewriteStrSettings { |
| 118 | + element_content_handlers: custom_components_handlers, |
| 119 | + ..RewriteStrSettings::default() |
| 120 | + }, |
| 121 | + )?; |
| 122 | + Ok(output) |
| 123 | + } |
| 124 | + |
| 125 | + fn process_file(&mut self, path: &Path) -> Result<()> { |
| 126 | + if path.extension().unwrap_or_default() != "html" { |
| 127 | + return Ok(()); |
| 128 | + } |
| 129 | + let mut file_content = String::new(); |
| 130 | + { |
| 131 | + let mut file = fs::File::open(path)?; |
| 132 | + file.read_to_string(&mut file_content)?; |
| 133 | + } |
| 134 | + |
| 135 | + let output = self.render_components(&file_content, path)?; |
| 136 | + let mut output_file = fs::File::create(path)?; |
| 137 | + output_file.write_all(output.as_bytes())?; |
| 138 | + Ok(()) |
| 139 | + } |
| 140 | + |
| 141 | + fn render_book_directory(&mut self, path: &Path) -> Result<()> { |
| 142 | + for entry in path.read_dir()? { |
| 143 | + let entry = entry?; |
| 144 | + let path = entry.path(); |
| 145 | + if path.is_dir() { |
| 146 | + self.render_book_directory(&path)?; |
| 147 | + } else { |
| 148 | + self.process_file(&path)?; |
| 149 | + } |
| 150 | + } |
| 151 | + Ok(()) |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +#[cfg(test)] |
| 156 | +mod tests { |
| 157 | + use crate::custom_component_renderer::standard_templates; |
| 158 | + |
| 159 | + const FAKE_BOOK_TOML: &str = r#" |
| 160 | + [book] |
| 161 | + src = "src" |
| 162 | +
|
| 163 | + [rust] |
| 164 | + edition = "2021" |
| 165 | +
|
| 166 | + [build] |
| 167 | + extra-watch-dirs = ["po", "third_party"] |
| 168 | +
|
| 169 | + [preprocessor.gettext] |
| 170 | + after = ["links"] |
| 171 | +
|
| 172 | + [preprocessor.svgbob] |
| 173 | + renderers = ["html"] |
| 174 | + after = ["gettext"] |
| 175 | + class = "bob" |
| 176 | +
|
| 177 | + [output.html] |
| 178 | + curly-quotes = true |
| 179 | +
|
| 180 | + [output.i18n] |
| 181 | + default_language = "en" |
| 182 | + translate_all_languages = false |
| 183 | +
|
| 184 | + [output.i18n.languages] |
| 185 | + "en" = "English" |
| 186 | + "es" = "Spanish (Español)" |
| 187 | + "ko" = "Korean (한국어)" |
| 188 | + "pt-BR" = "Brazilian Portuguese (Português do Brasil)" |
| 189 | + "#; |
| 190 | + |
| 191 | + #[test] |
| 192 | + fn test_render_book() { |
| 193 | + use super::*; |
| 194 | + use std::fs::File; |
| 195 | + use tempfile::tempdir; |
| 196 | + |
| 197 | + const INITIAL_HTML: &[u8] = b"<html><body><LanguagePicker/></body></html>"; |
| 198 | + |
| 199 | + let dir = tempdir().unwrap(); |
| 200 | + std::fs::create_dir(dir.path().join("html")).expect("Failed to create html directory"); |
| 201 | + std::fs::create_dir(dir.path().join("src")).expect("Failed to create src directory"); |
| 202 | + |
| 203 | + std::fs::write(dir.path().join("html/test.html"), INITIAL_HTML) |
| 204 | + .expect("Failed to write initial html"); |
| 205 | + std::fs::write(dir.path().join("book.toml"), FAKE_BOOK_TOML) |
| 206 | + .expect("Failed to write initial book.toml"); |
| 207 | + std::fs::write(dir.path().join("src/SUMMARY.md"), "") |
| 208 | + .expect("Failed to write initial SUMMARY.md"); |
| 209 | + |
| 210 | + let mdbook = mdbook::MDBook::load(dir.path()).expect("Failed to load mdbook"); |
| 211 | + let ctx = RenderContext::new( |
| 212 | + dir.path(), |
| 213 | + mdbook.book, |
| 214 | + mdbook.config, |
| 215 | + dir.path().join("i18n-helpers"), |
| 216 | + ); |
| 217 | + |
| 218 | + let mut renderer = BookDirectoryRenderer::new(ctx).expect("Failed to create renderer"); |
| 219 | + renderer.add_component(standard_templates::create_language_picker_component()); |
| 220 | + renderer.render_book().expect("Failed to render book"); |
| 221 | + |
| 222 | + let mut output = String::new(); |
| 223 | + let mut file = File::open(dir.path().join("html/test.html")).unwrap(); |
| 224 | + file.read_to_string(&mut output).unwrap(); |
| 225 | + |
| 226 | + const EXPECTED: &str = "<html><body><button id=\"language-toggle0\" class=\"icon-button\" type=\"button\"\n title=\"Change language\" aria-label=\"Change language\"\n aria-haspopup=\"true\" aria-expanded=\"false\"\n aria-controls=\"language-list0\">\n <i class=\"fa fa-globe\"></i>\n</button>\n<ul id=\"language-list0\" class=\"theme-popup\" aria-label=\"Languages\"\n role=\"menu\" style=\"left: auto; right: 10px;\">\n \n <li role=\"none\">\n <a id=\"en\"\n href=\"/test.html\"\n style=\"color: inherit;\">\n <button role=\"menuitem\" class=\"theme theme-selected \">\n English\n </button>\n </a>\n </li>\n \n <li role=\"none\">\n <a id=\"es\"\n href=\"/es/test.html\"\n style=\"color: inherit;\">\n <button role=\"menuitem\" class=\"theme \">\n Spanish (Español)\n </button>\n </a>\n </li>\n \n <li role=\"none\">\n <a id=\"ko\"\n href=\"/ko/test.html\"\n style=\"color: inherit;\">\n <button role=\"menuitem\" class=\"theme \">\n Korean (한국어)\n </button>\n </a>\n </li>\n \n <li role=\"none\">\n <a id=\"pt-BR\"\n href=\"/pt-BR/test.html\"\n style=\"color: inherit;\">\n <button role=\"menuitem\" class=\"theme \">\n Brazilian Portuguese (Português do Brasil)\n </button>\n </a>\n </li>\n \n</ul>\n\n<script>\n let langToggle = document.getElementById(\"language-toggle0\");\n let langList = document.getElementById(\"language-list0\");\n \n langToggle.addEventListener(\"click\", (event) => {{\n langList.style.display = langList.style.display == \"block\" ? \"none\" : \"block\";\n }});\n \n</script>\n\n<style>\n [dir=rtl] #language-list0 {\n left: 10px;\n right: auto;\n }\n \n</style>\n</html>"; |
| 227 | + |
| 228 | + assert_eq!(output, EXPECTED); |
| 229 | + } |
| 230 | +} |
0 commit comments