通用评论 vedio

App.js 15KB

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