Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/core/primitives/code/__workshop__/opticalAlignment.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import {AddCircleIcon} from '@sanity/icons'
import {Box, Card, Code, Flex, Stack} from '@sanity/ui'

export default function OpticalAlignment() {
Expand Down Expand Up @@ -37,9 +36,7 @@ export default function OpticalAlignment() {

<Flex>
<Card padding={2} scheme="dark">
<Code>
<AddCircleIcon />
</Code>
<Code>{`<AddCircleIcon />`}</Code>
</Card>
</Flex>
</Stack>
Expand Down
30 changes: 27 additions & 3 deletions src/core/primitives/code/code.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,30 @@
import {forwardRef, Suspense, lazy} from 'react'
import {forwardRef, lazy, Suspense} from 'react'
import {styled} from 'styled-components'
import {useArrayProp} from '../../hooks'
import {responsiveCodeFontStyle, ResponsiveFontStyleProps} from '../../styles/internal'
import {codeBaseStyle} from './styles'

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

/**
* @public
*/
export type StringifiableNode =
| string
| number
| bigint
| boolean
| null
| undefined
| Iterable<StringifiableNode>
/**
* @public
*/
export interface CodeProps {
as?: React.ElementType | keyof React.JSX.IntrinsicElements
/** Define the language to use for syntax highlighting. */
language?: string
children: StringifiableNode
size?: number | number[]
weight?: string
}
Expand All @@ -23,17 +35,29 @@ const StyledCode = styled.pre<ResponsiveFontStyleProps>(codeBaseStyle, responsiv
* @public
*/
export const Code = forwardRef(function Code(
props: CodeProps & Omit<React.HTMLProps<HTMLElement>, 'as' | 'size'>,
props: CodeProps & Omit<React.HTMLProps<HTMLElement>, 'as' | 'size' | 'children'>,
ref: React.ForwardedRef<HTMLElement>,
) {
const {children, language, size = 2, weight, ...restProps} = props

return (
<StyledCode data-ui="Code" {...restProps} $size={useArrayProp(size)} $weight={weight} ref={ref}>
<Suspense fallback={<code>{children}</code>}>
<LazyRefractor language={language} value={children} />
<LazyRefractor language={language} value={stringifyChildren(children)} />
</Suspense>
</StyledCode>
)
})
Code.displayName = 'ForwardRef(Code)'

function stringifyChildren(children: StringifiableNode): string {
if (!children || typeof children === 'boolean') {
return ''
}

if (Array.isArray(children)) {
return children.map((c) => stringifyChildren(c)).join('')
}

return String(children)
}
Loading