base markdown book with code block syntax highlighting and fully embedded assets

This commit is contained in:
2026-01-07 18:29:07 +01:00
commit 1c4e99b138
12 changed files with 3576 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/target
/themes

2928
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

23
Cargo.toml Normal file
View File

@@ -0,0 +1,23 @@
[package]
name = "blog"
version = "0.1.0"
edition = "2024"
[dependencies]
anyhow = "1.0.100"
axum = "0.8.8"
chrono = "0.4.42"
clap = { version = "4.5.54", features = ["derive"] }
lazy_static = "1.5.0"
pulldown-cmark = "0.13.0"
serde = { version = "1.0.228", features = ["derive"] }
syntect = "5.3.0"
tera = "1.20.1"
tokio = { version = "1.49.0", features = ["full"] }
tower-http = { version = "0.6.8", features = ["cors"] }
tracing = "0.1.44"
tracing-subscriber = "0.3.22"
[build-dependencies]
reqwest = { version = "0.13.1", features = ["blocking"] }
tokio = "1.49.0"

15
build.rs Normal file
View File

@@ -0,0 +1,15 @@
use std::fs::{File, create_dir};
use std::path::Path;
fn main() {
let dest_path = Path::new("themes/Catppuccin-Macchiato.tmTheme");
if !dest_path.exists() {
let mut response = reqwest::blocking::get("https://raw.githubusercontent.com/catppuccin/bat/refs/heads/main/themes/Catppuccin%20Macchiato.tmTheme")
.expect("Failed to download theme");
create_dir("themes").expect("Could not create themes dir");
let mut file = File::create(dest_path).expect("Failed to create theme file");
std::io::copy(&mut response, &mut file).expect("Failed to save theme");
}
}

16
example/01-ferris.md Normal file
View File

