pkra / laml-wc

A continuation of an experiment
https://pkra.github.io/laml-wc
0 stars 0 forks source link

table of contents #14

Closed scoskey closed 10 months ago

scoskey commented 11 months ago

or other navigation

of course there are tools that automatically generate such...

pkra commented 11 months ago

Oh yeah, that's an easy web component, I think.

pkra commented 11 months ago

The hardest part is probably around IDs / hashes. Cool URLs don't change and all that.

Do we expect authors to specify them? If we generate them, they probably shouldn't be random. Basing them on the heading content is usually a good plan but could lead to duplicates (e.g., each chapter having a section "Exercises").

pkra commented 11 months ago

Very quick experiment:

class toc extends HTMLElement {
  constructor() {
    super()
  }
  connectedCallback() {
    document.querySelectorAll('h-').forEach(node => { if (!node.id) node.id = self.crypto.randomUUID() })
    let headings = document.querySelectorAll('h-[aria-level="2"]');
    this.insertAdjacentHTML('beforeend',
      `<nav aria-label="table of contents">
        <ul>
        ${[...headings].map(node => 
           `<li>
                <a href="#${node.id}">${node.innerHTML}</a> 
               <ul>
                ${[...node.parentNode.querySelectorAll('h-[aria-level="3"]')].map(nested => 
                      `<li><a href="#${nested.id}">${nested.innerHTML}</li>`).join('')}
                </ul>
             </li>`).join('')}
         </ul>
       </nav>`)
  }
}
customElements.define('toc-', toc);
scoskey commented 11 months ago

Laughed about the cool URI's...

I guess the author could supply, otherwise it gets generated?

pkra commented 11 months ago

I guess the author could supply, otherwise it gets generated?

I suspect authors don't want to do that for each chapter & section (and whatever else they want in a customized TOC).

It's probably safe to generate them from heading content initially and consider duplicate IDs an author error. If we feel like it, we can later add a simple counter suffix when detecting duplicate IDs.

pkra commented 11 months ago

Ugh - sorry. Shouldn't reply so early. I copied but didn't register "or gets generated".

So yes, I agree vehemently. :rofl: