通用评论

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