Skip to content

Commit

Permalink
chore(plugin-active-header-links): tweaks (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mister-Hope authored Feb 6, 2024
1 parent fced29c commit 5b8d144
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 32 deletions.
2 changes: 1 addition & 1 deletion plugins/plugin-active-header-links/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"clean": "rimraf --glob ./lib ./*.tsbuildinfo"
},
"dependencies": {
"ts-debounce": "^4.0.0",
"@vueuse/core": "^10.7.1",
"vue": "^3.4.15",
"vue-router": "^4.2.5"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { debounce } from 'ts-debounce'
import { onBeforeUnmount, onMounted } from 'vue'
import { useDebounceFn, useEventListener } from '@vueuse/core'
import { useRouter } from 'vue-router'
import type { Router } from 'vue-router'

Expand All @@ -10,6 +9,20 @@ export interface UseActiveHeaderLinksOptions {
offset?: number
}

/**
* Update current hash and do not trigger `scrollBehavior`
*/
const updateHash = async (router: Router, hash: string): Promise<void> => {
const { path, query } = router.currentRoute.value
const { scrollBehavior } = router.options

// temporarily disable `scrollBehavior`
router.options.scrollBehavior = undefined
await router.replace({ path, query, hash })
// restore it after navigation
router.options.scrollBehavior = scrollBehavior
}

export const useActiveHeaderLinks = ({
headerLinkSelector,
headerAnchorSelector,
Expand Down Expand Up @@ -102,30 +115,5 @@ export const useActiveHeaderLinks = ({
}
}

const onScroll: () => Promise<void> = debounce(setActiveRouteHash, delay)

onMounted(() => {
window.addEventListener('scroll', onScroll)
})
onBeforeUnmount(() => {
window.removeEventListener('scroll', onScroll)
})
}

/**
* Update current hash and do not trigger `scrollBehavior`
*/
const updateHash = async (router: Router, hash: string): Promise<void> => {
// temporarily disable `scrollBehavior`
// restore it after navigation
const { scrollBehavior } = router.options
router.options.scrollBehavior = undefined

await router
.replace({
path: router.currentRoute.value.path,
query: router.currentRoute.value.query,
hash,
})
.finally(() => (router.options.scrollBehavior = scrollBehavior))
useEventListener('scroll', useDebounceFn(setActiveRouteHash, delay))
}
6 changes: 3 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 5b8d144

Please sign in to comment.