Skip to content

Commit

Permalink
feat: add option about title bar for code snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyinws committed Dec 20, 2024
1 parent 1091ea5 commit 7e5cd20
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 3 deletions.
6 changes: 5 additions & 1 deletion docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ export default defineConfig({
},
markdown: {
config(md) {
md.use(groupIconMdPlugin)
md.use(groupIconMdPlugin, {
titleBar: {
includeSnippet: true,
},
})
},
codeTransformers: [
transformerTwoslash(),
Expand Down
17 changes: 17 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions docs/test.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<<< ../src/builtin.ts

``` [nuxt.config.ts]
test
```
19 changes: 17 additions & 2 deletions src/markdown.ts
Original file line number Diff line number Diff line change
@@ -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 = /<label\b(?![^>]+\bdata-title\b)[^>]*>(.*?)<\/label>/g
const codeGroupOpenRule = md.renderer.rules['container_code-group_open']
Expand Down Expand Up @@ -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 `<div class="vp-code-block-title">
<div class="vp-code-block-title-bar">
<span class="vp-code-block-title-text" data-title="${md.utils.escapeHtml(title[1])}">${title[1]}</span>
Expand Down

0 comments on commit 7e5cd20

Please sign in to comment.