Skip to content

Commit

Permalink
naming refactor in anchor scrolling
Browse files Browse the repository at this point in the history
  • Loading branch information
rafapaezbas committed Mar 1, 2024
1 parent 4b9dd55 commit df32117
Showing 1 changed file with 14 additions and 16 deletions.
30 changes: 14 additions & 16 deletions lib/app-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,20 @@ customElements.define('app-router', class AppRouter extends HTMLElement {
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))
}
const anchor = opts.anchor
if (isDocumentationPage && 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)
if (!opts.back) history.pushState({ pathname, anchor: opts.anchor }, null, pathname)
break
}
}
Expand All @@ -47,8 +45,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)) {
const header = evt.target.href.split('#')[1]
this.load(evt.target.pathname, { header }).catch(console.error)
const anchor = evt.target.href.split('#')[1]
this.load(evt.target.pathname, { anchor }).catch(console.error)
} else {
this.load(route + evt.target.pathname).catch(console.error)
}
Expand All @@ -64,7 +62,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, header: evt.state?.header }).catch(console.error)
this.load(evt.state?.pathname, { back: true, anchor: evt.state?.anchor }).catch(console.error)
})

window.addEventListener('load', () => {
Expand Down

0 comments on commit df32117

Please sign in to comment.