Skip to content

Commit

Permalink
feat: scrollOffset option
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jan 16, 2022
1 parent 70cfffb commit b66785d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
16 changes: 15 additions & 1 deletion src/client/app/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { reactive, inject, markRaw, nextTick, readonly } from 'vue'
import type { Component, InjectionKey } from 'vue'
import { PageData } from '../shared'
import { inBrowser } from './utils'
import { siteDataRef } from './data'

export interface Route {
path: string
Expand Down Expand Up @@ -192,7 +193,20 @@ function scrollTo(el: HTMLElement, hash: string, smooth = false) {
}

if (target) {
const targetTop = (target as HTMLElement).offsetTop
let offset = siteDataRef.value.scrollOffset
if (typeof offset === 'string') {
offset =
document.querySelector(offset)!.getBoundingClientRect().bottom + 24
}
const targetPadding = parseInt(
window.getComputedStyle(target as HTMLElement).paddingTop,
10
)
const targetTop =
window.scrollY +
(target as HTMLElement).getBoundingClientRect().top -
offset +
targetPadding
// only smooth scroll if distance is smaller than screen height.
if (!smooth || Math.abs(targetTop - window.scrollY) > window.innerHeight) {
window.scrollTo(0, targetTop)
Expand Down
9 changes: 8 additions & 1 deletion src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ export interface UserConfig<ThemeConfig = any> {
outDir?: string
shouldPreload?: (link: string, page: string) => boolean

/**
* Configure the scroll offset when the theme has a sticky header.
* Can be a number or a selector element to get the offset from.
*/
scrollOffset?: number | string

/**
* Enable MPA / zero-JS mode
* @experimental
Expand Down Expand Up @@ -243,6 +249,7 @@ export async function resolveSiteData(
head: userConfig.head || [],
themeConfig: userConfig.themeConfig || {},
locales: userConfig.locales || {},
langs: createLangDictionary(userConfig)
langs: createLangDictionary(userConfig),
scrollOffset: userConfig.scrollOffset || 90
}
}
1 change: 1 addition & 0 deletions types/shared.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export interface SiteData<ThemeConfig = any> {
description: string
head: HeadConfig[]
themeConfig: ThemeConfig
scrollOffset: number | string
locales: Record<string, LocaleConfig>
/**
* Available locales for the site when it has defined `locales` in its
Expand Down

0 comments on commit b66785d

Please sign in to comment.