/* eslint no-console:0 */
'use strict';

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

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _reactRedux = require('react-redux');

var _index = require('../utils/index');

var _article = require('../actions/article');

var _articles = require('../actions/articles');

var _header = require('../actions/header');

var _index2 = require('../constants/index');

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _index3 = require('../components/article/index');

var ArticleComponents = _interopRequireWildcard(_index3);

var _Footer = require('../components/Footer');

var _Footer2 = _interopRequireDefault(_Footer);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _Common = {
  "inner-block": "Common__inner-block___2cOrF",
  "disable-inner-block": "Common__disable-inner-block___1MLd0",
  "components": "Common__components___2fQuj",
  "component": "Common__component___3bwMg",
  "hide": "Common__hide___2HyoH",
  "desc-text-color": "Common__desc-text-color___2fV3l",
  "desc-text-block": "Common__desc-text-block___1Z4b-",
  "text-link": "Common__text-link___1jaLy",
  "image": "Common__image___AKB6W",
  "imagediff": "Common__imagediff___2j7tX",
  "slideshow": "Common__slideshow___1Fz23",
  "embeddedcode": "Common__embeddedcode___3Avmp",
  "youtube": "Common__youtube___2oq1n",
  "topic-box": "Common__topic-box___2Q-kN"
};

var _Common2 = _interopRequireDefault(_Common);

var _reactDocumentMeta = require('react-document-meta');

var _reactDocumentMeta2 = _interopRequireDefault(_reactDocumentMeta);

var _async = require('async');

var _async2 = _interopRequireDefault(_async);

var _fb = "data:image/svg+x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iwwIEwyMi42NzU0Nzc0LDAgQzIzLjQwNjk3NzQsMCAyNCwwLjU5MjkyNDg1MiAyNCwxLjMyNDYwNTQ4IEwyNCwyMi42NzUzMDE0IEMyNCwyMy40MDY4ODg5IDIzLjQwNjg4NDMsMjQgMjIuNjc1NDc3NCwyNCBMMTYuNTU5NjUyNiwyNCBMMTYuNTU5NjUyNiwxNC43MDU4NzczIEwxOS42NzkyNjA2LDE0LjcwNTg3NzMgTDIwLjE0NjM3NzYsMTEuMDgzNzkyOCBMMTYuNTU5NjUyNiwxMS4wODM3OTI4IEwxNi41NTk2NTI2LDguNzcxMzIwNyBDMTYuNTU5NjUyNiw3LjcyMjY0MzY1IDE2Ljg1MDg1NTgsNy4wMDgwMDQ4NCAxOC4zNTQ2NDQ4LDcuMDA4MDA0ODQgTDIwLjI3MjY1NTcsNy4wMDcxNjY3MiBMMjAuMjcyNjU1NywzLjc2NzU0NTI3IEMxOS45NDA5NDMsMy43MjM0MDQxNyAxOC44MDIzOTE4LDMuNjI0Nzg1MTMgMTcuNDc3Nzc2LDMuNjI0Nzg1MTMgQzE0LjcxMjQxNzEsMy42MjQ3ODUxMyAxMi44MTkxNzc2LDUuMzEyNzYzMTMgMTIuODE5MTc3Niw4LjQxMjYwNDQzIEwxMi44MTkxNzc2LDExLjA4Mzc5MjggTDkuNjkxNTYwOSwxMS4wODM3OTI4IEw5LjY5MTU2MDksMTQuNzA1ODc3MyBMMTIuODE5MTc3NiwxNC43MDU4NzczIEwxMi44MTkxNzc2LDI0IEwxLjMyNDYxNTc2LDI0IFoiIGlkPSJpY29uLXNoYXJlLWZhY2Vib29rIj48L3BhdGg+CiAgICAgICAgICAgIDwvZz4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==";

var _fb2 = _interopRequireDefault(_fb);

var _line = "data:image/svg+xml;base64, ";

var _line2 = _interopRequireDefault(_line);

