'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.RenderText = exports.Editor = undefined; var _message2 = require('antd/es/message'); var _message3 = _interopRequireDefault(_message2); var _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; }; 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; }; }(); require('antd/es/message/style'); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios); var _jsCookie = require('js-cookie'); var _jsCookie2 = _interopRequireDefault(_jsCookie); var _reactIntlUniversal = require('react-intl-universal'); var _reactIntlUniversal2 = _interopRequireDefault(_reactIntlUniversal); var _constant = require('./constant'); var _Comment = require('./Comment'); var _helper = require('./helper'); var _CommentInput = require('./components/CommentInput'); var _CommentInput2 = _interopRequireDefault(_CommentInput); var _CommentList = require('./components/CommentList'); var _CommentList2 = _interopRequireDefault(_CommentList); var _Editor = require('./components/Editor'); var _Editor2 = _interopRequireDefault(_Editor); var _RenderText = require('./components/RenderText'); var _RenderText2 = _interopRequireDefault(_RenderText); var _EditComment = require('./components/EditComment/EditComment'); var _EditComment2 = _interopRequireDefault(_EditComment); var _lang = require('./lang'); require('./App.css'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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 App = function (_Component) { _inherits(App, _Component); function App(props) { _classCallCheck(this, App); var _this = _possibleConstructorReturn(this, (App.__proto__ || Object.getPrototypeOf(App)).call(this, props)); _this.state = { loading: {}, // oss 配置 oss: {}, // 评论数据 list: [], page: 1, total: 0, // 是否没有更多评论了 isNoMoreComment: false, initDone: false, locale: 'zh-CN', editModalVisible: false, action: '', replyId: '', commentId: '', userId: '', content: '', replyPage: 1, emojiList: [] }; _this.handleChangeLoading = _this.handleChangeLoading.bind(_this); _this.sCreateComment = _this.sCreateComment.bind(_this); _this.sUpdateComment = _this.sUpdateComment.bind(_this); _this.sDeleteComment = _this.sDeleteComment.bind(_this); _this.sCommentFavor = _this.sCommentFavor.bind(_this); _this.sCreateReply = _this.sCreateReply.bind(_this); _this.sDeleteReply = _this.sDeleteReply.bind(_this); _this.errorHandler = _this.errorHandler.bind(_this); _this.sGetComment = _this.sGetComment.bind(_this); _this.sReplyFavor = _this.sReplyFavor.bind(_this); _this.sGetReply = _this.sGetReply.bind(_this); _this.sUpdateReply = _this.sUpdateReply.bind(_this); _this.sOssSts = _this.sOssSts.bind(_this); _this.handleEdit = _this.handleEdit.bind(_this); _this.handleClose = _this.handleClose.bind(_this); return _this; } _createClass(App, [{ key: 'componentWillMount', value: function componentWillMount() { this.axios = _axios2.default; this.axios.defaults.withCredentials = true; if (this.props.token) { this.axios.defaults.headers.common['Authorization'] = 'Bearer ' + this.props.token; } } }, { key: 'componentDidMount', value: function componentDidMount() { this.loadLocales(); this.loadEmoji(); } /** * 加载语言包 * 只能根据url或者传入的props来确定加载哪个语言包 * 优先级:传入的props > url */ }, { key: 'loadLocales', value: function loadLocales() { var _this2 = this; var currentLocale = this.props.locales; var cookieLang = _jsCookie2.default.get('lnk_lang'); if (!currentLocale) { currentLocale = cookieLang || _reactIntlUniversal2.default.determineLocale({ urlLocaleKey: 'lang' }); } currentLocale = _lang.SUPPORT_LOCALES.find(function (item) { return item.value === currentLocale; }) ? currentLocale : 'zh-CN'; var version = require('./version.json').hash; // 使用绝对路径 var languageURL = _constant.LANGUAGE_LINK + '/' + currentLocale + '.json?v=' + version; return fetch(languageURL).then(function (response) { if (response.status >= 400) { throw new Error('Bad response from server'); } return response.json(); }).then(function (data) { // console.log('data: ', data); _reactIntlUniversal2.default.init({ currentLocale: currentLocale, locales: _defineProperty({}, currentLocale, data) }).then(function () { _this2.setState({ initDone: true, locale: currentLocale }); }); }); } /** * 加载表情包 */ }, { key: 'loadEmoji', value: function loadEmoji() { var _this3 = this; this.axios.get(this.props.emojiAPI + '/emoticons').then(function (response) { var emojiMap = {}; response.data.list.forEach(function (item) { emojiMap[item.name] = item.url; }); window.sessionStorage.setItem('emojiMap', JSON.stringify(emojiMap)); _this3.setState({ emojiList: response.data.list }); }).catch(this.errorHandler); } }, { key: 'handleEdit', value: function handleEdit(_ref) { var replyId = _ref.replyId, commentId = _ref.commentId, userId = _ref.userId, content = _ref.content, replyPage = _ref.replyPage; this.setState({ editModalVisible: true, action: content.replies ? 'comment' : content.reply ? 'replyToReply' : 'reply', replyId: replyId, commentId: commentId, userId: userId, content: content, replyPage: replyPage }); } }, { key: 'handleClose', value: function handleClose() { this.setState({ editModalVisible: false }); } }, { key: 'error', value: function error(msg) { var info = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this.props.showError) { _message3.default.error(msg); } if (this.props.onError) { this.props.onError(msg, info); } } }, { key: 'errorHandler', value: function errorHandler(error) { var locale = this.state.locale; var localResponse = _lang.LOCALES_RESPONSE[locale]; if (error.response && error.response.data && error.response.data.msg) { this.error(localResponse[error.response.data.msg] || _constant.ERROR_DEFAULT, { response: error.response }); return; } this.error(localResponse[error.response.data.msg] || _constant.ERROR_DEFAULT, { response: error.response }); } /** * 改变 loading 状态 * @param {string} key key * @param {string} value value */ }, { key: 'handleChangeLoading', value: function handleChangeLoading(key, value) { var loading = this.state.loading; loading[key] = value; this.setState({ loading: loading }); } /** * 获取评论列表 */ }, { key: 'sGetComment', value: function sGetComment() { var _this4 = this; var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref2$page = _ref2.page, page = _ref2$page === undefined ? 1 : _ref2$page, _ref2$filterSpeak = _ref2.filterSpeak, filterSpeak = _ref2$filterSpeak === undefined ? 0 : _ref2$filterSpeak; var pageType = this.props.pageType; this.handleChangeLoading('sGetComment', true); var _props = this.props, API = _props.API, type = _props.type, businessId = _props.businessId, limit = _props.limit; this.axios.get(API + '/comments?type=' + type + '&business_id=' + businessId + '&is_speak=' + filterSpeak + '&page=' + page + '&limit=' + limit).then(function (response) { var _response$data = response.data, list = _response$data.list, page = _response$data.page, total = _response$data.total; if (list) { var newList = list; var oldList = _this4.state.list; if (pageType === 'more') { if (page > 1) { // 删除临时数据 oldList = oldList.filter(function (o) { return !o.isTemporary; }); newList = oldList.concat(newList); } } else if (pageType === 'pagination') { // TODO 滚动到顶部 window.scrollTo(0, 0); } _this4.setState({ list: newList, page: page, total: total }); _this4.props.onCountChange(total); } else { _message3.default.info(_reactIntlUniversal2.default.get('message.noMoreComment')); _this4.setState({ isNoMoreComment: true }); } }).catch(this.errorHandler).finally(function () { _this4.handleChangeLoading('sGetComment', false); }); } /** * 获取更多回复 */ }, { key: 'sGetReply', value: function sGetReply() { var _this5 = this; var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, commentId = _ref3.commentId, _ref3$page = _ref3.page, page = _ref3$page === undefined ? 1 : _ref3$page; this.handleChangeLoading('sGetReply', true); var _props2 = this.props, API = _props2.API, limit = _props2.limit; this.axios.get(API + '/replies?comment_id=' + commentId + '&page=' + page + '&limit=' + limit).then(function (response) { if (!response.data.list) { _message3.default.info(_reactIntlUniversal2.default.get('message.noMoreData')); } var list = _this5.state.list.map(function (item) { if (item.id === commentId) { if (!item.replies) item.replies = []; if (response.data.list) { if (page === 1) { // 如果当前页数为第一页,则清空当前所有的 replies // 并将获取到的 replies 存放在 state item.replies = response.data.list; } else { item.replies = item.replies.filter(function (o) { return !o.isTemporary; }).concat(response.data.list); // 如果当前页数非第一页,则合并 replies } item.reply_count = response.data.total; item.reply_page = response.data.page; } else { item.isNoMoreReply = true; } } return item; }); _this5.setState({ list: list }); }).catch(this.errorHandler).finally(function () { _this5.handleChangeLoading('sGetReply', false); }); } /** * 添加评论 * @param {object} {content} comment content */ }, { key: 'sCreateComment', value: function sCreateComment() { var _this6 = this; var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, content = _ref4.content; var cb = arguments[1]; if (!content) return this.error(_reactIntlUniversal2.default.get('message.notNull')); this.handleChangeLoading('sCreateComment', true); var _props3 = this.props, API = _props3.API, type = _props3.type, businessId = _props3.businessId, businessUserId = _props3.businessUserId; this.axios(API + '/comments', { method: 'post', data: { type: type, business_id: businessId, business_user_id: businessUserId, content: content }, withCredentials: true }).then(function (response) { if (_this6.props.showAlertComment) { _message3.default.success(_reactIntlUniversal2.default.get('message.success')); } if ((0, _helper.isFunction)(cb)) cb(response.data); // 将数据写入到 list 中 // 临时插入 // 等到获取数据之后,删除临时数据 var _state = _this6.state, list = _state.list, total = _state.total; list.unshift(_extends({}, response.data, { replies: [], isTemporary: true // 临时的数据 })); _this6.setState({ list: list, total: total + 1 }); _this6.props.onCountChange(total + 1); }).catch(function (error) { _this6.props.onCommentFail(error.response.status); _this6.errorHandler(error); }).finally(function () { _this6.handleChangeLoading('sCreateComment', false); }); } /** * 删除评论 */ }, { key: 'sDeleteComment', value: function sDeleteComment(commentId) { var _this7 = this; this.handleChangeLoading('sDeleteComment', true); var API = this.props.API; this.axios(API + '/comments/' + commentId, { method: 'delete', withCredentials: true }).then(function () { var _state2 = _this7.state, list = _state2.list, total = _state2.total; var res = list.filter(function (item) { return item.id !== commentId; }); var deletedItem = list.find(function (item) { return item.id === commentId; }); _this7.setState({ list: res, total: total - 1 }); _this7.props.onDelete(_constant.COMMENT_TYPE.COMMENT, deletedItem); _this7.props.onCountChange(total - 1); }).catch(this.errorHandler).finally(function () { _this7.handleChangeLoading('sDeleteComment', false); }); } /** * 更新评论 * @param {object} {content} comment content */ }, { key: 'sUpdateComment', value: function sUpdateComment(_ref5) { var _this8 = this; var commentId = _ref5.commentId, content = _ref5.content; this.handleChangeLoading('sUpdateComment', true); var API = this.props.API; this.axios(API + '/comments/' + commentId, { method: 'post', data: { content: content }, withCredentials: true }).then(function () { var list = _this8.state.list; list = list.map(function (it) { if (it.id === commentId) { return _extends({}, it, { content: content }); } return it; }); _this8.props.onUpdateComment('comment'); _this8.setState({ list: list }); }).catch(this.errorHandler).finally(function () { _this8.handleChangeLoading('sUpdateComment', false); }); } /** * 添加回复 * 回复评论/回复回复 * @param {object} data { comment_id, content, [reply_id] } */ }, { key: 'sCreateReply', value: function sCreateReply(data, cb) { var _this9 = this; if (!data.content) return this.error(_reactIntlUniversal2.default.get('message.replyNoNull')); this.handleChangeLoading('sCreateReply', true); var API = this.props.API; this.axios(API + '/replies', { method: 'post', data: data, withCredentials: true }).then(function (response) { if (_this9.props.showAlertReply) { _message3.default.success(_reactIntlUniversal2.default.get('message.replySuccess')); } if ((0, _helper.isFunction)(cb)) cb(response.data); // 将数据写入到 list 中 // 临时插入 // 等到获取数据之后,删除临时数据 var list = _this9.state.list.map(function (item) { if (item.id === data.comment_id) { if (!item.replies) item.replies = []; item.replies.push(_extends({}, response.data, { isTemporary: true // 临时的数据 })); item.reply_count += 1; } return item; }); _this9.setState({ list: list }); }).catch(function (error) { _this9.props.onCommentFail(error.response.status); _this9.errorHandler(error); }).finally(function () { _this9.handleChangeLoading('sCreateReply', false); }); } /** * 删除回复 * @param {*} replyId * @param {*} commentId */ }, { key: 'sDeleteReply', value: function sDeleteReply(replyId, commentId) { var _this10 = this; this.handleChangeLoading('sDeleteReply', true); var API = this.props.API; this.axios(API + '/replies/' + replyId + '?CommentID=' + commentId, { method: 'delete', withCredentials: true }).then(function () { var deletedItem = null; var list = _this10.state.list.map(function (item) { if (item.id === commentId) { var replies = item.replies.filter(function (item) { return item.id !== replyId; }); deletedItem = item.replies.find(function (item) { return item.id === replyId; }); item.replies = replies; item.reply_count -= 1; } return item; }); _this10.setState({ list: list }); _this10.props.onDelete(_constant.COMMENT_TYPE.REPLY, deletedItem); }).catch(this.errorHandler).finally(function () { _this10.handleChangeLoading('sDeleteReply', false); }); } /** * 更新回复 * 回复评论/回复回复 * @param {object} data { comment_id, content, reply_id } */ }, { key: 'sUpdateReply', value: function sUpdateReply(_ref6) { var _this11 = this; var commentId = _ref6.commentId, content = _ref6.content, replyId = _ref6.replyId, replyPage = _ref6.replyPage; this.handleChangeLoading('sUpdateReply', true); var API = this.props.API; this.axios(API + '/replies/' + replyId, { method: 'post', data: { comment_id: commentId, content: content }, withCredentials: true }).then(function () { for (var i = 1; i <= replyPage; i++) { _this11.sGetReply({ commentId: commentId, page: i }); } _this11.props.onUpdateComment('reply'); }).catch(this.errorHandler).finally(function () { _this11.handleChangeLoading('sUpdateReply', false); }); } /** * 评论 点赞/取消点赞 * @param {string} commentId { commentId } * @param {boolean} favored 是否已经点过赞 */ }, { key: 'sCommentFavor', value: function sCommentFavor(commentId, favored) { var _this12 = this; this.handleChangeLoading('sCommentFavor', true); var API = this.props.API; this.axios(API + '/comments/' + commentId + '/favor', { method: favored ? 'delete' : 'put', withCredentials: true }).then(function (response) { if (_this12.props.showAlertFavor) { _message3.default.success(favored ? _reactIntlUniversal2.default.get('message.cancelLickSuccess') : _reactIntlUniversal2.default.get('message.likeSuccess')); } // 更新 list 中的该项数据的 favored var list = _this12.state.list.map(function (item) { if (item.id === commentId) { item.favored = !favored; item.favor_count += favored ? -1 : 1; } return item; }); _this12.setState({ list: list }); }).catch(this.errorHandler).finally(function () { _this12.handleChangeLoading('sCommentFavor', false); }); } /** * 回复 点赞/取消点赞 * @param {string} replyId replyId * @param {string} commentId commentId * @param {boolean} favored 是否已经点过赞 */ }, { key: 'sReplyFavor', value: function sReplyFavor(replyId, commentId, favored) { var _this13 = this; this.handleChangeLoading('sReplyFavor', true); var API = this.props.API; this.axios(API + '/replies/' + replyId + '/favor', { method: favored ? 'delete' : 'put', data: { comment_id: commentId }, withCredentials: true }).then(function (response) { _message3.default.success(favored ? _reactIntlUniversal2.default.get('message.cancelLickSuccess') : _reactIntlUniversal2.default.get('message.likeSuccess')); // 更新 list 中的该项数据的 favored var list = _this13.state.list.map(function (item) { if (item.id === commentId) { item.replies = item.replies.map(function (r) { if (r.id === replyId) { r.favored = !favored; // r.favor_count = response.data.favor_count; // 点赞数 +1,而不是使用后端返回的点赞数 // 不然如果返回的不是增加 1,用户可能以为程序错误 r.favor_count += favored ? -1 : 1; } return r; }); } return item; }); _this13.setState({ list: list }); }).catch(this.errorHandler).finally(function () { _this13.handleChangeLoading('sReplyFavor', false); }); } /** * 获取 OSS 上传的参数 */ }, { key: 'sOssSts', value: function sOssSts() { var _this14 = this; this.handleChangeLoading('sOssSts', true); var API = this.props.API; this.axios.get(API + '/oss/sts').then(function (response) { _this14.setState({ oss: _extends({}, response.data) }); }).catch(this.errorHandler).finally(function () { _this14.handleChangeLoading('sOssSts', false); }); } }, { key: 'render', value: function render() { // 添加到 Context 的数据 var value = _extends({}, this.state, this.props, { sCreateComment: this.sCreateComment, sGetComment: this.sGetComment, sCommentFavor: this.sCommentFavor, sReplyFavor: this.sReplyFavor, sCreateReply: this.sCreateReply, sGetReply: this.sGetReply, sOssSts: this.sOssSts, sDeleteComment: this.sDeleteComment, sDeleteReply: this.sDeleteReply, sUpdateReply: this.sUpdateReply, sUpdateComment: this.sUpdateComment, handleEdit: this.handleEdit }); return this.state.initDone && _react2.default.createElement( _Comment.CommentContext.Provider, { value: value }, _react2.default.createElement( 'div', { className: 'comment' }, this.props.showEditor && _react2.default.createElement(_CommentInput2.default, { content: this.props.children }), this.props.showList && _react2.default.createElement( 'div', { style: { marginTop: 20 } }, _react2.default.createElement(_CommentList2.default, null) ) ), this.state.editModalVisible && _react2.default.createElement(_EditComment2.default, { visible: this.state.editModalVisible, action: this.state.action, replyId: this.state.replyId, replyPage: this.state.replyPage, commentId: this.state.commentId, userId: this.state.content.user_id, content: this.state.content, handleClose: this.handleClose, preRenderValue: this.props.preRenderValue }) ); } }]); return App; }(_react.Component); App.propTypes = { type: _propTypes2.default.number.isRequired, // 评论的 type businessId: _propTypes2.default.string.isRequired, // 评论的 business_id businessUserId: _propTypes2.default.number, API: _propTypes2.default.string, // 评论的 API 前缀 showList: _propTypes2.default.bool, // 是否显示评论列表 showEditor: _propTypes2.default.bool, // 是否显示评论输入框 showAlertComment: _propTypes2.default.bool, // 评论成功之后,是否通过 Antd 的 Message 组件进行提示 showAlertReply: _propTypes2.default.bool, // 回复成功之后,是否通过 Antd 的 Message 组件进行提示 showAlertFavor: _propTypes2.default.bool, // 点赞/取消点赞成功之后,是否通过 Antd 的 Message 组件进行提示 showError: _propTypes2.default.bool, // 是否使用Antd的Message组件提示错误信息 onError: _propTypes2.default.func, // 错误回调, 出错了会被调用 userId: _propTypes2.default.number, // 用户id, comment内部不维护用户id, 调用组件时传递过来, 目前用于判断是否显示删除按钮 pageType: _propTypes2.default.string, // 分页类型 page: _propTypes2.default.number, // 页码 limit: _propTypes2.default.number, // 一次加载评论数量 onPageChange: _propTypes2.default.func, // 页码变化回调 onGetMoreBtnClick: _propTypes2.default.func, // 点击查看更多按钮回调 onDelete: _propTypes2.default.func, onUpdateComment: _propTypes2.default.func, locales: _propTypes2.default.string, // 传入的语言环境, en-US/zh-CN onCountChange: _propTypes2.default.func, // 评论数量变更时的回调 onCommentFail: _propTypes2.default.func, // 评论失败时的回调 preRenderValue: _propTypes2.default.func // 编辑器渲染前对值需要做的工作 }; App.defaultProps = { businessUserId: 0, API: '//api.links123.net/comment/v1', emojiAPI: '//api.links123.net/link/v1', LOGINLINK: process.env.RUN_MOD === 'production' ? 'https://passport.links123.com/login' : 'http://test.links123.net:5050/login', showList: true, showEditor: true, showAlertComment: false, showAlertReply: false, showAlertFavor: false, showError: true, showEdit: false, pageType: 'more', limit: _constant.LIMIT, onGetMoreBtnClick: function onGetMoreBtnClick() {}, onPageChange: function onPageChange(page) {}, onDelete: function onDelete() {}, onUpdateComment: function onUpdateComment() {}, onBeforeUpdateComment: function onBeforeUpdateComment() {}, onCountChange: function onCountChange() {}, onCommentFail: function onCommentFail() {}, preRenderValue: function preRenderValue(v) { return v; } }; exports.Editor = _Editor2.default; exports.RenderText = _RenderText2.default; exports.default = App; //# sourceMappingURL=App.js.map