theme: Add anchor links via JS

This commit is contained in:
Bjørn Erik Pedersen 2025-02-16 20:27:58 +01:00
parent ac3b5505c8
commit 18e1aa916d
6 changed files with 30 additions and 12 deletions

View File

@ -1,6 +1,23 @@
export const navbar = (Alpine) => ({
init: function () {
Alpine.bind(this.$root, this.root);
return this.$nextTick(() => {
let contentEl = document.querySelector('.content:not(.content--ready)');
if (contentEl) {
contentEl.classList.add('content--ready');
let anchorTemplate = document.getElementById('anchor-heading');
if (anchorTemplate) {
let els = contentEl.querySelectorAll('h2[id], h3[id], h4[id], h5[id], h6[id], dt[id]');
for (let i = 0; i < els.length; i++) {
let el = els[i];
let a = anchorTemplate.content.cloneNode(true).firstElementChild;
a.href = '#' + el.id;
el.appendChild(a);
}
}
}
});
},
root: {
['@scroll.window.debounce.10ms'](event) {

View File

@ -88,7 +88,8 @@ disableAliases = true
[markup.goldmark.parser]
autoHeadingID = true
autoHeadingIDType = "github"
autoDefinitionTermID = true
autoIDType = "github"
[markup.goldmark.parser.attribute]
block = true

View File

@ -1,10 +1 @@
<h{{ .Level }} id="{{ .Anchor | safeURL }}">{{ .Text | safeHTML }}
{{- if in (slice 2 3 4 6) .Level }}{{" " -}}
<a class="anchor" name="{{ .Anchor }}"></a>
<a class="inline-flex items-center" href="#{{ .Anchor | safeURL }}" aria-label="Anchor">
<svg class="fill-primary hover:fill-primary/70 w-4 h-4">
<use href="#icon--anchor"></use>
</svg>
</a>
{{- end -}}
</h{{ .Level }}>
<h{{ .Level }} id="{{ .Anchor | safeURL }}">{{ .Text | safeHTML }}</h{{ .Level }}>

View File

@ -60,6 +60,8 @@
</div>
{{/* Common icons. */}}
{{ partial "layouts/icons.html" . }}
{{/* Common templates. */}}
{{ partial "layouts/templates.html" . }}
{{/* Footer. */}}
{{ block "footer" . }}
{{ partial "layouts/footer.html" . }}

View File

@ -2,7 +2,7 @@
x-data="navbar"
class="print:hidden sticky top-0 z-50 bg-blue-950 flex flex-none flex-wrap items-center justify-between px-4 py-5 shadow-md shadow-slate-900/5 transition duration-500 sm:px-6 lg:px-8 dark:shadow-none"
:class="$store.nav.scroll.atTop ? '': 'bg-blue-950/80'">
<div class="relative flex basis-0 items-cente mr-2 lg:mr-8">
<div class="relative flex basis-0 items-center mr-2 lg:mr-8">
{{ with site.Home }}
<a
class="text-white text-xl font-bold upper"

View File

@ -0,0 +1,7 @@
<template id="anchor-heading">
<a class="inline-flex items-center" aria-label="Anchor">
<svg class="ml-2 fill-primary hover:fill-primary/70 w-4 h-4">
<use href="#icon--anchor"></use>
</svg>
</a>
</template>