|
| 1 | +use super::error::RendererError; |
| 2 | +use super::CustomComponent; |
| 3 | +use crate::tera_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::{BTreeMap, 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 Renderer { |
| 38 | + ctx: Arc<RenderContext>, |
| 39 | + serialized_ctx: serde_json::Value, |
| 40 | + components: Vec<CustomComponent>, |
| 41 | +} |
| 42 | + |
| 43 | +impl Renderer { |
| 44 | + pub(crate) fn new(ctx: RenderContext) -> Result<Renderer> { |
| 45 | + Ok(Renderer { |
| 46 | + serialized_ctx: serde_json::to_value(&ctx)?, |
| 47 | + ctx: Arc::new(ctx), |
| 48 | + components: Vec::new(), |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + pub(crate) fn add_component(&mut self, mut component: CustomComponent) { |
| 53 | + component.register_function("get_context", self.create_get_context_function()); |
| 54 | + self.components.push(component); |
| 55 | + } |
| 56 | + |
| 57 | + fn create_get_context_function(&self) -> impl tera::Function { |
| 58 | + let ctx_rx = Arc::clone(&self.ctx); |
| 59 | + move |args: &HashMap<String, serde_json::value::Value>| -> tera::Result<tera::Value> { |
| 60 | + let key = args |
| 61 | + .get("key") |
| 62 | + .ok_or_else(|| tera::Error::from(format!("No key argument provided")))? |
| 63 | + .as_str() |
| 64 | + .ok_or_else(|| { |
| 65 | + tera::Error::from(format!("Key has invalid type, expected string")) |
| 66 | + })?; |
| 67 | + let value = ctx_rx |
| 68 | + .config |
| 69 | + .get(key) |
| 70 | + .ok_or_else(|| tera::Error::from(format!("Could not find key {key} in config")))?; |
| 71 | + let value = to_value(value)?; |
| 72 | + Ok(value) |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + pub(crate) fn render_book(&mut self) -> Result<()> { |
| 77 | + let dest_dir = &self |
| 78 | + .ctx |
| 79 | + .destination |
| 80 | + .parent() |
| 81 | + .ok_or_else(|| { |
| 82 | + RendererError::InvalidPath(format!( |
| 83 | + "Destination directory {:?} has no parent", |
| 84 | + self.ctx.destination |
| 85 | + )) |
| 86 | + })? |
| 87 | + .to_owned(); |
| 88 | + if !dest_dir.is_dir() { |
| 89 | + return Err(RendererError::InvalidPath(format!( |
| 90 | + "{:?} is not a directory", |
| 91 | + dest_dir |
| 92 | + ))); |
| 93 | + } |
| 94 | + self.render_book_directory(&dest_dir) |
| 95 | + } |
| 96 | + |
| 97 | + fn render_book_directory(&mut self, path: &Path) -> Result<()> { |
| 98 | + for entry in path.read_dir()? { |
| 99 | + let entry = entry?; |
| 100 | + let path = entry.path(); |
| 101 | + if path.is_dir() { |
| 102 | + self.render_book_directory(&path)?; |
| 103 | + } else { |
| 104 | + self.process_file(&path)?; |
| 105 | + } |
| 106 | + } |
| 107 | + Ok(()) |
| 108 | + } |
| 109 | + |
| 110 | + fn process_file(&mut self, path: &Path) -> Result<()> { |
| 111 | + if path.extension().unwrap_or_default() != "html" { |
| 112 | + return Ok(()); |
| 113 | + } |
| 114 | + let mut file_content = String::new(); |
| 115 | + { |
| 116 | + let mut file = fs::File::open(path)?; |
| 117 | + file.read_to_string(&mut file_content)?; |
| 118 | + } |
| 119 | + |
| 120 | + let output = self.render_components(&file_content, path)?; |
| 121 | + let mut output_file = fs::File::create(path)?; |
| 122 | + output_file.write_all(output.as_bytes())?; |
| 123 | + Ok(()) |
| 124 | + } |
| 125 | + |
| 126 | + fn render_components(&mut self, file_content: &str, path: &Path) -> Result<String> { |
| 127 | + let rendering_context = RenderingContext::new( |
| 128 | + path.to_owned(), |
| 129 | + self.ctx.config.book.language.clone(), |
| 130 | + &self.serialized_ctx, |
| 131 | + &self.ctx, |
| 132 | + )?; |
| 133 | + let custom_components_handlers = self |
| 134 | + .components |
| 135 | + .iter() |
| 136 | + .map(|component| { |
| 137 | + element!(component.component_name(), |el| { |
| 138 | + let attributes: BTreeMap<String, String> = el |
| 139 | + .attributes() |
| 140 | + .iter() |
| 141 | + .map(|attribute| (attribute.name(), attribute.value())) |
| 142 | + .collect(); |
| 143 | + let rendered = component.render(&rendering_context, attributes)?; |
| 144 | + el.replace(&rendered, ContentType::Html); |
| 145 | + Ok(()) |
| 146 | + }) |
| 147 | + }) |
| 148 | + .collect(); |
| 149 | + let output = lol_html::rewrite_str( |
| 150 | + file_content, |
| 151 | + RewriteStrSettings { |
| 152 | + element_content_handlers: custom_components_handlers, |
| 153 | + ..RewriteStrSettings::default() |
| 154 | + }, |
| 155 | + )?; |
| 156 | + Ok(output) |
| 157 | + } |
| 158 | +} |
0 commit comments