"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = Ansi;

var _react = _interopRequireDefault(require("react"));

var _anser = require("anser");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/*
 * Copyright 2020 The Kubernetes Authors
 *
 * Licensed 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.
 */
const Markdown = _react.default.lazy(() => Promise.resolve().then(() => require('../Markdown')));
/** Special overrides for CSS classes; otherwise, we will use the raw values from `anser`, e.g. "italic" and "underline" and "strikethrough" */


const decos = {
  dim: 'semi-transparent'
};

function tagOf(entry) {
  return entry.decorations.find(_ => _ === 'bold') ? 'strong' : 'span';
}

function classOf(entry) {
  const fg = entry.fg ? entry.fg.replace(/^ansi-(.*)/, 'ansi-$1-fg') : '';
  const bg = entry.bg ? entry.bg.replace(/^ansi-(.*)/, 'ansi-$1-bg') : '';
  const deco = entry.decorations.map(_ => decos[_] || _);
  return `${fg} ${bg} ${deco.join(' ')}`;
}

function content(source) {
  if (/kuiexec/.test(source)) {
    // special case for embedded links; Markdown trims prefix and suffix whitespace
    const match = source.match(/^(\s?)(\s*)/); // one \n is ok, because <pre> inserts a linebreak for us

    return _react.default.createElement(_react.default.Fragment, null, match && match[1] && _react.default.createElement("pre", null, match[1]), _react.default.createElement(Markdown, {
      className: "pre-wrap",
      source: source
    }));
  } else {
    return source;
  }
}

function Ansi(props) {
  // eslint-disable-next-line @typescript-eslint/camelcase
  const model = (0, _anser.ansiToJson)(props.children, {
    use_classes: true
  });

  if (props.onRender) {
    props.onRender();
  }

  const style = {
    margin: 0
  };

  if (!props.noWrap) {
    style.wordBreak = 'break-all';
  } else {
    style.whiteSpace = 'nowrap';
  }

  return _react.default.createElement("pre", {
    className: props.className,
    style: style
  }, model.map((_, idx) => _.content && _react.default.createElement(tagOf(_), {
    key: idx,
    className: classOf(_)
  }, content(_.content))));
}