var _Article = {
  "article-container": "Article__article-container___1BnQY",
  "article-inner": "Article__article-inner___2LTX4",
  "title-row": "Article__title-row___1sAcL",
  "topic-name": "Article__topic-name___2m1Gc",
  "subtitle": "Article__subtitle___jkHqI",
  "article-meta": "Article__article-meta___2EX42",
  "leading-img": "Article__leading-img___c3aY8",
  "introduction": "Article__introduction___290ul",
  "placeholder": "Article__placeholder___1Xw8E",
  "base-ph": "Article__base-ph___2JULJ",
  "ph-title-1": "Article__ph-title-1___wH9m0",
  "ph-title-2": "Article__ph-title-2___1WgG9",
  "ph-author": "Article__ph-author___3YqG-",
  "ph-image": "Article__ph-image___2BMa1",
  "ph-content": "Article__ph-content___1e1s-",
  "ph-content-last": "Article__ph-content-last___GBrS6",
  "photo-container": "Article__photo-container___3y3-3",
  "photo-page-inner": "Article__photo-page-inner___3OEs9"
};

var _Article2 = _interopRequireDefault(_Article);

var _LeadingImage = {
  "extended-leading-img": "LeadingImage__extended-leading-img___3_6cg",
  "leading-img": "LeadingImage__leading-img___1B9Y1",
  "small-leading-img": "LeadingImage__small-leading-img___30M4A"
};

var _LeadingImage2 = _interopRequireDefault(_LeadingImage);

var _iconTopicArrowRight = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjEwcHgiIGhlaWdodD0iMTZweCIgdmlld0JveD0iMCAwIDEwIDE2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCAzOS4xICgzMTcyMCkgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+aWNvbi10b3BpYy1hcnJvdy1yaWdodDwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJNb2JpbGUiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJBcnRpY2xlLeKAky1QaG90b2dyYXBoeS3igJMtTW9iaWxlIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtOTMuMDAwMDAwLCAtMTAxLjAwMDAwMCkiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSIjQzcxQjBBIj4KICAgICAgICAgICAgPGcgaWQ9IlRvcGljIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyNC4wMDAwMDAsIDk2LjAwMDAwMCkiPgogICAgICAgICAgICAgICAgPHBvbHlsaW5lIGlkPSJpY29uLXRvcGljLWFycm93LXJpZ2h0IiBwb2ludHM9IjcwIDYgNzcgMTMuMDA2NTk2OCA3MC4wMTMxODExIDIwIj48L3BvbHlsaW5lPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=";

var _iconTopicArrowRight2 = _interopRequireDefault(_iconTopicArrowRight);

var _twitter = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjI4cHgiIGhlaWdodD0iMjRweCIgdmlld0JveD0iMCAwIDI4IDI0IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IHNrZXRjaHRvb2wgMzkuMSAoMzE3MjApIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPHRpdGxlPkR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AgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=";

var _twitter2 = _interopRequireDefault(_twitter);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

var articlePostition = {
  beginY: 120,
  endY: 200,
  percent: 0
};

var ArticlePlaceholder = function ArticlePlaceholder() {
  return _react2.default.createElement(
    'div',
    { className: (0, _classnames2.default)(_Article2.default['placeholder']) },
    _react2.default.createElement(
      'div',
      { className: (0, _classnames2.default)(_Article2.default['title-row'], _Common2.default['inner-block']) },
      _react2.default.createElement('div', { className: _Article2.default['ph-title-1'] }),
      _react2.default.createElement('div', { className: _Article2.default['ph-title-2'] }),
      _react2.default.createElement('div', { className: _Article2.default['ph-author'] })
    ),
    _react2.default.createElement(
      'div',
      { className: (0, _classnames2.default)(_Article2.default['leading-img'], _LeadingImage2.default['leading-img']) },
      _react2.default.createElement('div', { className: _Article2.default['ph-image'] })
    ),
    _react2.default.createElement(
      'div',
      { className: (0, _classnames2.default)(_Article2.default.introduction, _Common2.default['inner-block']) },
      _react2.default.createElement('div', { className: _Article2.default['ph-content'] }),
      _react2.default.createElement('div', { className: _Article2.default['ph-content'] }),
      _react2.default.createElement('div', { className: _Article2.default['ph-content-last'] })
    )
  );
};

