import React from 'react'
import HTMLtoJSX from 'html-2-jsx'
import styled from 'styled-components'
import {Absolute, BorderBox, Box, StyledOcticon as Octicon, Relative, Text} from '@primer/components'
import {LiveEditor, LiveError, LivePreview, LiveProvider} from 'react-live'
import {getIconByName} from '@githubprimer/octicons-react'
import ClipboardCopy from './ClipboardCopy'
import Frame from './Frame'
import CodeExampleStyles from './CodeExampleStyles'
const StyledLiveProvider = styled(LiveProvider)`
${CodeExampleStyles}
`
const LANG_PATTERN = /\blanguage-\.?(jsx|html)\b/
const converter = new HTMLtoJSX({
indent: ' ',
createClass: false
})
const defaultTransform = code => `${code}`
const languageTransforms = {
html: html => defaultTransform(converter.convert(html)),
jsx: defaultTransform
}
export default function CodeExample(props) {
const {children, dangerouslySetInnerHTML, inert, source, ...rest} = props
const lang = getLanguage(props.className)
if (lang && !inert) {
const liveProps = {
code: source,
scope: {Octicon, getIconByName},
transformCode: getTransformForLanguage(lang),
mountStylesheet: false
}
return (
)
} else {
const rest = {
children,
dangerouslySetInnerHTML
}
// eslint-disable-next-line react/no-danger-with-children
return
}
}
CodeExample.defaultProps = {
my: 4
}
function getLanguage(className) {
const match = className && className.match(LANG_PATTERN)
return match ? match[1] : undefined
}
function getTransformForLanguage(lang) {
return lang in languageTransforms ? languageTransforms[lang] : null
}