Custom header anchors (#82)

* generate custom header anchors

* implemented anchor navigation

* fixed scroll to bottom anchors

---------

Co-authored-by: rafapaezbas <rafa@holepunch.com>
This commit is contained in:
rafapaezbas
2024-02-29 17:56:47 +01:00
committed by GitHub
parent dc7a0250dc
commit 1c7a120113
11 changed files with 426 additions and 389 deletions

View File

@@ -16,9 +16,25 @@ customElements.define('app-router', class AppRouter extends HTMLElement {
this.unload()
document.documentElement.scrollTop = 0
this.dataset.load = element.tagName.toLowerCase()
await element.load(page)
document.documentElement.scrollTop = 0
if (!opts.back) history.pushState({ pathname }, null, pathname)
await element.load(page, opts)
const isDocumentationPage = pathname.startsWith('/documentation')
if (isDocumentationPage && !!opts.header) {
const anchor = opts.header
if (anchor) {
const element = this.routes['/documentation'].shadowRoot.getElementById(anchor)
element.scrollIntoView()
const elementY = Math.floor(element.getBoundingClientRect().y)
const pearHeaderHeight = 170
const extraScroll = 80
const isUnderPearHeader = elementY < pearHeaderHeight + extraScroll
if (isUnderPearHeader) {
window.scrollBy(0, -1 * (pearHeaderHeight + extraScroll - elementY))
}
}
}
if (!opts.back) history.pushState({ pathname, header: opts.header }, null, pathname)
break
}
}
@@ -31,7 +47,8 @@ customElements.define('app-router', class AppRouter extends HTMLElement {
const { tagName } = evt.target.getRootNode().host || {}
const route = tagName ? this.getAttribute(tagName) : ''
if (evt.target.pathname.startsWith(route)) {
this.load(evt.target.pathname).catch(console.error)
const header = evt.target.href.split('#')[1]
this.load(evt.target.pathname, { header }).catch(console.error)
} else {
this.load(route + evt.target.pathname).catch(console.error)
}
@@ -47,7 +64,7 @@ customElements.define('app-router', class AppRouter extends HTMLElement {
this.addEventListener('click', (evt) => this.link(evt))
window.addEventListener('popstate', (evt) => {
this.load(evt.state?.pathname, { back: true }).catch(console.error)
this.load(evt.state?.pathname, { back: true, header: evt.state?.header }).catch(console.error)
})
window.addEventListener('load', () => {