forked from facebook/create-react-app
/
CodeExample.js
275 lines (234 loc) · 6.51 KB
/
CodeExample.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import React from 'react';
import ReactDOM from 'react-dom';
import styled from 'styled-components';
import { object, arrayOf, oneOf } from 'prop-types';
import unescape from 'unescape-html';
import reactElementToJSXString from 'react-element-to-jsx-string';
import pretty from 'pretty';
import { renderToStaticMarkup } from 'react-dom/server';
import Code from '../Code/';
import Button from '../Button';
import * as theme from '../../style/theme';
/**
* Remove props that are undefined or null
* Don't show React.Fragment in code example
*/
const cleanUpCode = markup => {
const markupProps = markup.props || {};
return Object.keys(markupProps).reduce((acc, curr) => {
let currProp = markupProps[curr];
let newProp;
// clean up child code
if (curr === 'children' && typeof currProp !== 'string') {
newProp = React.Children.map(currProp, child => {
// hide fragments if containing just strings
const isFragmentString =
child.type === React.Fragment &&
child.props &&
typeof child.props.children === 'string';
return isFragmentString
? child.props.children
: {
...child,
props: cleanUpCode(child),
};
});
}
// hide undefined or null props
const isNotDefined = [undefined, null].indexOf(currProp) !== -1;
return {
...acc,
...(isNotDefined
? {}
: {
[curr]: newProp || currProp,
}),
};
}, {});
};
const getJSXAsStringFromMarkup = (markup, options) => {
const { cleanProps, filterProps = [], ...otherOptions } = options || {};
const reactElementToJSXStringOptions = {
showDefaultProps: false,
showFunctions: true,
functionValue: fn => fn.name,
displayName: ReactElement => ReactElement.props.mdxType,
filterProps: ['mdxType', 'originalType', ...filterProps],
...otherOptions,
};
if (cleanProps) {
markup = {
...markup,
props: cleanUpCode(markup),
};
}
// valid element can be passed to reactElementToJSXString directly
if (React.isValidElement(markup)) {
return reactElementToJSXString(markup, reactElementToJSXStringOptions);
}
// if it's array, we need to pass elemenets one by one
if (Array.isArray(markup)) {
return markup
.map(markupItem =>
reactElementToJSXString(markupItem, reactElementToJSXStringOptions)
)
.join('\n');
}
// if it's pure text, return it
if (typeof markup === 'string') {
return markup;
}
return '';
};
export default class CodeExample extends React.Component {
static displayName = 'CodeExample';
static propTypes = {
codeJSXOptions: object,
codeTypes: arrayOf(oneOf(['jsx', 'html'])),
};
static defaultProps = {
codeTypes: ['jsx', 'html'],
};
state = {
codePreviewType: this.props.codeTypes && this.props.codeTypes[0],
copyButtonText: 'Copy to clipboard',
copyButtonClass: '',
};
constructor(props) {
super(props);
this.codeBlockRef = React.createRef();
}
handleCodePreviewTypeToggle(e, type) {
this.setState({
codePreviewType: type,
});
}
handleCopyCode(e, element) {
const selection = window.getSelection();
const range = document.createRange();
const elem = ReactDOM.findDOMNode(element);
range.selectNodeContents(elem);
selection.removeAllRanges();
selection.addRange(range);
let newText = 'Copied!';
let newClass = 'success';
try {
document.execCommand('copy');
// selection.removeAllRanges();
} catch (e) {
newText = 'Error! Press Ctrl + C';
newClass = 'error';
}
const {
copyButtonText: originalText,
copyButtonClass: originalClass,
} = this.state;
this.setState(
{
copyButtonText: newText,
copyButtonClass: newClass,
},
() => {
setTimeout(() => {
this.setState({
copyButtonText: originalText,
copyButtonClass: originalClass,
});
}, 1200);
}
);
}
render() {
const { children, codeJSXOptions, codeTypes, ...other } = this.props;
let codeToShow;
switch (this.state.codePreviewType) {
case 'html':
codeToShow = pretty(
typeof children === 'string'
? unescape(children)
: renderToStaticMarkup(children),
{
ocd: true,
}
);
break;
case 'jsx':
codeToShow = getJSXAsStringFromMarkup(children, codeJSXOptions);
break;
default:
codeToShow = '';
}
return (
<StyledWrapper {...other}>
{codeTypes.map(codeType => (
<StyledCodeTypeToggle
key={codeType}
role="button"
onClick={e => this.handleCodePreviewTypeToggle(e, codeType)}
className={
this.state.codePreviewType === codeType ? 'is-active' : ''
}
>
{codeType.toUpperCase()}
</StyledCodeTypeToggle>
))}
<StyledCopyButton
className={this.state.copyButtonClass}
onClick={e => this.handleCopyCode(e, this.codeBlockRef.current)}
>
{this.state.copyButtonText}
</StyledCopyButton>
<Code
inline={false}
ref={this.codeBlockRef}
data-testid={this.state.codePreviewType}
language={
this.state.codePreviewType === 'html'
? 'markup'
: this.state.codePreviewType
}
>
{codeToShow}
</Code>
</StyledWrapper>
);
}
}
const StyledCopyButton = styled(Button)`
position: absolute;
bottom: 0;
right: 0;
transform: translateY(100%);
margin-bottom: 0;
background: ${props => props.theme.colors.white};
&:hover {
background: ${props => props.theme.colors.grey};
}
&.success {
background: ${props => props.theme.colors.success};
}
&.error {
background: ${props => props.theme.colors.error};
}
`;
StyledCopyButton.defaultProps = {
theme,
};
const StyledWrapper = styled.div`
position: relative;
`;
const StyledCodeTypeToggle = styled(Button)`
margin-bottom: 0;
border-top-left-radius: ${props => props.theme.borderRadius.default};
border-top-right-radius: ${props => props.theme.borderRadius.default};
&:hover {
background: ${props => props.theme.colors.grey};
}
&.is-active {
background-color: ${props => props.theme.colors.black};
color: ${props => props.theme.colors.white};
}
`;
StyledCodeTypeToggle.defaultProps = {
theme,
};