From 047867d72abd9ae7c578e266f60a10eb1d23eb60 Mon Sep 17 00:00:00 2001 From: Justineo Date: Thu, 21 Oct 2021 18:38:51 +0800 Subject: [PATCH] feat: improve hash target positioning upon initial navigation --- app/router.scrollBehavior.js | 18 +++++++++++++++++- assets/styles/global.styl | 4 ++++ plugins/target.js | 3 +++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/app/router.scrollBehavior.js b/app/router.scrollBehavior.js index eb19879..bbe8c51 100644 --- a/app/router.scrollBehavior.js +++ b/app/router.scrollBehavior.js @@ -4,6 +4,22 @@ function timeout (t) { }) } +let paddingTopInPixels = null +function getScrollPaddingTopInPixels () { + if (paddingTopInPixels !== null) { + return paddingTopInPixels + } + const measurer = document.createElement('div') + const paddingTop = getComputedStyle(document.documentElement).scrollPaddingTop + measurer.style.position = 'absolute' + measurer.style.visibility = 'hidden' + measurer.style.height = paddingTop + document.body.appendChild(measurer) + paddingTopInPixels = measurer.offsetHeight + measurer.remove() + return paddingTopInPixels +} + export default async function scrollBehavior (to) { if (to.hash) { // scroll to anchor by returning the selector @@ -11,7 +27,7 @@ export default async function scrollBehavior (to) { return { selector: decodeURIComponent(to.hash), offset: { - y: 120 + y: getScrollPaddingTopInPixels() } } } diff --git a/assets/styles/global.styl b/assets/styles/global.styl index e2a9a4d..6957da3 100644 --- a/assets/styles/global.styl +++ b/assets/styles/global.styl @@ -19,6 +19,7 @@ html font-weight 400 color #333 scroll-behavior smooth + scroll-padding-top 120px html body @@ -39,3 +40,6 @@ a:focus main line-height 1.5 + +.DocSearch-Container + backdrop-filter blur(4px) diff --git a/plugins/target.js b/plugins/target.js index e9d86e7..3d699bf 100644 --- a/plugins/target.js +++ b/plugins/target.js @@ -21,6 +21,9 @@ export default ({ app, route }) => { setTimeout(() => { const selector = decodeURIComponent(to.hash) const anchor = document.querySelector(selector) + if (!anchor) { + return + } if (anchor.tagName === 'CODE') { target = anchor.closest('tr')