通用评论

App.js 16KB

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