|
| 1 | +import type { Plugin } from 'vite' |
| 2 | +// node import |
| 3 | +import { replacer } from '../../../packages/docs/utils' |
| 4 | + |
| 5 | +export function MarkdownTransform(): Plugin { |
| 6 | + return { |
| 7 | + name: 'yyj-docs:md-transform', |
| 8 | + enforce: 'pre', |
| 9 | + async transform(code, id) { |
| 10 | + if (!id.match(/\.md\b/)) { |
| 11 | + return null |
| 12 | + } |
| 13 | + |
| 14 | + // 满足 /projects/*.md 的条件 |
| 15 | + if (id.match(/\/projects\//)) { |
| 16 | + // const [projectsPath, _name] = id.split('/') |
| 17 | + // const name = _name.toLowerCase().slice(0, -3) |
| 18 | + |
| 19 | + const frontmatterEnds = code.indexOf('---\n\n') |
| 20 | + const firstHeader = code.search(/\n#{2,6}\s.+/) |
| 21 | + const slideIndex = firstHeader < 0 |
| 22 | + ? ( |
| 23 | + (frontmatterEnds < 0) |
| 24 | + ? 0 |
| 25 | + : frontmatterEnds + 4) |
| 26 | + : firstHeader |
| 27 | + |
| 28 | + const { footer, header } = getProjectMarkdown() |
| 29 | + if (header) { |
| 30 | + code = code.slice(0, slideIndex) + header + code.slice(slideIndex) |
| 31 | + } |
| 32 | + |
| 33 | + if (footer) { |
| 34 | + code = replacer(code, footer, 'footer', 'tail') |
| 35 | + } |
| 36 | + |
| 37 | + return code |
| 38 | + } |
| 39 | + |
| 40 | + // code = |
| 41 | + }, |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * 包裹项目介绍的 Markdown 额外信息 |
| 47 | + * |
| 48 | + * 根据 frontmatter 中字段生成 |
| 49 | + */ |
| 50 | +export function getProjectMarkdown() { |
| 51 | + const projectInfo = ` |
| 52 | +# {{ $frontmatter.title }} |
| 53 | +
|
| 54 | +> {{ $frontmatter.description }} |
| 55 | +
|
| 56 | +当前状态:<StatusBadge :status="$frontmatter.status" /> |
| 57 | +
|
| 58 | +<SiteLinkBadge :link="$frontmatter.link" /> |
| 59 | +<GitHubBadge :repo="$frontmatter.repo" /> |
| 60 | +` |
| 61 | + |
| 62 | + const footer = '' |
| 63 | + const header = `${projectInfo}\n` |
| 64 | + |
| 65 | + return { |
| 66 | + footer, |
| 67 | + header, |
| 68 | + } |
| 69 | +} |
0 commit comments