Continuing the discussion from Is there markdown for creating a table of contents in a topic?:
Ok, I’d really like to see this happen, so here’s my attempt at making a spec for it.
This feature allows the automatic creation of a table of contents for any post (although it’s best suited to Wiki posts).
Details
- To invoke the feature, add the
[contents]
markup to a post. - After cooking the markdown, the code scans the post below the
[contents]
markup and adds an anchor before each Header element (this allows for a preamble or top-level title to be excluded from the contents). - The text and anchor of those Header elements are then composed into a
<ul>
and inserted at the location of the[contents]
markup. - Each sub-list should be indented by relative hierarchy, not Header size. This allows for “jumps” in Header size to produce a tidily indented list.
- List item styling, however, is applied based on the Header level it refers to.
Examples with the list item styles H1 H2 and H3:
H1
H2
H2
H2
H1
H3
H3
H3
H2
H3
H3
H3
H1
H3
H3
H2
H3
H3
H1
H2
H3
H3
H2
H3
H3
Options
[contents min=1 max=3]
where min and max are the limits of H elements to index. I suppose it should support up to H6 given that those can be generated with HTML. 1 and 3 are the default if left unspecified.
I toyed with a style= parameter for bullets or numbers, but I think numbers will be misleading because the contents of the post are subject to change, making the numbering inconsistent over time.
Example output
Pay close attention to the numbers!
<div class="toc-wrapper">
<ul class ="toc-h1">
<li><a href="#h1-1">Header text</a></li>
<li><a href="#h1-2">Header text</a></li>
<li><a href="#h1-3">Header text</a></li>
<ul class="toc-h2">
<li><a href="#h2-1">Subheader text</a></li>
<li><a href="#h2-2">Subheader text</a></li>
<ul class="toc-h3>
<li>a href="#h3-1">Sub-subheader text</a>
<li>a href="#h3-2">Sub-subheader text</a>
<li>a href="#h3-3">Sub-subheader text</a>
</ul>
<li><a href="#h2-3">Subheader text</a></li>
</ul>
<li><a href="#h1-4">Header text</a></li>
<li><a href="#h1-3">Header text</a></li>
<ul class="toc-h3">
<li><a href="#h3-4">Sub-subheader text</a></li>
<li><a href="#h3-5">Sub-subheader text</a></li>
</ul>
</ul>
</div>
Where “h1-3” is the anchor of the third H1 element in the topic etc.
I suppose you could generate random strings if you want to reduce the chances of clashing with a user-generated Anchor somewhere else in the post.
##Mockup
This post: Laser Cutter - Trotec Speedy 300 - Tools - Discourse – South London Makerspace
Makes his sort of thing, only prettier because I’m just slapping this together in Paint. If I have time later, I might do a more carefully designed mockup.
##Thoughts
It takes up a lot of vertical space. Maybe it could be pushed into one of the gutters at wider window sizes? Or even float over the gutter as you scroll, so you can always access it from all points in the post?