Repository navigation
Description
Have you read the Contributing Guidelines on issues?
- I have read the Contributing Guidelines on issues.
Description
Docusaurus currently allows manually altering (and even outright replacing) the ToC in Docs, as per #3915 (comment), but this is not documented.
This issue is as much a question on whether this is something we can expect to rely on, as a request to document it if the answer is "yes".
Has this been requested on Canny?
No response
Motivation
This is useful for documentation that is generated from other sources (in this case, a man page): while the HTML can be injected, the ToC does not follow suit (and I wouldn't expect it to. Or is that preferable?).
API design
Here is a doc which largely consists of externally-generated HTML, for which we additionally generate the ToC via a script.
# rgbds(5) — object file format documentation
import generated from '!!raw-loader!./rgbds.5.html';
<div className="manual-text" dangerouslySetInnerHTML={{ __html: generated }} />
export const toc = [
{
"value": "DESCRIPTION",
"id": "DESCRIPTION",
"level": 2,
},
{
"value": "FILE STRUCTURE",
"id": "FILE_STRUCTURE",
"level": 2,
},
{
"value": "Header",
"id": "Header",
"level": 3,
},
{
"value": "Source file info",
"id": "Source_file_info",
"level": 3,
},
{
"value": "Symbols",
"id": "Symbols",
"level": 3,
},
{
"value": "Sections",
"id": "Sections",
"level": 3,
},
{
"value": "Assertions",
"id": "Assertions",
"level": 3,
},
{
"value": "RPN EXPRESSIONS",
"id": "RPN_EXPRESSIONS",
"level": 3,
},
{
"value": "SEE ALSO",
"id": "SEE_ALSO",
"level": 2,
},
{
"value": "HISTORY",
"id": "HISTORY",
"level": 2,
},
];Have you tried building it?
If the existing behavior is to be accepted as official, then nothing needs to be built; otherwise, what replacement API is deemed better will need to be discussed first.
Self-service
- I'd be willing to contribute this feature to Docusaurus myself.
Activity
Josh-Cena commentedon Dec 27, 2021
Hi, since this feature is already in place, is it essentially a documentation request?
The TOC shape is most likely stable, and it's kind of documented here: https://docusaurus.io/docs/next/markdown-features/inline-toc#custom-table-of-contents However, up till now we haven't figured out an ergonomic way to let you use it. For example, #3915 is very likely to be solved by letting you code a TOC yourself.
ISSOtm commentedon Dec 29, 2021
This is first a question about whether modifying the ToC like in the example is intended to be part of the API, or is just exposed internals.
If the answer is yes, then this is a documentation request. If it's no, this is a request for an alternative.
This is not intended to supersede #3915, as is explained in the comment that I originally linked to, though it can be used as a stopgap in the meantime.
slorber commentedon Dec 29, 2021
This is internal implementation detail that is IMHO stable enough to use externally.
We could document it and make it officially a public API, but it probably requires some upfront thinking to be sure that the current API is the best way to solve your use-case
ISSOtm commentedon Dec 29, 2021
It fits exactly my use case, since this document has the entirety of its content auto-generated.
However, if only a section were to be as such, then I'd want to be able to splice the ToC accordingly, more similarly to #3915. I think this could be arranged by having a file—
autogenned.md—use this mechanism to manually specify the entirety of its own ToC, and then includingautogenned.mdperforming the splice like requested in that PR.Hopefully I didn't sound too confused?
slorber commentedon Dec 30, 2021
If we add this to our doc, we should probably dogfood this on our own doc, explaining the constraints (like elements requiring a unique id for linking to work). We could showcase manual construction of a toc for generated HTML (like your case).
We should probably add this to this page (to be renamed as just "TOC"?): https://docusaurus.io/docs/markdown-features/inline-toc
Do you want to submit a PR?
I'm not sure what you mean by
autogenned.mdbut I'd rather avoid showcasing the "import mdx partial" case of #3915, as it's not really a feature but an actual bug/limitation that we really want to solve.Josh-Cena commentedon Dec 30, 2021
@slorber What about we invent a "TOC enhancement" syntax ourselves and parse that in the TOC generating remark plugin?
I don't have a clear plan yet, but it would be something like:
import Content, {partialToc} from './_partial.md'; # A Markdown page ## Actual Heading 1 [[insert toc]] - Inserted Heading 1 - Inserted Heading 2 - Subheading 1 ## Actual Heading 2 <Content /> [[import toc: partialToc]]Which will generate a TOC:
However, importing partials are very difficult. We either have to actually read the imported file and parse that as well, or we just let the user import that and we spread it into the final TOC. In the former case, we need to actually keep track of the imported component => MD file path mapping and read & parse more files, and means sacrificed performance; in the latter case, it means we can't be sure how the partial TOC should be spread. For example, for the example above, if
./_partial.mdactually looks like:Then the final TOC should have the two "Imported Subheading"'s as children of "Actual Heading 2" instead of spreading it to the root of TOC.
In hindsight it may be better if we have started off designing our server-side TOC structure as a flat list instead of a recursive tree. It's going to be rendered on client-side as a list anyways and we hardly take advantage of the tree structure. For now we recursively render each TOC level, but we could well use
tocItems.map(i => <TOCItem item={i} />)...slorber commentedon Dec 30, 2021
@Josh-Cena I'm not sure it's really related to this issue, as here the content is in HTML and not a mdx partial import.
That's something I thought about but do we really want to invent a syntax that will only serve temporarily? I'm already not a fan of inventing a non-std md syntax 😅
The end goal is that the TOC works for imported files automatically, without asking the user to use any new fancy syntax.
I don't think we should do that, it duplicates work to each doc importing a partial and also adds more weight to each page, as the shared toc ends up being duplicated in each doc
We'd rather favor composition and have a remark plugin that compose the toc from current doc and partials without inlining the partial tocs into the document, like your spread example, but handled automatically by the remark plugin, not hand-written by the user
Good point, it will probably be needed to flatten that structure
So we are maybe not ready to make this "manual toc" feature an official public API 😅
Josh-Cena commentedon Dec 30, 2021
I'm proposing this custom TOC syntax in place of handwriting the entire TOC structure which contains a lot of boilerplate. If we have that, we don't need to document the
export toc = ...syntax at all. Also, currently it's all or nothing: you write everything or you let Remark do it all, there's no progressive enhancement. Such an API is not ready to be documented, and we can't extend this API to allow enhancement either, we have to do it from scratch.As I said, it means we have to "understand" that
<Content />is an MDX partial, not a JSX component, which isn't easy. I've tried a while back to implement a Remark plugin and call Babel to parse the JSX for me, but overall it's a very painful thing to let Remark understand JSX. It also means we have to insert an extra{toc}named import back into theimport Content from './_partial.mdx'statement, and that can be intractable.Then there's the question of (a) user wanting to hide some headings from the TOC and (b) user wanting to insert extra headings that would otherwise not be visible to Remark. We would need a way to let users handwrite & insert part of the TOC, hence the proposal for the
[[Inserted TOC]]and[[Imported TOC]]syntax. Even if[[Imported TOC]]can be heavylifted by us,[[Inserted TOC]]is there to stay.Glad I made the flattened list point through :P Going to see what we can do about it
Josh-Cena commentedon Jan 1, 2022
This will be triaged as a feature request and we will figure out an ergonomic way to tweak the TOC structure.
Just for reference, VuePress has this
[[toc]]syntax: https://v2.vuepress.vuejs.org/guide/markdown.html#table-of-contents It's not anywhere close to the functionality we are discussing here, but the syntax is similar[-]Manually alter the sidebar ToC from within docs[/-][+]Ergonomic way to enhance ToC within Markdown: imported toc, insert TOC slice...[/+][-]Ergonomic way to enhance ToC within Markdown: imported toc, insert TOC slice...[/-][+]Ergonomic way to enhance ToC within Markdown: imported TOC, insert TOC slice...[/+]ISSOtm commentedon Jan 1, 2022
Fine by me, then. I'll keep relying on
tocuntil then.18 remaining items
slorber commentedon Jul 20, 2023
@nullromo we are not using remark-toc: we have our own custom Docusaurus toc remark plugin.
If the remark-toc package does not behave the way you want we can't do anything for you, and you should report it to that plugin author directly.
In any case, you can provide an explicit toc structure yourself on any doc that overrides the one we compute:
You can also take over how this structure is rendered with swizzle.
I agree that's probably not ideal and requires maintenance, but that works
If your goal is to only have placeholders in headings (and not dynamic headings that are present/absent conditionally), that can probably be implemented with a remark plugin:
## Getting Started with %%PRODUCT_NAME%%We don't provide such plugins but you'll find useful information here and code examples here:
#395
This code example is probably the best to get started: #395 (comment)
You can probably tweak it a bit so that it also substitutes variables in markdown headings
You could even imagine a plugin that add/remove sections conditionally:
If your remark plugin runs before our custom toc plugin (tip: use
beforeDefaultRemarkPlugins, see https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-content-docs#beforeDefaultRemarkPlugins), you have the ability to add/remove content to the MDX doc dynamically. We'll compute the toc based on what remains in the AST after those plugins have run.So if your "before" remark plugin removes everything that's inside a JSX
<ProductAOnly>block, then our TOC plugin won't see the headings that have been removed earlier.Our TOC plugin is pretty simply, it mostly collects all headings found in the MD AST and add them to the
export const toc. In pseudo-code:nullromo commentedon Jul 20, 2023
@slorber Thanks for the advice. I was able to come up with a plugin just like how you described. Unfortunately, I still didn't find a way to actually parse through the JSX nodes within the AST, so I just have to use a regex to determine which nodes I want to remove. I'll post the code here (with names changed) for reference.
Plugin
Components
Markdown
I don't necessarily like the regex matching technique here because it kind of blindly removes stuff without really knowing what's going on. For example, if my approach is to remove everything between the opening and closing tags (
<ProductAParagraph>and</ProductAParagraph>), then what happens when I try to use a self-closing tag (<ProductAParagraph />)? Things are going to get messed up.So if there's any way that you know of to actually process JSX from inside a remark plugin, I'd love to hear about it.
In any case, thanks a lot for the help! Glad I now have a suitable workaround 🎉
slorber commentedon Jul 21, 2023
First: I'd recommend implementing this in Docusaurus v3 (MDX is now at v2), currently in alpha.
That was just to give you a direction, I have not implemented this myself. If you want to build this properly you have to learn MDX / Unified and how all things work together: you can't skip reading the doc and investing some time.
You should inspect the produced AST tree and see which nodes you want to remove. Most likely the nodes will look like this:
What I would do is use a visitor to visit all
mdxJsxFlowElement, and remove some of them conditionally. You don't need a regexp for that and self-closing tags are handled: there will be no children in such nodes.Again this is just an idea and direction: you'll have to figure out the details yourself and learn how these things work.
jeluard commentedon Mar 21, 2024
Exporting the global
tocapparently doesn't work anymore with docusaurus v3. Is there an alternative to programmatically set the toc?slorber commentedon Mar 21, 2024
@jeluard while improving the TOC to support imported docs, I noticed a strange behavior.
Related discussion:
#7530 (comment)
Apparently, exporting
tocwould only work on docs that don't contain any heading.But as soon as you have headings (>= level 2), they get used in priority over your exported TOC.
This didn't look good to me, so I fixed this behavior for Docusaurus v3.2/canary to always let you the ability to override the generated toc:
https://stackblitz.com/edit/github-zjz2fr?file=docs%2Fintro.mdx,package.json
jeluard commentedon Mar 21, 2024
@slorber I can confirm that it works as expected with canary docusaurus. Thanks!
rtrbt commentedon Apr 16, 2024
Just in case someone else reads this: Some of the custom ToCs in this issue set their children like this:
to create the same ToC as
However (probably since #6729 ) setting children is not necessary anymore and the child entries don't show up in the ToC. This works:
slorber commentedon Apr 16, 2024
Yes I confirm in 2021 we had a nested structure, and now there's no
childrenanymore, the TOC structure is flat.ISSOtm commentedon Apr 19, 2024
Thank you for the notice! I updated upstream, and edited the OP accordingly. This works much better :)
axmmisaka commentedon May 10, 2024
I am wondering if docusaurus has supported customisation of ToC generation, as it appears on the docs website that it did not, but I have discovered a potential use case for us here: lf-lang/lf-lang.github.io#238
We offer docs in 5 different target languages, each might have its unique ToC, and we achieve the language switching via docusaurus tabs. I am thinking of swizziing the tab switch and customise the ToC that is displayed, if possible.
slorber commentedon May 10, 2024
@axmmisaka if you want to put headings inside tabs and expect the TOC to update according to the selected tab, there's another issue for that: #5343
axmmisaka commentedon May 10, 2024
Thanks for the reply.
I would assume that this issue has been designated as a wontfix and contributing to upstream would be the way to have it.
My understanding is that part of the difficulty arise from the fact that we will need to tell remark to parse in a way which records whether or not the header is in a
Tab.A workaround I could think of is to allow the author to supply a header and switch between them on-the-go. This would look ugly but would bypass the remark issue.
I could contribute, for sure, once I am certain that I will not be pip-ed by my employer in the next cycle...... 🤣 but I am skeptical if such change could be merged upstream as we have a very special use-case.
gdude2002 commentedon Jun 25, 2025
Since the Docusaurus docs mentioned leaving use-cases on this issue, I figured I'd throw my (fairly niche) hat into the ring.
On this page, I have some fairly custom React components, representing classes that convert strings to rich types:
Of course, the current TOC approach gives me this:
In this case, it would be nice (though not enough of a need for me to go generating my own full TOCs) to be able to list these components as children under their headers. Currently, I don't think I have any serious way to do this, and I know it's fairly niche, but it is a use-case!