通用评论

index.js 17KB

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