mdBook icon indicating copy to clipboard operation
mdBook copied to clipboard

Is it possible to remember the folding state of foldable chapters configured via `output.html.fold`?

Open your-diary opened this issue 1 year ago • 2 comments

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?

a

Version

No response

your-diary avatar Aug 25 '23 14:08 your-diary

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.

qaqland avatar Sep 01 '23 03:09 qaqland

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);
    });

julio4 avatar Feb 01 '24 08:02 julio4