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 _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 _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], -1 === t.indexOf(o) && {}.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 (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } } return t; }
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; }
import PropTypes from "prop-types";
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); }
/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */

/*
 * 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, { useEffect, useMemo, useState } from 'react';
import classNames from 'classnames';
import { highlight } from 'refractor';
import { keys, useCombinedRefs } from '../../services';
import { EuiButtonIcon } from '../button';
import { keysOf } from '../common';
import { EuiCopy } from '../copy';
import { EuiFocusTrap } from '../focus_trap';
import { EuiI18n } from '../i18n';
import { useInnerText } from '../inner_text';
import { useMutationObserver } from '../observer/mutation_observer';
import { useResizeObserver } from '../observer/resize_observer';
import { EuiOverlayMask } from '../overlay_mask';
var isAstElement = function isAstElement(node) {
  return node.hasOwnProperty('type') && node.type === 'element';
};
var nodeToHtml = function nodeToHtml(node, idx, nodes) {
  var depth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  if (isAstElement(node)) {
    var properties = node.properties,
      tagName = node.tagName,
      children = node.children;
    return /*#__PURE__*/React.createElement(tagName, _objectSpread(_objectSpread({}, properties), {}, {
      key: "node-".concat(depth, "-").concat(idx),
      className: classNames(properties.className)
    }), children && children.map(function (el, i) {
      return nodeToHtml(el, i, nodes, depth + 1);
    }));
  }
  return node.value;
};
var addLineData = function addLineData(nodes) {
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    lineNumber: 1
  };
  return nodes.reduce(function (result, node) {
    var lineStart = data.lineNumber;
    if (node.type === 'text') {
      if (!node.value.match(/\r\n?|\n/)) {
        node.lineStart = lineStart;
        node.lineEnd = lineStart;
        result.push(node);
      } else {
        var lines = node.value.split(/\r\n?|\n/);
        lines.forEach(function (line, i) {
          var num = i === 0 ? data.lineNumber : ++data.lineNumber;
          result.push({
            type: 'text',
            value: i === lines.length - 1 ? line : "".concat(line, "\n"),
            lineStart: num,
            lineEnd: num
          });
        });
      }
      return result;
    }
    if (node.children && node.children.length) {
      var _first$lineStart, _last$lineEnd;
      var children = addLineData(node.children, data);
      var first = children[0];
      var last = children[children.length - 1];
      var start = (_first$lineStart = first.lineStart) !== null && _first$lineStart !== void 0 ? _first$lineStart : lineStart;
      var end = (_last$lineEnd = last.lineEnd) !== null && _last$lineEnd !== void 0 ? _last$lineEnd : lineStart;
      if (start !== end) {
        children.forEach(function (node) {
          result.push(node);
        });
      } else {
        node.lineStart = start;
        node.lineEnd = end;
        node.children = children;
        result.push(node);
      }
      return result;
    }
    result.push(node);
    return result;
  }, []);
};
function wrapLines(nodes) {
  var grouped = [];
  nodes.forEach(function (node) {
    var lineStart = node.lineStart - 1;
    if (grouped[lineStart]) {
      grouped[lineStart].push(node);
    } else {
      grouped[lineStart] = [node];
    }
  });
  var wrapped = [];
  grouped.forEach(function (node) {
    wrapped.push({
      type: 'element',
      tagName: 'span',
      properties: {
        className: ['euiCodeBlock__line']
      },
      children: node
    });
  });
  return wrapped;
}
var highlightByLine = function highlightByLine(children, language) {
  return wrapLines(addLineData(highlight(children, language)));
};
var fontSizeToClassNameMap = {
  s: 'euiCodeBlock--fontSmall',
  m: 'euiCodeBlock--fontMedium',
  l: 'euiCodeBlock--fontLarge'
};
export var FONT_SIZES = keysOf(fontSizeToClassNameMap);
var paddingSizeToClassNameMap = {
  none: '',
  s: 'euiCodeBlock--paddingSmall',
  m: 'euiCodeBlock--paddingMedium',
  l: 'euiCodeBlock--paddingLarge'
};
export var PADDING_SIZES = keysOf(paddingSizeToClassNameMap);
/**
 * This is the base component extended by EuiCode and EuiCodeBlock.
 * These components share the same propTypes definition with EuiCodeBlockImpl.
 */
