通用评论

App.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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["Authorization"] = `Bearer ${
  62. this.props.token
  63. }`;
  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, filterSpeak = 0 } = {}) {
  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}&is_speak=${filterSpeak}&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, error.response.data);
  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, successCallback }) {
  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. if (successCallback) {
  358. successCallback();
  359. }
  360. })
  361. .catch(error => {
  362. this.props.onCommentFail(error.response.status, error.response.data);
  363. this.errorHandler(error);
  364. })
  365. .finally(() => {
  366. this.handleChangeLoading("sUpdateComment", false);
  367. });
  368. }
  369. /**
  370. * 添加回复
  371. * 回复评论/回复回复
  372. * @param {object} data { comment_id, content, [reply_id] }
  373. */
  374. sCreateReply(data, cb) {
  375. if (!data.content) return this.error(intl.get("message.replyNoNull"));
  376. this.handleChangeLoading("sCreateReply", true);
  377. const { API } = this.props;
  378. this.axios(`${API}/replies`, {
  379. method: "post",
  380. data,
  381. withCredentials: true
  382. })
  383. .then(response => {
  384. if (this.props.showAlertReply) {
  385. message.success(intl.get("message.replySuccess"));
  386. }
  387. if (isFunction(cb)) cb(response.data);
  388. // 将数据写入到 list 中
  389. // 临时插入
  390. // 等到获取数据之后,删除临时数据
  391. const list = this.state.list.map(item => {
  392. if (item.id === data.comment_id) {
  393. if (!item.replies) item.replies = [];
  394. item.replies.push({
  395. ...response.data,
  396. isTemporary: true // 临时的数据
  397. });
  398. item.reply_count += 1;
  399. }
  400. return item;
  401. });
  402. this.setState({ list });
  403. })
  404. .catch(error => {
  405. this.props.onCommentFail(error.response.status, error.response.data);
  406. this.errorHandler(error);
  407. })
  408. .finally(() => {
  409. this.handleChangeLoading("sCreateReply", false);
  410. });
  411. }
  412. /**
  413. * 删除回复
  414. * @param {*} replyId
  415. * @param {*} commentId
  416. */
  417. sDeleteReply(replyId, commentId) {
  418. this.handleChangeLoading("sDeleteReply", true);
  419. const { API } = this.props;
  420. this.axios(`${API}/replies/${replyId}?CommentID=${commentId}`, {
  421. method: "delete",
  422. withCredentials: true
  423. })
  424. .then(() => {
  425. let deletedItem = null;
  426. const list = this.state.list.map(item => {
  427. if (item.id === commentId) {
  428. const replies = item.replies.filter(item => item.id !== replyId);
  429. deletedItem = item.replies.find(item => item.id === replyId);
  430. item.replies = replies;
  431. item.reply_count -= 1;
  432. }
  433. return item;
  434. });
  435. this.setState({ list });
  436. this.props.onDelete(COMMENT_TYPE.REPLY, deletedItem);
  437. })
  438. .catch(this.errorHandler)
  439. .finally(() => {
  440. this.handleChangeLoading("sDeleteReply", false);
  441. });
  442. }
  443. /**
  444. * 更新回复
  445. * 回复评论/回复回复
  446. * @param {object} data { comment_id, content, reply_id }
  447. */
  448. sUpdateReply({ commentId, content, replyId, replyPage, successCallback }) {
  449. this.handleChangeLoading("sUpdateReply", true);
  450. const { API } = this.props;
  451. this.axios(`${API}/replies/${replyId}`, {
  452. method: "post",
  453. data: {
  454. comment_id: commentId,
  455. content
  456. },
  457. withCredentials: true
  458. })
  459. .then(() => {
  460. for (let i = 1; i <= replyPage; i++) {
  461. this.sGetReply({ commentId, page: i });
  462. }
  463. if (successCallback) {
  464. successCallback();
  465. }
  466. this.props.onUpdateComment("reply");
  467. })
  468. .catch(error => {
  469. this.props.onCommentFail(error.response.status, error.response.data);
  470. this.errorHandler(error);
  471. })
  472. .finally(() => {
  473. this.handleChangeLoading("sUpdateReply", false);
  474. });
  475. }
  476. /**
  477. * 评论 点赞/取消点赞
  478. * @param {string} commentId { commentId }
  479. * @param {boolean} favored 是否已经点过赞
  480. */
  481. sCommentFavor(commentId, favored) {
  482. this.handleChangeLoading("sCommentFavor", true);
  483. const { API } = this.props;
  484. this.axios(`${API}/comments/${commentId}/favor`, {
  485. method: favored ? "delete" : "put",
  486. withCredentials: true
  487. })
  488. .then(response => {
  489. if (this.props.showAlertFavor) {
  490. message.success(
  491. favored
  492. ? intl.get("message.cancelLickSuccess")
  493. : intl.get("message.likeSuccess")
  494. );
  495. }
  496. // 更新 list 中的该项数据的 favored
  497. const list = this.state.list.map(item => {
  498. if (item.id === commentId) {
  499. item.favored = !favored;
  500. item.favor_count += favored ? -1 : 1;
  501. }
  502. return item;
  503. });
  504. this.setState({ list });
  505. })
  506. .catch(this.errorHandler)
  507. .finally(() => {
  508. this.handleChangeLoading("sCommentFavor", false);
  509. });
  510. }
  511. /**
  512. * 回复 点赞/取消点赞
  513. * @param {string} replyId replyId
  514. * @param {string} commentId commentId
  515. * @param {boolean} favored 是否已经点过赞
  516. */
  517. sReplyFavor(replyId, commentId, favored) {
  518. this.handleChangeLoading("sReplyFavor", true);
  519. const { API } = this.props;
  520. this.axios(`${API}/replies/${replyId}/favor`, {
  521. method: favored ? "delete" : "put",
  522. data: {
  523. comment_id: commentId
  524. },
  525. withCredentials: true
  526. })
  527. .then(response => {
  528. message.success(
  529. favored
  530. ? intl.get("message.cancelLickSuccess")
  531. : intl.get("message.likeSuccess")
  532. );
  533. // 更新 list 中的该项数据的 favored
  534. const list = this.state.list.map(item => {
  535. if (item.id === commentId) {
  536. item.replies = item.replies.map(r => {
  537. if (r.id === replyId) {
  538. r.favored = !favored;
  539. // r.favor_count = response.data.favor_count;
  540. // 点赞数 +1,而不是使用后端返回的点赞数
  541. // 不然如果返回的不是增加 1,用户可能以为程序错误
  542. r.favor_count += favored ? -1 : 1;
  543. }
  544. return r;
  545. });
  546. }
  547. return item;
  548. });
  549. this.setState({ list });
  550. })
  551. .catch(this.errorHandler)
  552. .finally(() => {
  553. this.handleChangeLoading("sReplyFavor", false);
  554. });
  555. }
  556. /**
  557. * 获取 OSS 上传的参数
  558. */
  559. sOssSts() {
  560. this.handleChangeLoading("sOssSts", true);
  561. const { API } = this.props;
  562. this.axios
  563. .get(`${API}/oss/sts`)
  564. .then(response => {
  565. this.setState({ oss: { ...response.data } });
  566. })
  567. .catch(this.errorHandler)
  568. .finally(() => {
  569. this.handleChangeLoading("sOssSts", false);
  570. });
  571. }
  572. render() {
  573. // 添加到 Context 的数据
  574. const value = {
  575. ...this.state,
  576. ...this.props,
  577. sCreateComment: this.sCreateComment,
  578. sGetComment: this.sGetComment,
  579. sCommentFavor: this.sCommentFavor,
  580. sReplyFavor: this.sReplyFavor,
  581. sCreateReply: this.sCreateReply,
  582. sGetReply: this.sGetReply,
  583. sOssSts: this.sOssSts,
  584. sDeleteComment: this.sDeleteComment,
  585. sDeleteReply: this.sDeleteReply,
  586. sUpdateReply: this.sUpdateReply,
  587. sUpdateComment: this.sUpdateComment,
  588. handleEdit: this.handleEdit
  589. };
  590. return (
  591. this.state.initDone && (
  592. <CommentContext.Provider value={value}>
  593. <div className="comment">
  594. {this.props.showEditor && (
  595. <CommentInput content={this.props.children} />
  596. )}
  597. {this.props.showList && (
  598. <div style={{ marginTop: 20 }}>
  599. <CommentList />
  600. </div>
  601. )}
  602. </div>
  603. {this.state.editModalVisible && (
  604. <EditComment
  605. visible={this.state.editModalVisible}
  606. action={this.state.action}
  607. replyId={this.state.replyId}
  608. replyPage={this.state.replyPage}
  609. commentId={this.state.commentId}
  610. userId={this.state.content.user_id}
  611. content={this.state.content}
  612. handleClose={this.handleClose}
  613. preRenderValue={this.props.preRenderValue}
  614. />
  615. )}
  616. </CommentContext.Provider>
  617. )
  618. );
  619. }
  620. }
  621. App.propTypes = {
  622. type: PropTypes.number.isRequired, // 评论的 type
  623. businessId: PropTypes.string.isRequired, // 评论的 business_id
  624. businessUserId: PropTypes.number,
  625. API: PropTypes.string, // 评论的 API 前缀
  626. showList: PropTypes.bool, // 是否显示评论列表
  627. showEditor: PropTypes.bool, // 是否显示评论输入框
  628. showAlertComment: PropTypes.bool, // 评论成功之后,是否通过 Antd 的 Message 组件进行提示
  629. showAlertReply: PropTypes.bool, // 回复成功之后,是否通过 Antd 的 Message 组件进行提示
  630. showAlertFavor: PropTypes.bool, // 点赞/取消点赞成功之后,是否通过 Antd 的 Message 组件进行提示
  631. showError: PropTypes.bool, // 是否使用Antd的Message组件提示错误信息
  632. onError: PropTypes.func, // 错误回调, 出错了会被调用
  633. userId: PropTypes.number, // 用户id, comment内部不维护用户id, 调用组件时传递过来, 目前用于判断是否显示删除按钮
  634. pageType: PropTypes.string, // 分页类型
  635. page: PropTypes.number, // 页码
  636. limit: PropTypes.number, // 一次加载评论数量
  637. onPageChange: PropTypes.func, // 页码变化回调
  638. onGetMoreBtnClick: PropTypes.func, // 点击查看更多按钮回调
  639. onDelete: PropTypes.func,
  640. onUpdateComment: PropTypes.func,
  641. locales: PropTypes.string, // 传入的语言环境, en-US/zh-CN
  642. onCountChange: PropTypes.func, // 评论数量变更时的回调
  643. onCommentFail: PropTypes.func, // 评论失败时的回调
  644. preRenderValue: PropTypes.func // 编辑器渲染前对值需要做的工作
  645. };
  646. App.defaultProps = {
  647. businessUserId: 0,
  648. API: "//api.links123.net/comment/v1",
  649. emojiAPI: "//api.links123.net/link/v1",
  650. LOGINLINK:
  651. process.env.RUN_MOD === "production"
  652. ? "https://passport.links123.com/login"
  653. : "http://test.links123.net:5050/login",
  654. showList: true,
  655. showEditor: true,
  656. showAlertComment: false,
  657. showAlertReply: false,
  658. showAlertFavor: false,
  659. showError: true,
  660. showEdit: false,
  661. pageType: "more",
  662. limit: LIMIT,
  663. onGetMoreBtnClick: () => {},
  664. onPageChange: page => {},
  665. onDelete: () => {},
  666. onUpdateComment: () => {},
  667. onBeforeUpdateComment: () => {},
  668. onCountChange: () => {},
  669. onCommentFail: () => {},
  670. preRenderValue: v => v
  671. };
  672. export { Editor, RenderText };
  673. export default App;