通用评论

index.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. import React, { Fragment } from "react";
  2. import PropTypes from "prop-types";
  3. import { Icon, Button, Popover, Input, message } from "antd";
  4. import classnames from "classnames";
  5. import intl from "react-intl-universal";
  6. import dayjs from "dayjs";
  7. import shortid from "shortid";
  8. import { OSS_LINK } from "../../constant";
  9. import { isFunction } from "../../helper";
  10. import Upload from "./Upload";
  11. import Emoji from "./Emoji";
  12. import Comment from "../../Comment";
  13. import {
  14. OSS_ENDPOINT,
  15. OSS_BUCKET,
  16. DRIVER_LICENSE_PATH,
  17. ERROR_DEFAULT
  18. } from "../../constant";
  19. import "./index.css";
  20. const { TextArea } = Input;
  21. const client = oss => {
  22. return new window.OSS.Wrapper({
  23. accessKeyId: oss.access_key_id,
  24. accessKeySecret: oss.access_key_secret,
  25. stsToken: oss.security_token,
  26. endpoint: OSS_ENDPOINT, //常量,你可以自己定义
  27. bucket: OSS_BUCKET
  28. });
  29. };
  30. const uploadPath = (path, file) => {
  31. return `${path}/${dayjs().format("YYYYMMDD")}/${shortid.generate()}.${
  32. file.type.split("/")[1]
  33. }`;
  34. };
  35. const UploadToOss = (oss, path, file) => {
  36. const url = uploadPath(path, file);
  37. return new Promise((resolve, reject) => {
  38. client(oss)
  39. .multipartUpload(url, file)
  40. .then(data => {
  41. resolve(data);
  42. })
  43. .catch(error => {
  44. reject(error);
  45. });
  46. });
  47. };
  48. class Editor extends React.Component {
  49. constructor(props) {
  50. super(props);
  51. this.state = {
  52. showUpload: false,
  53. value: props.value || "", // 编辑器里面的值
  54. fileList: props.fileList || [], // 图片列表
  55. fileMap: {}, // 已经上传的图片路径和 uid 的映射 { uid: path }
  56. uploadVisible: false
  57. };
  58. this.handleChange = this.handleChange.bind(this);
  59. this.handleClickEmoji = this.handleClickEmoji.bind(this);
  60. this.handleChangeFileList = this.handleChangeFileList.bind(this);
  61. this.handleShowUpload = this.handleShowUpload.bind(this);
  62. this.handleUpload = this.handleUpload.bind(this);
  63. this.handleSubmit = this.handleSubmit.bind(this);
  64. this.handlePaste = this.handlePaste.bind(this);
  65. this.resetState = this.resetState.bind(this);
  66. this.handleEmojiScroll = this.handleEmojiScroll.bind(this);
  67. }
  68. componentDidMount() {
  69. const { app, onRef } = this.props;
  70. if (
  71. app.currentUser &&
  72. (app.currentUser.user_id > 0 || app.currentUser.id > 0)
  73. ) {
  74. app.sOssSts();
  75. }
  76. if (isFunction(onRef)) {
  77. onRef(this);
  78. }
  79. }
  80. handleEmojiScroll(e) {
  81. if (!this.emoji) {
  82. return;
  83. }
  84. e.preventDefault();
  85. if (e.deltaY > 0) {
  86. this.emoji.next();
  87. } else if (e.deltaY < 0) {
  88. this.emoji.prev();
  89. }
  90. }
  91. /**
  92. * 编辑器的值改变事件
  93. * 将最新的值存储到 state 中
  94. * @param {string} value 输入的值
  95. */
  96. handleChange(value) {
  97. this.setState({ value });
  98. if (this.props.onChange) {
  99. this.props.onChange(value);
  100. }
  101. }
  102. /**
  103. * 点击 emoji 的事件
  104. * 点击后,需要将改 emoji 插入到编辑器中
  105. * 插入的值为 [emoji chinese name]
  106. * 参数 emoji 即为 emoji chinese name
  107. * @param {string}} emoji emoji 的中文,如 微笑
  108. */
  109. handleClickEmoji(emoji) {
  110. let value = this.props.value || this.state.value;
  111. value += `[${emoji}]`;
  112. this.handleChange(value);
  113. }
  114. /**
  115. * 监听文件列表改变事件
  116. * @param {Array} fileList 文件列表
  117. */
  118. handleChangeFileList(fileList) {
  119. let list = fileList;
  120. if (fileList.length > this.props.maxUpload) {
  121. list = fileList.slice(0, this.props.maxUpload);
  122. }
  123. this.props.handleChangeFileList(list);
  124. this.setState({ fileList: list });
  125. }
  126. /**
  127. * 控制上传 Popover 的显示和隐藏
  128. * @param {boolean} showUpload 是否显示上传的 Popover
  129. */
  130. handleShowUpload(showUpload) {
  131. if (typeof showUpload === "boolean") {
  132. this.setState({ showUpload: showUpload });
  133. } else {
  134. this.setState({ showUpload: !this.state.showUpload });
  135. }
  136. }
  137. /**
  138. * 上传文件
  139. * @param {object} param 文件对象
  140. */
  141. handleUpload({ uid, path }) {
  142. const { fileMap } = this.state;
  143. let { fileList } = this.state;
  144. fileMap[uid] = path;
  145. fileList = fileList.map(item => {
  146. if (item.uid === uid) {
  147. item.thumbUrl = OSS_LINK + path;
  148. }
  149. return item;
  150. });
  151. this.props.handleChangeFileList(fileList);
  152. this.setState({ fileMap, fileList });
  153. }
  154. /**
  155. * 粘贴回调
  156. */
  157. handlePaste(e) {
  158. if (this.state.fileList.length >= this.props.maxUpload) {
  159. return;
  160. }
  161. const items = e.clipboardData && e.clipboardData.items;
  162. let file = null;
  163. if (items && items.length) {
  164. for (let i = 0; i < items.length; i++) {
  165. if (items[i].type.indexOf("image") !== -1) {
  166. file = items[i].getAsFile();
  167. break;
  168. }
  169. }
  170. if (file === null) return;
  171. }
  172. this.setState({
  173. uploadVisible: true
  174. });
  175. let reader = new FileReader();
  176. reader.readAsDataURL(file);
  177. reader.onloadend = () => {
  178. // DRIVER_LICENSE_PATH oss 的存储路径位置
  179. UploadToOss(this.props.app.oss, DRIVER_LICENSE_PATH, file)
  180. .then(data => {
  181. const fileList = this.state.fileList.concat({
  182. url: OSS_LINK + data.name,
  183. thumbUrl: OSS_LINK + data.name,
  184. type: file.type,
  185. uid: new Date().valueOf()
  186. });
  187. this.props.handleChangeFileList(fileList);
  188. this.setState({
  189. fileList
  190. });
  191. })
  192. .catch(e => {
  193. const msg = e.message || ERROR_DEFAULT;
  194. if (this.props.showError) {
  195. message.error(msg);
  196. }
  197. if (this.props.onError) {
  198. this.props.onError(msg, { response: e.response });
  199. }
  200. });
  201. };
  202. }
  203. /**
  204. * 提交编辑器内容
  205. * 提交功能,交给父组件来实现
  206. * 需要父组件传入 onSubmit
  207. */
  208. handleSubmit() {
  209. const { maxLength } = this.props;
  210. let { value, fileMap, fileList } = this.state;
  211. if (value.length > maxLength) {
  212. // message.error(`字数不得超过${maxLength}字`);
  213. message.error(intl.get("editor.maxLength", { maxLength }));
  214. return;
  215. }
  216. const files = [];
  217. if (fileList.length) {
  218. fileList.forEach(item => {
  219. if (item.url) {
  220. files.push(item.url);
  221. return;
  222. }
  223. if (!fileMap[item.uid]) {
  224. return;
  225. }
  226. files.push(`${OSS_LINK}${fileMap[item.uid]}`);
  227. });
  228. }
  229. if (this.props.beforeSubmit) {
  230. Promise.resolve(this.props.beforeSubmit({ text: value, files })).then(
  231. res => {
  232. if (!(res === false)) {
  233. this.props.onSubmit({ text: value, files }, (res, action) => {
  234. this.resetState();
  235. if (action === "comment" && this.props.onCommentSuccess) {
  236. this.props.onCommentSuccess(res);
  237. }
  238. });
  239. }
  240. }
  241. );
  242. } else {
  243. this.props.onSubmit({ text: value, files }, (res, action) => {
  244. this.resetState();
  245. if (action === "comment" && this.props.onCommentSuccess) {
  246. this.props.onCommentSuccess(res);
  247. }
  248. });
  249. }
  250. }
  251. resetState() {
  252. this.handleChange("");
  253. this.handleChangeFileList([]);
  254. this.setState({
  255. showUpload: false,
  256. value: "",
  257. fileList: [],
  258. fileMap: {}
  259. });
  260. }
  261. checkDisabledSubmit() {
  262. const { btnDisabled, value, fileList } = this.props;
  263. if (btnDisabled) {
  264. return true;
  265. }
  266. if (value && value !== "") {
  267. return false;
  268. }
  269. if (this.state.value && this.state.value !== "") {
  270. return false;
  271. }
  272. if (fileList && fileList.length > 0) {
  273. return false;
  274. }
  275. if (this.state.fileList.length > 0) {
  276. return false;
  277. }
  278. return true;
  279. }
  280. render() {
  281. const {
  282. value,
  283. // placeholder,
  284. rows,
  285. showEmoji,
  286. showUpload,
  287. multiple,
  288. emojiPopoverPlacement,
  289. uploadPopoverPlacement,
  290. uploadOverlayClassName,
  291. fileList,
  292. maxUpload,
  293. // btnSubmitText,
  294. btnLoading,
  295. button,
  296. emojiToolIcon,
  297. imageToolIcon,
  298. maxLength,
  299. autoFocus,
  300. app
  301. } = this.props;
  302. let placeholder = this.props.placeholder || intl.get("editor.placeholder");
  303. let btnSubmitText =
  304. this.props.btnSubmitText || intl.get("editor.SubmitBtn");
  305. const handleSubmit = this.handleSubmit;
  306. const disabledSubmit = this.checkDisabledSubmit();
  307. const inputValue = value || this.state.value;
  308. const uploadFileList = fileList || this.state.fileList;
  309. const isLogin =
  310. app.currentUser &&
  311. (app.currentUser.user_id > 0 || app.currentUser.id > 0);
  312. return (
  313. <div className="comment-editor-container" onPaste={this.handlePaste}>
  314. {isLogin ? (
  315. <Fragment>
  316. <div
  317. className={classnames({
  318. "comment-editor-toolbar": true,
  319. "comment-editor-toolbar-error": inputValue.length > maxLength
  320. })}
  321. ></div>
  322. <div className="comment-editor">
  323. <TextArea
  324. value={inputValue}
  325. onChange={e => this.handleChange(e.target.value)}
  326. rows={rows}
  327. placeholder={placeholder}
  328. autoFocus={autoFocus}
  329. />
  330. <div className="comment-toolbar">
  331. <div className="comment-toolbar-left">
  332. {showEmoji && (
  333. <Popover
  334. trigger="click"
  335. placement={emojiPopoverPlacement}
  336. autoAdjustOverflow={false}
  337. overlayStyle={{ zIndex: 9999 }}
  338. content={
  339. <div
  340. style={{ width: 240, height: 205 }}
  341. onWheel={this.handleEmojiScroll}
  342. >
  343. <Emoji
  344. onClick={this.handleClickEmoji}
  345. ref={node => {
  346. this.emoji = node;
  347. }}
  348. emojiList={this.props.app.emojiList}
  349. />
  350. </div>
  351. }
  352. overlayClassName="comment-emoji-popover"
  353. >
  354. {emojiToolIcon || (
  355. <Icon type="smile-o" className="comment-toolbar-icon" />
  356. )}
  357. </Popover>
  358. )}
  359. {showUpload ? (
  360. <Popover
  361. trigger="click"
  362. // TODO: 针对非 react.js,直接使用 click 事件来控制展开或关闭
  363. visible={this.state.uploadVisible}
  364. placement={uploadPopoverPlacement}
  365. overlayClassName={uploadOverlayClassName}
  366. autoAdjustOverflow={false}
  367. overlayStyle={{ zIndex: 9999 }}
  368. onVisibleChange={visible => {
  369. this.setState({
  370. uploadVisible: visible
  371. });
  372. }}
  373. content={
  374. <div
  375. style={{
  376. width: 336, // 一行显示3张
  377. minHeight: 100,
  378. margin: "0 auto"
  379. }}
  380. >
  381. <Upload
  382. onRef={node => (this.uploadRef = node)}
  383. multiple={multiple}
  384. onChangeFileList={this.handleChangeFileList}
  385. onUpload={this.handleUpload}
  386. maxUpload={maxUpload}
  387. fileList={uploadFileList}
  388. showError={this.props.showError}
  389. onError={this.props.onError}
  390. />
  391. <div className="clearfix" />
  392. </div>
  393. }
  394. title={
  395. <div style={{ margin: "5px auto" }}>
  396. <span>
  397. {intl.get("editor.uploadTip")}
  398. {maxUpload >= 2 ? (
  399. <span style={{ color: "#666", fontWeight: 400 }}>
  400. {intl.get("editor.uploadCount", {
  401. count: maxUpload - uploadFileList.length
  402. })}
  403. </span>
  404. ) : null}
  405. </span>
  406. </div>
  407. }
  408. >
  409. {imageToolIcon ? (
  410. React.cloneElement(imageToolIcon, {
  411. onClick: () => this.handleShowUpload(true)
  412. })
  413. ) : (
  414. <Icon
  415. type="picture"
  416. className="comment-toolbar-icon"
  417. style={{ marginLeft: 20 }}
  418. onClick={() => this.handleShowUpload(true)}
  419. />
  420. )}
  421. </Popover>
  422. ) : null}
  423. </div>
  424. <div className="comment-toolbar-right">
  425. {button ? (
  426. React.cloneElement(button, {
  427. onClick: button.props.onClick || handleSubmit
  428. })
  429. ) : (
  430. <Button
  431. onClick={() => this.handleSubmit()}
  432. type="primary"
  433. loading={btnLoading}
  434. disabled={disabledSubmit}
  435. >
  436. {btnSubmitText}
  437. </Button>
  438. )}
  439. </div>
  440. </div>
  441. </div>
  442. </Fragment>
  443. ) : (
  444. <Fragment>
  445. <div className="comment-unlogin-tip">
  446. {intl.get("comment.unlogin")}
  447. </div>
  448. <div className="comment-unlogin-button">
  449. <Button
  450. type="primary"
  451. onClick={() => {
  452. window.location.href = `${app.LOGINLINK}?f=${window.location.href}`;
  453. }}
  454. >
  455. {intl.get("account.login")}
  456. </Button>
  457. </div>
  458. </Fragment>
  459. )}
  460. </div>
  461. );
  462. }
  463. }
  464. Editor.propTypes = {
  465. rows: PropTypes.number,
  466. placeholder: PropTypes.string,
  467. showEmoji: PropTypes.bool,
  468. emojiPopoverPlacement: PropTypes.string,
  469. showUpload: PropTypes.bool,
  470. uploadPopoverPlacement: PropTypes.string,
  471. uploadOverlayClassName: PropTypes.string,
  472. multiple: PropTypes.bool,
  473. closeUploadWhenBlur: PropTypes.bool,
  474. maxUpload: PropTypes.number,
  475. value: PropTypes.string,
  476. onChange: PropTypes.func,
  477. onSubmit: PropTypes.func,
  478. beforeSubmit: PropTypes.func,
  479. btnSubmitText: PropTypes.string,
  480. btnLoading: PropTypes.bool,
  481. btnDisabled: PropTypes.bool,
  482. button: PropTypes.node,
  483. emojiToolIcon: PropTypes.node,
  484. imageToolIcon: PropTypes.node,
  485. showError: PropTypes.bool,
  486. onError: PropTypes.func,
  487. maxLength: PropTypes.number
  488. };
  489. Editor.defaultProps = {
  490. rows: 5,
  491. // placeholder: "说点什么吧",
  492. showEmoji: true,
  493. showUpload: true,
  494. multiple: true,
  495. emojiPopoverPlacement: "bottomLeft",
  496. closeUploadWhenBlur: false,
  497. uploadPopoverPlacement: "bottomLeft",
  498. uploadOverlayClassName: "",
  499. maxUpload: 1,
  500. // btnSubmitText: "发表",
  501. btnLoading: false,
  502. btnDisabled: false,
  503. showError: true,
  504. maxLength: 5000,
  505. app: {},
  506. handleChangeFileList: () => {}
  507. };
  508. export default Comment(Editor);