diff --git a/packages/vitepress-plugin-page-properties/src/vite/index.ts b/packages/vitepress-plugin-page-properties/src/vite/index.ts index 09908c12..f0737c80 100644 --- a/packages/vitepress-plugin-page-properties/src/vite/index.ts +++ b/packages/vitepress-plugin-page-properties/src/vite/index.ts @@ -1,11 +1,24 @@ import { env } from 'node:process' +import { relative } from 'node:path' import type { Plugin } from 'vite' import GrayMatter from 'gray-matter' +import { pathEndsWith, pathEquals, pathStartsWith } from './path' + +export interface Context { + helpers: { + pathEquals: (path: string, equalsWith: string) => boolean + pathStartsWith: (path: string, startsWith: string) => boolean + pathEndsWith: (path: string, endsWith: string) => boolean + idEquals: (equalsWith: string) => boolean + idStartsWith: (startsWith: string) => boolean + idEndsWith: (endsWith: string) => boolean + } +} export function PagePropertiesMarkdownSection(options?: { - getPagePropertiesTitle?: (code: string, id: string) => string + getPagePropertiesTitle?: (code: string, id: string, context: Context) => string excludes?: string[] - exclude?: (id: string) => boolean + exclude?: (id: string, context: Context) => boolean }): Plugin { const { getPagePropertiesTitle = () => { @@ -15,19 +28,36 @@ export function PagePropertiesMarkdownSection(options?: { exclude = () => false, } = options ?? {} + let root = '' + return { name: '@nolebase/vitepress-plugin-page-properties-markdown-section', + configResolved(config) { + root = config.root ?? '' + }, transform(code, id) { + function idEndsWith(endsWith) { + return pathEndsWith(relative(root, id), endsWith) + } + + function idEquals(equals) { + return pathEquals(relative(root, id), equals) + } + + function idStartsWith(startsWith) { + return pathStartsWith(relative(root, id), startsWith) + } + if (!id.endsWith('.md')) return null if (excludes.includes(id)) return null - if (exclude(id)) + if (exclude(id, { helpers: { pathEndsWith, pathEquals, pathStartsWith, idEndsWith, idEquals, idStartsWith } })) return null const targetComponent = env.NODE_ENV === 'development' - ? `
\n\n\n##### ${getPagePropertiesTitle(code, id)}\n\n