Skip to content

Commit

Permalink
feat: highlight current region in sidebar (#272)
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanrivest authored and ulivz committed Apr 27, 2018
1 parent 2d6f02f commit 6b6d268
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/app/app.js
Expand Up @@ -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 }
}
Expand Down
29 changes: 29 additions & 0 deletions lib/default-theme/Layout.vue
Expand Up @@ -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 },
Expand Down Expand Up @@ -111,6 +112,8 @@ export default {
this.$watch('$page', updateMeta)
updateMeta()
window.addEventListener('scroll', this.onScroll)
// configure progress bar
nprogress.configure({ showSpinner: false })
Expand All @@ -129,6 +132,8 @@ export default {
beforeDestroy () {
updateMetaTags(null, this.currentMetaTags)
window.removeEventListener('scroll', this.onScroll)
},
methods: {
Expand All @@ -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
}
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -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",
Expand Down

2 comments on commit 6b6d268

@meteorlxy
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yarn.lock didn't update?

@ulivz
Copy link
Member

@ulivz ulivz commented on 6b6d268 Apr 27, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

update at: 87e88f3

Please sign in to comment.