forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic_site.rs
More file actions
283 lines (256 loc) · 10.2 KB
/
Copy pathstatic_site.rs
File metadata and controls
283 lines (256 loc) · 10.2 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
//! Static documentation site generator
//!
//! Produces a single `index.html` that works with `file://` — no server needed.
use std::path::Path;
use crate::assets;
use crate::markdown::render_markdown;
use crate::model::DocIndex;
pub struct StaticSiteGenerator;
impl StaticSiteGenerator {
/// Generate a static documentation site in `output_dir`.
///
/// Produces a single `index.html` file with inlined CSS, JS, and JSON.
/// Markdown doc bodies are pre-rendered to HTML and injected as `html_body`
/// fields in the JSON (the Rust types are never modified).
pub fn generate(index: &DocIndex, output_dir: &Path) -> std::io::Result<()> {
Self::generate_with_scip(index, output_dir, None)
}
/// Generate a static documentation site with optional embedded SCIP data.
///
/// When `scip_json` is provided, the pre-processed SCIP JSON is embedded
/// inline so the browser can build a ScipStore for interactive symbol
/// resolution (progressive enhancement over the pre-rendered DocIndex).
///
/// Syntax highlighting and type linking are handled entirely client-side
/// via tree-sitter WASM + ScipStore in the browser.
pub fn generate_with_scip(
index: &DocIndex,
output_dir: &Path,
scip_json: Option<&str>,
) -> std::io::Result<()> {
Self::generate_full(index, output_dir, scip_json, None)
}
/// Generate a static documentation site with all optional features.
///
/// `source_link_base`: e.g. "https://github.com/org/repo/blob/abc123"
pub fn generate_full(
index: &DocIndex,
output_dir: &Path,
scip_json: Option<&str>,
source_link_base: Option<&str>,
) -> std::io::Result<()> {
Self::generate_impl(index, output_dir, scip_json, source_link_base, true)
}
/// Generate a split documentation site with separate files:
/// docs.json, index.html (minimal shell), fe-web.js, fe-highlight.css
///
/// This is the composable output mode — the host site loads the files
/// individually and can override styles via normal CSS cascade.
pub fn generate_split(
index: &DocIndex,
output_dir: &Path,
scip_json: Option<&str>,
source_link_base: Option<&str>,
) -> std::io::Result<()> {
Self::generate_impl(index, output_dir, scip_json, source_link_base, false)
}
fn generate_impl(
index: &DocIndex,
output_dir: &Path,
scip_json: Option<&str>,
source_link_base: Option<&str>,
self_contained: bool,
) -> std::io::Result<()> {
std::fs::create_dir_all(output_dir)?;
// Serialize to a JSON Value so we can inject html_body fields
let mut value = serde_json::to_value(index).map_err(std::io::Error::other)?;
inject_html_bodies(&mut value);
let json = serde_json::to_string(&value).map_err(std::io::Error::other)?;
let title = index_title(index);
if self_contained {
let html = assets::html_shell_full(&title, &json, scip_json, source_link_base);
std::fs::write(output_dir.join("index.html"), html)?;
} else {
// Write separate files
let sv = crate::model::SCHEMA_VERSION;
let cv = env!("CARGO_PKG_VERSION");
let merged = if let Some(scip) = scip_json {
format!(
r#"{{"schema_version":{sv},"compiler_version":"{cv}","index":{json},"scip":{scip}}}"#
)
} else {
format!(r#"{{"schema_version":{sv},"compiler_version":"{cv}","index":{json}}}"#)
};
std::fs::write(output_dir.join("docs.json"), &merged)?;
std::fs::write(output_dir.join("fe-web.js"), assets::web_component_bundle())?;
std::fs::write(
output_dir.join("fe-highlight.css"),
assets::FE_HIGHLIGHT_CSS,
)?;
std::fs::write(output_dir.join("styles.css"), assets::STYLES_CSS)?;
// Minimal shell that loads the separate files
let source_script = if let Some(base) = source_link_base {
format!(
"\n <script>window.FE_SOURCE_BASE = \"{}\";</script>",
crate::escape::escape_script_content(base)
)
} else {
String::new()
};
let html = format!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title}</title>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="fe-highlight.css">
</head>
<body>
<script src="fe-web.js" data-src="docs.json"></script>{source_script}
<fe-doc-viewer title="{title}" src="docs.json" routing="hash"></fe-doc-viewer>
</body>
</html>"#,
title = crate::escape::escape_html_text(&title),
source_script = source_script,
);
std::fs::write(output_dir.join("index.html"), html)?;
}
Ok(())
}
}
/// Walk the JSON and inject `html_body` next to every `docs.body` field.
/// Also injects `html_content` into each doc section for distinct rendering.
pub fn inject_html_bodies(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(map) => {
// If this object has a "docs" field with a "body", inject "html_body"
if let Some(docs) = map.get_mut("docs")
&& let Some(docs_obj) = docs.as_object_mut()
{
if let Some(body) = docs_obj.get("body").and_then(|b| b.as_str()) {
let html = render_markdown(body);
docs_obj.insert("html_body".to_string(), serde_json::Value::String(html));
}
// Render each section's content to HTML
if let Some(sections) = docs_obj.get_mut("sections")
&& let Some(sections_arr) = sections.as_array_mut()
{
for section in sections_arr {
if let Some(section_obj) = section.as_object_mut()
&& let Some(content) =
section_obj.get("content").and_then(|c| c.as_str())
{
let html = render_markdown(content);
section_obj.insert(
"html_content".to_string(),
serde_json::Value::String(html),
);
}
}
}
}
// Recurse into all values
for v in map.values_mut() {
inject_html_bodies(v);
}
}
serde_json::Value::Array(arr) => {
for v in arr {
inject_html_bodies(v);
}
}
_ => {}
}
}
/// Derive a title from the index (use the root module name if available).
fn index_title(index: &DocIndex) -> String {
if let Some(root) = index.modules.first() {
format!("{} — Fe Documentation", root.name)
} else {
"Fe Documentation".to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::*;
fn sample_index() -> DocIndex {
let mut index = DocIndex::new();
index.add_item(DocItem {
path: "mylib::Greeter".into(),
name: "Greeter".into(),
kind: DocItemKind::Struct,
visibility: DocVisibility::Public,
docs: Some(DocContent::from_raw("A **friendly** greeter.")),
signature: "pub struct Greeter".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
generics: vec![],
where_bounds: vec![],
children: vec![],
source: None,
source_text: None,
trait_impls: vec![],
implementors: vec![],
});
index.modules = vec![DocModuleTree {
name: "mylib".into(),
path: "mylib".into(),
children: vec![],
items: vec![DocModuleItem {
name: "Greeter".into(),
path: "mylib::Greeter".into(),
kind: DocItemKind::Struct,
summary: Some("A friendly greeter.".into()),
}],
}];
index
}
#[test]
fn generates_index_html() {
let index = sample_index();
let dir = std::env::temp_dir().join("fe_web_static_test");
let _ = std::fs::remove_dir_all(&dir);
StaticSiteGenerator::generate(&index, &dir).expect("generate failed");
let html_path = dir.join("index.html");
assert!(html_path.exists(), "index.html should exist");
let html = std::fs::read_to_string(&html_path).unwrap();
// Contains inlined CSS
assert!(html.contains(":root"), "should contain CSS");
// Uses fe-doc-viewer component
assert!(html.contains("fe-doc-viewer"), "should use fe-doc-viewer");
// Contains the JSON data
assert!(html.contains("mylib::Greeter"), "should contain item path");
// Contains pre-rendered markdown (html_body with <strong>)
assert!(html.contains("html_body"), "should contain html_body key");
// In the <script> tag, </ is escaped to <\/ for XSS safety
assert!(
html.contains(r"<strong>friendly<\/strong>"),
"markdown should be pre-rendered"
);
// Cleanup
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn inject_html_bodies_works() {
let index = sample_index();
let mut value = serde_json::to_value(&index).unwrap();
inject_html_bodies(&mut value);
let json = serde_json::to_string_pretty(&value).unwrap();
assert!(json.contains("html_body"));
assert!(json.contains("<strong>friendly</strong>"));
}
#[test]
fn title_uses_root_module_name() {
let index = sample_index();
assert_eq!(index_title(&index), "mylib \u{2014} Fe Documentation");
}
#[test]
fn title_fallback_when_no_modules() {
let index = DocIndex::new();
assert_eq!(index_title(&index), "Fe Documentation");
}
}