通用评论

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