From 6b6d26870ff2b83918ce3356c7b3553feb26c9c7 Mon Sep 17 00:00:00 2001 From: Ryan Rivest Date: Fri, 27 Apr 2018 11:25:39 -0400 Subject: [PATCH] feat: highlight current region in sidebar (#272) --- lib/app/app.js | 2 +- lib/default-theme/Layout.vue | 29 +++++++++++++++++++++++++++++ package.json | 1 + 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/app/app.js b/lib/app/app.js index 8040f5fc7a..924a966356 100644 --- a/lib/app/app.js +++ b/lib/app/app.js @@ -57,7 +57,7 @@ export function createApp () { if (saved) { return saved } else if (to.hash) { - return { selector: to.hash } + return false } else { return { x: 0, y: 0 } } diff --git a/lib/default-theme/Layout.vue b/lib/default-theme/Layout.vue index f45e52e236..7ad99f1190 100644 --- a/lib/default-theme/Layout.vue +++ b/lib/default-theme/Layout.vue @@ -29,6 +29,7 @@ import Page from './Page.vue' import Sidebar from './Sidebar.vue' import { pathToComponentName } from '@app/util' import { resolveSidebarItems } from './util' +import throttle from 'lodash.throttle' export default { components: { Home, Page, Sidebar, Navbar }, @@ -111,6 +112,8 @@ export default { this.$watch('$page', updateMeta) updateMeta() + window.addEventListener('scroll', this.onScroll) + // configure progress bar nprogress.configure({ showSpinner: false }) @@ -129,6 +132,8 @@ export default { beforeDestroy () { updateMetaTags(null, this.currentMetaTags) + + window.removeEventListener('scroll', this.onScroll) }, methods: { @@ -152,6 +157,30 @@ export default { this.toggleSidebar(false) } } + }, + onScroll: throttle(function () { + this.setActiveHash() + }, 300), + setActiveHash () { + const sidebarLinks = [].slice.call(document.querySelectorAll('.sidebar-link')) + const anchors = [].slice.call(document.querySelectorAll('.header-anchor')) + .filter(anchor => sidebarLinks.some(sidebarLink => sidebarLink.hash === anchor.hash)) + + const scrollTop = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop) + + for (let i = 0; i < anchors.length; i++) { + const anchor = anchors[i] + const nextAnchor = anchors[i + 1] + + const isActive = i === 0 && scrollTop === 0 || + (scrollTop >= anchor.parentElement.offsetTop + 10 && + (!nextAnchor || scrollTop < nextAnchor.parentElement.offsetTop - 10)) + + if (isActive && this.$route.hash !== anchor.hash) { + this.$router.replace(anchor.hash) + return + } + } } } } diff --git a/package.json b/package.json index 441450d921..18686e7a1b 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "koa-mount": "^3.0.0", "koa-static": "^4.0.2", "loader-utils": "^1.1.0", + "lodash.throttle": "^4.1.1", "lru-cache": "^4.1.2", "markdown-it": "^8.4.1", "markdown-it-anchor": "^4.0.0",