通用评论

index.js 17KB

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