UNPKG

@elastic/eui

Version:

Elastic UI Component Library

228 lines (222 loc) 14.6 kB
var _excluded = ["language", "transparentBackground", "paddingSize", "fontSize", "isCopyable", "whiteSpace", "children", "className", "overflowHeight", "isVirtualized", "lineNumbers"]; function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /* * 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 } 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'; // 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, _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, 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({ 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 = euiCodeBlockStyles(euiTheme); var cssStyles = [styles.euiCodeBlock, styles[fontSize], transparentBackground && styles.transparentBackground, hasControls && (hasBothControls ? styles.hasBothControls[paddingSize] : styles.hasControls[paddingSize])]; var _useMemo = useMemo(function () { var isWhiteSpacePre = whiteSpace === 'pre' || isVirtualized; var styles = euiCodeBlockPreStyles(euiTheme); var cssStyles = [styles.euiCodeBlock__pre, isWhiteSpacePre ? styles.whiteSpace.pre.pre : styles.whiteSpace.preWrap.preWrap]; var preProps = { className: 'euiCodeBlock__pre', css: [].concat(cssStyles, [styles.padding[paddingSize], hasControls && (isWhiteSpacePre ? styles.whiteSpace.pre.controlsOffset[paddingSize] : styles.whiteSpace.preWrap.controlsOffset[paddingSize])]), tabIndex: isVirtualized ? 0 : tabIndex }; var preFullscreenProps = { className: 'euiCodeBlock__pre', css: [].concat(cssStyles, [ // Force fullscreen to use xl padding styles.padding.xl, hasControls && (isWhiteSpacePre ? styles.whiteSpace.pre.controlsOffset.xl : styles.whiteSpace.preWrap.controlsOffset.xl)]), tabIndex: 0, onKeyDown: onKeyDown }; return [preProps, preFullscreenProps]; }, [euiTheme, whiteSpace, isVirtualized, hasControls, paddingSize, onKeyDown, tabIndex]), _useMemo2 = _slicedToArray(_useMemo, 2), preProps = _useMemo2[0], preFullscreenProps = _useMemo2[1]; var codeProps = useMemo(function () { var styles = euiCodeBlockCodeStyles(euiTheme); var cssStyles = [styles.euiCodeBlock__code, isVirtualized && styles.isVirtualized]; return _objectSpread({ className: 'euiCodeBlock__code', css: cssStyles, 'data-code-language': language }, rest); }, [language, euiTheme, isVirtualized, rest]); return ___EmotionJSX("div", { css: cssStyles, className: classNames('euiCodeBlock', className), style: overflowHeightStyles }, isVirtualized ? ___EmotionJSX(EuiCodeBlockVirtualized, { data: data, rowHeight: fontSizeToRowHeightMap[fontSize], overflowHeight: overflowHeight, preProps: preProps, codeProps: codeProps }) : ___EmotionJSX("pre", _extends({}, preProps, { ref: combinedRef, style: overflowHeightStyles }), ___EmotionJSX("code", codeProps, content)), ___EmotionJSX(EuiCodeBlockControls, { controls: [fullScreenButton, copyButton], paddingSize: paddingSize }), isFullScreen && ___EmotionJSX(EuiCodeBlockFullScreenWrapper, null, isVirtualized ? ___EmotionJSX(EuiCodeBlockVirtualized, { data: data, rowHeight: fontSizeToRowHeightMap.l, preProps: preFullscreenProps, codeProps: codeProps }) : ___EmotionJSX("pre", preFullscreenProps, ___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, /** * 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])])]) };