function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

import { rpx2vw4style as __rpx2vw__ } from "babel-runtime-jsx-style-transform";

function _extends() { _extends = Object.assign || 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 _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

import { __rest } from "tslib";
import React, { createElement, Component, createRef } from "react";
import { View } from "@alifd/meet-react-component-one";
import { previewImage } from '@uni/image';
import { isWeb } from '@uni/env';
import { isMiniappPlatform } from '../utils';
import { guid } from '../utils/hooks';
import HtmlParser from './html-parser';
import Node from './node';
import { getVideoContext } from './util';

var RichText = /*#__PURE__*/function (_Component) {
  _inherits(RichText, _Component);

  var _super = _createSuper(RichText);

  function RichText() {
    var _this;

    _classCallCheck(this, RichText);

    _this = _super.apply(this, arguments);
    _this.state = {
      nodes: []
    };
    _this.imgList = [];
    _this.videos = {};
    _this.plugins = [];
    _this.ref = /*#__PURE__*/createRef();

    _this.wrapTable = function () {
      var rootNode = _this.ref.current;

      if (rootNode) {
        var tables = rootNode.getElementsByTagName('table');

        _toConsumableArray(tables).forEach(function (tableNode) {
          var tmp = document.createElement('div');
          tmp.style.overflowX = 'auto';
          tmp.style.padding = '1px';
          tmp.appendChild(tableNode.cloneNode(true));
          tableNode.parentNode.insertBefore(tmp, tableNode);
          tableNode.remove();
        });
      }
    };

    _this.replaceErrorImg = function () {
      var rootNode = _this.ref.current;

      if (rootNode) {
        _toConsumableArray(rootNode.getElementsByTagName('img')).forEach(function (img) {
          if (img && img.addEventListener) {
            img.addEventListener('error', function () {
              img.src = _this.props.errorImage;
            });
          }
        });
      }
    };

    _this.parseHtmlText = function (text) {
      var nodes = new HtmlParser(_assertThisInitialized(_this)).parse(text);

      _this.setState({
        nodes: nodes
      });
    };

    _this.handleImageClick = function (i) {
      if (_this.props.enableImagePreview) {
        previewImage({
          urls: _this.imgList,
          current: i || 0
        }).then(function () {});
      }
    };

    _this.handleImageError = function (src, i) {
      var errorImage = _this.props.errorImage;
      _this.imgList[i] = errorImage;
    };

    _this.handleVideoLoad = function (id) {
      _this.videos[id] = getVideoContext(id);
    };

    _this.handleVideoPlay = function (id) {
      if (_this.props.pauseVideo) {
        Object.entries(_this.videos).forEach(function (_ref) {
          var _ref2 = _slicedToArray(_ref, 2),
              videoId = _ref2[0],
              ctx = _ref2[1];

          if (videoId !== id && ctx && ctx.pause) {
            ctx.pause();
          }
        });
      }
    };

    return _this;
  }

  _createClass(RichText, [{
    key: "componentWillMount",
    value: function componentWillMount() {
      if (isMiniappPlatform) {
        var text = this.props.text;
        this.parseHtmlText(text);
      }
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      if (isMiniappPlatform) {
        var text = nextProps.text;
        this.parseHtmlText(text);
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      if (isWeb) {
        this.afterWebRender();
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (isWeb && this.props.text !== prevProps.text) {
        this.afterWebRender();
      }
    }
  }, {
    key: "afterWebRender",
    value: function afterWebRender() {
      var _this$props = this.props,
          enableTableScroll = _this$props.enableTableScroll,
          errorImage = _this$props.errorImage;

      if (enableTableScroll) {
        this.wrapTable();
      }

      if (errorImage) {
        this.replaceErrorImg();
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _a = this.props,
          style = _a.style,
          lazyLoad = _a.lazyLoad,
          text = _a.text,
          otherProps = __rest(_a, ["style", "lazyLoad", "text"]);

      return /*#__PURE__*/React.createElement(View, {
        id: "mtRichTextRoot-".concat(guid()),
        ref: this.ref,
        className: "".concat(this.props.prefix, "rich-text"),
        style: __rpx2vw__(style)
      }, isMiniappPlatform ? /*#__PURE__*/React.createElement(Node, _extends({
        lazyLoad: lazyLoad,
        nodes: this.state.nodes,
        onImageClick: this.handleImageClick,
        onImgError: this.handleImageError,
        onVideoLoad: this.handleVideoLoad,
        onVideoPlay: this.handleVideoPlay
      }, otherProps)) : /*#__PURE__*/React.createElement("div", {
        dangerouslySetInnerHTML: {
          __html: text || ''
        }
      }));
    }
  }]);

  return RichText;
}(Component);

RichText.defaultProps = {
  prefix: 'mt-',
  text: '',
  errorImage: 'https://gw.alicdn.com/imgextra/i4/O1CN014BzOrR1EjHycne0VV_!!6000000000387-2-tps-200-200.png',
  lazyLoad: false,
  enableImagePreview: true,
  useAnchor: false,
  pauseVideo: true,
  enableTableScroll: false,
  tagStyle: {
    table: 'box-sizing: border-box; ',
    li: 'margin: 5px 0;',
    img: 'width: auto'
  }
};
export default RichText;