Skip to content

Commit 4619cef

Browse files
committed
fix: use stricter type definition for children of <Code>
1 parent 95e7c7f commit 4619cef

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

src/core/primitives/code/__workshop__/opticalAlignment.tsx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,7 @@ export default function OpticalAlignment() {
3737

3838
<Flex>
3939
<Card padding={2} scheme="dark">
40-
<Code>
41-
<AddCircleIcon />
42-
</Code>
40+
<Code>{`<AddCircleIcon />`}</Code>
4341
</Card>
4442
</Flex>
4543
</Stack>

src/core/primitives/code/code.tsx

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,30 @@
1-
import {forwardRef, Suspense, lazy} from 'react'
1+
import {forwardRef, lazy, Suspense} from 'react'
22
import {styled} from 'styled-components'
33
import {useArrayProp} from '../../hooks'
44
import {responsiveCodeFontStyle, ResponsiveFontStyleProps} from '../../styles/internal'
55
import {codeBaseStyle} from './styles'
66

77
const LazyRefractor = lazy(() => import('./refractor'))
88

9+
/**
10+
* @public
11+
*/
12+
export type StringifiableNode =
13+
| string
14+
| number
15+
| bigint
16+
| boolean
17+
| null
18+
| undefined
19+
| Iterable<StringifiableNode>
920
/**
1021
* @public
1122
*/
1223
export interface CodeProps {
1324
as?: React.ElementType | keyof React.JSX.IntrinsicElements
1425
/** Define the language to use for syntax highlighting. */
1526
language?: string
27+
children: StringifiableNode
1628
size?: number | number[]
1729
weight?: string
1830
}
@@ -23,17 +35,29 @@ const StyledCode = styled.pre<ResponsiveFontStyleProps>(codeBaseStyle, responsiv
2335
* @public
2436
*/
2537
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'>,
2739
ref: React.ForwardedRef<HTMLElement>,
2840
) {
2941
const {children, language, size = 2, weight, ...restProps} = props
3042

3143
return (
3244
<StyledCode data-ui="Code" {...restProps} $size={useArrayProp(size)} $weight={weight} ref={ref}>
3345
<Suspense fallback={<code>{children}</code>}>
34-
<LazyRefractor language={language} value={String(children)} />
46+
<LazyRefractor language={language} value={stringifyChildren(children)} />
3547
</Suspense>
3648
</StyledCode>
3749
)
3850
})
3951
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

Comments
 (0)