65 lines
1.8 KiB
Rust
65 lines
1.8 KiB
Rust
//! File rendering: code highlighting and markdown.
|
|
|
|
use crate::config::Config;
|
|
|
|
use linemd::Parser;
|
|
|
|
pub struct Renderer {
|
|
hl_registry: giallo::Registry,
|
|
}
|
|
|
|
impl Renderer {
|
|
pub fn new() -> Self {
|
|
let mut hl_registry = giallo::Registry::builtin().unwrap();
|
|
hl_registry.link_grammars();
|
|
Self { hl_registry }
|
|
}
|
|
pub fn render(
|
|
&self,
|
|
config: &Config,
|
|
filetype: &str,
|
|
content: &[u8],
|
|
pretty: bool,
|
|
repo_hash_str: &str,
|
|
file_path: &str,
|
|
) -> String {
|
|
if config.image_extensions.contains_key(filetype) {
|
|
return format!(
|
|
r#"<img alt="No description" src="/inline/{repo_hash_str}/{file_path}"/>"#
|
|
);
|
|
} else if config.video_extensions.contains_key(filetype) {
|
|
return format!(r#"<video src="/inline/{repo_hash_str}/{file_path}"></video>"#);
|
|
} else if config.audio_extensions.contains_key(filetype) {
|
|
return format!(r#"<audio src="/inline/{repo_hash_str}/{file_path}"></audio>"#);
|
|
}
|
|
let Ok(content) = str::from_utf8(content) else {
|
|
return String::from("Cannot render file as it is not valid UTF-8.");
|
|
};
|
|
if pretty && filetype == "md" {
|
|
linemd::render_as_html(content.parse_md())
|
|
} else {
|
|
let hl_options = giallo::HighlightOptions::new(
|
|
filetype,
|
|
giallo::ThemeVariant::Single("catppuccin-frappe"),
|
|
);
|
|
let highlighted = self
|
|
.hl_registry
|
|
.highlight(content, &hl_options)
|
|
.unwrap_or_else(|_e| {
|
|
// If extension is unknown
|
|
let hl_options = giallo::HighlightOptions::new(
|
|
giallo::PLAIN_GRAMMAR_NAME,
|
|
giallo::ThemeVariant::Single("catppuccin-frappe"),
|
|
);
|
|
self.hl_registry.highlight(content, &hl_options).unwrap()
|
|
});
|
|
giallo::HtmlRenderer::default().render(
|
|
&highlighted,
|
|
&giallo::RenderOptions {
|
|
show_line_numbers: true,
|
|
..Default::default()
|
|
},
|
|
)
|
|
}
|
|
}
|
|
}
|