@@ -0,0 +1,16 @@
# The Mascot: Ferris
**Ferris** is the unofficial mascot of the Rust community. He is a crab because Rust programmers often call themselves "Rustaceans" (a play on the word crustacean).
### Why a crab?
- Rustaceans are known for being friendly and helpful.
- Crabs have hard shells (like Rust's safety guarantees).
- They have powerful claws (like Rust's powerful type system).
```rust
fn main() {
println!("Hello from Ferris!");
}
```
> "The Rust community is one of the most welcoming in the tech world."

14
example/02-coffee.md Normal file
View File

@@ -0,0 +1,14 @@
# The Dark Elixir: A History of Coffee
Coffee is more than just a drink; it's a global phenomenon. Legend has it that a goat herder named Kaldi discovered coffee in Ethiopia after noticing his goats became very energetic after eating berries from a certain tree.
### Common Coffee Roasts
| Roast | Color | Oil on Surface | Flavor Profile |
| :--- | :--- | :--- | :--- |
| **Light** | Light Brown | None | Toasted grain, high acidity |
| **Medium** | Medium Brown | Rare | Balanced flavor, aroma |
| **Dark** | Shiny Black | Heavy | Bitter, smoky, or burnt |
---
**Fun Fact:** Coffee is actually a fruit! The "beans" are the pits of a cherry-like berry.

17
example/03-space.md Normal file
View File

@@ -0,0 +1,17 @@
# To the Stars: Voyager 1
Voyager 1 is a space probe launched by NASA on September 5, 1977. As of today, it is the most distant human-made object from Earth.
### Voyager 1 Mission Checklist
- [x] Flyby of Jupiter (1979)
- [x] Flyby of Saturn (1980)
- [x] Enter Interstellar Space (2012)
- [ ] Reach the next star (Estimated in 40,000 years)
### The Golden Record
The probe carries a gold-plated audio-visual disc in case it is ever found by intelligent life. It contains:
- Greetings in 55 languages.
- Sounds of whales, a baby crying, and waves breaking.
- Music by Bach, Mozart, and Chuck Berry.
> "The Voyager mission is a testament to human curiosity and our desire to touch the stars."

11
example/SUMMARY.md Normal file
View File

@@ -0,0 +1,11 @@
# The Random Collection
Welcome to this automatically generated book! This is the **Summary** page, acting as the entry point for our small website.
### Table of Contents
1. [The Mascot: Ferris](./01-ferris.md) - A look at the Rust mascot.
2. [The Dark Elixir](./02-coffee.md) - A brief history of coffee.
3. [To the Stars](./03-space.md) - Facts about the Voyager 1 probe.
---
*Generated for the Axum Markdown Server test.*

59
src/codeblocks.rs Normal file
View File

@@ -0,0 +1,59 @@
use pulldown_cmark::{CodeBlockKind, CowStr, Event, Parser as MarkdownParser, Tag, TagEnd};
use syntect::html::highlighted_html_for_string;
use crate::{SYNTAX_SET, THEME_SET};
// I found this at <https://github.com/pulldown-cmark/pulldown-cmark/issues/167#issuecomment-3700787117>
pub struct CodeblockRenderer<'a> {
inner: MarkdownParser<'a>,
}
impl<'a> CodeblockRenderer<'a> {
pub fn new(inner: MarkdownParser<'a>) -> Self {
Self { inner }
}
}
impl<'a> Iterator for CodeblockRenderer<'a> {
type Item = Event<'a>;
fn next(&mut self) -> Option<Self::Item> {
let event = self.inner.next()?;
// Intercept CodeBlock starts
let Event::Start(Tag::CodeBlock(kind)) = event else {
return Some(event);
};
let mut code_content = String::new();
while let Some(inner_event) = self.inner.next() {
match inner_event {
Event::End(TagEnd::CodeBlock) => break,
Event::Text(code) => code_content.push_str(&code),
_ => {}
}
}
let lang = match kind {
CodeBlockKind::Indented => "text",
CodeBlockKind::Fenced(ref language) => language.as_ref(),
};
let rendered_html = render_code_to_html(&code_content, lang);
Some(Event::Html(CowStr::Boxed(rendered_html.into_boxed_str())))
}
}
pub fn render_code_to_html(code: &str, lang: &str) -> String {
let syntax = SYNTAX_SET
.find_syntax_by_token(lang)
.unwrap_or_else(|| SYNTAX_SET.find_syntax_plain_text());
let theme = &THEME_SET.themes["Catppuccin Macchiato"];
highlighted_html_for_string(code, &SYNTAX_SET, syntax, theme)
.unwrap_or_else(|_| format!("<pre><code>{}</code></pre>", code))
}

200
src/main.rs Normal file
View File

@@ -0,0 +1,200 @@
use axum::{
Router,
extract::{Path, State},
http::StatusCode,
response::{Html, IntoResponse, Response},
routing::get,
};
use clap::{Parser, Subcommand};
use lazy_static::lazy_static;
use pulldown_cmark::{Options, Parser as MarkdownParser, html};
use std::sync::Arc;
use std::{io::Cursor, path::PathBuf};
use syntect::{highlighting::ThemeSet, parsing::SyntaxSet};
use tera::{Context, Tera};
mod codeblocks;
use codeblocks::*;
lazy_static! {
pub static ref TEMPLATES: Tera = {
let mut tera = Tera::default();
tera.add_raw_templates(vec![
("page.html", include_str!("../templates/page.html")),
("style.css", include_str!("../templates/style.css")),
])
.unwrap();
tera
};
pub static ref SYNTAX_SET: SyntaxSet = SyntaxSet::load_defaults_newlines();
pub static ref THEME_SET: ThemeSet = {
let mut set = ThemeSet::load_defaults();
let theme_bytes = include_bytes!("../themes/Catppuccin-Macchiato.tmTheme");
let mut cursor = Cursor::new(theme_bytes);
match syntect::highlighting::ThemeSet::load_from_reader(&mut cursor) {
Ok(theme) => {
set.themes.insert("Catppuccin Macchiato".to_string(), theme);
}
Err(e) => {
tracing::error!("Failed to load embedded theme: {}", e);
}
}
set
};
}
#[derive(Parser)]
#[command(author, version, about = "A simple markdown book server")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Serve the markdown files in a directory
Serve {
/// Path to the directory containing SUMMARY.md
path: PathBuf,
/// Port to listen on
#[arg(short, long, default_value = "3456")]
port: u16,
},
}
struct AppState {
docs_dir: PathBuf,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
lazy_static::initialize(&TEMPLATES);
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.init();
let cli = Cli::parse();
match cli.command {
Commands::Serve { path, port } => {
let abs_path = std::fs::canonicalize(&path)?;
let shared_state = Arc::new(AppState { docs_dir: abs_path });
let app = Router::new()
.route("/", get(render_summary))
.route("/{page}", get(render_page))
.route("/style.css", get(serve_css))
.with_state(shared_state);
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port)).await?;
tracing::info!("Listening on http://localhost:{}", port);
axum::serve(listener, app).await?;
}
}
Ok(())
}
async fn render_summary(State(state): State<Arc<AppState>>) -> impl IntoResponse {
render_md_file("SUMMARY.md", state).await
}
async fn render_page(
State(state): State<Arc<AppState>>,
Path(page): Path<String>,
) -> impl IntoResponse {
let filename = if page.ends_with(".md") {
page
} else {
format!("{}.md", page)
};
render_md_file(&filename, state).await
}
async fn serve_css() -> impl IntoResponse {
match TEMPLATES.render("style.css", &tera::Context::new()) {
Ok(css) => Response::builder()
.header("content-type", "text/css")
.body(css.into())
.unwrap(),
Err(_) => (StatusCode::NOT_FOUND, "CSS not found").into_response(),
}
}
async fn render_md_file(filename: &str, state: Arc<AppState>) -> Html<String> {
let file_path = state.docs_dir.join(filename);
let content = match tokio::fs::read_to_string(&file_path).await {
Ok(c) => c,
Err(_) => return Html("<h1>404</h1><p>Page not found</p>".to_string()),
};
let mut options = Options::empty();
options.insert(Options::ENABLE_TABLES);
options.insert(Options::ENABLE_FOOTNOTES);
options.insert(Options::ENABLE_STRIKETHROUGH);
options.insert(Options::ENABLE_TASKLISTS);
let parser = MarkdownParser::new_ext(&content, options);
let renderer = CodeblockRenderer::new(parser);
let mut html_output = String::new();
html::push_html(&mut html_output, renderer);
let (prev_page, next_page) = get_nav_links(&state.docs_dir, filename);
let mut context = Context::new();
context.insert("title", filename);
context.insert("content", &html_output);
context.insert("prev_page", &prev_page);
context.insert("next_page", &next_page);
match TEMPLATES.render("page.html", &context) {
Ok(rendered) => Html(rendered),
Err(e) => Html(format!("<h1>Template Error</h1><pre>{}</pre>", e)),
}
}
fn get_nav_links(dir: &PathBuf, current_file: &str) -> (Option<String>, Option<String>) {
let mut files: Vec<String> = std::fs::read_dir(dir)
.unwrap()
.filter_map(|entry| {
let path = entry.ok()?.path();
if path.extension()? == "md" && path.file_name()? != "SUMMARY.md" {
Some(path.file_name()?.to_str()?.to_string())
} else {
None
}
})
.collect();
files.sort();
if current_file == "SUMMARY.md" {
return (None, files.first().cloned());
}
let pos = files.iter().position(|f| f == current_file);
match pos {
Some(i) => {
let prev = if i == 0 {
// If first page, point back to summary page
Some(".".to_string())
} else {
// Otherwise point to the previous file in the list
files.get(i - 1).cloned()
};
let next = files.get(i + 1).cloned();
(prev, next)
}
None => (None, None),
}
}

