Skip to content

Commit

Permalink
fix(plugin-vitepress): add missing userConfig.base in the page path (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
fraxken authored Apr 6, 2024
1 parent 74265f5 commit e2d6963
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions packages/plugin-vitepress/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ const md = new MarkdownIt({
html: true
})

async function createOramaContentLoader(paths: string[], root: string) {
async function createOramaContentLoader(paths: string[], root: string, base: string) {
const contents = paths
.map((file) => ({
path: file.replace(root, '').replace('.md', ''),
html: md.render(readFileSync(file, 'utf-8'), '')
}))
.map(parseHTMLContent)
.map(formatForOrama)
.map((data) => formatForOrama(data, base))
.flat()

const db = await create({
Expand Down Expand Up @@ -84,15 +84,15 @@ function parseHTMLContent({ html, path }: { html: string; path: string }): Array
return sections
}

function formatForOrama(data: Array<ParserResult>): Array<OramaSchema> {
function formatForOrama(data: Array<ParserResult>, base: string): Array<OramaSchema> {
try {
const firstH1Header = data.find((section) => section.header === 'h1')

return data.map((res) => ({
title: res.title,
content: res.content,
section: firstH1Header!.title.replace(/\s$/, ''),
path: res?.path + '#' + slugify.default(res.title, { lower: true }),
path: base + res?.path + '#' + slugify.default(res.title, { lower: true }),
category: ''
}))
} catch (error) {
Expand All @@ -101,6 +101,10 @@ function formatForOrama(data: Array<ParserResult>): Array<OramaSchema> {
}
}

function removeTrailingSlash(value: string) {
return value.endsWith('/') ? value.slice(0, -1) : value
}

export function OramaPlugin(pluginOptions: OramaPluginOptions = {}): Plugin {
let resolveConfig: any
const virtualModuleId = 'virtual:search-data'
Expand Down Expand Up @@ -155,10 +159,11 @@ export function OramaPlugin(pluginOptions: OramaPluginOptions = {}): Plugin {
if (id !== resolvedVirtualModuleId) return

const root = resolveConfig.vitepress.root
const base = removeTrailingSlash(resolveConfig.vitepress.userConfig?.base ?? '')
const pages = resolveConfig.vitepress.pages.map((page: string) => `${root}/${page}`)

return `
const data = ${JSON.stringify(await createOramaContentLoader(pages, root))};
const data = ${JSON.stringify(await createOramaContentLoader(pages, root, base))};
const analytics = ${JSON.stringify(pluginOptions.analytics)};
export default { data, analytics };
`
Expand Down

0 comments on commit e2d6963

Please sign in to comment.