-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
495 lines (436 loc) · 15.8 KB
/
build.rs
File metadata and controls
495 lines (436 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// SPDX-FileCopyrightText: 2026 Sephyi <me@sephy.io>
//
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
use pulldown_cmark::{html, Event, Options, Parser, Tag, TagEnd};
use serde::Deserialize;
use std::fmt::Write as FmtWrite;
use std::fs;
use std::path::Path;
use syntect::highlighting::ThemeSet;
use syntect::html::highlighted_html_for_string;
use syntect::parsing::SyntaxSet;
use walkdir::WalkDir;
#[derive(Deserialize, Debug)]
struct Frontmatter {
title: String,
order: u32,
section: String,
description: String,
}
struct Heading {
level: u8,
text: String,
id: String,
}
struct DocPage {
slug: String,
title: String,
order: u32,
section: String,
description: String,
html_content: String,
headings: Vec<Heading>,
word_excerpt: String,
}
fn main() {
println!("cargo::rerun-if-changed=content/docs/");
let out_dir = std::env::var("OUT_DIR").unwrap();
let content_dir = Path::new("content/docs");
if !content_dir.exists() {
generate_empty_module(&out_dir);
return;
}
let ss = SyntaxSet::load_defaults_newlines();
let ts = ThemeSet::load_defaults();
let theme = &ts.themes["base16-ocean.dark"];
let mut pages: Vec<DocPage> = Vec::new();
let mut routes = vec![
"/".to_string(),
"/docs".to_string(),
"/not-found".to_string(),
];
for entry in WalkDir::new(content_dir)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
{
let raw = fs::read_to_string(entry.path())
.unwrap_or_else(|e| panic!("Failed to read {}: {e}", entry.path().display()));
let (fm, markdown) = parse_frontmatter(&raw);
let slug = entry
.path()
.file_stem()
.unwrap()
.to_str()
.unwrap()
.to_string();
let headings = extract_headings(&markdown);
let html_content = render_markdown_with_syntax_highlighting(&markdown, &ss, theme);
let word_excerpt = extract_excerpt(&markdown, 200);
routes.push(format!("/docs/{slug}"));
pages.push(DocPage {
slug,
title: fm.title,
order: fm.order,
section: fm.section,
description: fm.description,
html_content,
headings,
word_excerpt,
});
}
// Sort by logical section order, then by order within section
let section_order = ["Basics", "Usage", "Internals", "Integration", "Reference"];
let section_rank = |s: &str| -> usize {
section_order
.iter()
.position(|&x| x == s)
.unwrap_or(usize::MAX)
};
pages.sort_by(|a, b| {
section_rank(&a.section)
.cmp(§ion_rank(&b.section))
.then(a.order.cmp(&b.order))
});
generate_rust_module(&pages, &out_dir);
generate_search_index(&pages, &out_dir);
// Routes manifest for pre-rendering
fs::write(Path::new(&out_dir).join("routes.txt"), routes.join("\n")).unwrap();
}
fn parse_frontmatter(content: &str) -> (Frontmatter, String) {
let content = content.trim_start();
if !content.starts_with("---") {
panic!("Missing YAML frontmatter delimiter");
}
let after_first = &content[3..];
let end = after_first
.find("---")
.expect("Missing closing frontmatter delimiter");
let yaml = &after_first[..end];
let markdown = &after_first[end + 3..];
let fm: Frontmatter = serde_yaml::from_str(yaml).expect("Invalid frontmatter YAML");
(fm, markdown.trim().to_string())
}
fn extract_headings(markdown: &str) -> Vec<Heading> {
let parser = Parser::new_ext(markdown, Options::all());
let mut headings = Vec::new();
let mut current_level: Option<u8> = None;
let mut current_text = String::new();
for event in parser {
match event {
Event::Start(Tag::Heading { level, .. }) => {
current_level = Some(level as u8);
current_text.clear();
}
Event::Text(text) if current_level.is_some() => {
current_text.push_str(&text);
}
Event::Code(code) if current_level.is_some() => {
current_text.push_str(&code);
}
Event::End(TagEnd::Heading(_)) => {
if let Some(level) = current_level.take() {
let id = slug::slugify(¤t_text);
headings.push(Heading {
level,
text: current_text.clone(),
id,
});
}
}
_ => {}
}
}
headings
}
fn render_markdown_with_syntax_highlighting(
markdown: &str,
ss: &SyntaxSet,
theme: &syntect::highlighting::Theme,
) -> String {
let parser = Parser::new_ext(markdown, Options::all());
let mut in_code_block = false;
let mut code_lang = String::new();
let mut code_content = String::new();
let mut events: Vec<Event> = Vec::new();
for event in parser {
match event {
Event::Start(Tag::CodeBlock(ref kind)) => {
in_code_block = true;
code_content.clear();
code_lang = match kind {
pulldown_cmark::CodeBlockKind::Fenced(lang) => lang.to_string(),
_ => String::new(),
};
}
Event::Text(ref text) if in_code_block => {
code_content.push_str(text);
}
Event::End(TagEnd::CodeBlock) => {
in_code_block = false;
let lang_display = if code_lang.is_empty() {
"text"
} else {
&code_lang
};
let (highlighted, bg_style) =
if let Some(syntax) = ss.find_syntax_by_token(&code_lang) {
let raw = highlighted_html_for_string(&code_content, ss, syntax, theme)
.unwrap_or_else(|_| html_escape(&code_content));
strip_syntect_pre(&raw)
} else {
(html_escape(&code_content), String::new())
};
let html = format!(
r#"<div class="code-block-wrapper relative group rounded-lg overflow-hidden my-6" data-lang="{lang_display}"{bg_style}><div class="code-block-header flex items-center justify-between px-4 py-2 text-xs border-b border-white/10"><span class="text-white/50">{lang_display}</span><button class="copy-btn opacity-0 group-hover:opacity-100 transition-opacity text-white/40 hover:text-white/80" data-code="{escaped}">Copy</button></div><pre><code>{highlighted}</code></pre></div>"#,
escaped = html_escape(&code_content)
);
events.push(Event::Html(html.into()));
continue;
}
Event::Start(Tag::Heading { .. }) => {
events.push(event);
continue;
}
_ => {}
}
if !in_code_block {
events.push(event);
}
}
let mut html_output = String::new();
html::push_html(&mut html_output, events.into_iter());
add_heading_ids(&html_output)
}
fn add_heading_ids(html: &str) -> String {
let mut result = html.to_string();
for level in 1..=6 {
let open_tag = format!("<h{level}>");
let close_tag = format!("</h{level}>");
let mut search_from = 0;
let mut new_result = String::new();
while let Some(start) = result[search_from..].find(&open_tag) {
let abs_start = search_from + start;
let content_start = abs_start + open_tag.len();
if let Some(end) = result[content_start..].find(&close_tag) {
let abs_end = content_start + end;
let text = &result[content_start..abs_end];
let plain = strip_html_tags(text);
let id = slug::slugify(&plain);
new_result.push_str(&result[search_from..abs_start]);
write!(new_result, "<h{level} id=\"{id}\">{text}{close_tag}").unwrap();
search_from = abs_end + close_tag.len();
} else {
break;
}
}
new_result.push_str(&result[search_from..]);
result = new_result;
}
result
}
fn strip_html_tags(s: &str) -> String {
let mut result = String::new();
let mut in_tag = false;
for ch in s.chars() {
match ch {
'<' => in_tag = true,
'>' => in_tag = false,
_ if !in_tag => result.push(ch),
_ => {}
}
}
result
}
/// Strip syntect's outer `<pre style="...">...</pre>` wrapper.
/// Returns (inner_html, style_attr) where style_attr is ` style="..."` or empty.
fn strip_syntect_pre(html: &str) -> (String, String) {
// syntect wraps output in: <pre style="background-color:#2b303b;">\n<span ...>...</span>\n</pre>\n
if let Some(rest) = html.strip_prefix("<pre ") {
// Extract the style attribute from the opening <pre> tag
if let Some(close_bracket) = rest.find('>') {
let attrs = &rest[..close_bracket]; // e.g. style="background-color:#2b303b;"
let style_attr = if attrs.contains("style=") {
format!(" {attrs}")
} else {
String::new()
};
let inner = &rest[close_bracket + 1..];
// Strip trailing </pre> and whitespace
let inner = inner
.trim_end()
.strip_suffix("</pre>")
.unwrap_or(inner)
.trim();
return (inner.to_string(), style_attr);
}
}
(html.to_string(), String::new())
}
fn html_escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
fn extract_excerpt(markdown: &str, max_words: usize) -> String {
let parser = Parser::new(markdown);
let mut words = Vec::new();
for event in parser {
if let Event::Text(text) = event {
words.extend(text.split_whitespace().map(String::from));
if words.len() >= max_words {
break;
}
}
}
words.truncate(max_words);
words.join(" ")
}
fn generate_rust_module(pages: &[DocPage], out_dir: &str) {
let mut code = String::new();
writeln!(code, "pub const SECTION_ORDER: &[&str] = &[\"Basics\", \"Usage\", \"Internals\", \"Integration\", \"Reference\"];").unwrap();
writeln!(code).unwrap();
writeln!(code, "#[derive(Debug, Clone)]").unwrap();
writeln!(code, "pub struct DocPageData {{").unwrap();
writeln!(code, " pub slug: &'static str,").unwrap();
writeln!(code, " pub title: &'static str,").unwrap();
writeln!(code, " pub section: &'static str,").unwrap();
writeln!(code, " pub description: &'static str,").unwrap();
writeln!(code, " pub order: u32,").unwrap();
writeln!(code, " pub html_content: &'static str,").unwrap();
writeln!(
code,
" pub headings: &'static [(u8, &'static str, &'static str)],"
)
.unwrap();
writeln!(code, "}}").unwrap();
writeln!(code).unwrap();
for (i, page) in pages.iter().enumerate() {
write!(code, "static HEADINGS_{i}: &[(u8, &str, &str)] = &[").unwrap();
for h in &page.headings {
write!(
code,
"({}, \"{}\", \"{}\"),",
h.level,
h.text.replace('"', "\\\""),
h.id
)
.unwrap();
}
writeln!(code, "];").unwrap();
}
writeln!(code).unwrap();
writeln!(code, "pub static PAGES: &[DocPageData] = &[").unwrap();
for (i, page) in pages.iter().enumerate() {
writeln!(code, " DocPageData {{").unwrap();
writeln!(code, " slug: \"{}\",", page.slug).unwrap();
writeln!(
code,
" title: \"{}\",",
page.title.replace('"', "\\\"")
)
.unwrap();
writeln!(code, " section: \"{}\",", page.section).unwrap();
writeln!(
code,
" description: \"{}\",",
page.description.replace('"', "\\\"")
)
.unwrap();
writeln!(code, " order: {},", page.order).unwrap();
writeln!(
code,
" html_content: r##\"{}\"##,",
page.html_content
)
.unwrap();
writeln!(code, " headings: HEADINGS_{i},").unwrap();
writeln!(code, " }},").unwrap();
}
writeln!(code, "];").unwrap();
writeln!(code).unwrap();
writeln!(
code,
"pub fn get_page(slug: &str) -> Option<&'static DocPageData> {{"
)
.unwrap();
writeln!(code, " PAGES.iter().find(|p| p.slug == slug)").unwrap();
writeln!(code, "}}").unwrap();
writeln!(code).unwrap();
writeln!(
code,
"pub fn get_pages_by_section(section: &str) -> Vec<&'static DocPageData> {{"
)
.unwrap();
writeln!(
code,
" PAGES.iter().filter(|p| p.section == section).collect()"
)
.unwrap();
writeln!(code, "}}").unwrap();
writeln!(code).unwrap();
writeln!(code, "pub fn get_adjacent(slug: &str) -> (Option<&'static DocPageData>, Option<&'static DocPageData>) {{").unwrap();
writeln!(
code,
" let idx = PAGES.iter().position(|p| p.slug == slug);"
)
.unwrap();
writeln!(code, " match idx {{").unwrap();
writeln!(code, " Some(i) => (").unwrap();
writeln!(
code,
" if i > 0 {{ Some(&PAGES[i - 1]) }} else {{ None }},"
)
.unwrap();
writeln!(code, " PAGES.get(i + 1),").unwrap();
writeln!(code, " ),").unwrap();
writeln!(code, " None => (None, None),").unwrap();
writeln!(code, " }}").unwrap();
writeln!(code, "}}").unwrap();
fs::write(Path::new(out_dir).join("content_generated.rs"), code).unwrap();
}
fn generate_search_index(pages: &[DocPage], out_dir: &str) {
let entries: Vec<serde_json::Value> = pages
.iter()
.map(|p| {
let heading_texts: Vec<&str> = p.headings.iter().map(|h| h.text.as_str()).collect();
serde_json::json!({
"slug": p.slug,
"title": p.title,
"section": p.section,
"headings": heading_texts,
"excerpt": p.word_excerpt,
})
})
.collect();
let json = serde_json::to_string(&entries).unwrap();
fs::write(Path::new(out_dir).join("search_index.json"), &json).unwrap();
// Write to target/site/ so cargo-leptos serves it as a static asset.
let site_dir = Path::new("target/site");
if site_dir.exists() {
fs::write(site_dir.join("search_index.json"), &json).unwrap();
}
}
fn generate_empty_module(out_dir: &str) {
let code = r#"
pub const SECTION_ORDER: &[&str] = &[];
#[derive(Debug, Clone)]
pub struct DocPageData {
pub slug: &'static str,
pub title: &'static str,
pub section: &'static str,
pub description: &'static str,
pub order: u32,
pub html_content: &'static str,
pub headings: &'static [(u8, &'static str, &'static str)],
}
pub static PAGES: &[DocPageData] = &[];
pub fn get_page(_slug: &str) -> Option<&'static DocPageData> { None }
pub fn get_pages_by_section(_section: &str) -> Vec<&'static DocPageData> { vec![] }
pub fn get_adjacent(_slug: &str) -> (Option<&'static DocPageData>, Option<&'static DocPageData>) { (None, None) }
"#;
fs::write(Path::new(out_dir).join("content_generated.rs"), code).unwrap();
fs::write(Path::new(out_dir).join("routes.txt"), "/\n").unwrap();
fs::write(Path::new(out_dir).join("search_index.json"), "[]").unwrap();
}