Skip to content

Commit de1e4ec

Browse files
committed
feat: base code block theme on primer colorMode
1 parent b211843 commit de1e4ec

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/hooks/use-prism-theme.js

Lines changed: 17 additions & 0 deletions
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

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

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

100101
function Code({className = '', prompt, children}) {
102+
const {theme: codeTheme} = usePrismTheme()
101103
if (prompt) {
102104
return (
103-
<CodeBlock style={themes.github.plain}>
105+
<CodeBlock style={codeTheme.plain}>
104106
<MonoText>{children}</MonoText>
105107
</CodeBlock>
106108
)
@@ -114,7 +116,7 @@ function Code({className = '', prompt, children}) {
114116
}
115117

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

0 commit comments

Comments
 (0)