This commit is contained in:
りき萌 2024-02-14 23:31:39 +01:00
parent 1305ffbb16
commit 1013c53975
21 changed files with 988 additions and 43 deletions

View file

@ -229,15 +229,7 @@ impl Generator {
.thumbnail
.as_ref()
.map(|thumbnail| Thumbnail {
url: format!(
"{}/static/pic/{}",
config.site,
config
.pics
.get(&thumbnail.id)
.map(|x| &**x)
.unwrap_or("404.png")
),
url: config.pic_url(&thumbnail.id),
alt: thumbnail.alt.clone(),
}),
scripts: roots.attributes.scripts.clone(),

View file

@ -99,4 +99,12 @@ impl Config {
}
Ok(())
}
pub fn pic_url(&self, id: &str) -> String {
format!(
"{}/static/pic/{}",
self.site,
self.pics.get(id).map(|x| &**x).unwrap_or("404.png")
)
}
}

View file

@ -7,7 +7,7 @@ use crate::{
config::Config,
html::EscapeAttribute,
state::{FileId, Treehouse},
tree::{attributes::Content, SemaBranchId},
tree::{attributes::Content, mini_template, SemaBranchId},
};
use super::{markdown, EscapeHtml};
@ -26,6 +26,12 @@ pub fn branch_to_html(
!branch.children.is_empty() || matches!(branch.attributes.content, Content::Link(_));
let class = if has_children { "branch" } else { "leaf" };
let mut class = String::from(class);
if !branch.attributes.classes.branch.is_empty() {
class.push(' ');
class.push_str(&branch.attributes.classes.branch);
}
let component = if let Content::Link(_) = branch.attributes.content {
"th-b-linked"
} else {
@ -64,7 +70,7 @@ pub fn branch_to_html(
s.push_str("<th-bp></th-bp>");
let raw_block_content = &source.input()[branch.content.clone()];
let mut unindented_block_content = String::with_capacity(raw_block_content.len());
let mut final_markdown = String::with_capacity(raw_block_content.len());
for line in raw_block_content.lines() {
// Bit of a jank way to remove at most branch.indent_level spaces from the front.
let mut space_count = 0;
@ -76,8 +82,8 @@ pub fn branch_to_html(
}
}
unindented_block_content.push_str(&line[space_count..]);
unindented_block_content.push('\n');
final_markdown.push_str(&line[space_count..]);
final_markdown.push('\n');
}
let broken_link_callback = &mut |broken_link: BrokenLink<'_>| {
@ -112,8 +118,11 @@ pub fn branch_to_html(
None
}
};
if branch.attributes.template {
final_markdown = mini_template::render(config, treehouse, &final_markdown);
}
let markdown_parser = pulldown_cmark::Parser::new_with_broken_link_callback(
&unindented_block_content,
&final_markdown,
{
use pulldown_cmark::Options;
Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES

View file

@ -60,6 +60,10 @@ pub struct Attributes {
/// Strings of extra CSS class names to include in the generated HTML.
#[serde(default)]
pub classes: Classes,
/// Enable `mini_template` templating in this branch.
#[serde(default)]
pub template: bool,
}
/// Controls for block content presentation.
@ -88,6 +92,10 @@ pub enum Content {
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize)]
pub struct Classes {
/// Classes to append to the branch itself (<li is="th-b">).
#[serde(default)]
pub branch: String,
/// Classes to append to the branch's <ul> element containing its children.
#[serde(default)]
pub branch_children: String,

View file

@ -0,0 +1,213 @@
//! Minimalistic templating engine that integrates with the .tree format and Markdown.
//!
//! Mostly to avoid pulling in Handlebars everywhere; mini_template, unlike Handlebars, also allows
//! for injecting *custom, stateful* context into the renderer, which is important for things like
//! the `pic` template to work.
use std::ops::Range;
use pulldown_cmark::escape::escape_html;
use crate::{config::Config, state::Treehouse};
struct Lexer<'a> {
input: &'a str,
position: usize,
// Despite this parser's intentional simplicity, a peekahead buffer needs to be used for
// performance because tokens are usually quite long and therefore reparsing them would be
// too expensive.
peek_buffer: Option<(Token, usize)>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TokenKind {
/// Verbatim text, may be inside of a template.
Text,
Open(EscapingMode), // {%
Close, // %}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EscapingMode {
EscapeHtml,
NoEscaping,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Token {
kind: TokenKind,
range: Range<usize>,
}
impl<'a> Lexer<'a> {
fn new(input: &'a str) -> Self {
Self {
input,
position: 0,
peek_buffer: None,
}
}
fn current(&self) -> Option<char> {
self.input[self.position..].chars().next()
}
fn advance(&mut self) {
self.position += self.current().map(|c| c.len_utf8()).unwrap_or(0);
}
fn create_token(&self, start: usize, kind: TokenKind) -> Token {
Token {
kind,
range: start..self.position,
}
}
fn next_inner(&mut self) -> Option<Token> {
if let Some((token, after_token)) = self.peek_buffer.take() {
self.position = after_token;
return Some(token);
}
let start = self.position;
match self.current() {
Some('{') => {
self.advance();
if self.current() == Some('%') {
self.advance();
if self.current() == Some('!') {
Some(self.create_token(start, TokenKind::Open(EscapingMode::NoEscaping)))
} else {
Some(self.create_token(start, TokenKind::Open(EscapingMode::EscapeHtml)))
}
} else {
self.advance();
Some(self.create_token(start, TokenKind::Text))
}
}
Some('%') => {
self.advance();
if self.current() == Some('}') {
self.advance();
Some(self.create_token(start, TokenKind::Close))
} else {
self.advance();
Some(self.create_token(start, TokenKind::Text))
}
}
Some(_) => {
while !matches!(self.current(), Some('{' | '%') | None) {
self.advance();
}
Some(self.create_token(start, TokenKind::Text))
}
None => None,
}
}
fn peek_inner(&mut self) -> Option<Token> {
let position = self.position;
let token = self.next();
let after_token = self.position;
self.position = position;
if let Some(token) = token.clone() {
self.peek_buffer = Some((token, after_token));
}
token
}
fn next(&mut self) -> Option<Token> {
self.next_inner().map(|mut token| {
// Coalesce multiple Text tokens into one.
if token.kind == TokenKind::Text {
while let Some(Token {
kind: TokenKind::Text,
..
}) = self.peek_inner()
{
let next_token = self.next_inner().unwrap();
token.range.end = next_token.range.end;
}
}
token
})
}
}
struct Renderer<'a> {
lexer: Lexer<'a>,
output: String,
}
struct InvalidTemplate;
impl<'a> Renderer<'a> {
fn emit_token_verbatim(&mut self, token: &Token) {
self.output.push_str(&self.lexer.input[token.range.clone()]);
}
fn render(&mut self, config: &Config, treehouse: &Treehouse) {
let kind_of = |token: &Token| token.kind;
while let Some(token) = self.lexer.next() {
match token.kind {
TokenKind::Open(escaping) => {
let inside = self.lexer.next();
let close = self.lexer.next();
if let Some((TokenKind::Text, TokenKind::Close)) = inside
.as_ref()
.map(kind_of)
.zip(close.as_ref().map(kind_of))
{
match Self::render_template(
config,
treehouse,
self.lexer.input[inside.as_ref().unwrap().range.clone()].trim(),
) {
Ok(s) => match escaping {
EscapingMode::EscapeHtml => {
_ = escape_html(&mut self.output, &s);
}
EscapingMode::NoEscaping => self.output.push_str(&s),
},
Err(InvalidTemplate) => {
inside.inspect(|token| self.emit_token_verbatim(token));
close.inspect(|token| self.emit_token_verbatim(token));
}
}
} else {
inside.inspect(|token| self.emit_token_verbatim(token));
close.inspect(|token| self.emit_token_verbatim(token));
}
}
_ => self.emit_token_verbatim(&token),
}
}
}
fn render_template(
config: &Config,
_treehouse: &Treehouse,
template: &str,
) -> Result<String, InvalidTemplate> {
let (function, arguments) = template.split_once(' ').unwrap_or((template, ""));
match function {
"pic" => Ok(config.pic_url(arguments)),
"c++" => Ok("<script>alert(1)</script>".into()),
_ => Err(InvalidTemplate),
}
}
}
pub fn render(config: &Config, treehouse: &Treehouse, input: &str) -> String {
let mut renderer = Renderer {
lexer: Lexer::new(input),
output: String::new(),
};
renderer.render(config, treehouse);
renderer.output
}

View file

@ -1,4 +1,5 @@
pub mod attributes;
pub mod mini_template;
use std::ops::Range;