Marco Roth 2 weeks ago committed by GitHub
commit 8cd028c927
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,7 @@
---
title: Frontmatter Title Resolved
---
# {{ $frontmatter.title }}
This page uses a frontmatter title expression.

@ -28,4 +28,24 @@ describe('local search', () => {
.count()
).toBe(0)
})
test('resolve $frontmatter expressions in search results', async () => {
await page.locator('.VPNavBarSearchButton').click()
const input = await page.waitForSelector('input#localsearch-input')
await input.type('Frontmatter Title Resolved')
await page.waitForSelector('ul#localsearch-list', { state: 'visible' })
const searchResults = page.locator('#localsearch-list')
expect(
await searchResults
.filter({ hasText: 'Frontmatter Title Resolved' })
.count()
).toBe(1)
expect(
await searchResults.filter({ hasText: '$frontmatter.title' }).count()
).toBe(0)
})
})

@ -56,12 +56,23 @@ export async function localSearchPlugin(
const env: MarkdownEnv = { path: file, relativePath, cleanUrls }
const md_raw = await fs.promises.readFile(file, 'utf-8')
const md_src = processIncludes(md, srcDir, md_raw, file, [], cleanUrls)
let html: string
if (options._render) {
return await options._render(md_src, env, md)
html = await options._render(md_src, env, md)
} else {
const html = await md.renderAsync(md_src, env)
return env.frontmatter?.search === false ? '' : html
html = await md.renderAsync(md_src, env)
if (env.frontmatter?.search === false) {
return ''
}
}
if (env.frontmatter) {
html = resolveFrontmatterExpressions(html, env.frontmatter)
}
return html
}
const indexByLocales = new Map<string, MiniSearch<IndexObject>>()
@ -248,3 +259,22 @@ function getSearchableText(content: string) {
function clearHtmlTags(str: string) {
return str.replace(/<[^>]*>/g, '')
}
function resolveFrontmatterExpressions(
html: string,
frontmatter: Record<string, any>
): string {
return html.replace(
/\{\{\s*\$frontmatter\.(\S+?)\s*\}\}/g,
(match, key: string) => {
const value = key
.split('.')
.reduce(
(object, key) => (object != null ? object[key] : undefined),
frontmatter
)
return value != null ? String(value) : match
}
)
}

Loading…
Cancel
Save