/*
 * 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 = (this && this.__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());
    });
};
import * as React from 'react';
import { v4 as uuid } from 'uuid';
import { dirname, join, relative } from 'path';
import * as ReactMarkdown from 'react-markdown';
import { Link, StructuredListWrapper, StructuredListHead, StructuredListRow, StructuredListCell, StructuredListBody, OrderedList, UnorderedList, ListItem } from 'carbon-components-react';
import CodeSnippet from '../spi/CodeSnippet';
import 'carbon-components/scss/components/link/_link.scss';
import '../../../web/scss/components/List/Carbon.scss';
import '../../../web/scss/components/StructuredList/Carbon.scss';
export default class Markdown extends React.PureComponent {
    constructor() {
        super(...arguments);
        this._uuid = uuid();
    }
    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 = join(dirname(this.props.fullpath), props.href);
                                const relativeToCWD = relative(process.cwd() || process.env.PWD, absoluteHref);
                                file = relativeToCWD;
                            }
                            return this.props.repl.pexec(`open ${this.props.repl.encodeComponent(file)}`);
                        });
                    return React.createElement(Link, Object.assign({}, props, { href: href, target: target, onClick: onClick }));
                },
                code: props => React.createElement(CodeSnippet, { 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 = join(dirname(this.props.fullpath), props.src);
                        const relativeToCWD = 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 ? OrderedList : UnorderedList, { nested: props.depth > 0, className: props.className }, props.children);
                },
                listItem: props => React.createElement(ListItem, { className: props.className }, props.children),
                table: props => (React.createElement(StructuredListWrapper, { className: props.className + ' kui--table-like' }, props.children)),
                tableHead: props => React.createElement(StructuredListHead, { className: props.className }, props.children),
                tableBody: props => React.createElement(StructuredListBody, { className: props.className }, props.children),
                tableRow: props => (React.createElement(StructuredListRow, { head: props.isHeader, className: props.className }, props.children)),
                tableCell: props => (React.createElement(StructuredListCell, { head: props.isHeader, className: props.className }, props.children))
            } }));
    }
}
//# sourceMappingURL=Markdown.js.map