-
Notifications
You must be signed in to change notification settings - Fork 842
/
_code_block.tsx
336 lines (290 loc) Β· 9.18 KB
/
_code_block.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, {
FunctionComponent,
KeyboardEvent,
CSSProperties,
useEffect,
useRef,
useState,
} from 'react';
import { createPortal } from 'react-dom';
import classNames from 'classnames';
import hljs from 'highlight.js';
import { EuiCopy } from '../copy';
import { EuiButtonIcon } from '../button';
import { EuiOverlayMask } from '../overlay_mask';
import { EuiFocusTrap } from '../focus_trap';
import { keyCodes } from '../../services';
import { EuiI18n } from '../i18n';
import { EuiInnerText } from '../inner_text';
import { keysOf } from '../common';
import { FontSize, PaddingSize } from './code';
const fontSizeToClassNameMap = {
s: 'euiCodeBlock--fontSmall',
m: 'euiCodeBlock--fontMedium',
l: 'euiCodeBlock--fontLarge',
};
export const FONT_SIZES = keysOf(fontSizeToClassNameMap);
const paddingSizeToClassNameMap: { [paddingSize in PaddingSize]: string } = {
none: '',
s: 'euiCodeBlock--paddingSmall',
m: 'euiCodeBlock--paddingMedium',
l: 'euiCodeBlock--paddingLarge',
};
export const PADDING_SIZES = keysOf(paddingSizeToClassNameMap);
interface Props {
className?: string;
fontSize?: FontSize;
/**
* Displays the passed code in an inline format. Also removes any margins set.
*/
inline?: boolean;
/**
* Displays an icon button to copy the code snippet to the clipboard.
*/
isCopyable?: boolean;
/**
* Sets the syntax highlighting for a specific language
*/
language?: string;
overflowHeight?: number;
paddingSize?: PaddingSize;
transparentBackground?: boolean;
/**
* Specify how `white-space` inside the element is handled.
* `pre` respects line breaks/white space but doesn't force them to wrap the line
* `pre-wrap` respects line breaks/white space but does force them to wrap the line when necessary.
*/
whiteSpace?: 'pre' | 'pre-wrap';
}
/**
* This is the base component extended by EuiCode and EuiCodeBlock.
* These components share the same propTypes definition with EuiCodeBlockImpl.
*/
export const EuiCodeBlockImpl: FunctionComponent<Props> = ({
transparentBackground = false,
paddingSize = 'l',
fontSize = 's',
isCopyable = false,
whiteSpace = 'pre-wrap',
language,
inline,
children,
className,
overflowHeight,
...rest
}) => {
const [isFullScreen, setIsFullScreen] = useState(false);
const [isPortalTargetReady, setIsPortalTargetReady] = useState(false);
const codeTarget = useRef<HTMLDivElement | null>(null);
const code = useRef<HTMLElement | null>(null);
const codeFullScreen = useRef<HTMLElement | null>(null);
useEffect(() => {
codeTarget.current = document.createElement('div');
setIsPortalTargetReady(true);
}, []);
useEffect(() => {
/**
* because React maintains a mapping between its Virtual DOM representation and the actual
* DOM elements (including text nodes), and hljs modifies the DOM structure which leads
* to React updating detached nodes, we render to a document fragment and
* copy from that fragment into the target elements
* (https://github.com/elastic/eui/issues/2322)
*/
const html = isPortalTargetReady ? codeTarget.current!.innerHTML : '';
if (code.current) {
code.current.innerHTML = html;
}
if (codeFullScreen.current) {
codeFullScreen.current.innerHTML = html;
}
if (language) {
if (code.current) {
hljs.highlightBlock(code.current);
}
if (codeFullScreen.current) {
hljs.highlightBlock(codeFullScreen.current);
}
}
});
const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
if (event.keyCode === keyCodes.ESCAPE) {
event.preventDefault();
event.stopPropagation();
closeFullScreen();
}
};
const toggleFullScreen = () => {
setIsFullScreen(!isFullScreen);
};
const closeFullScreen = () => {
setIsFullScreen(false);
};
const classes = classNames(
'euiCodeBlock',
fontSizeToClassNameMap[fontSize],
paddingSizeToClassNameMap[paddingSize],
{
'euiCodeBlock--transparentBackground': transparentBackground,
'euiCodeBlock--inline': inline,
'euiCodeBlock--hasControls': isCopyable || overflowHeight,
},
className
);
const codeClasses = classNames('euiCodeBlock__code', language);
const preClasses = classNames('euiCodeBlock__pre', {
'euiCodeBlock__pre--whiteSpacePre': whiteSpace === 'pre',
'euiCodeBlock__pre--whiteSpacePreWrap': whiteSpace === 'pre-wrap',
});
const optionalStyles: CSSProperties = {};
if (overflowHeight) {
optionalStyles.maxHeight = overflowHeight;
}
const codeSnippet = <code ref={code} className={codeClasses} {...rest} />;
const wrapperProps = {
className: classes,
style: optionalStyles,
};
if (inline) {
return isPortalTargetReady ? (
<>
{createPortal(children, codeTarget.current!)}
<span {...wrapperProps}>{codeSnippet}</span>
</>
) : null;
}
const getCopyButton = (textToCopy?: string) => {
let copyButton: JSX.Element | undefined;
if (isCopyable && textToCopy) {
copyButton = (
<div className="euiCodeBlock__copyButton">
<EuiI18n token="euiCodeBlock.copyButton" default="Copy">
{(copyButton: string) => (
<EuiCopy textToCopy={textToCopy}>
{copy => (
<EuiButtonIcon
size="s"
onClick={copy}
iconType="copy"
color="text"
aria-label={copyButton}
/>
)}
</EuiCopy>
)}
</EuiI18n>
</div>
);
}
return copyButton;
};
let fullScreenButton: JSX.Element | undefined;
if (!inline && overflowHeight) {
fullScreenButton = (
<EuiI18n
tokens={[
'euiCodeBlock.fullscreenCollapse',
'euiCodeBlock.fullscreenExpand',
]}
defaults={['Collapse', 'Expand']}>
{([fullscreenCollapse, fullscreenExpand]: string[]) => (
<EuiButtonIcon
className="euiCodeBlock__fullScreenButton"
size="s"
onClick={toggleFullScreen}
iconType={isFullScreen ? 'cross' : 'fullScreen'}
color="text"
aria-label={isFullScreen ? fullscreenCollapse : fullscreenExpand}
/>
)}
</EuiI18n>
);
}
const getCodeBlockControls = (textToCopy?: string) => {
let codeBlockControls;
const copyButton = getCopyButton(textToCopy);
if (copyButton || fullScreenButton) {
codeBlockControls = (
<div className="euiCodeBlock__controls">
{fullScreenButton}
{copyButton}
</div>
);
}
return codeBlockControls;
};
const getFullScreenDisplay = (codeBlockControls?: JSX.Element) => {
let fullScreenDisplay;
if (isFullScreen) {
// Force fullscreen to use large font and padding.
const fullScreenClasses = classNames(
'euiCodeBlock',
fontSizeToClassNameMap[fontSize],
'euiCodeBlock-paddingLarge',
'euiCodeBlock-isFullScreen',
className
);
fullScreenDisplay = (
<EuiOverlayMask>
<EuiFocusTrap clickOutsideDisables={true}>
<div className={fullScreenClasses}>
<pre className={preClasses}>
<code
ref={codeFullScreen}
className={codeClasses}
tabIndex={0}
onKeyDown={onKeyDown}
/>
</pre>
{codeBlockControls}
</div>
</EuiFocusTrap>
</EuiOverlayMask>
);
}
return fullScreenDisplay;
};
return isPortalTargetReady ? (
<>
{createPortal(children, codeTarget.current!)}
<EuiInnerText fallback="">
{(innerTextRef, innerText) => {
const codeBlockControls = getCodeBlockControls(innerText);
return (
<div {...wrapperProps}>
<pre
ref={innerTextRef}
style={optionalStyles}
className={preClasses}>
{codeSnippet}
</pre>
{/*
If the below fullScreen code renders, it actually attaches to the body because of
EuiOverlayMask's React portal usage.
*/}
{codeBlockControls}
{getFullScreenDisplay(codeBlockControls)}
</div>
);
}}
</EuiInnerText>
</>
) : null;
};