spring-bootasciidocspring-restdocs

How to collapse TOC(table of contents) in spring RestDoc (asciidoc)?


I had used SpringRestDoc and want to collapse Table of Contents.

Below my index.adoc

= Service Rest Docs API Document
:doctype: book
:icons: font
:source-highlighter: highlightjs
:toc2: left
:theme: flatly
:toclevels: 1
:sectlinks:

[[introduction]]

== information

----
Spring Rest Document
----

...

Thanks,


Solution

  • The default template for Asciidoctor does not include functionality to expand/collapse the ToC. You would need to add your own CSS/JavaScript to achieve that goal.

    The simplest way to do that is to use a "docinfo" file. See https://docs.asciidoctor.org/asciidoctor/latest/docinfo/ for details.

    Here is a very simplistic implementation that demonstrates the concept:

    1. In your document, in the header (say, just under the :doctype: attribute definition), add the line :docinfo: shared.

    2. Create a file called "docinfo.html" in the same folder as your document; this file contains your custom CSS and JavaScript.

    3. Add the following content to the docinfo.html file:

      <style>
      button.tocSwitch {
        position: absolute;
        top: 0;
        left: 0;
      }
      </style>
      
      <script>
      document.addEventListener('DOMContentLoaded', function () {
        var target = document.querySelector('#header')
        var button = document.createElement('button')
        button.className = 'tocSwitch'
        button.innerHTML = 'ToC'
        button.addEventListener('click', function (e) {
          e.stopPropagation()
          var toc = document.querySelector('#toc')
          var body = document.querySelector('body')
          if (body.classList.contains('toc2')) {
            body.classList.remove('toc2')
            body.classList.remove('toc-left')
            toc.style.display = 'none'
          }
          else {
            body.classList.add('toc2')
            body.classList.add('toc-left')
            toc.style.display = 'block'
          }
        })
        target.appendChild(button)
      })
      </script>
      

    This content defines some CSS styling for a button, and some JavaScript the dynamically creates the button, adds the button to the header of the page, and an event listener such that when you click the button, the appropriate class name and CSS style adjustments are made to show/hide the ToC.