通用评论

App.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. } else {
  150. message.info(intl.get("message.noMoreComment"));
  151. this.setState({
  152. isNoMoreComment: true
  153. });
  154. }
  155. })
  156. .catch(this.errorHandler)
  157. .finally(() => {
  158. this.handleChangeLoading("sGetComment", false);
  159. });
  160. }
  161. /**
  162. * 获取更多回复
  163. */
  164. sGetReply({ commentId, page = 1 } = {}) {
  165. this.handleChangeLoading("sGetReply", true);
  166. const { API, limit } = this.props;
  167. this.axios
  168. .get(`${API}/replies?comment_id=${commentId}&page=${page}&limit=${limit}`)
  169. .then(response => {
  170. if (!response.data.list) {
  171. message.info(intl.get("message.noMoreData"));
  172. }
  173. const list = this.state.list.map(item => {
  174. if (item.id === commentId) {
  175. if (!item.replies) item.replies = [];
  176. if (response.data.list) {
  177. if (page === 1) {
  178. // 如果当前页数为第一页,则清空当前所有的 replies
  179. // 并将获取到的 replies 存放在 state
  180. item.replies = response.data.list;
  181. } else {
  182. item.replies = item.replies
  183. .filter(o => !o.isTemporary)
  184. .concat(response.data.list);
  185. // 如果当前页数非第一页,则合并 replies
  186. }
  187. item.reply_count = response.data.total;
  188. item.reply_page = response.data.page;
  189. } else {
  190. item.isNoMoreReply = true;
  191. }
  192. }
  193. return item;
  194. });
  195. this.setState({ list });
  196. })
  197. .catch(this.errorHandler)
  198. .finally(() => {
  199. this.handleChangeLoading("sGetReply", false);
  200. });
  201. }
  202. /**
  203. * 添加评论
  204. * @param {object} {content} comment content
  205. */
  206. sCreateComment({ content } = {}, cb) {
  207. if (!content) return this.error(intl.get("message.notNull"));
  208. this.handleChangeLoading("sCreateComment", true);
  209. const { API, type, businessId, businessUserId } = this.props;
  210. this.axios(`${API}/comments`, {
  211. method: "post",
  212. data: {
  213. type,
  214. business_id: businessId,
  215. business_user_id: businessUserId,
  216. content
  217. },
  218. withCredentials: true
  219. })
  220. .then(response => {
  221. if (this.props.showAlertComment) {
  222. message.success(intl.get("message.success"));
  223. }
  224. if (isFunction(cb)) cb();
  225. // 将数据写入到 list 中
  226. // 临时插入
  227. // 等到获取数据之后,删除临时数据
  228. const { list, total } = this.state;
  229. list.unshift({
  230. ...response.data,
  231. isTemporary: true // 临时的数据
  232. });
  233. this.setState({ list, total: total + 1 });
  234. })
  235. .catch(this.errorHandler)
  236. .finally(() => {
  237. this.handleChangeLoading("sCreateComment", false);
  238. });
  239. }
  240. /**
  241. * 删除评论
  242. */
  243. sDeleteComment(commentId) {
  244. this.handleChangeLoading("sDeleteComment", true);
  245. const { API } = this.props;
  246. this.axios(`${API}/comments/${commentId}`, {
  247. method: "delete",
  248. withCredentials: true
  249. })
  250. .then(() => {
  251. const { list, total } = this.state;
  252. const res = list.filter(item => item.id !== commentId);
  253. this.setState({ list: res, total: total - 1 });
  254. this.props.onDelete(COMMENT_TYPE.COMMENT);
  255. })
  256. .catch(this.errorHandler)
  257. .finally(() => {
  258. this.handleChangeLoading("sDeleteComment", false);
  259. });
  260. }
  261. /**
  262. * 添加回复
  263. * 回复评论/回复回复
  264. * @param {object} data { comment_id, content, [reply_id] }
  265. */
  266. sCreateReply(data, cb) {
  267. if (!data.content) return this.error(intl.get("message.replyNoNull"));
  268. this.handleChangeLoading("sCreateReply", true);
  269. const { API } = this.props;
  270. this.axios(`${API}/replies`, {
  271. method: "post",
  272. data,
  273. withCredentials: true
  274. })
  275. .then(response => {
  276. if (this.props.showAlertReply) {
  277. message.success(intl.get("message.replySuccess"));
  278. }
  279. if (isFunction(cb)) cb();
  280. // 将数据写入到 list 中
  281. // 临时插入
  282. // 等到获取数据之后,删除临时数据
  283. const list = this.state.list.map(item => {
  284. if (item.id === data.comment_id) {
  285. if (!item.replies) item.replies = [];
  286. item.replies.push({
  287. ...response.data,
  288. isTemporary: true // 临时的数据
  289. });
  290. item.reply_count += 1;
  291. }
  292. return item;
  293. });
  294. this.setState({ list });
  295. })
  296. .catch(this.errorHandler)
  297. .finally(() => {
  298. this.handleChangeLoading("sCreateReply", false);
  299. });
  300. }
  301. /**
  302. * 删除回复
  303. * @param {*} replyId
  304. * @param {*} commentId
  305. */
  306. sDeleteReply(replyId, commentId) {
  307. this.handleChangeLoading("sDeleteReply", true);
  308. const { API } = this.props;
  309. this.axios(`${API}/replies/${replyId}?CommentID=${commentId}`, {
  310. method: "delete",
  311. withCredentials: true
  312. })
  313. .then(() => {
  314. const list = this.state.list.map(item => {
  315. if (item.id === commentId) {
  316. const replies = item.replies.filter(item => item.id !== replyId);
  317. item.replies = replies;
  318. item.reply_count -= 1;
  319. }
  320. return item;
  321. });
  322. this.setState({ list });
  323. this.props.onDelete(COMMENT_TYPE.REPLY);
  324. })
  325. .catch(this.errorHandler)
  326. .finally(() => {
  327. this.handleChangeLoading("sDeleteReply", false);
  328. });
  329. }
  330. /**
  331. * 评论 点赞/取消点赞
  332. * @param {string} commentId { commentId }
  333. * @param {boolean} favored 是否已经点过赞
  334. */
  335. sCommentFavor(commentId, favored) {
  336. this.handleChangeLoading("sCommentFavor", true);
  337. const { API } = this.props;
  338. this.axios(`${API}/comments/${commentId}/favor`, {
  339. method: favored ? "delete" : "put",
  340. withCredentials: true
  341. })
  342. .then(response => {
  343. if (this.props.showAlertFavor) {
  344. message.success(
  345. favored
  346. ? intl.get("message.cancelLickSuccess")
  347. : intl.get("message.likeSuccess")
  348. );
  349. }
  350. // 更新 list 中的该项数据的 favored
  351. const list = this.state.list.map(item => {
  352. if (item.id === commentId) {
  353. item.favored = !favored;
  354. item.favor_count += favored ? -1 : 1;
  355. }
  356. return item;
  357. });
  358. this.setState({ list });
  359. })
  360. .catch(this.errorHandler)
  361. .finally(() => {
  362. this.handleChangeLoading("sCommentFavor", false);
  363. });
  364. }
  365. /**
  366. * 回复 点赞/取消点赞
  367. * @param {string} replyId replyId
  368. * @param {string} commentId commentId
  369. * @param {boolean} favored 是否已经点过赞
  370. */
  371. sReplyFavor(replyId, commentId, favored) {
  372. this.handleChangeLoading("sReplyFavor", true);
  373. const { API } = this.props;
  374. this.axios(`${API}/replies/${replyId}/favor`, {
  375. method: favored ? "delete" : "put",
  376. data: {
  377. comment_id: commentId
  378. },
  379. withCredentials: true
  380. })
  381. .then(response => {
  382. message.success(
  383. favored
  384. ? intl.get("message.cancelLickSuccess")
  385. : intl.get("message.likeSuccess")
  386. );
  387. // 更新 list 中的该项数据的 favored
  388. const list = this.state.list.map(item => {
  389. if (item.id === commentId) {
  390. item.replies = item.replies.map(r => {
  391. if (r.id === replyId) {
  392. r.favored = !favored;
  393. // r.favor_count = response.data.favor_count;
  394. // 点赞数 +1,而不是使用后端返回的点赞数
  395. // 不然如果返回的不是增加 1,用户可能以为程序错误
  396. r.favor_count += favored ? -1 : 1;
  397. }
  398. return r;
  399. });
  400. }
  401. return item;
  402. });
  403. this.setState({ list });
  404. })
  405. .catch(this.errorHandler)
  406. .finally(() => {
  407. this.handleChangeLoading("sReplyFavor", false);
  408. });
  409. }
  410. /**
  411. * 获取 OSS 上传的参数
  412. */
  413. sOssSts() {
  414. this.handleChangeLoading("sOssSts", true);
  415. const { API } = this.props;
  416. this.axios
  417. .get(`${API}/oss/sts`)
  418. .then(response => {
  419. this.setState({ oss: { ...response.data } });
  420. })
  421. .catch(this.errorHandler)
  422. .finally(() => {
  423. this.handleChangeLoading("sOssSts", false);
  424. });
  425. }
  426. render() {
  427. // 添加到 Context 的数据
  428. const value = {
  429. ...this.state,
  430. ...this.props,
  431. sCreateComment: this.sCreateComment,
  432. sGetComment: this.sGetComment,
  433. sCommentFavor: this.sCommentFavor,
  434. sReplyFavor: this.sReplyFavor,
  435. sCreateReply: this.sCreateReply,
  436. sGetReply: this.sGetReply,
  437. sOssSts: this.sOssSts,
  438. sDeleteComment: this.sDeleteComment,
  439. sDeleteReply: this.sDeleteReply
  440. };
  441. return (
  442. this.state.initDone && (
  443. <CommentContext.Provider value={value}>
  444. <div className="comment">
  445. {this.props.showEditor && (
  446. <CommentInput content={this.props.children} />
  447. )}
  448. {this.props.showList && (
  449. <div style={{ marginTop: 20 }}>
  450. <CommentList />
  451. </div>
  452. )}
  453. </div>
  454. </CommentContext.Provider>
  455. )
  456. );
  457. }
  458. }
  459. App.propTypes = {
  460. type: PropTypes.number.isRequired, // 评论的 type
  461. businessId: PropTypes.string.isRequired, // 评论的 business_id
  462. businessUserId: PropTypes.number,
  463. API: PropTypes.string, // 评论的 API 前缀
  464. showList: PropTypes.bool, // 是否显示评论列表
  465. showEditor: PropTypes.bool, // 是否显示评论输入框
  466. showAlertComment: PropTypes.bool, // 评论成功之后,是否通过 Antd 的 Message 组件进行提示
  467. showAlertReply: PropTypes.bool, // 回复成功之后,是否通过 Antd 的 Message 组件进行提示
  468. showAlertFavor: PropTypes.bool, // 点赞/取消点赞成功之后,是否通过 Antd 的 Message 组件进行提示
  469. showError: PropTypes.bool, // 是否使用Antd的Message组件提示错误信息
  470. onError: PropTypes.func, // 错误回调, 出错了会被调用
  471. userId: PropTypes.number, // 用户id, comment内部不维护用户id, 调用组件时传递过来, 目前用于判断是否显示删除按钮
  472. pageType: PropTypes.string, // 分页类型
  473. page: PropTypes.number, // 页码
  474. limit: PropTypes.number, // 一次加载评论数量
  475. onPageChange: PropTypes.func, // 页码变化回调
  476. onGetMoreBtnClick: PropTypes.func, // 点击查看更多按钮回调
  477. onDelete: PropTypes.func,
  478. locales: PropTypes.string // 传入的语言环境, en-US/zh-CN
  479. };
  480. App.defaultProps = {
  481. businessUserId: 0,
  482. API: "//api.links123.net/comment/v1",
  483. showList: true,
  484. showEditor: true,
  485. showAlertComment: false,
  486. showAlertReply: false,
  487. showAlertFavor: false,
  488. showError: true,
  489. pageType: "more",
  490. limit: LIMIT,
  491. onGetMoreBtnClick: () => {},
  492. onPageChange: page => {},
  493. onDelete: () => {}
  494. };
  495. export { Editor, RenderText };
  496. export default App;