feat: set Prev/Next to page data

pull/56/head
Yugo Ogura 5 years ago
parent 5419abdcc6
commit 709eeb31e3

@ -104,13 +104,17 @@ function createVitePressPlugin({
ctx.body = vueSrc ctx.body = vueSrc
debug(ctx.url, ctx.status) debug(ctx.url, ctx.status)
const pageDataWithLinks = {
...pageData,
...getNextAndPrev(siteData.themeConfig.sidebar, ctx.path)
}
await next() await next()
// make sure this is the main <script> block // make sure this is the main <script> block
if (!ctx.query.type) { if (!ctx.query.type) {
// inject pageData to generated script // inject pageData to generated script
ctx.body += `\nexport const __pageData = ${JSON.stringify( ctx.body += `\nexport const __pageData = ${JSON.stringify(
JSON.stringify(pageData) JSON.stringify(pageDataWithLinks)
)}` )}`
} }
return return
@ -127,6 +131,35 @@ function createVitePressPlugin({
} }
} }
function getNextAndPrev(sidebar: { [key: string]: any }, pagePath: string) {
let candidates: { text: string; link: string }[] = []
Object.keys(sidebar).forEach((k) => {
if (!pagePath.startsWith(k)) {
return
}
sidebar[k].forEach((sidebarItem: { [key: string]: any }) => {
if (!sidebarItem.children) {
return
}
sidebarItem.children.forEach((candidate: any) => {
candidates.push(candidate)
})
})
})
const path = pagePath.replace(/\.(md|html)$/, '')
const currentLinkIndex = candidates.findIndex((v) => v.link === path)
return {
...(currentLinkIndex !== -1
? { next: candidates[currentLinkIndex + 1] }
: {}),
...(currentLinkIndex !== -1
? { prev: candidates[currentLinkIndex - 1] }
: {})
}
}
export async function createServer(options: ServerConfig = {}) { export async function createServer(options: ServerConfig = {}) {
const config = await resolveConfig(options.root) const config = await resolveConfig(options.root)

Loading…
Cancel
Save