Skip to content

Commit defce0b

Browse files
authored
fix(code-block): Highlighting not matching usual Prismjs's highlighting (#1247)
1 parent 2e7e030 commit defce0b

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

packages/code-block/src/code-block.tsx

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,33 +12,57 @@ export type CodeBlockProps = Readonly<{
1212
code: string;
1313
}>;
1414

15+
const stylesForToken = (token: Prism.Token, theme: Theme) => {
16+
let styles = { ...theme[token.type] };
17+
18+
const aliases = Array.isArray(token.alias) ? token.alias : [token.alias];
19+
20+
for (const alias of aliases) {
21+
styles = { ...styles, ...theme[alias] };
22+
}
23+
24+
return styles;
25+
};
26+
1527
const CodeBlockLine = ({
1628
token,
1729
theme,
30+
inheritedStyles,
1831
}: {
1932
token: string | Prism.Token;
2033
theme: Theme;
34+
inheritedStyles?: React.CSSProperties;
2135
}) => {
2236
if (token instanceof Prism.Token) {
37+
const styleForToken = {
38+
...inheritedStyles,
39+
...stylesForToken(token, theme),
40+
};
41+
2342
if (token.content instanceof Prism.Token) {
2443
return (
25-
<span style={theme[token.type]}>
44+
<span style={styleForToken}>
2645
<CodeBlockLine theme={theme} token={token.content} />
2746
</span>
2847
);
2948
} else if (typeof token.content === "string") {
30-
return <span style={theme[token.type]}>{token.content}</span>;
49+
return <span style={styleForToken}>{token.content}</span>;
3150
}
3251
return (
3352
<>
3453
{token.content.map((subToken, i) => (
35-
<CodeBlockLine key={i} theme={theme} token={subToken} />
54+
<CodeBlockLine
55+
inheritedStyles={styleForToken}
56+
key={i}
57+
theme={theme}
58+
token={subToken}
59+
/>
3660
))}
3761
</>
3862
);
3963
}
4064

41-
return <>{token}</>;
65+
return <span style={inheritedStyles}>{token}</span>;
4266
};
4367

4468
/**

0 commit comments

Comments
 (0)