通用评论

index.js 17KB

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