通用评论

App.js 16KB

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