Skip to content

Commit

Permalink
fix(code-block): support [ in filename
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz committed Jul 24, 2023
1 parent 46e0666 commit b3969dd
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/runtime/parser/handlers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,22 @@ export function parseThematicBlock (lang: string) {
}
}

const language = lang.replace(/[{|[](.+)/, '').match(/^[^ \t]+(?=[ \t]|$)/)
const highlightTokens = lang.match(/{([^}]*)}/)
const filenameTokens = lang.match(/\[([^\]]*)\]/)
const meta = lang.replace(/^\w*\s*(\[[^\]]*\]|\{[^}]*\})?\s*(\[[^\]]*\]|\{[^}]*\})?\s*/, '')
const languageMatches = lang.replace(/[{|[](.+)/, '').match(/^[^ \t]+(?=[ \t]|$)/)
const highlightTokensMatches = lang.match(/{([^}]*)}/)
const filenameMatches = lang.match(/\[((\\]|[^\]])*)\]/)
console.log(filenameMatches)

const meta = lang
.replace(languageMatches?.[0] ?? '', '')
.replace(highlightTokensMatches?.[0] ?? '', '')
.replace(filenameMatches?.[0] ?? '', '')
.trim()

return {
language: language ? language[0] : undefined,
highlights: parseHighlightedLines(highlightTokens && highlightTokens[1]),
filename: Array.isArray(filenameTokens) && filenameTokens[1] ? filenameTokens[1] : undefined,
language: languageMatches?.[0] || undefined,
highlights: parseHighlightedLines(highlightTokensMatches?.[1] || undefined),
// https://github.com/nuxt/content/pull/2169
filename: filenameMatches?.[1].replace(/\\]/g, ']') || undefined,
meta
}
}
Expand Down
67 changes: 67 additions & 0 deletions test/markdown/code-block-props.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { expect, it } from 'vitest'
import { parseMarkdown } from '../utils/parser'

const md = `
\`\`\`ts {1-3} [@[...slug\\\\].vue] meta=meta-value
class C {
private name: string = "foo"
}
const c = new C()
\`\`\`
`.trim()

it('Code block with Props', async () => {
const { body } = await parseMarkdown(md, {
highlight: false
})
expect(body).toHaveProperty('type', 'root')
expect(body.children).toHaveLength(1)
expect(body.children).toMatchInlineSnapshot(`
[
{
"children": [
{
"children": [
{
"type": "text",
"value": "class C {
private name: string = \\"foo\\"
}
const c = new C()
",
},
],
"props": {
"__ignoreMap": "",
},
"tag": "code",
"type": "element",
},
],
"props": {
"className": [
"language-ts",
],
"code": "class C {
private name: string = \\"foo\\"
}
const c = new C()
",
"filename": "@[...slug].vue",
"highlights": [
1,
2,
3,
],
"language": "ts",
"meta": "meta=meta-value",
},
"tag": "pre",
"type": "element",
},
]
`)
})

0 comments on commit b3969dd

Please sign in to comment.