export var EuiCodeBlockImpl = function EuiCodeBlockImpl(_ref) {
  var _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,
    language = _ref.language,
    inline = _ref.inline,
    children = _ref.children,
    className = _ref.className,
    overflowHeight = _ref.overflowHeight,
    rest = _objectWithoutProperties(_ref, ["transparentBackground", "paddingSize", "fontSize", "isCopyable", "whiteSpace", "language", "inline", "children", "className", "overflowHeight"]);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isFullScreen = _useState2[0],
    setIsFullScreen = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    wrapperRef = _useState4[0],
    setWrapperRef = _useState4[1];
  var _useInnerText = useInnerText(''),
    _useInnerText2 = _slicedToArray(_useInnerText, 2),
    innerTextRef = _useInnerText2[0],
    _innerText = _useInnerText2[1];
  var innerText = useMemo(function () {
    return _innerText === null || _innerText === void 0 ? void 0 : _innerText.replace(/[\r\n?]{2}|\n\n/g, '\n');
  }, [_innerText]);
  var _useState5 = useState(-1),
    _useState6 = _slicedToArray(_useState5, 2),
    tabIndex = _useState6[0],
    setTabIndex = _useState6[1];
  var combinedRef = useCombinedRefs([innerTextRef, setWrapperRef]);
  var _useResizeObserver = useResizeObserver(wrapperRef),
    width = _useResizeObserver.width,
    height = _useResizeObserver.height;
  var content = useMemo(function () {
    if (!language || typeof children !== 'string') {
      return children;
    }
    var nodes = inline ? highlight(children, language) : highlightByLine(children, language);
    return nodes.length === 0 ? children : nodes.map(nodeToHtml);
  }, [children, language, inline]);
  var doesOverflow = function doesOverflow() {
    if (!wrapperRef) return;
    var clientWidth = wrapperRef.clientWidth,
      clientHeight = wrapperRef.clientHeight,
      scrollWidth = wrapperRef.scrollWidth,
      scrollHeight = wrapperRef.scrollHeight;
    var doesOverflow = scrollHeight > clientHeight || scrollWidth > clientWidth;
    setTabIndex(doesOverflow ? 0 : -1);
  };
  useMutationObserver(wrapperRef, doesOverflow, {
    subtree: true,
    childList: true
  });
  useEffect(doesOverflow, [width, height, wrapperRef]);
  var onKeyDown = function onKeyDown(event) {
    if (event.key === keys.ESCAPE) {
      event.preventDefault();
      event.stopPropagation();
      closeFullScreen();
    }
  };
  var toggleFullScreen = function toggleFullScreen() {
    setIsFullScreen(!isFullScreen);
  };
  var closeFullScreen = function closeFullScreen() {
    setIsFullScreen(false);
  };
  var classes = classNames('euiCodeBlock', fontSizeToClassNameMap[fontSize], paddingSizeToClassNameMap[paddingSize], {
    'euiCodeBlock--transparentBackground': transparentBackground,
    'euiCodeBlock--inline': inline,
    'euiCodeBlock--hasControls': isCopyable || overflowHeight
  }, _defineProperty({
    prismjs: !(className === null || className === void 0 ? void 0 : className.includes('prismjs'))
  }, "language-".concat(language || 'none'), !(className === null || className === void 0 ? void 0 : className.includes('language'))), className);
  var codeClasses = classNames('euiCodeBlock__code', language);
  var preClasses = classNames('euiCodeBlock__pre', {
    'euiCodeBlock__pre--whiteSpacePre': whiteSpace === 'pre',
    'euiCodeBlock__pre--whiteSpacePreWrap': whiteSpace === 'pre-wrap'
  });
  var optionalStyles = {};
  if (overflowHeight) {
    optionalStyles.maxHeight = overflowHeight;
  }
  var codeSnippet = /*#__PURE__*/React.createElement("code", _extends({
    className: codeClasses
  }, rest), content);
  var wrapperProps = {
    className: classes,
    style: optionalStyles
  };
  if (inline) {
    return /*#__PURE__*/React.createElement("span", wrapperProps, codeSnippet);
  }
  var getCopyButton = function getCopyButton(textToCopy) {
    var copyButton;
    if (isCopyable && textToCopy) {
      copyButton = /*#__PURE__*/React.createElement("div", {
        className: "euiCodeBlock__copyButton"
      }, /*#__PURE__*/React.createElement(EuiI18n, {
        token: "euiCodeBlock.copyButton",
        default: "Copy"
      }, function (copyButton) {
        return /*#__PURE__*/React.createElement(EuiCopy, {
          textToCopy: textToCopy
        }, function (copy) {
          return /*#__PURE__*/React.createElement(EuiButtonIcon, {
            onClick: copy,
            iconType: "copy",
            color: "text",
            "aria-label": copyButton
          });
        });
      }));
    }
    return copyButton;
  };
  var fullScreenButton;
  if (!inline && overflowHeight) {
    fullScreenButton = /*#__PURE__*/React.createElement(EuiI18n, {
      tokens: ['euiCodeBlock.fullscreenCollapse', 'euiCodeBlock.fullscreenExpand'],
      defaults: ['Collapse', 'Expand']
    }, function (_ref2) {
      var _ref3 = _slicedToArray(_ref2, 2),
        fullscreenCollapse = _ref3[0],
        fullscreenExpand = _ref3[1];
      return /*#__PURE__*/React.createElement(EuiButtonIcon, {
        className: "euiCodeBlock__fullScreenButton",
        onClick: toggleFullScreen,
        iconType: isFullScreen ? 'cross' : 'fullScreen',
        color: "text",
        "aria-label": isFullScreen ? fullscreenCollapse : fullscreenExpand
      });
    });
  }
  var getCodeBlockControls = function getCodeBlockControls(textToCopy) {
    var codeBlockControls;
    var copyButton = getCopyButton(textToCopy);
    if (copyButton || fullScreenButton) {
      codeBlockControls = /*#__PURE__*/React.createElement("div", {
        className: "euiCodeBlock__controls"
      }, fullScreenButton, copyButton);
    }
    return codeBlockControls;
  };
  var getFullScreenDisplay = function getFullScreenDisplay(codeBlockControls) {
    var fullScreenDisplay;
    if (isFullScreen) {
      // Force fullscreen to use large font and padding.
      var fullScreenClasses = classNames('euiCodeBlock', fontSizeToClassNameMap[fontSize], 'euiCodeBlock-paddingLarge', 'euiCodeBlock-isFullScreen', className);

      /* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
      fullScreenDisplay = /*#__PURE__*/React.createElement(EuiOverlayMask, null, /*#__PURE__*/React.createElement(EuiFocusTrap, {
        clickOutsideDisables: true
      }, /*#__PURE__*/React.createElement("div", {
        className: fullScreenClasses
      }, /*#__PURE__*/React.createElement("pre", {
        className: preClasses,
        tabIndex: 0
      }, /*#__PURE__*/React.createElement("code", {
        className: codeClasses,
        onKeyDown: onKeyDown
      }, content)), codeBlockControls)));
      /* eslint-enable jsx-a11y/no-noninteractive-element-interactions */
    }
    return fullScreenDisplay;
  };
  var codeBlockControls = getCodeBlockControls(innerText);
  return /*#__PURE__*/React.createElement("div", wrapperProps, /*#__PURE__*/React.createElement("pre", {
    ref: combinedRef,
    style: optionalStyles,
    className: preClasses,
    tabIndex: tabIndex
  }, codeSnippet), codeBlockControls, getFullScreenDisplay(codeBlockControls));
};
EuiCodeBlockImpl.propTypes = {
  className: PropTypes.string,
  fontSize: PropTypes.oneOf(["s", "m", "l"]),
  /**
     * Displays the passed code in an inline format. Also removes any margins set.
     */
  inline: PropTypes.bool,
  /**
     * Displays an icon button to copy the code snippet to the clipboard.
     */
  isCopyable: PropTypes.bool,
  /**
     * Sets the syntax highlighting for a specific language
     * @see https://github.com/wooorm/refractor#syntaxes
     * for options
     */
  language: PropTypes.string,
  overflowHeight: PropTypes.number,
  paddingSize: PropTypes.oneOf(["none", "s", "m", "l"]),
  transparentBackground: PropTypes.bool,
  /**
     * 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.oneOf(["pre", "pre-wrap"])
};