import React, {
useState,
Fragment,
useRef,
useEffect,
createRef,
useReducer,
} from 'react'
import { convertToReactComponent } from '@patternfly/ast-helpers'
import { ErrorBoundary } from 'react-error-boundary'
import * as reactCoreModule from '@patternfly/react-core'
import * as reactIconsModule from '@patternfly/react-icons'
import * as reactDragDropModule from '@patternfly/react-drag-drop'
import styles from '@patternfly/react-styles/css/components/_index'
import * as reactTokensModule from '@patternfly/react-tokens'
import { ExampleToolbar } from './ExampleToolbar'
import { config } from '../../pf-docs.config.mjs'
interface LiveExampleProps {
src?: string
html?: string
isFullscreenPreview?: boolean
}
function fallbackRender({ error }: any) {
return (
Something went wrong:
{error.message}
)
}
function getLivePreview(editorCode: string) {
const scope = {
...reactCoreModule,
...reactIconsModule,
...reactDragDropModule,
styles,
...reactTokensModule,
...{ useState, Fragment, useRef, useEffect, createRef, useReducer },
...config.scope,
}
const { code: transformedCode } = convertToReactComponent(editorCode)
const componentNames = Object.keys(scope)
const componentValues = Object.values(scope)
const getPreviewComponent = new Function(
'React',
...componentNames,
transformedCode,
)
const PreviewComponent = getPreviewComponent(React, ...componentValues)
return
}
export const LiveExample = ({
src,
html,
isFullscreenPreview,
}: LiveExampleProps) => {
const inputCode = src || html || ''
const [code, setCode] = useState(inputCode)
let livePreview = null
let lang = 'ts'
if (html) {
livePreview = (
)
lang = 'html'
} else {
livePreview = getLivePreview(code)
lang = 'ts'
}
return (
{livePreview}
)
}