通用评论

App.js 16KB

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