mdBook
mdBook copied to clipboard
Is it possible to remember the folding state of foldable chapters configured via `output.html.fold`?
Question
Chapters can be made fold-able via [output.html.fold]
but its folding state is reset every time I reload the browser.
Is it possible to remember the folding state, for example, via Cookie?
Version
No response
Is it possible to remember the folding state, for example, via Cookie?
sidebar status is save and load with "localStorage", you can see save actions here:
https://github.com/rust-lang/mdBook/blob/02f3823e4caae28cc0b1ceac284f81743f8fd29b/src/theme/book.js#L459
https://github.com/rust-lang/mdBook/blob/02f3823e4caae28cc0b1ceac284f81743f8fd29b/src/theme/book.js#L481
and load action when it is displayed:
https://github.com/rust-lang/mdBook/blob/02f3823e4caae28cc0b1ceac284f81743f8fd29b/src/theme/index.hbs#L99-L104
foldable chapters is controlled by js-click to toggle css class "expanded"
https://github.com/rust-lang/mdBook/blob/02f3823e4caae28cc0b1ceac284f81743f8fd29b/src/theme/book.js#L465-L471
afaik it's a js work but maybe need process anchor in rust.
i hope this could help you.
I ended up implementing a quick scripts to add an id to each expandable/toggle sections and keep track of the folding state in localStorage.
function toggleSection(ev) {
ev.currentTarget.parentElement.classList.toggle('expanded');
const toggleId = ev.currentTarget.parentElement.getAttribute('toggle-id');
const isExpanded = ev.currentTarget.parentElement.classList.contains('expanded');
try {
localStorage.setItem(`mdbook-sidebar-toggle-${toggleId}`, isExpanded ? 1 : 0);
} catch (e) {}
}
Array.from(sidebarAnchorToggles).forEach(function (el, id) {
el.parentElement.setAttribute('toggle-id', id);
const isActive = el.parentElement.nextSibling.querySelector('.active') !== null || el.previousSibling.classList.contains('active');
if (!isActive) {
try {
const isExpanded = localStorage.getItem(`mdbook-sidebar-toggle-${id}`) === '1';
if (!isExpanded) {
el.parentElement.classList.remove('expanded');
}
localStorage.setItem(`mdbook-sidebar-toggle-${id}`, isExpanded ? 1 : 0);
} catch (e) {
el.parentElement.classList.remove('expanded');
}
}
el.addEventListener('click', toggleSection);
});