通用评论

index.js 17KB

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