"use strict";

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

var React = _interopRequireWildcard(require("react"));

var _uuid = require("uuid");

var _path = require("path");

var ReactMarkdown = _interopRequireWildcard(require("react-markdown"));

var _carbonComponentsReact = require("carbon-components-react");

var _CodeSnippet = _interopRequireDefault(require("../spi/CodeSnippet"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }

/*
 * Copyright 2020 IBM Corporation
 *
 * 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.
 */
var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }

  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }

    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }

    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }

    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};

class Markdown extends React.PureComponent {
  constructor() {
    super(...arguments);
    this._uuid = (0, _uuid.v4)();
  }

  onCopy(value) {
    navigator.clipboard.writeText(value);
  }

  anchorFrom(txt) {
    return `${this._uuid}-${txt}`;
  }

  render() {
    return React.createElement(ReactMarkdown, {
      source: this.props.source,
      className: this.props.className || 'padding-content scrollable scrollable-x scrollable-auto marked-content page-content',
      renderers: {
        link: props => {
          const isLocal = !/^http/i.test(props.href);
          const target = !isLocal ? '_blank' : undefined;
          const href = isLocal ? '#' : props.href;
          const onClick = !isLocal ? undefined : () => __awaiter(this, void 0, void 0, function* () {
            let file = props.href;

            if (props.href.startsWith('#kuiexec?command=')) {
              const cmdline = decodeURIComponent(props.href.slice('#kuiexec?command='.length));

              if (cmdline) {
                return this.props.repl.pexec(cmdline);
              }
            } else if (props.href.charAt(0) === '#') {
              const elt = this.props.tab.querySelector(`[data-markdown-anchor="${this.anchorFrom(props.href.slice(1))}"]`);

              if (elt) {
                return elt.scrollIntoView();
              }
            } else if (this.props.fullpath) {
              const absoluteHref = (0, _path.join)((0, _path.dirname)(this.props.fullpath), props.href);
              const relativeToCWD = (0, _path.relative)(process.cwd() || process.env.PWD, absoluteHref);
              file = relativeToCWD;
            }

            return this.props.repl.pexec(`open ${this.props.repl.encodeComponent(file)}`);
          });
          return React.createElement(_carbonComponentsReact.Link, Object.assign({}, props, {
            href: href,
            target: target,
            onClick: onClick
          }));
        },
        code: props => React.createElement(_CodeSnippet.default, {
          value: props.value,
          onCopy: this.onCopy.bind(this, props.value)
        }),
        heading: props => {
          const valueChild = props.children && props.children.length === 1 ? props.children[0] : props.children.find(_ => _.props.value);
          const anchor = !valueChild || !valueChild.props || !valueChild.props.value ? undefined : this.anchorFrom(valueChild.props.value.toLowerCase().replace(/ /g, '-'));
          return React.createElement(`h${props.level}`, Object.assign({}, props, {
            'data-markdown-anchor': anchor,
            'data-is-href': valueChild && valueChild.props && valueChild.props.href
          }), props.children);
        },
        image: props => {
          const isLocal = !/^http/i.test(props.src);

          if (isLocal && this.props.fullpath) {
            const absoluteSrc = (0, _path.join)((0, _path.dirname)(this.props.fullpath), props.src);
            const relativeToCWD = (0, _path.relative)(process.cwd() || process.env.PWD, absoluteSrc);
            return React.createElement("img", {
              src: relativeToCWD
            });
          } else {
            return React.createElement("img", Object.assign({}, props));
          }
        },
        list: props => {
          return React.createElement(props.ordered ? _carbonComponentsReact.OrderedList : _carbonComponentsReact.UnorderedList, {
            nested: props.depth > 0,
            className: props.className
          }, props.children);
        },
        listItem: props => React.createElement(_carbonComponentsReact.ListItem, {
          className: props.className
        }, props.children),
        table: props => React.createElement(_carbonComponentsReact.StructuredListWrapper, {
          className: props.className + ' kui--table-like'
        }, props.children),
        tableHead: props => React.createElement(_carbonComponentsReact.StructuredListHead, {
          className: props.className
        }, props.children),
        tableBody: props => React.createElement(_carbonComponentsReact.StructuredListBody, {
          className: props.className
        }, props.children),
        tableRow: props => React.createElement(_carbonComponentsReact.StructuredListRow, {
          head: props.isHeader,
          className: props.className
        }, props.children),
        tableCell: props => React.createElement(_carbonComponentsReact.StructuredListCell, {
          head: props.isHeader,
          className: props.className
        }, props.children)
      }
    });
  }

}

exports.default = Markdown;