1
- /* eslint-disable react/no-array-index-key */
2
1
import * as React from 'react' ;
3
2
import type { PrismLanguage } from './languages-available' ;
4
3
import { Prism } from './prism' ;
5
4
import type { Theme } from './themes' ;
6
5
7
- export type CodeBlockProps = Readonly < {
6
+ export interface CodeBlockProps extends React . ComponentPropsWithoutRef < 'pre' > {
8
7
lineNumbers ?: boolean ;
9
- style ?: React . CSSProperties ;
10
8
11
9
/**
12
10
* This applies a certain font family on all elements render in this component,
@@ -18,7 +16,7 @@ export type CodeBlockProps = Readonly<{
18
16
theme : Theme ;
19
17
language : PrismLanguage ;
20
18
code : string ;
21
- } > ;
19
+ }
22
20
23
21
const stylesForToken = ( token : Prism . Token , theme : Theme ) => {
24
22
let styles = { ...theme [ token . type ] } ;
@@ -75,33 +73,34 @@ const CodeBlockLine = ({
75
73
} ;
76
74
77
75
export const CodeBlock = React . forwardRef < HTMLPreElement , CodeBlockProps > (
78
- ( props , ref ) => {
79
- const languageGrammar = Prism . languages [ props . language ] ;
76
+ ( { code , fontFamily , lineNumbers , theme , language , ... rest } , ref ) => {
77
+ const languageGrammar = Prism . languages [ language ] ;
80
78
if ( typeof languageGrammar === 'undefined' ) {
81
79
throw new Error (
82
- `CodeBlock: There is no language defined on Prism called ${ props . language } ` ,
80
+ `CodeBlock: There is no language defined on Prism called ${ language } ` ,
83
81
) ;
84
82
}
85
83
86
- const lines = props . code . split ( / \r \n | \r | \n / gm) ;
84
+ const lines = code . split ( / \r \n | \r | \n / gm) ;
87
85
const tokensPerLine = lines . map ( ( line ) =>
88
86
Prism . tokenize ( line , languageGrammar ) ,
89
87
) ;
90
88
91
89
return (
92
90
< pre
91
+ { ...rest }
93
92
ref = { ref }
94
- style = { { ...props . theme . base , width : '100%' , ...props . style } }
93
+ style = { { ...theme . base , width : '100%' , ...rest . style } }
95
94
>
96
95
< code >
97
96
{ tokensPerLine . map ( ( tokensForLine , lineIndex ) => (
98
97
< p key = { lineIndex } style = { { margin : 0 , minHeight : '1em' } } >
99
- { props . lineNumbers ? (
98
+ { lineNumbers ? (
100
99
< span
101
100
style = { {
102
101
width : '2em' ,
103
102
display : 'inline-block' ,
104
- fontFamily : props . fontFamily ,
103
+ fontFamily : fontFamily ,
105
104
} }
106
105
>
107
106
{ lineIndex + 1 }
@@ -110,9 +109,9 @@ export const CodeBlock = React.forwardRef<HTMLPreElement, CodeBlockProps>(
110
109
111
110
{ tokensForLine . map ( ( token , i ) => (
112
111
< CodeBlockLine
113
- inheritedStyles = { { fontFamily : props . fontFamily } }
112
+ inheritedStyles = { { fontFamily : fontFamily } }
114
113
key = { i }
115
- theme = { props . theme }
114
+ theme = { theme }
116
115
token = { token }
117
116
/>
118
117
) ) }
0 commit comments