var Article = function (_Component) {
  _inherits(Article, _Component);

  _createClass(Article, null, [{
    key: 'fetchData',


    // for server side rendering,
    // we get not only the article itself but also get related articles and
    // other articles in the same topic for BETTER SEO
    value: function fetchData(_ref) {
      var params = _ref.params;
      var store = _ref.store;

      // get article itself first
      return store.dispatch((0, _article.fetchArticleIfNeeded)(params.slug)).then(function () {
        var state = store.getState();
        var articleId = _lodash2.default.get(state, 'selectedArticle.id');
        var article = _lodash2.default.get(state, ['entities', 'articles', articleId]);
        var topicId = _lodash2.default.get(article, 'topics');
        var relateds = _lodash2.default.get(article, 'relateds', []);

        // fetch related articles and other articles in the same topic
        return new Promise(function (resolve, reject) {
          // eslint-disable-line
          // load in parallel
          _async2.default.parallel([function (callback) {
            if (_lodash2.default.get(relateds, 'length', 0) > 0) {
              // fetch related articles
              store.dispatch((0, _articles.fetchRelatedArticlesIfNeeded)(articleId, relateds)).then(function () {
                callback(null);
              });
            } else {
              // fallback - fetch feature articles
              store.dispatch((0, _articles.fetchFeatureArticles)()).then(function () {
                callback(null);
              });
            }
          }, function (callback) {
            store.dispatch((0, _articles.fetchArticlesByUuidIfNeeded)(topicId, _index2.TOPIC)).then(function () {
              callback(null);
            });
          }], function (err, results) {
            // eslint-disable-line
            if (err) {
              console.warn('fetchData occurs error:', err);
            }
            resolve();
          });
        });
      });
    }
  }]);

  function Article(props) {
    _classCallCheck(this, Article);

    var _this = _possibleConstructorReturn(this, (Article.__proto__ || Object.getPrototypeOf(Article)).call(this, props));

    _this._isFeatureArticlesFetched = false;

    _this._setArticleBounding = _this._setArticleBounding.bind(_this);
    _this._handleScroll = _this._handleScroll.bind(_this);
    return _this;
  }

  _createClass(Article, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this._setArticleBounding();
      this._sendPageLevelAction();
      window.addEventListener('resize', this._setArticleBounding);

      // detect sroll position
      window.addEventListener('scroll', this._handleScroll);
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      this._setArticleBounding();
      this._sendPageLevelAction();
    }
  }, {
    key: 'componentWillMount',
    value: function componentWillMount() {
      var _props = this.props;
      var params = _props.params;
      var selectedArticle = _props.selectedArticle;

      var slug = _lodash2.default.get(params, 'slug');

      // Check if selectedArticle is up to date
      if (_lodash2.default.get(selectedArticle, 'slug') !== slug) {
        // fetch data we need to render the whole article page
        this._fetchData();
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this._isFeatureArticlesFetched = false;
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var params = nextProps.params;
      var selectedArticle = nextProps.selectedArticle;

      var slug = _lodash2.default.get(params, 'slug');

      // Check if selectedArticle is up to date
      if (selectedArticle.slug !== slug) {
        // fetch data we need to render the whole article page
        this._fetchData();
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      window.removeEventListener('resize', this._setArticleBounding);
      window.removeEventListener('scroll', this._handleScroll);
    }
  }, {
    key: '_sendPageLevelAction',
    value: function _sendPageLevelAction() {
      var _props2 = this.props;
      var entities = _props2.entities;
      var selectedArticle = _props2.selectedArticle;
      var setArticleTopicList = _props2.setArticleTopicList;
      var setPageTitle = _props2.setPageTitle;
      var setPageType = _props2.setPageType;


      var article = _lodash2.default.get(entities, ['articles', selectedArticle.id], {});
      var topicName = _lodash2.default.get(entities, ['topics', _lodash2.default.get(article, 'topics'), 'name']);

      if (_lodash2.default.get(article, 'style') === _index2.PHOTOGRAPHY_ARTICLE_STYLE) {
        setPageType(_index2.PHOTOGRAPHY_ARTICLE);
      } else {
        setPageType(_index2.ARTICLE);
      }

      // set navbar title for this article
      setPageTitle(article.id, article.title, topicName);

      var topicArr = this._getTopicArticles(_lodash2.default.get(article, 'topics'));
      // dispatch action for the navbar to display article list
      setArticleTopicList(topicArr);
    }

    // fetch article whole data, including body, related articls and other articles in the same topic

  }, {
    key: '_fetchData',
    value: function _fetchData() {
      var _props3 = this.props;
      var entities = _props3.entities;
      var fetchArticleIfNeeded = _props3.fetchArticleIfNeeded;
      var fetchArticlesByUuidIfNeeded = _props3.fetchArticlesByUuidIfNeeded;
      var fetchFeatureArticles = _props3.fetchFeatureArticles;
      var fetchRelatedArticlesIfNeeded = _props3.fetchRelatedArticlesIfNeeded;
      var params = _props3.params;
      var slugToId = _props3.slugToId;

      var slug = _lodash2.default.get(params, 'slug');

      // fetch article
      fetchArticleIfNeeded(slug);

      var article = _lodash2.default.get(entities, ['articles', slugToId[slug]]);
      var topicId = _lodash2.default.get(article, 'topics');
      var relateds = _lodash2.default.get(article, 'relateds', []);

      //  fetch other articles in the same topic
      fetchArticlesByUuidIfNeeded(topicId, _index2.TOPIC);

      // fetch related articles
      fetchRelatedArticlesIfNeeded(_lodash2.default.get(article, 'id'), relateds);

      if (!this._isFeatureArticlesFetched) {
        // fallback - fetch feature articles
        fetchFeatureArticles();
        this._isFeatureArticlesFetched = true;
      }
    }
  }, {
    key: '_getCumulativeOffset',
    value: function _getCumulativeOffset(element) {
      var top = 0;
      do {
        top += element.offsetTop || 0;
        element = element.offsetParent;
      } while (element);

      return top;
    }
  }, {
    key: '_setArticleBounding',
    value: function _setArticleBounding() {
      var beginEl = _reactDom2.default.findDOMNode(this.refs.progressBegin);
      var endEl = _reactDom2.default.findDOMNode(this.refs.progressEnding);
      articlePostition.beginY = _lodash2.default.get(beginEl, 'offsetTop', articlePostition.beginY);
      articlePostition.endY = _lodash2.default.get(endEl, 'offsetTop', articlePostition.endY);
    }
  }, {
    key: '_handleScroll',
    value: function _handleScroll() {
      var beginY = articlePostition.beginY;
      var endY = articlePostition.endY;
      var percent = articlePostition.percent;

      var scrollRatio = Math.abs((window.scrollY - beginY) / (endY - beginY));
      if (window.scrollY < beginY) {
        scrollRatio = 0;
      } else if (scrollRatio > 1) {
        scrollRatio = 1;
      }
      var curPercent = Math.round(scrollRatio * 100);
      if (percent !== curPercent) {
        articlePostition.percent = curPercent;
        // update the header progress bar
        this.props.setReadProgress(curPercent);
      }
    }
  }, {
    key: '_composeAuthors',
    value: function _composeAuthors(article) {
      article = article || {};
      var authors = [];
      var list = ['writters', 'photographers', 'designers', 'engineers'];
      list.forEach(function (item) {
        if (Array.isArray(article[item])) {
          article[item].forEach(function (author) {
            // remove 's'. writters -> writter
            var type = item.slice(0, -1);
            authors.push(_lodash2.default.merge({}, author, { type: type }));
          });
        }
      });
      return authors;
    }
  }, {
    key: '_getTopicArticles',
    value: function _getTopicArticles(topicId) {
      var _props4 = this.props;
      var articlesByUuids = _props4.articlesByUuids;
      var entities = _props4.entities;

      var articleIds = _lodash2.default.get(articlesByUuids, [topicId, 'items'], []);
      return _lodash2.default.map(articleIds, function (id) {
        return _lodash2.default.merge({}, _lodash2.default.get(entities, ['articles', id]));
      });
    }
  }, {
    key: '_getFeatureArticles',
    value: function _getFeatureArticles() {
      var _props5 = this.props;
      var entities = _props5.entities;
      var featureArticles = _props5.featureArticles;

      var rtn = [];

      if (featureArticles.isFetching) {
        return rtn;
      } else if (featureArticles.error !== null) {
        this._isFeatureArticlesFetched = false;
        return rtn;
      }

      var articles = _lodash2.default.get(entities, 'articles', {});
      var articleIds = _lodash2.default.get(featureArticles, 'items', []);
      _lodash2.default.forEach(articleIds, function (id) {
        if (_lodash2.default.has(articles, id)) {
          rtn.push(_lodash2.default.merge({}, articles[id]));
        }
      });
      return rtn;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props6 = this.props;
      var entities = _props6.entities;
      var params = _props6.params;
      var selectedArticle = _props6.selectedArticle;

      var isFetching = _lodash2.default.get(selectedArticle, 'isFetching');

      if (_lodash2.default.get(selectedArticle, 'slug') !== _lodash2.default.get(params, 'slug')) {
        return null;
      }

      var article = (0, _index.denormalizeArticles)(_lodash2.default.get(selectedArticle, 'id'), entities)[0] || {};
      var topicArr = this._getTopicArticles(_lodash2.default.get(article, 'topics.id'));
      var topicName = _lodash2.default.get(article, 'topics.name');
      var relatedArticles = _lodash2.default.get(article, 'relateds');

      // fallback - use feature article
      if (_lodash2.default.get(relatedArticles, 'length', 0) === 0) {
        relatedArticles = this._getFeatureArticles();
      }

      var authors = this._composeAuthors(article);
      var bodyData = _lodash2.default.get(article, ['content', 'apiData'], []);
      var heroImage = _lodash2.default.get(article, ['heroImage'], null);
      var heroImageSize = _lodash2.default.get(article, ['heroImageSize'], 'normal');
      var introData = _lodash2.default.get(article, ['brief', 'apiData'], []);
      var copyright = _lodash2.default.get(article, ['copyright'], []);
      var cUrl = (0, _index.getAbsPath)(this.context.location.pathname, this.context.location.search);
      var outerClass = article.style === _index2.PHOTOGRAPHY_ARTICLE_STYLE ? (0, _classnames2.default)(_Article2.default['article-container'], _Article2.default['photo-container']) : _Article2.default['article-container'];
      var contentClass = article.style === _index2.PHOTOGRAPHY_ARTICLE_STYLE ? (0, _classnames2.default)(_Article2.default['article-inner'], _Article2.default['photo-page-inner']) : _Article2.default['article-inner'];

      var topicBlock = topicName ? _react2.default.createElement(
        'span',
        { className: _Article2.default['topic-name'] },
        topicName,
        ' ',
        _react2.default.createElement('img', { src: _iconTopicArrowRight2.default })
      ) : null;

      var subtitle = _lodash2.default.get(article, 'subtitle', '');
      var subtitleBlock = subtitle ? _react2.default.createElement(
        'span',
        { className: _Article2.default['subtitle'] },
        subtitle
      ) : null;

      var meta = {
        title: _lodash2.default.get(article, ['title'], _index2.SITE_NAME.FULL),
        description: _lodash2.default.get(article, ['ogDescription'], _index2.SITE_META.DESC),
        canonical: _index2.SITE_META.URL + 'a/' + _lodash2.default.get(article, ['slug'], ''),
        meta: { property: {} },
        auto: { ograph: true }
      };

      if (_lodash2.default.get(heroImage, ['image', 'url'])) {
        _lodash2.default.set(meta, ['meta', 'property', 'og:image'], _lodash2.default.get(heroImage, ['image', 'url']));
      }

      return _react2.default.createElement(
        _reactDocumentMeta2.default,
        meta,
        _react2.default.createElement(
          'div',
          null,
          isFetching ? _react2.default.createElement(
            'div',
            { className: outerClass },
            _react2.default.createElement(ArticlePlaceholder, null)
          ) : _react2.default.createElement(
            'div',
            { className: outerClass },
            _react2.default.createElement(
              'div',
              { className: contentClass },
              _react2.default.createElement(
                'div',
                { className: (0, _classnames2.default)(_Article2.default['title-row'], _Common2.default['inner-block']) },
                _react2.default.createElement(
                  'hgroup',
                  null,
                  _react2.default.createElement(
                    'h3',
                    null,
                    topicBlock,
                    subtitleBlock
                  ),
                  _react2.default.createElement(
                    'h1',
                    null,
                    article.title
                  )
                )
              ),
              _react2.default.createElement(
                'div',
                { ref: 'progressBegin', className: (0, _classnames2.default)(_Article2.default['article-meta'], _Common2.default['inner-block']) },
                _react2.default.createElement(
                  ArticleComponents.HeadingAuthor,
                  {
                    authors: authors,
                    extendByline: _lodash2.default.get(article, 'extendByline')
                  },
                  _react2.default.createElement(ArticleComponents.PublishDate, {
                    date: article.publishedDate
                  })
                ),
                _react2.default.createElement(ArticleComponents.ShareBt, {
                  appId: _index2.appId,
                  url: cUrl,
                  title: article.title,
                  fbIcon: _fb2.default,
                  twitterIcon: _twitter2.default,
                  lineIcon: _line2.default
                })
              ),
              _react2.default.createElement(
                'div',
                { className: _Article2.default['leading-img'] },
                _react2.default.createElement(ArticleComponents.LeadingImage, {
                  size: heroImageSize,
                  image: _lodash2.default.get(heroImage, ['image', 'resizedTargets']),
                  id: _lodash2.default.get(heroImage, 'id'),
                  description: _lodash2.default.get(heroImage, 'description')
                })
              ),
              _react2.default.createElement(
                'div',
                { className: (0, _classnames2.default)(_Article2.default.introduction, _Common2.default['inner-block']) },
                _react2.default.createElement(ArticleComponents.Introduction, {
                  data: introData
                })
              ),
              _react2.default.createElement(ArticleComponents.Body, {
                data: bodyData
              })
            ),
            _react2.default.createElement(
              'div',
              { ref: 'progressEnding',
                className: (0, _classnames2.default)('inner-max', 'center-block', _Common2.default['components']) },
              _react2.default.createElement(
                'div',
                { className: (0, _classnames2.default)('inner-max', _Common2.default['component']) },
                _react2.default.createElement(ArticleComponents.BottomTags, {
                  data: article.tags
                })
              ),
              _react2.default.createElement(ArticleComponents.BottomRelateds, {
                relateds: relatedArticles,
                currentId: article.id,
                topicName: topicName,
                topicArr: topicArr
              })
            )
          ),
          _react2.default.createElement(_Footer2.default, {
            theme: _lodash2.default.get(article, 'style') === _index2.PHOTOGRAPHY_ARTICLE_STYLE ? _index2.PHOTOGRAPHY : _index2.ARTICLE,
            copyright: copyright })
        )
      );
    }
  }]);

  return Article;
}(_react.Component);

function mapStateToProps(state) {
  return {
    articlesByUuids: state.articlesByUuids,
    entities: state.entities,
    featureArticles: state.featureArticles,
    selectedArticle: state.selectedArticle,
    slugToId: state.slugToId
  };
}

Article.contextTypes = {
  device: _react2.default.PropTypes.string,
  location: _react2.default.PropTypes.object
};

exports.Article = Article;
exports.default = (0, _reactRedux.connect)(mapStateToProps, { fetchArticleIfNeeded: _article.fetchArticleIfNeeded, fetchRelatedArticlesIfNeeded: _articles.fetchRelatedArticlesIfNeeded, fetchFeatureArticles: _articles.fetchFeatureArticles,
  fetchArticlesByUuidIfNeeded: _articles.fetchArticlesByUuidIfNeeded, setReadProgress: _header.setReadProgress, setPageType: _header.setPageType, setPageTitle: _header.setPageTitle, setArticleTopicList: _header.setArticleTopicList })(Article);