@elastic/eui
Version:
Elastic UI Component Library
248 lines (242 loc) • 14.9 kB
JavaScript
var _excluded = ["language", "transparentBackground", "paddingSize", "fontSize", "isCopyable", "copyAriaLabel", "whiteSpace", "children", "className", "overflowHeight", "isVirtualized", "lineNumbers", "aria-label"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], t.indexOf(o) >= 0 || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; }
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React, { useMemo } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { useCombinedRefs, useEuiTheme, useEuiMemoizedStyles, tabularCopyMarkers } from '../../services';
import { DEFAULT_LANGUAGE, checkSupportedLanguage, getHtmlContent, highlightByLine } from './utils';
import { useOverflow } from './code_block_overflow';
import { useCopy } from './code_block_copy';
import { useFullScreen, EuiCodeBlockFullScreenWrapper } from './code_block_full_screen';
import { EuiCodeBlockControls } from './code_block_controls';
import { EuiCodeBlockVirtualized } from './code_block_virtualized';
import { euiCodeBlockStyles, euiCodeBlockPreStyles, euiCodeBlockCodeStyles } from './code_block.styles';
import { EuiScreenReaderOnly } from '../accessibility';
import { useEuiI18n } from '../i18n';
// Based on observed line height for non-virtualized code blocks
import { jsx as ___EmotionJSX } from "@emotion/react";
var fontSizeToRowHeightMap = {
s: 18,
m: 21,
l: 24
};
export var FONT_SIZES = ['s', 'm', 'l'];
export var PADDING_SIZES = ['none', 's', 'm', 'l'];
// This exclusive union enforces specific props based on isVirtualized
export var EuiCodeBlock = function EuiCodeBlock(_ref) {
var _ref$language = _ref.language,
_language = _ref$language === void 0 ? DEFAULT_LANGUAGE : _ref$language,
_ref$transparentBackg = _ref.transparentBackground,
transparentBackground = _ref$transparentBackg === void 0 ? false : _ref$transparentBackg,
_ref$paddingSize = _ref.paddingSize,
paddingSize = _ref$paddingSize === void 0 ? 'l' : _ref$paddingSize,
_ref$fontSize = _ref.fontSize,
fontSize = _ref$fontSize === void 0 ? 's' : _ref$fontSize,
_ref$isCopyable = _ref.isCopyable,
isCopyable = _ref$isCopyable === void 0 ? false : _ref$isCopyable,
copyAriaLabel = _ref.copyAriaLabel,
_ref$whiteSpace = _ref.whiteSpace,
whiteSpace = _ref$whiteSpace === void 0 ? 'pre-wrap' : _ref$whiteSpace,
children = _ref.children,
className = _ref.className,
overflowHeight = _ref.overflowHeight,
_isVirtualized = _ref.isVirtualized,
_ref$lineNumbers = _ref.lineNumbers,
lineNumbers = _ref$lineNumbers === void 0 ? false : _ref$lineNumbers,
ariaLabel = _ref['aria-label'],
rest = _objectWithoutProperties(_ref, _excluded);
var euiTheme = useEuiTheme();
var language = useMemo(function () {
return checkSupportedLanguage(_language);
}, [_language]);
var lineNumbersConfig = useMemo(function () {
var config = _typeof(lineNumbers) === 'object' ? lineNumbers : {};
return lineNumbers ? _objectSpread({
start: 1,
show: true
}, config) : {
start: 1,
show: false
};
}, [lineNumbers]);
// Used by `FixedSizeList` when `isVirtualized=true` or `children` is parsable
var data = useMemo(function () {
if (typeof children !== 'string') {
return [];
}
return highlightByLine(children, language, lineNumbersConfig, euiTheme);
}, [children, language, lineNumbersConfig, euiTheme]);
// Used by `pre` when `isVirtualized=false` or `children` is not parsable
var content = useMemo(function () {
return getHtmlContent(data, children);
}, [data, children]);
var isVirtualized = useMemo(function () {
return !!(_isVirtualized && Array.isArray(data));
}, [_isVirtualized, data]);
var _useCopy = useCopy({
copyAriaLabel: copyAriaLabel,
isCopyable: isCopyable,
isVirtualized: isVirtualized,
children: children
}),
innerTextRef = _useCopy.innerTextRef,
copyButton = _useCopy.copyButton;
var _useOverflow = useOverflow({
overflowHeight: overflowHeight
}),
setWrapperRef = _useOverflow.setWrapperRef,
tabIndex = _useOverflow.tabIndex,
overflowHeightStyles = _useOverflow.overflowHeightStyles;
var combinedRef = useCombinedRefs([innerTextRef, setWrapperRef]);
var _useFullScreen = useFullScreen({
overflowHeight: overflowHeight
}),
fullScreenButton = _useFullScreen.fullScreenButton,
isFullScreen = _useFullScreen.isFullScreen,
onKeyDown = _useFullScreen.onKeyDown;
var hasControls = !!(copyButton || fullScreenButton);
var hasBothControls = !!(copyButton && fullScreenButton);
var styles = useEuiMemoizedStyles(euiCodeBlockStyles);
var cssStyles = [styles.euiCodeBlock, styles[fontSize], transparentBackground && styles.transparentBackground, hasControls && (hasBothControls ? styles.hasBothControls[paddingSize] : styles.hasControls[paddingSize])];
var preStyles = useEuiMemoizedStyles(euiCodeBlockPreStyles);
var _useMemo = useMemo(function () {
var isWhiteSpacePre = whiteSpace === 'pre' || isVirtualized;
var cssStyles = [preStyles.euiCodeBlock__pre, isWhiteSpacePre ? preStyles.whiteSpace.pre.pre : preStyles.whiteSpace.preWrap.preWrap];
var preProps = {
className: 'euiCodeBlock__pre',
css: [].concat(cssStyles, [preStyles.padding[paddingSize], hasControls && (isWhiteSpacePre ? preStyles.whiteSpace.pre.controlsOffset[paddingSize] : preStyles.whiteSpace.preWrap.controlsOffset[paddingSize])]),
tabIndex: isVirtualized ? 0 : tabIndex
};
var preFullscreenProps = {
className: 'euiCodeBlock__pre',
css: [].concat(cssStyles, [
// Force fullscreen to use xl padding
preStyles.padding.xl, hasControls && (isWhiteSpacePre ? preStyles.whiteSpace.pre.controlsOffset.xl : preStyles.whiteSpace.preWrap.controlsOffset.xl)]),
tabIndex: 0
};
return [preProps, preFullscreenProps];
}, [preStyles, whiteSpace, isVirtualized, hasControls, paddingSize, tabIndex]),
_useMemo2 = _slicedToArray(_useMemo, 2),
preProps = _useMemo2[0],
preFullscreenProps = _useMemo2[1];
var codeStyles = useEuiMemoizedStyles(euiCodeBlockCodeStyles);
var codeProps = useMemo(function () {
var cssStyles = [codeStyles.euiCodeBlock__code, isVirtualized && codeStyles.isVirtualized];
return _objectSpread({
className: 'euiCodeBlock__code',
css: cssStyles,
'data-code-language': language
}, rest);
}, [codeStyles, language, isVirtualized, rest]);
var codeBlockLabel = useEuiI18n('euiCodeBlock.label', '{language} code block:', {
language: language
});
// pre tags don't accept aria-label without an
// appropriate role, we add a SR only text instead
var codeBlockLabelElement = ___EmotionJSX(React.Fragment, null, tabularCopyMarkers.hiddenNoCopyBoundary, ___EmotionJSX(EuiScreenReaderOnly, null, ___EmotionJSX("div", null, ariaLabel ? "".concat(ariaLabel, ", ") : undefined, codeBlockLabel)), tabularCopyMarkers.hiddenNoCopyBoundary);
return ___EmotionJSX("div", {
css: cssStyles,
className: classNames('euiCodeBlock', className),
style: overflowHeightStyles
}, isVirtualized ? ___EmotionJSX(EuiCodeBlockVirtualized, {
data: data,
label: codeBlockLabelElement,
rowHeight: fontSizeToRowHeightMap[fontSize],
overflowHeight: overflowHeight,
preProps: preProps,
codeProps: codeProps
}) : ___EmotionJSX("pre", _extends({}, preProps, {
ref: combinedRef,
style: overflowHeightStyles
}), codeBlockLabelElement, ___EmotionJSX("code", codeProps, content)), ___EmotionJSX(EuiCodeBlockControls, {
controls: [fullScreenButton, copyButton],
paddingSize: paddingSize
}), isFullScreen && ___EmotionJSX(EuiCodeBlockFullScreenWrapper, {
onClose: onKeyDown
}, isVirtualized ? ___EmotionJSX(EuiCodeBlockVirtualized, {
data: data,
label: codeBlockLabelElement,
rowHeight: fontSizeToRowHeightMap.l,
preProps: preFullscreenProps,
codeProps: codeProps
}) : ___EmotionJSX("pre", preFullscreenProps, codeBlockLabelElement, ___EmotionJSX("code", codeProps, content)), ___EmotionJSX(EuiCodeBlockControls, {
controls: [fullScreenButton, copyButton],
paddingSize: "l"
})));
};
EuiCodeBlock.propTypes = {
className: PropTypes.string,
"aria-label": PropTypes.string,
"data-test-subj": PropTypes.string,
css: PropTypes.any,
/**
* Sets the syntax highlighting for a specific language
* @see [https://prismjs.com/#supported-languages](https://prismjs.com/#supported-languages) for options
*/
language: PropTypes.string,
transparentBackground: PropTypes.bool,
paddingSize: PropTypes.any,
fontSize: PropTypes.any,
/**
* 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: PropTypes.oneOfType([PropTypes.oneOf(["pre", "pre-wrap"]), PropTypes.oneOfType([PropTypes.oneOf(["pre"]), PropTypes.oneOf(["pre", "pre-wrap"])])]),
/**
* Displays an icon button to copy the code snippet to the clipboard.
*/
isCopyable: PropTypes.bool,
/**
* Customizes the aria-label for the copy button.
*
* @default 'Copy'
*/
copyAriaLabel: PropTypes.string,
/**
* Displays line numbers.
* Optionally accepts a configuration object for setting the starting number,
* visually highlighting ranges, or annotating specific lines:
* `{ start: 100, highlight: '1, 5-10, 20-30, 40', annotations: { 6: 'A special note about this line' } }`
*/
lineNumbers: PropTypes.oneOfType([PropTypes.bool.isRequired, PropTypes.shape({
start: PropTypes.number,
highlight: PropTypes.string,
annotations: PropTypes.any
}).isRequired]),
/**
* Sets the maximum container height.
* Accepts a pixel value (`300`) or a percentage (`'100%'`)
* Ensure the container has calcuable height when using a percentage
*/
overflowHeight: PropTypes.oneOfType([PropTypes.oneOfType([PropTypes.number.isRequired, PropTypes.string.isRequired]), PropTypes.oneOfType([PropTypes.oneOfType([PropTypes.number.isRequired, PropTypes.string.isRequired]).isRequired, PropTypes.oneOfType([PropTypes.number.isRequired, PropTypes.string.isRequired])])]),
/**
* Renders code block lines virtually.
* Useful for improving load times of large code blocks.
*
* When using this configuration, `overflowHeight` is required and
* `whiteSpace` can only be `pre`.
*/
isVirtualized: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOfType([PropTypes.oneOf([true]).isRequired, PropTypes.oneOf([false])])])
};