29
templates/page.html Normal file
View File

@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<article>
{{ content | safe }}
</article>
<nav>
<!-- {% if prev_page %} -->
<!-- <a class="btn" href="/{{ prev_page }}">← Previous</a> -->
<!-- {% else %} -->
<!-- <span class="btn disabled">← Previous</span> -->
<!-- {% endif %} -->
<a href="/">Home (Summary)</a>
<!-- {% if next_page %} -->
<!-- <a class="btn" href="/{{ next_page }}">Next →</a> -->
<!-- {% else %} -->
<!-- <span class="btn disabled">Next →</span> -->
<!-- {% endif %} -->
</nav>
</body>
</html>

262
templates/style.css Normal file
View File

@@ -0,0 +1,262 @@
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&display=swap');
:root {
--bg-color: #0d0d12;
--container-bg: rgba(25, 25, 35, 0.75);
--text-main: #e2e2e9;
--text-muted: #a1a1b5;
--accent-pink: #ff4d94;
--accent-pink-glow: rgba(255, 77, 148, 0.3);
--accent-pink-dark: #cc3d76;
--code-bg: rgba(25, 25, 35, 0.75);
--border-color: rgba(255, 255, 255, 0.1);
--selection-bg: rgba(255, 77, 148, 0.4);
--radius-sm: 6px;
--radius-md: 12px;
--radius-lg: 20px;
--blur-amount: 12px;
--container-width: 850px;
}
* {
box-sizing: border-box;
}
body {
background-color: var(--bg-color);
background-image: radial-gradient(circle at top right, #1a1a2e, #0d0d12);
color: var(--text-main);
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
line-height: 1.7;
margin: 0;
padding: 40px 20px;
display: flex;
justify-content: center;
min-height: 100vh;
}
article {
max-width: 1000px;
}
::selection {
background: var(--selection-bg);
color: #fff;
}
h1, h2, h3, h4, h5, h6 {
color: #fff;
margin-top: 2rem;
margin-bottom: 1rem;
font-weight: 700;
line-height: 1.25;
}
h1 {
font-size: 2.5rem;
border-bottom: 2px solid var(--accent-pink);
padding-bottom: 0.8rem;
}
h2 {
font-size: 1.8rem;
color: var(--accent-pink);
}
h3 {
font-size: 1.5rem;
}
a {
color: var(--accent-pink);
text-decoration: none;
transition: color 0.2s ease, text-shadow 0.2s ease;
}
a:hover {
color: #ff80b3;
text-shadow: 0 0 8px var(--accent-pink-glow);
}
p { margin-bottom: 1.2rem; }
ul, ol {
padding-left: 1.5rem;
margin-bottom: 1.2rem;
}
li { margin-bottom: 0.5rem; }
blockquote {
margin: 2rem 0;
padding: 0.1rem 1.5rem;
border-left: 4px solid var(--accent-pink);
background: rgba(255, 77, 148, 0.05);
border-radius: var(--radius-sm);
color: var(--text-muted);
font-style: italic;
}
pre {
background: var(--code-bg);
background-color: var(--code-bg) !important;
padding: 1.2rem;
border-radius: var(--radius-md);
overflow-x: auto;
border: 1px solid var(--border-color);
margin: 1.5rem 0;
}
code {
font-size: 0.9em;
background: rgba(255, 255, 255, 0.1);
padding: 0.2rem 0.4rem;
border-radius: var(--radius-sm);
font-style: normal !important;
}
pre code {
background: none !important;
padding: 0;
}
pre,
code,
pre span,
code span,
pre [style],
code [style] {
font-family: 'JetBrains Mono', 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, monospace !important;
font-style: normal !important;
font-variant-ligatures: contextual;
}
table {
width: 100%;
border-collapse: collapse;
margin: 2rem 0;
}
th {
background: rgba(255, 77, 148, 0.1);
color: var(--accent-pink);
text-align: left;
}
th, td {
padding: 12px;
border: 1px solid var(--border-color);
}
tr:nth-child(even) {
background: rgba(255, 255, 255, 0.02);
}
hr {
border: none;
height: 1px;
background: linear-gradient(to right, transparent, var(--border-color), transparent);
margin: 3rem 0;
}
img {
max-width: 100%;
border-radius: var(--radius-md);
margin: 1.5rem 0;
border: 1px solid var(--border-color);
}
input[type="checkbox"] {
appearance: none;
-webkit-appearance: none;
background-color: transparent;
margin: 0;
margin-right: 0.5rem;
font: inherit;
color: var(--accent-pink);
width: 1.25em;
height: 1.25em;
border: 2px solid var(--text-muted);
border-radius: var(--radius-sm);
transform: translateY(-0.075em);
display: inline-grid;
place-content: center;
transition: border-color 0.2s ease, background-color 0.2s ease;
}
input[type="checkbox"]::before {
content: "";
width: 0.65em;
height: 0.65em;
transform: scale(0);
transition: 120ms transform ease-in-out;
box-shadow: inset 1em 1em var(--accent-pink);
clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%);
}
input[type="checkbox"]:checked {
border-color: var(--accent-pink);
}
input[type="checkbox"]:checked::before {
transform: scale(1);
}
body {
padding-top: 100px;
}
nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 1000;
background: var(--container-bg);
backdrop-filter: blur(var(--blur-amount));
-webkit-backdrop-filter: blur(var(--blur-amount));
border-bottom: 1px solid var(--border-color);
padding: 1rem 2rem;
display: flex;
justify-content: space-between;
align-items: center;
}
nav a {
color: var(--text-main);
text-decoration: none;
font-weight: 600;
margin-left: 20px;
transition: color 0.2s ease;
}
nav a:hover {
color: var(--accent-pink);
}
.btn {
display: inline-block;
color: #fff;
padding: 0.6rem 1.2rem;
border: solid 1px var(--accent-pink);
border-radius: var(--radius-md);
font-weight: 600;
cursor: pointer;
text-decoration: none;
transition: background 0.2s ease;
}
.btn:hover {
background-color: rgba(255, 255, 255, 0.05);
text-decoration: none;
}
.btn.disabled {
color: var(--text-muted);
cursor: not-allowed;
border-color: var(--text-muted);
}