Skip to content

Commit e4a2f34

Browse files
committed
feat: base code block theme on primer colorMode
1 parent c9a70f2 commit e4a2f34

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/hooks/use-prism-theme.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import {useTheme} from '@primer/react'
2+
import {themes} from 'prism-react-renderer'
3+
import {useMemo} from 'react'
4+
5+
const colorModeToThemeMap = {
6+
light: themes.github,
7+
dark: themes.vsDark,
8+
day: themes.github,
9+
night: themes.vsDark,
10+
}
11+
12+
export const usePrismTheme = () => {
13+
const {resolvedColorMode} = useTheme()
14+
15+
const theme = useMemo(() => colorModeToThemeMap[resolvedColorMode ?? 'day'], [resolvedColorMode])
16+
return {theme}
17+
}

src/mdx/code.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import React from 'react'
22
import {Box, Text, Button, themeGet} from '@primer/react'
33
import {Octicon} from '@primer/react/deprecated'
4-
import {Highlight, themes, Prism} from 'prism-react-renderer'
4+
import {Highlight, Prism} from 'prism-react-renderer'
55
import styled from 'styled-components'
66
import {CheckIcon, CopyIcon} from '@primer/octicons-react'
77
import copyToClipboard from 'copy-to-clipboard'
88
import {announce} from '../util/aria-live'
9+
import {usePrismTheme} from '../hooks/use-prism-theme'
910
;(typeof global !== 'undefined' ? global : window).Prism = Prism
1011
require('prismjs/components/prism-bash')
1112

@@ -99,9 +100,10 @@ const CodeBlock = ({children, code, className, style}) => (
99100
)
100101

101102
function Code({className = '', prompt, children}) {
103+
const {theme: codeTheme} = usePrismTheme()
102104
if (prompt) {
103105
return (
104-
<CodeBlock style={themes.github.plain}>
106+
<CodeBlock style={codeTheme.plain}>
105107
<MonoText>{children}</MonoText>
106108
</CodeBlock>
107109
)
@@ -115,7 +117,7 @@ function Code({className = '', prompt, children}) {
115117
}
116118

117119
return (
118-
<Highlight code={code} language={className.replace(/language-/, '') || 'bash'} theme={themes.github}>
120+
<Highlight code={code} language={className.replace(/language-/, '') || 'bash'} theme={codeTheme}>
119121
{({className: highlightClassName, style, tokens, getLineProps, getTokenProps}) => (
120122
<CodeBlock className={highlightClassName} style={style} code={code}>
121123
{tokens.map((line, i) => (

0 commit comments

Comments
 (0)