通用评论

index.js 16KB

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