通用评论

index.js 16KB

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