This repository has been archived by the owner on Mar 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
/
ExternalExampleLayout.tsx
90 lines (75 loc) · 2.36 KB
/
ExternalExampleLayout.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { Provider, themes, ThemeInput } from '@stardust-ui/react'
import * as _ from 'lodash'
import * as React from 'react'
import { match } from 'react-router'
import SourceRender from 'react-source-render'
import { ExampleSource } from 'docs/src/types'
import {
exampleSourcesContext,
exampleKebabNameToSourceFilename,
parseExamplePath,
} from 'docs/src/utils'
import PageNotFound from '../views/PageNotFound'
import { babelConfig, importResolver } from './Playground/renderConfig'
const examplePaths = exampleSourcesContext.keys()
type ExternalExampleLayoutProps = {
match: match<{
exampleName: string
rtl: string
}>
}
type ExternalExampleLayoutState = {
renderId: number
themeName: string
}
class ExternalExampleLayout extends React.Component<
ExternalExampleLayoutProps,
ExternalExampleLayoutState
> {
state = {
renderId: 0,
themeName: undefined,
}
componentDidMount() {
window.resetExternalLayout = () =>
this.setState(prevState => ({ renderId: prevState.renderId + 1 }))
window.switchTheme = (themeName: string) => this.setState({ themeName })
}
render() {
const { exampleName } = this.props.match.params
const exampleFilename = exampleKebabNameToSourceFilename(exampleName)
const examplePath = _.find(
examplePaths,
path => exampleFilename === parseExamplePath(path).exampleName,
)
if (!examplePath) return <PageNotFound />
const exampleSource: ExampleSource = exampleSourcesContext(examplePath)
const theme = this.getTheme()
return (
<Provider key={this.state.renderId} theme={theme}>
<SourceRender
babelConfig={babelConfig}
source={exampleSource.js}
renderHtml={false}
resolver={importResolver}
unstable_hot
>
{({ element, error }) => (
<>
{element}
{/* This block allows to see issues with examples as visual regressions. */}
{error && <div style={{ fontSize: '5rem', color: 'red' }}>{error.toString()}</div>}
</>
)}
</SourceRender>
</Provider>
)
}
private getTheme = (): ThemeInput => {
const { themeName } = this.state
const theme: ThemeInput = (themeName && themes[themeName]) || {}
theme.rtl = this.props.match.params.rtl === 'true'
return theme
}
}
export default ExternalExampleLayout