import React , { ReactNode } from 'react' ; import styled from 'styled-components' ; import { ChevronRight } from '@sparkpost/matchbox-icons' ; import { pre , code , prefix , line , chevron } from './styles' ; type DarkProp = { $dark ? : boolean ; } ; const StyledPre = styled ( 'pre' ) < DarkProp > `
  ${ pre }
` ; const StyledCode = styled ( 'code' ) < DarkProp > `
  ${ code }
` ; const StyledCodePrefix = styled ( 'div' ) < DarkProp > `
  ${ prefix }
` ; const StyledLineNumber = styled ( 'span' ) < DarkProp > `
  ${ line }
` ; const StyledChevron = styled ( ChevronRight ) `
  ${ chevron }
` ; export type CodeBlockProps = { /**
     * The string of code to render
     */ code : string ; className ? : string ; /**
     * Height in pixels of the <pre> block
     */ height ? : number ; /**
     * Render line numbers
     */ numbered ? : boolean ; /**
     * Whether the code block is styled dark or light
     */ dark ? : boolean ; children ? : React . ReactNode ; } ; function CodeBlock ( props ) { const { children , code , height , className , numbered = false , dark = false } = props ; return ( < StyledPre className = { className } style = { { height : height ? `${ height }px` : 'auto' } } $dark = { dark } > < CodePrefix dark = { dark } code = { code } numbered = { numbered } / > < StyledCode $dark = { dark } > { } { children ? ( React . Children . map < ReactNode , ReactNode > ( children , ( child ) => { if ( React . isValidElement ( child ) ) { return React . cloneElement ( child , { children : code } ) ; } } ) ) : ( < > { code } < />)} < /StyledCode> < /StyledPre>); } function CodePrefix ( { code , numbered , dark } ) { const rows = code . split ( /\r\n|\r|\n/ ) ; return ( < StyledCodePrefix aria - hidden = "true" > { rows . map ( ( _row , rowIndex ) => { const key = `code-block-row-${ rowIndex }` ; if ( numbered ) { return ( < StyledLineNumber $dark = { dark } key = { key } > { rowIndex + 1 } { } < /StyledLineNumber>); } return ( < StyledLineNumber $dark = { dark } key = { key } > < StyledChevron /> < /StyledLineNumber>); } ) } < /StyledCodePrefix>); } export default CodeBlock ;