//! A site's sidebar: its title, the search box and the tree its Topics
//! sections form, as markup and as the JSON `DevpageSidebar` takes over from.
use crate::document::Document;
use crate::nav;
use super::escape;
/// A site's sidebar, unless it sets `sidebar: false`: its title — left to the
/// navbar when there is one — then `groups`, the tree its Topics sections form,
/// collapsed but for the branch down to the page shown, under the search box.
/// It is the markup
/// [`DevpageSidebar`](crate::widgets::SIDEBAR) renders from the same tree,
/// which follows it as JSON: the page script has React take the sidebar over
/// without changing a node. Before the page paints, a small script opens the
/// entries the reader opened on another visit, as the widget will.
pub(super) fn sidebar(document: &Document, groups: &[nav::Group], current: &str) -> String {
if !document.sidebar {
return String::new();
}
let title = document.navbar.is_empty().then(|| SidebarTitle {
label: document.title.clone(),
href: document.entry(),
logo: document.logo_url(),
});
let mut html = format!(
"<nav id=\"devpage-nav\" data-sidebar=\"{}\">",
escape(&document.entry())
);
if let Some(title) = &title {
html.push_str(&format!(
"<a class=\"document-title{}\" href=\"{}\">{}{}</a>",
if title.href == current {
" current"
} else {
""
},
escape(&title.href),
super::navbar::logo(document),
escape(&title.label)
));
}
html.push_str(SEARCH_BOX);
let groups: Vec<SidebarGroup> = groups
.iter()
.map(|g| SidebarGroup::of(document, g))
.collect();
tree(&groups, current, &mut html);
html.push_str(RESIZE_HANDLE);
html.push_str("</nav>");
let data = SidebarData {
document: document.entry(),
document_path: document.part_url(&document.path()),
current: current.to_string(),
title,
groups,
};
// `<` escaped, so no label can close the script.
let json = serde_json::to_string(&data)
.unwrap_or_default()
.replace('<', "\\u003c");
html.push_str(&format!(
"<script type=\"application/json\" id=\"devpage-sidebar\">{json}</script><script>{OPEN_REMEMBERED}</script>"
));
html
}
/// The search box at the top of the sidebar, as `DevpageSidebar` renders it
/// before anything is typed: the field, and the `/` that focuses it.
const SEARCH_BOX: &str = "<div class=\"search\"><input type=\"search\" placeholder=\"Search\" aria-label=\"Search the documents\" autocomplete=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"false\" aria-autocomplete=\"list\" value=\"\"><kbd>/</kbd></div>";
/// The handle on the sidebar's edge, as `DevpageSidebar` renders it: dragged,
/// it sets the sidebar's width.
const RESIZE_HANDLE: &str = "<div class=\"resize\" role=\"separator\" aria-orientation=\"vertical\" aria-label=\"Resize the sidebar\" tabindex=\"0\"></div>";
/// Runs before the page paints. It gives the sidebar the width the reader
/// dragged it to, which `DevpageSidebar` keeps in `localStorage` under
/// `devpage-sidebar-width`. It opens the entries the reader opened on
/// another visit to the document, which `DevpageSidebar` keeps in
/// `localStorage` under `devpage-sidebar:` and the document's address: only
/// what the widget's first render will, so React takes over the same DOM.
/// Then it scrolls the sidebar so the page shown is in sight, in the middle
/// when it was not, as `DevpageSidebar` does after a page swap.
const OPEN_REMEMBERED: &str = "(()=>{const nav=document.getElementById(\"devpage-nav\");let opened;try{const w=parseInt(localStorage.getItem(\"devpage-sidebar-width\"));if(w)document.documentElement.style.setProperty(\"--sidebar-width\",w+\"px\")}catch{}try{opened=JSON.parse(localStorage.getItem(\"devpage-sidebar:\"+nav.dataset.sidebar))}catch{}if(Array.isArray(opened))for(const li of nav.querySelectorAll(\"li.branch:not(.open)\"))if(opened.includes(li.dataset.href)){li.classList.add(\"open\");li.querySelector(\".chevron\").setAttribute(\"aria-expanded\",\"true\")}const a=nav.querySelector(\"ul a.current\");if(!a)return;const n=nav.getBoundingClientRect(),r=a.getBoundingClientRect();if(r.top<n.top||r.bottom>n.bottom)nav.scrollTop+=r.top-n.top-(n.height-r.height)/2})()";
/// What `DevpageSidebar` renders: the document it belongs to (its address,
/// which keys what the reader opened, and its document file's, which a
/// search hit names it by), the page shown, the title link when the sidebar
/// has one, and the tree.
#[derive(serde::Serialize)]
struct SidebarData {
/// The document's address, which keys what the reader opened.
document: String,
/// The address of the document's file, which a search hit names the
/// document by.
document_path: String,
/// The address of the page shown.
current: String,
/// The title link; `None` when the navbar shows the title instead.
title: Option<SidebarTitle>,
/// The tree the Topics sections form.
groups: Vec<SidebarGroup>,
}
/// The link at the top of the sidebar to the document's entry page.
#[derive(serde::Serialize)]
struct SidebarTitle {
/// The link's text: the document's title.
label: String,
/// The address of the document's entry page.
href: String,
/// The logo's address; `None` when the document has none, or its file
/// is missing from the served folder.
logo: Option<String>,
}
/// One group of the tree: its entries under an optional heading.
#[derive(serde::Serialize)]
struct SidebarGroup {
/// The group's heading; `None` when it has none.
title: Option<String>,
/// The group's entries, in order.
entries: Vec<SidebarEntry>,
}
/// One entry of the tree: a page's link and the groups nested under it.
#[derive(serde::Serialize)]
struct SidebarEntry {
/// The link's text: the entry's label in the Topics tree.
label: String,
/// The page's address; an entry whose file has none is left out.
href: String,
/// The groups nested under the entry; empty for a leaf.
children: Vec<SidebarGroup>,
}
impl SidebarGroup {
/// `group` of `document`'s Topics as the sidebar shows it, with each file as
/// its address. An entry whose file has no address is left out.
fn of(document: &Document, group: &nav::Group) -> Self {
Self {
title: group.title.clone(),
entries: group
.entries
.iter()
// An entry is a file the served folder resolved; one outside
// it would have no address, and is left out.
.filter_map(|entry| {
Some(SidebarEntry {
label: entry.label.clone(),
href: document.url(&entry.file)?,
children: entry
.children
.iter()
.map(|g| SidebarGroup::of(document, g))
.collect(),
})
})
.collect(),
}
}
}
impl SidebarEntry {
/// Whether the page shown is this entry or under it: the entries open
/// when a page is shown.
fn leads_to(&self, current: &str) -> bool {
self.is(current)
|| self
.children
.iter()
.flat_map(|g| &g.entries)
.any(|e| e.leads_to(current))
}
}
impl SidebarEntry {
/// Whether this entry is the page shown.
fn is(&self, current: &str) -> bool {
self.href == current
}
}
/// The tree as nested `<ul>` lists: a group's title as a heading in place, an
/// entry with children as a branch — its link, a chevron that opens and
/// closes it, and its children's list, shown while open. No text sits
/// between elements: React renders none.
fn tree(groups: &[SidebarGroup], current: &str, html: &mut String) {
if groups.is_empty() {
return;
}
html.push_str("<ul>");
for group in groups {
if let Some(title) = &group.title {
html.push_str(&format!(
"<li class=\"group\"><span>{}</span></li>",
escape(title)
));
}
for entry in &group.entries {
let href = escape(&entry.href);
let label = escape(&entry.label);
let class = if entry.is(current) {
" class=\"current\""
} else {
""
};
if entry.children.is_empty() {
html.push_str(&format!("<li><a href=\"{href}\"{class}>{label}</a></li>"));
continue;
}
let open = entry.leads_to(current);
html.push_str(&format!(
"<li class=\"branch{}\" data-href=\"{href}\"><div class=\"entry\"><a href=\"{href}\"{class}>{label}</a><button type=\"button\" class=\"chevron\" aria-expanded=\"{open}\" aria-label=\"{label}\"></button></div>",
if open { " open" } else { "" },
));
tree(&entry.children, current, html);
html.push_str("</li>");
}
}
html.push_str("</ul>");
}