通用评论

App.js 16KB

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