1
- import { forwardRef , Suspense , lazy } from 'react'
1
+ import { forwardRef , lazy , Suspense } from 'react'
2
2
import { styled } from 'styled-components'
3
3
import { useArrayProp } from '../../hooks'
4
4
import { responsiveCodeFontStyle , ResponsiveFontStyleProps } from '../../styles/internal'
5
5
import { codeBaseStyle } from './styles'
6
6
7
7
const LazyRefractor = lazy ( ( ) => import ( './refractor' ) )
8
8
9
+ /**
10
+ * @public
11
+ */
12
+ export type StringifiableNode =
13
+ | string
14
+ | number
15
+ | bigint
16
+ | boolean
17
+ | null
18
+ | undefined
19
+ | Iterable < StringifiableNode >
9
20
/**
10
21
* @public
11
22
*/
12
23
export interface CodeProps {
13
24
as ?: React . ElementType | keyof React . JSX . IntrinsicElements
14
25
/** Define the language to use for syntax highlighting. */
15
26
language ?: string
27
+ children : StringifiableNode
16
28
size ?: number | number [ ]
17
29
weight ?: string
18
30
}
@@ -23,17 +35,29 @@ const StyledCode = styled.pre<ResponsiveFontStyleProps>(codeBaseStyle, responsiv
23
35
* @public
24
36
*/
25
37
export const Code = forwardRef ( function Code (
26
- props : CodeProps & Omit < React . HTMLProps < HTMLElement > , 'as' | 'size' > ,
38
+ props : CodeProps & Omit < React . HTMLProps < HTMLElement > , 'as' | 'size' | 'children' > ,
27
39
ref : React . ForwardedRef < HTMLElement > ,
28
40
) {
29
41
const { children, language, size = 2 , weight, ...restProps } = props
30
42
31
43
return (
32
44
< StyledCode data-ui = "Code" { ...restProps } $size = { useArrayProp ( size ) } $weight = { weight } ref = { ref } >
33
45
< Suspense fallback = { < code > { children } </ code > } >
34
- < LazyRefractor language = { language } value = { String ( children ) } />
46
+ < LazyRefractor language = { language } value = { stringifyChildren ( children ) } />
35
47
</ Suspense >
36
48
</ StyledCode >
37
49
)
38
50
} )
39
51
Code . displayName = 'ForwardRef(Code)'
52
+
53
+ function stringifyChildren ( children : StringifiableNode ) : string {
54
+ if ( ! children || typeof children === 'boolean' ) {
55
+ return ''
56
+ }
57
+
58
+ if ( Array . isArray ( children ) ) {
59
+ return children . map ( ( c ) => stringifyChildren ( c ) ) . join ( '' )
60
+ }
61
+
62
+ return String ( children )
63
+ }
0 commit comments