通用评论

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. import React, { Component } from "react";
  2. import PropTypes from "prop-types";
  3. import { message } from "antd";
  4. import axios from "axios";
  5. import intl from "react-intl-universal";
  6. import { ERROR_DEFAULT, LIMIT, COMMENT_TYPE } from "./constant";
  7. import { CommentContext } from "./Comment";
  8. import { isFunction } from "./helper";
  9. import CommentInput from "./components/CommentInput";
  10. import CommentList from "./components/CommentList";
  11. import Editor from "./components/Editor";
  12. import RenderText from "./components/RenderText";
  13. import { SUPPORT_LOCALES, LOCALES_RESPONSE } from "./lang";
  14. import USdata from "./lang/en-US.js";
  15. import CNdata from "./lang/zh-CN.js";
  16. import "./App.css";
  17. const LOCALES = {
  18. "zh-CN": CNdata,
  19. "en-US": USdata
  20. };
  21. class App extends Component {
  22. constructor(props) {
  23. super(props);
  24. this.state = {
  25. loading: {},
  26. // oss 配置
  27. oss: {},
  28. // 评论数据
  29. list: [],
  30. page: 1,
  31. total: 0,
  32. // 是否没有更多评论了
  33. isNoMoreComment: false,
  34. initDone: false,
  35. locale: "zh-CN"
  36. };
  37. this.handleChangeLoading = this.handleChangeLoading.bind(this);
  38. this.sCreateComment = this.sCreateComment.bind(this);
  39. this.sDeleteComment = this.sDeleteComment.bind(this);
  40. this.sCommentFavor = this.sCommentFavor.bind(this);
  41. this.sCreateReply = this.sCreateReply.bind(this);
  42. this.sDeleteReply = this.sDeleteReply.bind(this);
  43. this.errorHandler = this.errorHandler.bind(this);
  44. this.sGetComment = this.sGetComment.bind(this);
  45. this.sReplyFavor = this.sReplyFavor.bind(this);
  46. this.sGetReply = this.sGetReply.bind(this);
  47. this.sOssSts = this.sOssSts.bind(this);
  48. }
  49. componentWillMount() {
  50. this.axios = axios;
  51. this.axios.defaults.withCredentials = true;
  52. if (this.props.token) {
  53. this.axios.defaults.headers.common["Authorization"] = `Bearer ${
  54. this.props.token
  55. }`;
  56. }
  57. }
  58. componentDidMount() {
  59. this.loadLocales();
  60. }
  61. /**
  62. * 加载语言包
  63. * 只能根据url或者传入的props来确定加载哪个语言包
  64. * 优先级:传入的props > url
  65. */
  66. loadLocales() {
  67. let { locales: currentLocale } = this.props;
  68. if (!currentLocale) {
  69. currentLocale = intl.determineLocale({
  70. urlLocaleKey: "lang"
  71. });
  72. }
  73. currentLocale = SUPPORT_LOCALES.find(item => item.value === currentLocale)
  74. ? currentLocale
  75. : "zh-CN";
  76. intl
  77. .init({
  78. currentLocale,
  79. locales: {
  80. [currentLocale]: LOCALES[currentLocale]
  81. }
  82. })
  83. .then(() => {
  84. this.setState({ initDone: true, locale: currentLocale });
  85. });
  86. }
  87. error(msg, info = {}) {
  88. if (this.props.showError) {
  89. message.error(msg);
  90. }
  91. if (this.props.onError) {
  92. this.props.onError(msg, info);
  93. }
  94. }
  95. errorHandler(error) {
  96. const { locale } = this.state;
  97. const localResponse = LOCALES_RESPONSE[locale];
  98. if (error.response && error.response.data && error.response.data.msg) {
  99. this.error(localResponse[error.response.data.msg] || ERROR_DEFAULT, {
  100. response: error.response
  101. });
  102. return;
  103. }
  104. this.error(localResponse[error.response.data.msg] || ERROR_DEFAULT, {
  105. response: error.response
  106. });
  107. }
  108. /**
  109. * 改变 loading 状态
  110. * @param {string} key key
  111. * @param {string} value value
  112. */
  113. handleChangeLoading(key, value) {
  114. const { loading } = this.state;
  115. loading[key] = value;
  116. this.setState({ loading });
  117. }
  118. /**
  119. * 获取评论列表
  120. */
  121. sGetComment({ page = 1 } = {}) {
  122. const { pageType } = this.props;
  123. this.handleChangeLoading("sGetComment", true);
  124. const { API, type, businessId, limit } = this.props;
  125. this.axios
  126. .get(
  127. `${API}/comments?type=${type}&business_id=${businessId}&page=${page}&limit=${limit}`
  128. )
  129. .then(response => {
  130. const { list, page, total } = response.data;
  131. if (list) {
  132. let newList = list;
  133. let { list: oldList } = this.state;
  134. if (pageType === "more") {
  135. if (page > 1) {
  136. // 删除临时数据
  137. oldList = oldList.filter(o => !o.isTemporary);
  138. newList = oldList.concat(newList);
  139. }
  140. } else if (pageType === "pagination") {
  141. // TODO 滚动到顶部
  142. window.scrollTo(0, 0);
  143. }
  144. this.setState({
  145. list: newList,
  146. page,
  147. total
  148. });
  149. this.props.onCountChange(total);
  150. } else {
  151. message.info(intl.get("message.noMoreComment"));
  152. this.setState({
  153. isNoMoreComment: true
  154. });
  155. }
  156. })
  157. .catch(this.errorHandler)
  158. .finally(() => {
  159. this.handleChangeLoading("sGetComment", false);
  160. });
  161. }
  162. /**
  163. * 获取更多回复
  164. */
  165. sGetReply({ commentId, page = 1 } = {}) {
  166. this.handleChangeLoading("sGetReply", true);
  167. const { API, limit } = this.props;
  168. this.axios
  169. .get(`${API}/replies?comment_id=${commentId}&page=${page}&limit=${limit}`)
  170. .then(response => {
  171. if (!response.data.list) {
  172. message.info(intl.get("message.noMoreData"));
  173. }
  174. const list = this.state.list.map(item => {
  175. if (item.id === commentId) {
  176. if (!item.replies) item.replies = [];
  177. if (response.data.list) {
  178. if (page === 1) {
  179. // 如果当前页数为第一页,则清空当前所有的 replies
  180. // 并将获取到的 replies 存放在 state
  181. item.replies = response.data.list;
  182. } else {
  183. item.replies = item.replies
  184. .filter(o => !o.isTemporary)
  185. .concat(response.data.list);
  186. // 如果当前页数非第一页,则合并 replies
  187. }
  188. item.reply_count = response.data.total;
  189. item.reply_page = response.data.page;
  190. } else {
  191. item.isNoMoreReply = true;
  192. }
  193. }
  194. return item;
  195. });
  196. this.setState({ list });
  197. })
  198. .catch(this.errorHandler)
  199. .finally(() => {
  200. this.handleChangeLoading("sGetReply", false);
  201. });
  202. }
  203. /**
  204. * 添加评论
  205. * @param {object} {content} comment content
  206. */
  207. sCreateComment({ content } = {}, cb) {
  208. if (!content) return this.error(intl.get("message.notNull"));
  209. this.handleChangeLoading("sCreateComment", true);
  210. const { API, type, businessId, businessUserId } = this.props;
  211. this.axios(`${API}/comments`, {
  212. method: "post",
  213. data: {
  214. type,
  215. business_id: businessId,
  216. business_user_id: businessUserId,
  217. content
  218. },
  219. withCredentials: true
  220. })
  221. .then(response => {
  222. if (this.props.showAlertComment) {
  223. message.success(intl.get("message.success"));
  224. }
  225. if (isFunction(cb)) cb();
  226. // 将数据写入到 list 中
  227. // 临时插入
  228. // 等到获取数据之后,删除临时数据
  229. const { list, total } = this.state;
  230. list.unshift({
  231. ...response.data,
  232. isTemporary: true // 临时的数据
  233. });
  234. this.setState({ list, total: total + 1 });
  235. this.props.onCountChange(total + 1);
  236. })
  237. .catch(this.errorHandler)
  238. .finally(() => {
  239. this.handleChangeLoading("sCreateComment", false);
  240. });
  241. }
  242. /**
  243. * 删除评论
  244. */
  245. sDeleteComment(commentId) {
  246. this.handleChangeLoading("sDeleteComment", true);
  247. const { API } = this.props;
  248. this.axios(`${API}/comments/${commentId}`, {
  249. method: "delete",
  250. withCredentials: true
  251. })
  252. .then(() => {
  253. const { list, total } = this.state;
  254. const res = list.filter(item => item.id !== commentId);
  255. this.setState({ list: res, total: total - 1 });
  256. this.props.onDelete(COMMENT_TYPE.COMMENT);
  257. this.props.onCountChange(total - 1);
  258. })
  259. .catch(this.errorHandler)
  260. .finally(() => {
  261. this.handleChangeLoading("sDeleteComment", false);
  262. });
  263. }
  264. /**
  265. * 添加回复
  266. * 回复评论/回复回复
  267. * @param {object} data { comment_id, content, [reply_id] }
  268. */
  269. sCreateReply(data, cb) {
  270. if (!data.content) return this.error(intl.get("message.replyNoNull"));
  271. this.handleChangeLoading("sCreateReply", true);
  272. const { API } = this.props;
  273. this.axios(`${API}/replies`, {
  274. method: "post",
  275. data,
  276. withCredentials: true
  277. })
  278. .then(response => {
  279. if (this.props.showAlertReply) {
  280. message.success(intl.get("message.replySuccess"));
  281. }
  282. if (isFunction(cb)) cb();
  283. // 将数据写入到 list 中
  284. // 临时插入
  285. // 等到获取数据之后,删除临时数据
  286. const list = this.state.list.map(item => {
  287. if (item.id === data.comment_id) {
  288. if (!item.replies) item.replies = [];
  289. item.replies.push({
  290. ...response.data,
  291. isTemporary: true // 临时的数据
  292. });
  293. item.reply_count += 1;
  294. }
  295. return item;
  296. });
  297. this.setState({ list });
  298. })
  299. .catch(this.errorHandler)
  300. .finally(() => {
  301. this.handleChangeLoading("sCreateReply", false);
  302. });
  303. }
  304. /**
  305. * 删除回复
  306. * @param {*} replyId
  307. * @param {*} commentId
  308. */
  309. sDeleteReply(replyId, commentId) {
  310. this.handleChangeLoading("sDeleteReply", true);
  311. const { API } = this.props;
  312. this.axios(`${API}/replies/${replyId}?CommentID=${commentId}`, {
  313. method: "delete",
  314. withCredentials: true
  315. })
  316. .then(() => {
  317. const list = this.state.list.map(item => {
  318. if (item.id === commentId) {
  319. const replies = item.replies.filter(item => item.id !== replyId);
  320. item.replies = replies;
  321. item.reply_count -= 1;
  322. }
  323. return item;
  324. });
  325. this.setState({ list });
  326. this.props.onDelete(COMMENT_TYPE.REPLY);
  327. })
  328. .catch(this.errorHandler)
  329. .finally(() => {
  330. this.handleChangeLoading("sDeleteReply", false);
  331. });
  332. }
  333. /**
  334. * 评论 点赞/取消点赞
  335. * @param {string} commentId { commentId }
  336. * @param {boolean} favored 是否已经点过赞
  337. */
  338. sCommentFavor(commentId, favored) {
  339. this.handleChangeLoading("sCommentFavor", true);
  340. const { API } = this.props;
  341. this.axios(`${API}/comments/${commentId}/favor`, {
  342. method: favored ? "delete" : "put",
  343. withCredentials: true
  344. })
  345. .then(response => {
  346. if (this.props.showAlertFavor) {
  347. message.success(
  348. favored
  349. ? intl.get("message.cancelLickSuccess")
  350. : intl.get("message.likeSuccess")
  351. );
  352. }
  353. // 更新 list 中的该项数据的 favored
  354. const list = this.state.list.map(item => {
  355. if (item.id === commentId) {
  356. item.favored = !favored;
  357. item.favor_count += favored ? -1 : 1;
  358. }
  359. return item;
  360. });
  361. this.setState({ list });
  362. })
  363. .catch(this.errorHandler)
  364. .finally(() => {
  365. this.handleChangeLoading("sCommentFavor", false);
  366. });
  367. }
  368. /**
  369. * 回复 点赞/取消点赞
  370. * @param {string} replyId replyId
  371. * @param {string} commentId commentId
  372. * @param {boolean} favored 是否已经点过赞
  373. */
  374. sReplyFavor(replyId, commentId, favored) {
  375. this.handleChangeLoading("sReplyFavor", true);
  376. const { API } = this.props;
  377. this.axios(`${API}/replies/${replyId}/favor`, {
  378. method: favored ? "delete" : "put",
  379. data: {
  380. comment_id: commentId
  381. },
  382. withCredentials: true
  383. })
  384. .then(response => {
  385. message.success(
  386. favored
  387. ? intl.get("message.cancelLickSuccess")
  388. : intl.get("message.likeSuccess")
  389. );
  390. // 更新 list 中的该项数据的 favored
  391. const list = this.state.list.map(item => {
  392. if (item.id === commentId) {
  393. item.replies = item.replies.map(r => {
  394. if (r.id === replyId) {
  395. r.favored = !favored;
  396. // r.favor_count = response.data.favor_count;
  397. // 点赞数 +1,而不是使用后端返回的点赞数
  398. // 不然如果返回的不是增加 1,用户可能以为程序错误
  399. r.favor_count += favored ? -1 : 1;
  400. }
  401. return r;
  402. });
  403. }
  404. return item;
  405. });
  406. this.setState({ list });
  407. })
  408. .catch(this.errorHandler)
  409. .finally(() => {
  410. this.handleChangeLoading("sReplyFavor", false);
  411. });
  412. }
  413. /**
  414. * 获取 OSS 上传的参数
  415. */
  416. sOssSts() {
  417. this.handleChangeLoading("sOssSts", true);
  418. const { API } = this.props;
  419. this.axios
  420. .get(`${API}/oss/sts`)
  421. .then(response => {
  422. this.setState({ oss: { ...response.data } });
  423. })
  424. .catch(this.errorHandler)
  425. .finally(() => {
  426. this.handleChangeLoading("sOssSts", false);
  427. });
  428. }
  429. render() {
  430. // 添加到 Context 的数据
  431. const value = {
  432. ...this.state,
  433. ...this.props,
  434. sCreateComment: this.sCreateComment,
  435. sGetComment: this.sGetComment,
  436. sCommentFavor: this.sCommentFavor,
  437. sReplyFavor: this.sReplyFavor,
  438. sCreateReply: this.sCreateReply,
  439. sGetReply: this.sGetReply,
  440. sOssSts: this.sOssSts,
  441. sDeleteComment: this.sDeleteComment,
  442. sDeleteReply: this.sDeleteReply
  443. };
  444. console.log(this.props.isMobile);
  445. return (
  446. this.state.initDone && (
  447. <CommentContext.Provider value={value}>
  448. <div className="comment">
  449. {this.props.showEditor && (
  450. <CommentInput content={this.props.children} />
  451. )}
  452. {this.props.showList && (
  453. <div style={{ marginTop: 20 }}>
  454. <CommentList />
  455. </div>
  456. )}
  457. </div>
  458. </CommentContext.Provider>
  459. )
  460. );
  461. }
  462. }
  463. App.propTypes = {
  464. type: PropTypes.number.isRequired, // 评论的 type
  465. businessId: PropTypes.string.isRequired, // 评论的 business_id
  466. businessUserId: PropTypes.number,
  467. API: PropTypes.string, // 评论的 API 前缀
  468. showList: PropTypes.bool, // 是否显示评论列表
  469. showEditor: PropTypes.bool, // 是否显示评论输入框
  470. showAlertComment: PropTypes.bool, // 评论成功之后,是否通过 Antd 的 Message 组件进行提示
  471. showAlertReply: PropTypes.bool, // 回复成功之后,是否通过 Antd 的 Message 组件进行提示
  472. showAlertFavor: PropTypes.bool, // 点赞/取消点赞成功之后,是否通过 Antd 的 Message 组件进行提示
  473. showError: PropTypes.bool, // 是否使用Antd的Message组件提示错误信息
  474. onError: PropTypes.func, // 错误回调, 出错了会被调用
  475. userId: PropTypes.number, // 用户id, comment内部不维护用户id, 调用组件时传递过来, 目前用于判断是否显示删除按钮
  476. pageType: PropTypes.string, // 分页类型
  477. page: PropTypes.number, // 页码
  478. limit: PropTypes.number, // 一次加载评论数量
  479. onPageChange: PropTypes.func, // 页码变化回调
  480. onGetMoreBtnClick: PropTypes.func, // 点击查看更多按钮回调
  481. <<<<<<< HEAD
  482. isMobile: PropTypes.bool,
  483. onDelete: PropTypes.func
  484. =======
  485. onDelete: PropTypes.func,
  486. locales: PropTypes.string, // 传入的语言环境, en-US/zh-CN
  487. onCountChange: PropTypes.func // 评论数量变更时的回调
  488. >>>>>>> upstream/master
  489. };
  490. App.defaultProps = {
  491. businessUserId: 0,
  492. API: "//api.links123.net/comment/v1",
  493. showList: true,
  494. showEditor: true,
  495. showAlertComment: false,
  496. showAlertReply: false,
  497. showAlertFavor: false,
  498. showError: true,
  499. pageType: "more",
  500. limit: LIMIT,
  501. onGetMoreBtnClick: () => {},
  502. onPageChange: page => {},
  503. onDelete: () => {},
  504. onCountChange: () => {}
  505. };
  506. export { Editor, RenderText };
  507. export default App;