From 7e5cd20ad0ac54b3a0742c393c3d9981a6428457 Mon Sep 17 00:00:00 2001 From: yuyinws Date: Fri, 20 Dec 2024 15:15:31 +0800 Subject: [PATCH] feat: add option about title bar for code snippets --- docs/.vitepress/config.ts | 6 +++++- docs/features.md | 17 +++++++++++++++++ docs/test.md | 5 +++++ src/markdown.ts | 19 +++++++++++++++++-- 4 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 docs/test.md diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 5e58526..6020171 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -32,7 +32,11 @@ export default defineConfig({ }, markdown: { config(md) { - md.use(groupIconMdPlugin) + md.use(groupIconMdPlugin, { + titleBar: { + includeSnippet: true, + }, + }) }, codeTransformers: [ transformerTwoslash(), diff --git a/docs/features.md b/docs/features.md index 1c9199f..683fdbe 100644 --- a/docs/features.md +++ b/docs/features.md @@ -86,6 +86,23 @@ export default defineConfig({ }) ``` +### Includes Code Snippets + +If you also want to add title bar for [Code Snippets +](https://vitepress.dev/guide/markdown#import-code-snippets): + +```ts {5} [.vitepress/config.ts] +export default defineConfig({ + markdown: { + config(md) { + md.use(groupIconMdPlugin, { + titleBar: { includeSnippet: true }, + }) + }, + }, +}) +``` + ## Built-in Icons ### Package Managers diff --git a/docs/test.md b/docs/test.md new file mode 100644 index 0000000..3ae3c16 --- /dev/null +++ b/docs/test.md @@ -0,0 +1,5 @@ +<<< ../src/builtin.ts + +``` [nuxt.config.ts] +test +``` diff --git a/src/markdown.ts b/src/markdown.ts index 17cefdb..fd5710f 100644 --- a/src/markdown.ts +++ b/src/markdown.ts @@ -1,6 +1,19 @@ import type Markdown from 'markdown-it' -export function groupIconMdPlugin(md: Markdown) { +interface MdPluginOptions { + titleBar: { + /** + * Whether the title bar is included in the [Snippets](https://vitepress.dev/guide/markdown#import-code-snippets) + * + * @defaultValue false + */ + includeSnippet?: boolean + } +} + +export function groupIconMdPlugin(md: Markdown, options?: MdPluginOptions) { + const _options = options || { titleBar: { includeSnippet: false } } + // code group rule const labelRE = /]+\bdata-title\b)[^>]*>(.*?)<\/label>/g const codeGroupOpenRule = md.renderer.rules['container_code-group_open'] @@ -34,8 +47,10 @@ export function groupIconMdPlugin(md: Markdown) { } const title = token.info.match(/\[(.*?)\]/) + const isIncludedSnippet = _options.titleBar.includeSnippet + // only render code block not in code-group - if (!isOnCodeGroup && title) { + if (!isOnCodeGroup && title && (!(token as any).src || isIncludedSnippet)) { return `
${title[1]}