通用评论

index.js 17KB

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