-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.tsx
278 lines (269 loc) · 7.73 KB
/
index.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
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
276
277
278
import React, { useRef, useEffect, useImperativeHandle } from 'react';
import CodeMirror, { ReactCodeMirrorProps, ReactCodeMirrorRef, ViewUpdate } from '@uiw/react-codemirror';
import copyTextToClipboard from '@uiw/copy-to-clipboard';
import { javascript } from '@codemirror/lang-javascript';
import { CodeSandboxProps } from '@uiw/react-codesandbox';
import { CodepenProps } from '@uiw/react-codepen';
import Split, { SplitProps } from '@uiw/react-split';
import ThirdPartyButton from './ThirdPartyButton';
import * as icon from './icon';
import { ErrorMessage } from './ErrorMessage';
import { useCodePreview } from './useCodePreview';
import './index.less';
export interface CodePreviewProps extends SplitProps {
prefixCls?: string;
style?: React.CSSProperties;
/**
* To specify a CSS class, use the className attribute.
*/
className?: string;
/**
* Whether to display the border.
*/
bordered?: boolean;
/**
* `JSX` source code
*/
code?: string;
/**
* Whether to display the code interface.
*/
noCode?: boolean;
/**
* Is the background white or plaid?
*/
bgWhite?: boolean;
/**
* Only show Edit
*/
onlyEdit?: boolean;
/**
* Whether to display the preview interface.
*/
noPreview?: boolean;
/**
* Preview area does not display scroll bars
*/
noScroll?: boolean;
/**
* Modify ReactCodemirror props.
*/
editProps?: ReactCodeMirrorProps;
/**
* Dependent component
*/
dependencies?: Record<string, any>;
codePenOption?: CodepenProps & {
/**
* Packages that do not require comments.
* @example ['uiw']
*/
includeModule?: string[];
};
codeSandboxOption?: CodeSandboxProps;
/** @default 'Code' */
btnText?: string;
/** @default 'Hide Editor' */
btnHideText?: string;
/**
* `light` / `dark` / `Extension` Defaults to `light`.
* @default light
*/
theme?: ReactCodeMirrorProps['theme'];
/**
* Specifies the initial state of the source panel.
*/
sourceState?: 'hidden' | 'shown';
}
export interface CodePreviewState {
errorMessage: string;
fullScreen: boolean;
width: number | string;
copied: boolean;
showEdit: boolean;
}
export interface CodePreviewRef {
editor?: React.RefObject<ReactCodeMirrorRef>;
demo?: HTMLDivElement | null;
}
const CodePreview = React.forwardRef<CodePreviewRef, CodePreviewProps>((props, ref) => {
const {
style,
prefixCls = 'w-code-preview',
className,
theme = 'light',
editProps = {},
codePenOption,
codeSandboxOption,
code: _Code = '',
dependencies = {},
btnText = 'Code',
btnHideText = 'Hide Editor',
onlyEdit = false,
bordered = true,
noCode = false,
noPreview = false,
noScroll = false,
bgWhite = false,
sourceState,
...otherProps
} = props;
const {
playerId,
setDemoDom,
code,
setCode,
fullScreen,
setFullScreen,
errorMessage,
width,
setWidth,
showEdit,
setShowEdit,
copied,
setCopied,
} = useCodePreview({ code: _Code, dependencies, ...props });
const demoRef = useRef<HTMLDivElement>(null);
const editor = useRef<ReactCodeMirrorRef>(null);
useImperativeHandle(ref, () => ({ editor: editor, demo: demoRef.current }), [editor, demoRef]);
const isOneItem = !noCode && !noPreview ? false : !noCode || !noPreview;
const visiable = width === 1 ? false : [isOneItem ? 1 : 2];
const cls = [
className,
prefixCls,
noScroll ? `${prefixCls}-noScroll` : null,
isOneItem ? `${prefixCls}-OneItem` : null,
bordered ? `${prefixCls}-bordered` : null,
fullScreen ? `${prefixCls}-fullScreen` : null,
]
.filter(Boolean)
.join(' ')
.trim();
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => setCode(_Code), [_Code]);
useEffect(() => {
if (demoRef.current) {
setDemoDom(demoRef.current);
}
window.addEventListener(
'popstate',
(e) => {
document.body.style.overflow = 'inherit';
},
false,
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const transitionend = () => setShowEdit(width !== 1);
useEffect(() => {
const dom = demoRef.current;
if (dom) {
dom.addEventListener('transitionend', transitionend);
}
return () => {
if (dom) {
dom.removeEventListener('transitionend', transitionend);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [width]);
const handleChange = (value: string, viewUpdate: ViewUpdate) => {
setCode(value);
if (editProps && editProps.onChange) {
editProps.onChange(value, viewUpdate);
}
};
const onSwitchSource = () => {
setWidth(width === 1 ? '50%' : 1);
setShowEdit(true);
};
// 通过状态props属性判断是否切换源码
const isShown = sourceState === 'shown';
useEffect(() => {
setWidth(isShown ? '50%' : 1);
setShowEdit(isShown);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isShown]);
const onCopyCode = () => {
copyTextToClipboard(code || '', (isCopy) => setCopied(isCopy));
setTimeout(() => setCopied(false), 2000);
};
const onFullScreen = () => {
setFullScreen(!fullScreen);
document.body.style.overflow = !fullScreen ? 'hidden' : 'inherit';
if (!fullScreen && demoRef.current) {
demoRef.current.style.maxWidth = 'inherit';
}
};
return (
<Split data-color-mode={theme} visiable={visiable} className={cls} style={{ flex: 1, ...style }} {...otherProps}>
{!onlyEdit && (
<div
className={[
`${prefixCls}-demo`,
!bgWhite ? `${prefixCls}-demo-bgPlaid` : null,
errorMessage ? `${prefixCls}-demo-error` : null,
]
.filter(Boolean)
.join(' ')
.trim()}
style={{
flex: 1,
display: !noPreview ? 'unset' : 'none',
...(width === 1 ? { width: '100%' } : {}),
}}
>
<ErrorMessage message={errorMessage} />
<div
className={[`${prefixCls}-demo-source`, errorMessage ? 'error' : null].filter(Boolean).join(' ').trim()}
id={playerId.current}
/>
</div>
)}
{(!noCode || onlyEdit) && (
<div ref={demoRef} style={{ overflow: 'hidden', width: onlyEdit ? '100%' : width }}>
{(showEdit || onlyEdit) && (
<CodeMirror
value={(code || '').replace(/\n$/, '')}
ref={editor}
theme={theme}
extensions={[javascript({ jsx: true })]}
{...editProps}
style={{ height: '100%' }}
height="100%"
onChange={handleChange}
/>
)}
</div>
)}
{!isOneItem && !(noCode && noPreview) && !onlyEdit && (
<div style={{ flex: 1, width: 29 }} className={`${prefixCls}-bar`}>
<ThirdPartyButton prefixCls={prefixCls} codePenOption={codePenOption} codeSandboxOption={codeSandboxOption} />
<div className={`${prefixCls}-bar-btn`} onClick={onSwitchSource}>
{width === 1 ? btnText : btnHideText}
</div>
<div
className={[`${prefixCls}-bar-iconbtns`, copied ? `${prefixCls}-bar-copied` : null]
.filter(Boolean)
.join(' ')
.trim()}
onClick={onCopyCode}
>
{copied ? icon.copyOk : icon.copy}
</div>
<div
className={[`${prefixCls}-bar-iconbtns`, fullScreen ? `${prefixCls}-bar-copied` : null]
.filter(Boolean)
.join(' ')
.trim()}
onClick={onFullScreen}
>
{icon.full}
</div>
</div>
)}
</Split>
);
});
CodePreview.displayName = 'CodePreview';
export default CodePreview;