通用评论

App.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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 EditComment from "./components/EditComment/EditComment";
  15. import { SUPPORT_LOCALES, LOCALES_RESPONSE } from "./lang";
  16. import "./App.css";
  17. class App extends Component {
  18. constructor(props) {
  19. super(props);
  20. this.state = {
  21. loading: {},
  22. // oss 配置
  23. oss: {},
  24. // 评论数据
  25. list: [],
  26. page: 1,
  27. total: 0,
  28. // 是否没有更多评论了
  29. isNoMoreComment: false,
  30. initDone: false,
  31. locale: "zh-CN",
  32. editModalVisible: false,
  33. action: "",
  34. replyId: "",
  35. commentId: "",
  36. userId: "",
  37. content: "",
  38. replyPage: 1,
  39. emojiList: []
  40. };
  41. this.handleChangeLoading = this.handleChangeLoading.bind(this);
  42. this.sCreateComment = this.sCreateComment.bind(this);
  43. this.sUpdateComment = this.sUpdateComment.bind(this);
  44. this.sDeleteComment = this.sDeleteComment.bind(this);
  45. this.sCommentFavor = this.sCommentFavor.bind(this);
  46. this.sCreateReply = this.sCreateReply.bind(this);
  47. this.sDeleteReply = this.sDeleteReply.bind(this);
  48. this.errorHandler = this.errorHandler.bind(this);
  49. this.sGetComment = this.sGetComment.bind(this);
  50. this.sReplyFavor = this.sReplyFavor.bind(this);
  51. this.sGetReply = this.sGetReply.bind(this);
  52. this.sUpdateReply = this.sUpdateReply.bind(this);
  53. this.sOssSts = this.sOssSts.bind(this);
  54. this.handleEdit = this.handleEdit.bind(this);
  55. this.handleClose = this.handleClose.bind(this);
  56. }
  57. componentWillMount() {
  58. this.axios = axios;
  59. this.axios.defaults.withCredentials = true;
  60. if (this.props.token) {
  61. this.axios.defaults.headers.common[
  62. "Authorization"
  63. ] = `Bearer ${this.props.token}`;
  64. }
  65. }
  66. componentDidMount() {
  67. this.loadLocales();
  68. this.loadEmoji();
  69. }
  70. /**
  71. * 加载语言包
  72. * 只能根据url或者传入的props来确定加载哪个语言包
  73. * 优先级:传入的props > url
  74. */
  75. loadLocales() {
  76. let { locales: currentLocale } = this.props;
  77. const cookieLang = Cookies.get("lnk_lang");
  78. if (!currentLocale) {
  79. currentLocale =
  80. cookieLang ||
  81. intl.determineLocale({
  82. urlLocaleKey: "lang"
  83. });
  84. }
  85. currentLocale = SUPPORT_LOCALES.find(item => item.value === currentLocale)
  86. ? currentLocale
  87. : "zh-CN";
  88. const version = require("./version.json").hash;
  89. // 使用绝对路径
  90. const languageURL = `${LANGUAGE_LINK}/${currentLocale}.json?v=${version}`;
  91. return fetch(languageURL)
  92. .then(response => {
  93. if (response.status >= 400) {
  94. throw new Error("Bad response from server");
  95. }
  96. return response.json();
  97. })
  98. .then(data => {
  99. // console.log('data: ', data);
  100. intl
  101. .init({
  102. currentLocale,
  103. locales: {
  104. [currentLocale]: data
  105. }
  106. })
  107. .then(() => {
  108. this.setState({ initDone: true, locale: currentLocale });
  109. });
  110. });
  111. }
  112. /**
  113. * 加载表情包
  114. */
  115. loadEmoji() {
  116. this.axios
  117. .get(`${this.props.emojiAPI}/emoticons`)
  118. .then(response => {
  119. const emojiMap = {};
  120. response.data.list.forEach(item => {
  121. emojiMap[item.name] = item.url;
  122. });
  123. window.sessionStorage.setItem("emojiMap", JSON.stringify(emojiMap));
  124. this.setState({ emojiList: response.data.list });
  125. })
  126. .catch(this.errorHandler);
  127. }
  128. handleEdit({ replyId, commentId, userId, content, replyPage }) {
  129. this.setState({
  130. editModalVisible: true,
  131. action: content.replies
  132. ? "comment"
  133. : content.reply
  134. ? "replyToReply"
  135. : "reply",
  136. replyId,
  137. commentId,
  138. userId,
  139. content,
  140. replyPage
  141. });
  142. }
  143. handleClose() {
  144. this.setState({
  145. editModalVisible: false
  146. });
  147. }
  148. error(msg, info = {}) {
  149. if (this.props.showError) {
  150. message.error(msg);
  151. }
  152. if (this.props.onError) {
  153. this.props.onError(msg, info);
  154. }
  155. }
  156. errorHandler(error) {
  157. const { locale } = this.state;
  158. const localResponse = LOCALES_RESPONSE[locale];
  159. if (error.response && error.response.data && error.response.data.msg) {
  160. this.error(localResponse[error.response.data.msg] || ERROR_DEFAULT, {
  161. response: error.response
  162. });
  163. return;
  164. }
  165. this.error(localResponse[error.response.data.msg] || ERROR_DEFAULT, {
  166. response: error.response
  167. });
  168. }
  169. /**
  170. * 改变 loading 状态
  171. * @param {string} key key
  172. * @param {string} value value
  173. */
  174. handleChangeLoading(key, value) {
  175. const { loading } = this.state;
  176. loading[key] = value;
  177. this.setState({ loading });
  178. }
  179. /**
  180. * 获取评论列表
  181. */
  182. sGetComment({ page = 1 } = {}) {
  183. const { pageType } = this.props;
  184. this.handleChangeLoading("sGetComment", true);
  185. const { API, type, businessId, limit } = this.props;
  186. this.axios
  187. .get(
  188. `${API}/comments?type=${type}&business_id=${businessId}&page=${page}&limit=${limit}`
  189. )
  190. .then(response => {
  191. const { list, page, total } = response.data;
  192. if (list) {
  193. let newList = list;
  194. let { list: oldList } = this.state;
  195. if (pageType === "more") {
  196. if (page > 1) {
  197. // 删除临时数据
  198. oldList = oldList.filter(o => !o.isTemporary);
  199. newList = oldList.concat(newList);
  200. }
  201. } else if (pageType === "pagination") {
  202. // TODO 滚动到顶部
  203. window.scrollTo(0, 0);
  204. }
  205. this.setState({
  206. list: newList,
  207. page,
  208. total
  209. });
  210. this.props.onCountChange(total);
  211. } else {
  212. message.info(intl.get("message.noMoreComment"));
  213. this.setState({
  214. isNoMoreComment: true
  215. });
  216. }
  217. })
  218. .catch(this.errorHandler)
  219. .finally(() => {
  220. this.handleChangeLoading("sGetComment", false);
  221. });
  222. }
  223. /**
  224. * 获取更多回复
  225. */
  226. sGetReply({ commentId, page = 1 } = {}) {
  227. this.handleChangeLoading("sGetReply", true);
  228. const { API, limit } = this.props;
  229. this.axios
  230. .get(`${API}/replies?comment_id=${commentId}&page=${page}&limit=${limit}`)
  231. .then(response => {
  232. if (!response.data.list) {
  233. message.info(intl.get("message.noMoreData"));
  234. }
  235. const list = this.state.list.map(item => {
  236. if (item.id === commentId) {
  237. if (!item.replies) item.replies = [];
  238. if (response.data.list) {
  239. if (page === 1) {
  240. // 如果当前页数为第一页,则清空当前所有的 replies
  241. // 并将获取到的 replies 存放在 state
  242. item.replies = response.data.list;
  243. } else {
  244. item.replies = item.replies
  245. .filter(o => !o.isTemporary)
  246. .concat(response.data.list);
  247. // 如果当前页数非第一页,则合并 replies
  248. }
  249. item.reply_count = response.data.total;
  250. item.reply_page = response.data.page;
  251. } else {
  252. item.isNoMoreReply = true;
  253. }
  254. }
  255. return item;
  256. });
  257. this.setState({ list });
  258. })
  259. .catch(this.errorHandler)
  260. .finally(() => {
  261. this.handleChangeLoading("sGetReply", false);
  262. });
  263. }
  264. /**
  265. * 添加评论
  266. * @param {object} {content} comment content
  267. */
  268. sCreateComment({ content } = {}, cb) {
  269. if (!content) return this.error(intl.get("message.notNull"));
  270. this.handleChangeLoading("sCreateComment", true);
  271. const { API, type, businessId, businessUserId } = this.props;
  272. this.axios(`${API}/comments`, {
  273. method: "post",
  274. data: {
  275. type,
  276. business_id: businessId,
  277. business_user_id: businessUserId,
  278. content
  279. },
  280. withCredentials: true
  281. })
  282. .then(response => {
  283. if (this.props.showAlertComment) {
  284. message.success(intl.get("message.success"));
  285. }
  286. if (isFunction(cb)) cb(response.data);
  287. // 将数据写入到 list 中
  288. // 临时插入
  289. // 等到获取数据之后,删除临时数据
  290. const { list, total } = this.state;
  291. list.unshift({
  292. ...response.data,
  293. replies: [],
  294. isTemporary: true // 临时的数据
  295. });
  296. this.setState({ list, total: total + 1 });
  297. this.props.onCountChange(total + 1);
  298. })
  299. .catch(error => {
  300. this.props.onCommentFail(error.response.status);
  301. this.errorHandler(error);
  302. })
  303. .finally(() => {
  304. this.handleChangeLoading("sCreateComment", false);
  305. });
  306. }
  307. /**
  308. * 删除评论
  309. */
  310. sDeleteComment(commentId) {
  311. this.handleChangeLoading("sDeleteComment", true);
  312. const { API } = this.props;
  313. this.axios(`${API}/comments/${commentId}`, {
  314. method: "delete",
  315. withCredentials: true
  316. })
  317. .then(() => {
  318. const { list, total } = this.state;
  319. const res = list.filter(item => item.id !== commentId);
  320. const deletedItem = list.find(item => item.id === commentId);
  321. this.setState({ list: res, total: total - 1 });
  322. this.props.onDelete(COMMENT_TYPE.COMMENT, deletedItem);
  323. this.props.onCountChange(total - 1);
  324. })
  325. .catch(this.errorHandler)
  326. .finally(() => {
  327. this.handleChangeLoading("sDeleteComment", false);
  328. });
  329. }
  330. /**
  331. * 更新评论
  332. * @param {object} {content} comment content
  333. */
  334. sUpdateComment({ commentId, content }) {
  335. this.handleChangeLoading("sUpdateComment", true);
  336. const { API } = this.props;
  337. this.axios(`${API}/comments/${commentId}`, {
  338. method: "post",
  339. data: {
  340. content
  341. },
  342. withCredentials: true
  343. })
  344. .then(() => {
  345. let { list } = this.state;
  346. list = list.map(it => {
  347. if (it.id === commentId) {
  348. return {
  349. ...it,
  350. content
  351. };
  352. }
  353. return it;
  354. });
  355. this.props.onUpdateComment("comment");
  356. this.setState({ list });
  357. })
  358. .catch(this.errorHandler)
  359. .finally(() => {
  360. this.handleChangeLoading("sUpdateComment", false);
  361. });
  362. }
  363. /**
  364. * 添加回复
  365. * 回复评论/回复回复
  366. * @param {object} data { comment_id, content, [reply_id] }
  367. */
  368. sCreateReply(data, cb) {
  369. if (!data.content) return this.error(intl.get("message.replyNoNull"));
  370. this.handleChangeLoading("sCreateReply", true);
  371. const { API } = this.props;
  372. this.axios(`${API}/replies`, {
  373. method: "post",
  374. data,
  375. withCredentials: true
  376. })
  377. .then(response => {
  378. if (this.props.showAlertReply) {
  379. message.success(intl.get("message.replySuccess"));
  380. }
  381. if (isFunction(cb)) cb(response.data);
  382. // 将数据写入到 list 中
  383. // 临时插入
  384. // 等到获取数据之后,删除临时数据
  385. const list = this.state.list.map(item => {
  386. if (item.id === data.comment_id) {
  387. if (!item.replies) item.replies = [];
  388. item.replies.push({
  389. ...response.data,
  390. isTemporary: true // 临时的数据
  391. });
  392. item.reply_count += 1;
  393. }
  394. return item;
  395. });
  396. this.setState({ list });
  397. })
  398. .catch(error => {
  399. this.props.onCommentFail(error.response.status);
  400. this.errorHandler(error);
  401. })
  402. .finally(() => {
  403. this.handleChangeLoading("sCreateReply", false);
  404. });
  405. }
  406. /**
  407. * 删除回复
  408. * @param {*} replyId
  409. * @param {*} commentId
  410. */
  411. sDeleteReply(replyId, commentId) {
  412. this.handleChangeLoading("sDeleteReply", true);
  413. const { API } = this.props;
  414. this.axios(`${API}/replies/${replyId}?CommentID=${commentId}`, {
  415. method: "delete",
  416. withCredentials: true
  417. })
  418. .then(() => {
  419. let deletedItem = null;
  420. const list = this.state.list.map(item => {
  421. if (item.id === commentId) {
  422. const replies = item.replies.filter(item => item.id !== replyId);
  423. deletedItem = item.replies.find(item => item.id === replyId);
  424. item.replies = replies;
  425. item.reply_count -= 1;
  426. }
  427. return item;
  428. });
  429. this.setState({ list });
  430. this.props.onDelete(COMMENT_TYPE.REPLY, deletedItem);
  431. })
  432. .catch(this.errorHandler)
  433. .finally(() => {
  434. this.handleChangeLoading("sDeleteReply", false);
  435. });
  436. }
  437. /**
  438. * 更新回复
  439. * 回复评论/回复回复
  440. * @param {object} data { comment_id, content, reply_id }
  441. */
  442. sUpdateReply({ commentId, content, replyId, replyPage }) {
  443. this.handleChangeLoading("sUpdateReply", true);
  444. const { API } = this.props;
  445. this.axios(`${API}/replies/${replyId}`, {
  446. method: "post",
  447. data: {
  448. comment_id: commentId,
  449. content
  450. },
  451. withCredentials: true
  452. })
  453. .then(() => {
  454. for (let i = 1; i <= replyPage; i++) {
  455. this.sGetReply({ commentId, page: i });
  456. }
  457. this.props.onUpdateComment("reply");
  458. })
  459. .catch(this.errorHandler)
  460. .finally(() => {
  461. this.handleChangeLoading("sUpdateReply", false);
  462. });
  463. }
  464. /**
  465. * 评论 点赞/取消点赞
  466. * @param {string} commentId { commentId }
  467. * @param {boolean} favored 是否已经点过赞
  468. */
  469. sCommentFavor(commentId, favored) {
  470. this.handleChangeLoading("sCommentFavor", true);
  471. const { API } = this.props;
  472. this.axios(`${API}/comments/${commentId}/favor`, {
  473. method: favored ? "delete" : "put",
  474. withCredentials: true
  475. })
  476. .then(response => {
  477. if (this.props.showAlertFavor) {
  478. message.success(
  479. favored
  480. ? intl.get("message.cancelLickSuccess")
  481. : intl.get("message.likeSuccess")
  482. );
  483. }
  484. // 更新 list 中的该项数据的 favored
  485. const list = this.state.list.map(item => {
  486. if (item.id === commentId) {
  487. item.favored = !favored;
  488. item.favor_count += favored ? -1 : 1;
  489. }
  490. return item;
  491. });
  492. this.setState({ list });
  493. })
  494. .catch(this.errorHandler)
  495. .finally(() => {
  496. this.handleChangeLoading("sCommentFavor", false);
  497. });
  498. }
  499. /**
  500. * 回复 点赞/取消点赞
  501. * @param {string} replyId replyId
  502. * @param {string} commentId commentId
  503. * @param {boolean} favored 是否已经点过赞
  504. */
  505. sReplyFavor(replyId, commentId, favored) {
  506. this.handleChangeLoading("sReplyFavor", true);
  507. const { API } = this.props;
  508. this.axios(`${API}/replies/${replyId}/favor`, {
  509. method: favored ? "delete" : "put",
  510. data: {
  511. comment_id: commentId
  512. },
  513. withCredentials: true
  514. })
  515. .then(response => {
  516. message.success(
  517. favored
  518. ? intl.get("message.cancelLickSuccess")
  519. : intl.get("message.likeSuccess")
  520. );
  521. // 更新 list 中的该项数据的 favored
  522. const list = this.state.list.map(item => {
  523. if (item.id === commentId) {
  524. item.replies = item.replies.map(r => {
  525. if (r.id === replyId) {
  526. r.favored = !favored;
  527. // r.favor_count = response.data.favor_count;
  528. // 点赞数 +1,而不是使用后端返回的点赞数
  529. // 不然如果返回的不是增加 1,用户可能以为程序错误
  530. r.favor_count += favored ? -1 : 1;
  531. }
  532. return r;
  533. });
  534. }
  535. return item;
  536. });
  537. this.setState({ list });
  538. })
  539. .catch(this.errorHandler)
  540. .finally(() => {
  541. this.handleChangeLoading("sReplyFavor", false);
  542. });
  543. }
  544. /**
  545. * 获取 OSS 上传的参数
  546. */
  547. sOssSts() {
  548. this.handleChangeLoading("sOssSts", true);
  549. const { API } = this.props;
  550. this.axios
  551. .get(`${API}/oss/sts`)
  552. .then(response => {
  553. this.setState({ oss: { ...response.data } });
  554. })
  555. .catch(this.errorHandler)
  556. .finally(() => {
  557. this.handleChangeLoading("sOssSts", false);
  558. });
  559. }
  560. render() {
  561. // 添加到 Context 的数据
  562. const value = {
  563. ...this.state,
  564. ...this.props,
  565. sCreateComment: this.sCreateComment,
  566. sGetComment: this.sGetComment,
  567. sCommentFavor: this.sCommentFavor,
  568. sReplyFavor: this.sReplyFavor,
  569. sCreateReply: this.sCreateReply,
  570. sGetReply: this.sGetReply,
  571. sOssSts: this.sOssSts,
  572. sDeleteComment: this.sDeleteComment,
  573. sDeleteReply: this.sDeleteReply,
  574. sUpdateReply: this.sUpdateReply,
  575. sUpdateComment: this.sUpdateComment,
  576. handleEdit: this.handleEdit
  577. };
  578. return (
  579. this.state.initDone && (
  580. <CommentContext.Provider value={value}>
  581. <div className="comment">
  582. {this.props.showEditor && (
  583. <CommentInput content={this.props.children} />
  584. )}
  585. {this.props.showList && (
  586. <div style={{ marginTop: 20 }}>
  587. <CommentList />
  588. </div>
  589. )}
  590. </div>
  591. {this.state.editModalVisible && (
  592. <EditComment
  593. visible={this.state.editModalVisible}
  594. action={this.state.action}
  595. replyId={this.state.replyId}
  596. replyPage={this.state.replyPage}
  597. commentId={this.state.commentId}
  598. userId={this.state.content.user_id}
  599. content={this.state.content}
  600. handleClose={this.handleClose}
  601. preRenderValue={this.props.preRenderValue}
  602. />
  603. )}
  604. </CommentContext.Provider>
  605. )
  606. );
  607. }
  608. }
  609. App.propTypes = {
  610. type: PropTypes.number.isRequired, // 评论的 type
  611. businessId: PropTypes.string.isRequired, // 评论的 business_id
  612. businessUserId: PropTypes.number,
  613. API: PropTypes.string, // 评论的 API 前缀
  614. showList: PropTypes.bool, // 是否显示评论列表
  615. showEditor: PropTypes.bool, // 是否显示评论输入框
  616. showAlertComment: PropTypes.bool, // 评论成功之后,是否通过 Antd 的 Message 组件进行提示
  617. showAlertReply: PropTypes.bool, // 回复成功之后,是否通过 Antd 的 Message 组件进行提示
  618. showAlertFavor: PropTypes.bool, // 点赞/取消点赞成功之后,是否通过 Antd 的 Message 组件进行提示
  619. showError: PropTypes.bool, // 是否使用Antd的Message组件提示错误信息
  620. onError: PropTypes.func, // 错误回调, 出错了会被调用
  621. userId: PropTypes.number, // 用户id, comment内部不维护用户id, 调用组件时传递过来, 目前用于判断是否显示删除按钮
  622. pageType: PropTypes.string, // 分页类型
  623. page: PropTypes.number, // 页码
  624. limit: PropTypes.number, // 一次加载评论数量
  625. onPageChange: PropTypes.func, // 页码变化回调
  626. onGetMoreBtnClick: PropTypes.func, // 点击查看更多按钮回调
  627. onDelete: PropTypes.func,
  628. onUpdateComment: PropTypes.func,
  629. locales: PropTypes.string, // 传入的语言环境, en-US/zh-CN
  630. onCountChange: PropTypes.func, // 评论数量变更时的回调
  631. onCommentFail: PropTypes.func, // 评论失败时的回调
  632. preRenderValue: PropTypes.func // 编辑器渲染前对值需要做的工作
  633. };
  634. App.defaultProps = {
  635. businessUserId: 0,
  636. API: "//api.links123.net/comment/v1",
  637. emojiAPI: "//api.links123.net/link/v1",
  638. LOGINLINK:
  639. process.env.RUN_MOD === "production"
  640. ? "https://passport.links123.com/login"
  641. : "http://test.links123.net:5050/login",
  642. showList: true,
  643. showEditor: true,
  644. showAlertComment: false,
  645. showAlertReply: false,
  646. showAlertFavor: false,
  647. showError: true,
  648. showEdit: false,
  649. pageType: "more",
  650. limit: LIMIT,
  651. onGetMoreBtnClick: () => {},
  652. onPageChange: page => {},
  653. onDelete: () => {},
  654. onUpdateComment: () => {},
  655. onBeforeUpdateComment: () => {},
  656. onCountChange: () => {},
  657. onCommentFail: () => {},
  658. preRenderValue: v => v
  659. };
  660. export { Editor, RenderText };
  661. export default App;