"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PADDING_SIZES = exports.FONT_SIZES = exports.EuiCodeBlock = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../services");
var _utils = require("./utils");
var _code_block_overflow = require("./code_block_overflow");
var _code_block_copy = require("./code_block_copy");
var _code_block_full_screen = require("./code_block_full_screen");
var _code_block_controls = require("./code_block_controls");
var _code_block_virtualized = require("./code_block_virtualized");
var _code_block = require("./code_block.styles");
var _react2 = require("@emotion/react");
var _excluded = ["language", "transparentBackground", "paddingSize", "fontSize", "isCopyable", "whiteSpace", "children", "className", "overflowHeight", "isVirtualized", "lineNumbers"];
/*
 * 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.
 */
// Based on observed line height for non-virtualized code blocks
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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; }
var fontSizeToRowHeightMap = {
  s: 18,
  m: 21,
  l: 24
};
var FONT_SIZES = ['s', 'm', 'l'];
exports.FONT_SIZES = FONT_SIZES;
var PADDING_SIZES = ['none', 's', 'm', 'l'];

// This exclusive union enforces specific props based on isVirtualized
exports.PADDING_SIZES = PADDING_SIZES;
var EuiCodeBlock = function EuiCodeBlock(_ref) {
  var _ref$language = _ref.language,
    _language = _ref$language === void 0 ? _utils.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 = (0, _services.useEuiTheme)();
  var language = (0, _react.useMemo)(function () {
    return (0, _utils.checkSupportedLanguage)(_language);
  }, [_language]);
  var lineNumbersConfig = (0, _react.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 = (0, _react.useMemo)(function () {
    if (typeof children !== 'string') {
      return [];
    }
    return (0, _utils.highlightByLine)(children, language, lineNumbersConfig, euiTheme);
  }, [children, language, lineNumbersConfig, euiTheme]);

  // Used by `pre` when `isVirtualized=false` or `children` is not parsable
  var content = (0, _react.useMemo)(function () {
    return (0, _utils.getHtmlContent)(data, children);
  }, [data, children]);
  var isVirtualized = (0, _react.useMemo)(function () {
    return !!(_isVirtualized && Array.isArray(data));
  }, [_isVirtualized, data]);
  var _useCopy = (0, _code_block_copy.useCopy)({
      isCopyable: isCopyable,
      isVirtualized: isVirtualized,
      children: children
    }),
    innerTextRef = _useCopy.innerTextRef,
    copyButton = _useCopy.copyButton;
  var _useOverflow = (0, _code_block_overflow.useOverflow)({
      overflowHeight: overflowHeight
    }),
    setWrapperRef = _useOverflow.setWrapperRef,
    tabIndex = _useOverflow.tabIndex,
    overflowHeightStyles = _useOverflow.overflowHeightStyles;
  var combinedRef = (0, _services.useCombinedRefs)([innerTextRef, setWrapperRef]);
  var _useFullScreen = (0, _code_block_full_screen.useFullScreen)({
      overflowHeight: overflowHeight
    }),
    fullScreenButton = _useFullScreen.fullScreenButton,
    isFullScreen = _useFullScreen.isFullScreen,
    onKeyDown = _useFullScreen.onKeyDown;
  var hasControls = !!(copyButton || fullScreenButton);
  var hasBothControls = !!(copyButton && fullScreenButton);
  var styles = (0, _code_block.euiCodeBlockStyles)(euiTheme);
  var cssStyles = [styles.euiCodeBlock, styles[fontSize], transparentBackground && styles.transparentBackground, hasControls && (hasBothControls ? styles.hasBothControls[paddingSize] : styles.hasControls[paddingSize])];
  var _useMemo = (0, _react.useMemo)(function () {
      var isWhiteSpacePre = whiteSpace === 'pre' || isVirtualized;
      var styles = (0, _code_block.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 = (0, _react.useMemo)(function () {
    var styles = (0, _code_block.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 (0, _react2.jsx)("div", {
    css: cssStyles,
    className: (0, _classnames.default)('euiCodeBlock', className),
    style: overflowHeightStyles
  }, isVirtualized ? (0, _react2.jsx)(_code_block_virtualized.EuiCodeBlockVirtualized, {
    data: data,
    rowHeight: fontSizeToRowHeightMap[fontSize],
    overflowHeight: overflowHeight,
    preProps: preProps,
    codeProps: codeProps
  }) : (0, _react2.jsx)("pre", _extends({}, preProps, {
    ref: combinedRef,
    style: overflowHeightStyles
  }), (0, _react2.jsx)("code", codeProps, content)), (0, _react2.jsx)(_code_block_controls.EuiCodeBlockControls, {
    controls: [fullScreenButton, copyButton],
    paddingSize: paddingSize
  }), isFullScreen && (0, _react2.jsx)(_code_block_full_screen.EuiCodeBlockFullScreenWrapper, null, isVirtualized ? (0, _react2.jsx)(_code_block_virtualized.EuiCodeBlockVirtualized, {
    data: data,
    rowHeight: fontSizeToRowHeightMap.l,
    preProps: preFullscreenProps,
    codeProps: codeProps
  }) : (0, _react2.jsx)("pre", preFullscreenProps, (0, _react2.jsx)("code", codeProps, content)), (0, _react2.jsx)(_code_block_controls.EuiCodeBlockControls, {
    controls: [fullScreenButton, copyButton],
    paddingSize: "l"
  })));
};
exports.EuiCodeBlock = EuiCodeBlock;
EuiCodeBlock.propTypes = {
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  css: _propTypes.default.any,
  /**
       * Sets the syntax highlighting for a specific language
       * @see [https://prismjs.com/#supported-languages](https://prismjs.com/#supported-languages) for options
       */
  language: _propTypes.default.string,
  transparentBackground: _propTypes.default.bool,
  paddingSize: _propTypes.default.any,
  fontSize: _propTypes.default.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.default.oneOfType([_propTypes.default.oneOf(["pre", "pre-wrap"]), _propTypes.default.oneOfType([_propTypes.default.oneOf(["pre"]), _propTypes.default.oneOf(["pre", "pre-wrap"])])]),
  /**
     * Displays an icon button to copy the code snippet to the clipboard.
     */
  isCopyable: _propTypes.default.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.default.oneOfType([_propTypes.default.bool.isRequired, _propTypes.default.shape({
    start: _propTypes.default.number,
    highlight: _propTypes.default.string,
    annotations: _propTypes.default.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.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.number.isRequired, _propTypes.default.string.isRequired]), _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.number.isRequired, _propTypes.default.string.isRequired]).isRequired, _propTypes.default.oneOfType([_propTypes.default.number.isRequired, _propTypes.default.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.default.oneOfType([_propTypes.default.bool, _propTypes.default.oneOfType([_propTypes.default.oneOf([true]).isRequired, _propTypes.default.oneOf([false])])])
};