Skip to content

Commit c4ce39e

Browse files
committed
fix(code-block-shiki): find code-block change and highlighter is valid
1 parent 0487fed commit c4ce39e

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

packages/tiptap-extension-code-block-shiki/src/codeBlockShiki.ts

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@ import { bundledLanguagesInfo, getHighlighter } from 'shiki/bundle/web'
1010
import type { Element } from 'hast'
1111
import style from './codeBlockShiki.css?raw'
1212

13-
const languages = bundledLanguagesInfo.map(item => [item.id, item.name, ...(item.aliases ?? [])]).flat()
14-
1513
export interface CodeBlockShikiOptions extends CodeBlockOptions {
1614
theme: StringLiteralUnion<BundledTheme, string>
1715
}
@@ -55,6 +53,9 @@ export const codeBlockShiki = CodeBlock.extend<CodeBlockShikiOptions, CodeBlockS
5553
if (
5654
transaction.docChanged
5755
&& ([oldNodeName, newNodeName].includes(this.name)
56+
// only toggle language for code block
57+
// @ts-expect-error attr
58+
|| transaction.steps.find(item => item.attr === 'language')
5859
)
5960
) {
6061
return getDecorations({
@@ -132,6 +133,13 @@ export const codeBlockShiki = CodeBlock.extend<CodeBlockShikiOptions, CodeBlockS
132133
},
133134
})
134135

136+
function formatLanguage(lang: string) {
137+
if (!lang)
138+
return null
139+
140+
return bundledLanguagesInfo.find(item => [item.id, item.name, ...(item.aliases ?? [])])?.id
141+
}
142+
135143
function getDecorations({
136144
doc,
137145
name,
@@ -144,16 +152,17 @@ function getDecorations({
144152
theme: CodeBlockShikiOptions['theme']
145153
}) {
146154
let decorations: Decoration[] = []
155+
if (!highlighter)
156+
return decorations
147157

148158
findChildren(doc, node => node.type.name === name).forEach((block) => {
149159
// @ts-expect-error language
150-
const language = block.node.attrs.language || 'text'
151-
if (!languages.includes(language) || highlighter)
152-
return
160+
block.node.attrs.language = formatLanguage(block.node.attrs.language) ?? 'text'
153161

154162
const preNode = highlighter!.codeToHast(block.node.textContent, {
155163
theme,
156-
lang: language,
164+
// @ts-expect-error language
165+
lang: block.node.attrs.language,
157166
}).children[0] as Element
158167

159168
decorations.push(Decoration.node(block.pos, block.pos + block.node.nodeSize, {

0 commit comments

Comments
 (0)