From 0f0665363605e29f93917a44102f7b6d617da2e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90=20Kevin=20Deng?= Date: Fri, 2 Dec 2022 10:19:31 +0800 Subject: [PATCH] fix: render code block without language (#276) --- components/content/ContentCode.vue | 4 ++-- composables/content.ts | 9 ++++----- tests/__snapshots__/content-rich.test.ts.snap | 16 ++++++++++++++++ tests/content-rich.test.ts | 10 ++++++++++ 4 files changed, 32 insertions(+), 7 deletions(-) diff --git a/components/content/ContentCode.vue b/components/content/ContentCode.vue index 4ffc9bc7..7b034b3c 100644 --- a/components/content/ContentCode.vue +++ b/components/content/ContentCode.vue @@ -1,7 +1,7 @@ diff --git a/composables/content.ts b/composables/content.ts index 4e3e87c0..54c71f51 100644 --- a/composables/content.ts +++ b/composables/content.ts @@ -38,7 +38,7 @@ function handleCodeBlock(el: Element) { const codeEl = el.childNodes[0] as Element const classes = codeEl.attrs.find(i => i.name === 'class')?.value const lang = classes?.split(/\s/g).find(i => i.startsWith('language-'))?.replace('language-', '') - const code = treeToText(codeEl.childNodes[0]) + const code = codeEl.childNodes[0] ? treeToText(codeEl.childNodes[0]) : '' return h(ContentCode, { lang, code: encodeURIComponent(code) }) } } @@ -61,11 +61,10 @@ export function parseMastodonHTML(html: string, customEmojis: Record(```|~~~)([\s\S]+?)\1/g, (_1, _2, raw) => { - const plain = htmlToText(raw) - const [lang, ...code] = plain.split('\n') + .replace(/>(```|~~~)(\w*)([\s\S]+?)\1/g, (_1, _2, lang, raw) => { + const code = htmlToText(raw) const classes = lang ? ` class="language-${lang}"` : '' - return `>
${code.join('\n')}
` + return `>
${code}
` }) const tree = parseFragment(processed) diff --git a/tests/__snapshots__/content-rich.test.ts.snap b/tests/__snapshots__/content-rich.test.ts.snap index fafa68b8..6e129390 100644 --- a/tests/__snapshots__/content-rich.test.ts.snap +++ b/tests/__snapshots__/content-rich.test.ts.snap @@ -25,6 +25,22 @@ exports[`content-rich > code frame 2 1`] = ` " `; +exports[`content-rich > code frame empty 1`] = ` +"

+

+
+

+" +`; + +exports[`content-rich > code frame no lang 1`] = ` +"

+
hello world
+
no lang +

+" +`; + exports[`content-rich > custom emoji 1`] = ` "Daniel Roe { const { formatted } = await render('

@antfu Testing
```ts
const a = hello
```

') expect(formatted).toMatchSnapshot() }) + + it('code frame no lang', async () => { + const { formatted } = await render('

```
hello world
```
no lang

') + expect(formatted).toMatchSnapshot() + }) + + it('code frame empty', async () => { + const { formatted } = await render('

```

```

') + expect(formatted).toMatchSnapshot() + }) }) async function render(content: string, emojis?: Record) {