limit toc to two levels and vary style

This commit is contained in:
Joseph Montanaro 2023-08-25 22:22:39 -07:00
parent d1aa23e7c7
commit 0519291bda

View File

@ -6,15 +6,23 @@
items.forEach(i => i.slug = makeSlug(i.text)); items.forEach(i => i.slug = makeSlug(i.text));
const selector = 'h1[id], h2[id], h3[id], h4[id], h6[id]'; const selector = 'h2[id], h3[id]';
let currentHeadingSlug = null; let currentHeadingSlug = null;
let currentSubheadingSlug = null;
function setCurrentHeading() { function setCurrentHeading() {
for (const h of document.querySelectorAll(selector)) { for (const h of document.querySelectorAll(selector)) {
const yPos = h.getBoundingClientRect().y; const yPos = h.getBoundingClientRect().y;
if (yPos > (window.innerHeight / 3)) { if (yPos > (window.innerHeight / 3)) {
break; break;
} }
currentHeadingSlug = h.id; if (h.tagName === 'H2') {
currentHeadingSlug = h.id;
currentSubheadingSlug = null;
}
if (h.tagName === 'H3') {
currentSubheadingSlug = h.id
}
console.log(currentHeadingSlug, currentSubheadingSlug);
} }
} }
@ -26,7 +34,6 @@
<style> <style>
/* move everything out to the left and center it vertically */
#toc { #toc {
position: sticky; position: sticky;
top: 1.5rem; top: 1.5rem;
@ -69,22 +76,37 @@
list-style: none; list-style: none;
} }
/* margin for indentation, padding so that the accent bar for the current /* margin for indentation */
item isn't right on top of it */
li { li {
margin-left: var(--indent, 0); display: flex;
padding-left: 0.5rem;
margin-bottom: 0.15rem;
font-size: 0.9rem; font-size: 0.9rem;
border-left: 0.1rem solid transparent;
} }
li:hover { li.depth-2 {
color: var(--content-color); align-items: stretch;
border-left: 0.1rem solid var(--accent-color); margin-bottom: 0.2rem;
} }
li.current { li.depth-3 {
align-items: center;
margin-bottom: 0.05rem;
}
.marker {
margin-right: 0.5rem;
}
.bar {
width: 0.1rem;
}
.dot {
width: 0.15rem;
height: 0.15rem;
border-radius: 50%;
}
li.current, li:hover {
color: var(--content-color); color: var(--content-color);
border-left: 0.1rem solid var(--accent-color); }
.current .marker, li:hover .marker {
background-color: var(--accent-color);
} }
a { a {
@ -100,12 +122,17 @@
</h5> </h5>
<ul> <ul>
{#each items as item} {#each items as item}
<li {#if item.depth === 2}
style:--indent="{(item.depth - 2) * 0.75}em" <li class="depth-2" class:current={item.slug === currentHeadingSlug} style:align-items="stretch">
class:current={item.slug === currentHeadingSlug} <span class="marker bar"></span>
> <a href="#{item.slug}">{item.text}</a>
<a href="#{item.slug}">{item.text}</a> </li>
</li> {:else if item.depth === 3}
<li class="depth-3" class:current={item.slug === currentSubheadingSlug} style:align-items="center" style:margin-left="0.75em">
<span class="marker dot"></span>
<a href="#{item.slug}">{item.text}</a>
</li>
{/if}
{/each} {/each}
</ul> </ul>
</div> </div>