Skip to content

Commit 9e28156

Browse files
committed
rustdoc: Move sidebar items into shared JavaScript.
It had been a source of huge bloat in rustdoc outputs. Of course, we can simply disable compiler docs (as `rustc` generates over 90M of HTML) but this approach fares better even after such decision. Each directory now has `sidebar-items.js`, which immediately calls `initSidebarItems` with a JSON sidebar data. This file is shared throughout every item in the sidebar. The current item is highlighted via a separate JS snippet (`window.sidebarCurrent`). The JS file is designed to be loaded asynchronously, as the sidebar is rendered before the content and slow sidebar loading blocks the entire rendering. For the minimal accessibility without JS, links to the parent items are left in HTML. In the future, it might also be possible to integrate crates data with the same fashion: `sidebar-items.js` at the root path will do that. (Currently rustdoc skips writing JS in that case.) This has a huge impact on the size of rustdoc outputs. Originally it was 326MB uncompressed (37.7MB gzipped, 6.1MB xz compressed); it is 169MB uncompressed (11.9MB gzipped, 5.9MB xz compressed) now. The sidebar JS only takes 10MB uncompressed & 0.3MB gzipped.
1 parent 14f0942 commit 9e28156

File tree

2 files changed

+99
-72
lines changed

2 files changed

+99
-72
lines changed

src/librustdoc/html/render.rs

Lines changed: 34 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -65,12 +65,10 @@ use html::item_type::ItemType;
6565
use html::layout;
6666
use html::markdown::Markdown;
6767
use html::markdown;
68-
use html::escape::Escape;
6968
use stability_summary;
7069

7170
/// A pair of name and its optional document.
72-
#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
73-
pub struct NameDoc(String, Option<String>);
71+
pub type NameDoc = (String, Option<String>);
7472

7573
/// Major driving force in all rustdoc rendering. This contains information
7674
/// about where in the tree-like hierarchy rendering is occurring and controls
@@ -96,12 +94,6 @@ pub struct Context {
9694
/// This describes the layout of each page, and is not modified after
9795
/// creation of the context (contains info like the favicon and added html).
9896
pub layout: layout::Layout,
99-
/// This map is a list of what should be displayed on the sidebar of the
100-
/// current page. The key is the section header (traits, modules,
101-
/// functions), and the value is the list of containers belonging to this
102-
/// header. This map will change depending on the surrounding context of the
103-
/// page.
104-
pub sidebar: HashMap<String, Vec<NameDoc>>,
10597
/// This flag indicates whether [src] links should be generated or not. If
10698
/// the source files are present in the html rendering, then this will be
10799
/// `true`.
@@ -265,7 +257,6 @@ pub fn run(mut krate: clean::Crate,
265257
passes: passes,
266258
current: Vec::new(),
267259
root_path: String::new(),
268-
sidebar: HashMap::new(),
269260
layout: layout::Layout {
270261
logo: "".to_string(),
271262
favicon: "".to_string(),
@@ -1227,7 +1218,16 @@ impl Context {
12271218
clean::ModuleItem(m) => m,
12281219
_ => unreachable!()
12291220
};
1230-
this.sidebar = this.build_sidebar(&m);
1221+
1222+
// render sidebar-items.js used throughout this module
1223+
{
1224+
let items = this.build_sidebar_items(&m);
1225+
let js_dst = this.dst.join("sidebar-items.js");
1226+
let mut js_out = BufferedWriter::new(try!(File::create(&js_dst)));
1227+
try!(write!(&mut js_out, "initSidebarItems({});",
1228+
json::as_json(&items)));
1229+
}
1230+
12311231
for item in m.items {
12321232
f(this,item);
12331233
}
@@ -1247,15 +1247,11 @@ impl Context {
12471247
}
12481248
}
12491249

1250-
fn build_sidebar(&self, m: &clean::Module) -> HashMap<String, Vec<NameDoc>> {
1250+
fn build_sidebar_items(&self, m: &clean::Module) -> HashMap<String, Vec<NameDoc>> {
12511251
let mut map = HashMap::new();
12521252
for item in &m.items {
12531253
if self.ignore_private_item(item) { continue }
12541254

1255-
// avoid putting foreign items to the sidebar.
1256-
if let &clean::ForeignFunctionItem(..) = &item.inner { continue }
1257-
if let &clean::ForeignStaticItem(..) = &item.inner { continue }
1258-
12591255
let short = shortty(item).to_static_str();
12601256
let myname = match item.name {
12611257
None => continue,
@@ -1264,7 +1260,7 @@ impl Context {
12641260
let short = short.to_string();
12651261
let v = map.entry(short).get().unwrap_or_else(
12661262
|vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
1267-
v.push(NameDoc(myname, Some(shorter_line(item.doc_value()))));
1263+
v.push((myname, Some(shorter_line(item.doc_value()))));
12681264
}
12691265

12701266
for (_, items) in &mut map {
@@ -2211,9 +2207,11 @@ impl<'a> fmt::Display for Sidebar<'a> {
22112207
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
22122208
let cx = self.cx;
22132209
let it = self.item;
2210+
let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
2211+
2212+
// this is not rendered via JS, as that would hamper the accessibility
22142213
try!(write!(fmt, "<p class='location'>"));
2215-
let len = cx.current.len() - if it.is_mod() {1} else {0};
2216-
for (i, name) in cx.current.iter().take(len).enumerate() {
2214+
for (i, name) in cx.current.iter().take(parentlen).enumerate() {
22172215
if i > 0 {
22182216
try!(write!(fmt, "::<wbr>"));
22192217
}
@@ -2223,40 +2221,25 @@ impl<'a> fmt::Display for Sidebar<'a> {
22232221
}
22242222
try!(write!(fmt, "</p>"));
22252223

2226-
fn block(w: &mut fmt::Formatter, short: &str, longty: &str,
2227-
cur: &clean::Item, cx: &Context) -> fmt::Result {
2228-
let items = match cx.sidebar.get(short) {
2229-
Some(items) => items,
2230-
None => return Ok(())
2231-
};
2232-
try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
2233-
for &NameDoc(ref name, ref doc) in items {
2234-
let curty = shortty(cur).to_static_str();
2235-
let class = if cur.name.as_ref().unwrap() == name &&
2236-
short == curty { "current" } else { "" };
2237-
try!(write!(w, "<a class='{ty} {class}' href='{href}{path}' \
2238-
title='{title}'>{name}</a>",
2239-
ty = short,
2240-
class = class,
2241-
href = if curty == "mod" {"../"} else {""},
2242-
path = if short == "mod" {
2243-
format!("{}/index.html", name)
2244-
} else {
2245-
format!("{}.{}.html", short, name)
2246-
},
2247-
title = Escape(doc.as_ref().unwrap()),
2248-
name = name));
2249-
}
2250-
try!(write!(w, "</div>"));
2251-
Ok(())
2224+
// sidebar refers to the enclosing module, not this module
2225+
let relpath = if shortty(it) == ItemType::Module { "../" } else { "" };
2226+
try!(write!(fmt,
2227+
"<script>window.sidebarCurrent = {{\
2228+
name: '{name}', \
2229+
ty: '{ty}', \
2230+
relpath: '{path}'\
2231+
}};</script>",
2232+
name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
2233+
ty = shortty(it).to_static_str(),
2234+
path = relpath));
2235+
if parentlen == 0 {
2236+
// there is no sidebar-items.js beyond the crate root path
2237+
// FIXME maybe dynamic crate loading can be merged here
2238+
} else {
2239+
try!(write!(fmt, "<script async src=\"{path}sidebar-items.js\"></script>",
2240+
path = relpath));
22522241
}
22532242

2254-
try!(block(fmt, "mod", "Modules", it, cx));
2255-
try!(block(fmt, "struct", "Structs", it, cx));
2256-
try!(block(fmt, "enum", "Enums", it, cx));
2257-
try!(block(fmt, "trait", "Traits", it, cx));
2258-
try!(block(fmt, "fn", "Functions", it, cx));
2259-
try!(block(fmt, "macro", "Macros", it, cx));
22602243
Ok(())
22612244
}
22622245
}

src/librustdoc/html/static/main.js

Lines changed: 65 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,27 @@
1515
"use strict";
1616
var resizeTimeout, interval;
1717

18+
// This mapping table should match the discriminants of
19+
// `rustdoc::html::item_type::ItemType` type in Rust.
20+
var itemTypes = ["mod",
21+
"externcrate",
22+
"import",
23+
"struct",
24+
"enum",
25+
"fn",
26+
"type",
27+
"static",
28+
"trait",
29+
"impl",
30+
"tymethod",
31+
"method",
32+
"structfield",
33+
"variant",
34+
"macro",
35+
"primitive",
36+
"associatedtype",
37+
"constant"];
38+
1839
$('.js-only').removeClass('js-only');
1940

2041
function getQueryStringParams() {
@@ -552,27 +573,6 @@
552573
showResults(results);
553574
}
554575

555-
// This mapping table should match the discriminants of
556-
// `rustdoc::html::item_type::ItemType` type in Rust.
557-
var itemTypes = ["mod",
558-
"externcrate",
559-
"import",
560-
"struct",
561-
"enum",
562-
"fn",
563-
"type",
564-
"static",
565-
"trait",
566-
"impl",
567-
"tymethod",
568-
"method",
569-
"structfield",
570-
"variant",
571-
"macro",
572-
"primitive",
573-
"associatedtype",
574-
"constant"];
575-
576576
function itemTypeFromName(typename) {
577577
for (var i = 0; i < itemTypes.length; ++i) {
578578
if (itemTypes[i] === typename) return i;
@@ -708,6 +708,50 @@
708708

709709
window.initSearch = initSearch;
710710

711+
// delayed sidebar rendering.
712+
function initSidebarItems(items) {
713+
var sidebar = $('.sidebar');
714+
var current = window.sidebarCurrent;
715+
716+
function block(shortty, longty) {
717+
var filtered = items[shortty];
718+
if (!filtered) return;
719+
720+
var div = $('<div>').attr('class', 'block ' + shortty);
721+
div.append($('<h2>').text(longty));
722+
723+
for (var i = 0; i < filtered.length; ++i) {
724+
var item = filtered[i];
725+
var name = item[0];
726+
var desc = item[1]; // can be null
727+
728+
var klass = shortty;
729+
if (name === current.name && shortty == current.ty) {
730+
klass += ' current';
731+
}
732+
var path;
733+
if (shortty === 'mod') {
734+
path = name + '/index.html';
735+
} else {
736+
path = shortty + '.' + name + '.html';
737+
}
738+
div.append($('<a>', {'href': current.relpath + path,
739+
'title': desc,
740+
'class': klass}).text(name));
741+
}
742+
sidebar.append(div);
743+
}
744+
745+
block("mod", "Modules");
746+
block("struct", "Structs");
747+
block("enum", "Enums");
748+
block("trait", "Traits");
749+
block("fn", "Functions");
750+
block("macro", "Macros");
751+
}
752+
753+
window.initSidebarItems = initSidebarItems;
754+
711755
window.register_implementors = function(imp) {
712756
var list = $('#implementors-list');
713757
var libs = Object.getOwnPropertyNames(imp);

0 commit comments

Comments
 (0)