Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 132 additions & 21 deletions crates/emmylua_doc_cli/src/html_generator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ mod markdown;
mod render;
mod types;

use std::collections::HashSet;
use std::path::Path;

use emmylua_code_analysis::LuaType;
use serde::Serialize;
use tera::Tera;

use crate::OutputDestination;
Expand Down Expand Up @@ -115,8 +117,11 @@ pub fn generate_html(
sort_nav(&mut nav);
fill_kind_letters(&mut nav);

// Build the search index before rendering mutates the page documents.
let search_entries = build_search_entries(&nav, &pages);

// Render item pages (in subdirectories -> "../" prefix).
for (filename, mut doc) in pages {
for (filename, doc) in &mut pages {
doc.kind_letter = doc
.kind
.chars()
Expand All @@ -128,7 +133,7 @@ pub fn generate_html(
mark_active(&mut sub_nav, &doc.kind, &doc.name);
finalize_nav(&mut sub_nav);
doc.nav = sub_nav;
let html = render_page(&tl, "item.html", &doc)?;
let html = render_page(&tl, "item.html", doc)?;
std::fs::write(output.join(&filename), html)?;
}

Expand All @@ -144,7 +149,7 @@ pub fn generate_html(
let index_html = render_page(&tl, "index.html", &index_doc)?;
std::fs::write(output.join("index.html"), index_html)?;

write_search_index(&output, &index_doc.nav)?;
write_search_index(&output, &search_entries)?;

eprintln!("Documentation html exported to {:?}", output);
Ok(())
Expand Down Expand Up @@ -475,38 +480,91 @@ fn render_page(
tl.render(template, &context).map_err(Into::into)
}

fn write_search_index(output: &Path, nav: &NavModel) -> Result<(), Box<dyn std::error::Error>> {
/// One entry in `static/search-index.js`.
#[derive(Debug, Serialize)]
struct SearchEntry {
name: String,
href: String,
kind: &'static str,
}

/// Builds search entries for pages and their members.
///
/// Members are documented on their owner's page; the anchor id comes from
/// `HtmlMember::anchor`, the same field the HTML template renders. Identical
/// `(name, href)` pairs are deduplicated while preserving insertion order.
fn build_search_entries(nav: &NavModel, pages: &[(String, HtmlDoc)]) -> Vec<SearchEntry> {
let mut entries = Vec::new();
let mut seen = HashSet::new();

for item in &nav.types {
entries.push(serde_json::json!({
"name": item.name,
"href": item.href,
"kind": type_kind(&item.name),
}));
push_search_entry(
&mut entries,
&mut seen,
item.name.clone(),
item.href.clone(),
type_kind(&item.name),
);
}
for item in &nav.modules {
entries.push(serde_json::json!({
"name": item.name,
"href": item.href,
"kind": "module",
}));
push_search_entry(
&mut entries,
&mut seen,
item.name.clone(),
item.href.clone(),
"module",
);
}
for item in &nav.globals {
entries.push(serde_json::json!({
"name": item.name,
"href": item.href,
"kind": "global",
}));
push_search_entry(
&mut entries,
&mut seen,
item.name.clone(),
item.href.clone(),
"global",
);
}
let json = serde_json::to_string(&entries)?;
for (href, doc) in pages {
let methods = doc.methods.iter().map(|member| (member, "method"));
let fields = doc.fields.iter().map(|member| (member, "field"));
for (member, kind) in methods.chain(fields) {
push_search_entry(
&mut entries,
&mut seen,
member.name.clone(),
format!("{href}#{}", member.anchor),
kind,
);
}
}
entries
}

fn push_search_entry(
entries: &mut Vec<SearchEntry>,
seen: &mut HashSet<(String, String)>,
name: String,
href: String,
kind: &'static str,
) {
if seen.insert((name.clone(), href.clone())) {
entries.push(SearchEntry { name, href, kind });
}
}

fn write_search_index(
output: &Path,
entries: &[SearchEntry],
) -> Result<(), Box<dyn std::error::Error>> {
let json = serde_json::to_string(entries)?;
std::fs::write(
output.join("static").join("search-index.js"),
format!("window.SEARCH_INDEX = {json};"),
)?;
Ok(())
}

fn type_kind(name: &str) -> &str {
fn type_kind(name: &str) -> &'static str {
if name.starts_with("enum ") {
"enum"
} else if name.starts_with("alias ") {
Expand All @@ -515,3 +573,56 @@ fn type_kind(name: &str) -> &str {
"class"
}
}

#[cfg(test)]
mod tests {
use super::*;
use types::HtmlMember;

fn member(name: &str) -> HtmlMember {
HtmlMember {
name: name.to_string(),
anchor: name.to_string(),
short_name: name.rsplit('.').next().unwrap_or(name).to_string(),
..Default::default()
}
}

#[test]
fn search_entries_dedupe_identical_members() {
let mut doc = HtmlDoc::default();
doc.methods.push(member("Mod.foo"));
doc.fields.push(member("Mod.foo"));
let pages = vec![("module/Mod.html".to_string(), doc)];

let entries = build_search_entries(&NavModel::default(), &pages);

assert_eq!(entries.len(), 1, "duplicate member entries: {entries:?}");
assert_eq!(entries[0].name, "Mod.foo");
assert_eq!(entries[0].href, "module/Mod.html#Mod.foo");
assert_eq!(entries[0].kind, "method");
}

#[test]
fn search_entries_use_member_anchor_for_href() {
let mut doc = HtmlDoc::default();
doc.methods.push(HtmlMember {
name: "Mod.foo bar".to_string(),
anchor: "Mod.foo%20bar".to_string(),
..Default::default()
});
let pages = vec![("module/Mod.html".to_string(), doc)];

let entries = build_search_entries(&NavModel::default(), &pages);

assert_eq!(entries.len(), 1);
assert_eq!(entries[0].name, "Mod.foo bar");
assert_eq!(entries[0].href, "module/Mod.html#Mod.foo%20bar");
}

#[test]
fn search_entries_empty_without_docs() {
let entries = build_search_entries(&NavModel::default(), &[]);
assert!(entries.is_empty(), "unexpected entries: {entries:?}");
}
}
7 changes: 7 additions & 0 deletions crates/emmylua_doc_cli/src/html_generator/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ pub struct HtmlMember {
/// Full name including the owner prefix (e.g. `buffer.put`); used as the
/// in-page anchor id so deep links stay unique.
pub name: String,
/// DOM id for this member. The HTML template and the search index both use
/// it, so anchor links cannot drift apart.
///
/// TODO: sanitize / percent-encode anchors for non-name keys (e.g.
/// `["a#b"]`); currently they mirror `name` verbatim.
pub anchor: String,
/// Bare member name (e.g. `put`); shown in the TOC, rustdoc-style.
pub short_name: String,
/// Rendered `<pre>` code block.
Expand Down Expand Up @@ -183,6 +189,7 @@ impl HtmlMember {
}
});
HtmlMember {
anchor: name.clone(),
name,
short_name,
display,
Expand Down
2 changes: 1 addition & 1 deletion crates/emmylua_doc_cli/template/html/item.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ <h2><a class="section-link" href="#fields">Fields</a><span class="section-count"
{% if doc.methods %}
<li><a href="#methods">Methods</a></li>
{% for m in doc.methods %}
<li class="toc-sub"><a href="#{{ m.name }}">{{ m.short_name }}</a></li>
<li class="toc-sub"><a href="#{{ m.anchor }}">{{ m.short_name }}</a></li>
{% endfor %}
{% endif %}
{% if doc.fields %}
Expand Down
2 changes: 1 addition & 1 deletion crates/emmylua_doc_cli/template/html/macros.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{% macro member(m) %}
<div class="member{% if m.deprecated %} is-deprecated{% endif %}" id="{{ m.name }}">
<div class="member{% if m.deprecated %} is-deprecated{% endif %}" id="{{ m.anchor }}">
<div class="member-head">
<span class="member-signature">{{ m.display | safe }}</span>
{% if m.deprecated %}<span class="deprecated-badge">Deprecated</span>{% endif %}
Expand Down
16 changes: 16 additions & 0 deletions crates/emmylua_doc_cli/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ pub fn generate_html_fixture(fixture_name: &str, source: &str) -> PathBuf {
generate_fixture_with_format(fixture_name, source, Format::Html)
}

/// Reads the generated HTML search index as a list of JSON entries.
pub fn read_search_index(out: &Path) -> Vec<serde_json::Value> {
let path = out.join("static").join("search-index.js");
let js = std::fs::read_to_string(&path)
.unwrap_or_else(|err| panic!("read search index {}: {err}", path.display()));
let json = js
.strip_prefix("window.SEARCH_INDEX =")
.unwrap_or_else(|| panic!("unexpected search index format: {js}"))
.trim()
.strip_suffix(';')
.unwrap_or_else(|| panic!("unexpected search index format: {js}"))
.trim();
serde_json::from_str(json)
.unwrap_or_else(|err| panic!("parse search index {}: {err}", path.display()))
}

/// Generates a JSON fixture and returns the generated `doc.json` contents.
pub fn generate_json_fixture(fixture_name: &str, source: &str) -> serde_json::Value {
let out = generate_fixture_with_format(fixture_name, source, Format::Json);
Expand Down
Loading
Loading