通用评论

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. /**
  282. * **处理Enter事件**
  283. * 1. `allowEnter` & `onPressEnter`同时有效时才能触发
  284. * 2. `e.preventDefault`为了防止enter事件后仍触发换行
  285. * 3. enter事件开启,仍可以用`shift + enter`触发换行
  286. * -- evo 20200222
  287. */
  288. handlePressEnter = e => {
  289. const { allowEnter, onPressEnter } = this.props;
  290. if (allowEnter && onPressEnter) {
  291. if (!e.shiftKey) {
  292. e.preventDefault();
  293. onPressEnter();
  294. }
  295. }
  296. };
  297. render() {
  298. const {
  299. value,
  300. // placeholder,
  301. rows,
  302. showEmoji,
  303. showUpload,
  304. multiple,
  305. emojiPopoverPlacement,
  306. uploadPopoverPlacement,
  307. uploadOverlayClassName,
  308. fileList,
  309. maxUpload,
  310. // btnSubmitText,
  311. btnLoading,
  312. button,
  313. emojiToolIcon,
  314. imageToolIcon,
  315. maxLength,
  316. autoFocus,
  317. app
  318. } = this.props;
  319. let placeholder = this.props.placeholder || intl.get("editor.placeholder");
  320. let btnSubmitText =
  321. this.props.btnSubmitText || intl.get("editor.SubmitBtn");
  322. const handleSubmit = this.handleSubmit;
  323. const disabledSubmit = this.checkDisabledSubmit();
  324. const inputValue = value || this.state.value;
  325. const uploadFileList = fileList || this.state.fileList;
  326. const isLogin =
  327. app.currentUser &&
  328. (app.currentUser.user_id > 0 || app.currentUser.id > 0);
  329. return (
  330. <div className="comment-editor-container" onPaste={this.handlePaste}>
  331. {isLogin ? (
  332. <Fragment>
  333. <div
  334. className={classnames({
  335. "comment-editor-toolbar": true,
  336. "comment-editor-toolbar-error": inputValue.length > maxLength
  337. })}
  338. ></div>
  339. <div className="comment-editor">
  340. <TextArea
  341. value={inputValue}
  342. onChange={e => {
  343. this.handleChange(e.target.value);
  344. }}
  345. rows={rows}
  346. placeholder={placeholder}
  347. autoFocus={autoFocus}
  348. onPressEnter={this.handlePressEnter}
  349. />
  350. <div className="comment-toolbar">
  351. <div className="comment-toolbar-left">
  352. {showEmoji && (
  353. <Popover
  354. trigger="click"
  355. placement={emojiPopoverPlacement}
  356. autoAdjustOverflow={false}
  357. overlayStyle={{ zIndex: 9999 }}
  358. content={
  359. <div
  360. style={{ width: 240, height: 205 }}
  361. onWheel={this.handleEmojiScroll}
  362. >
  363. <Emoji
  364. onClick={this.handleClickEmoji}
  365. ref={node => {
  366. this.emoji = node;
  367. }}
  368. emojiList={this.props.app.emojiList}
  369. />
  370. </div>
  371. }
  372. overlayClassName="comment-emoji-popover"
  373. >
  374. {emojiToolIcon || (
  375. <Icon type="smile-o" className="comment-toolbar-icon" />
  376. )}
  377. </Popover>
  378. )}
  379. {showUpload ? (
  380. <Popover
  381. trigger="click"
  382. // TODO: 针对非 react.js,直接使用 click 事件来控制展开或关闭
  383. visible={this.state.uploadVisible}
  384. placement={uploadPopoverPlacement}
  385. overlayClassName={uploadOverlayClassName}
  386. autoAdjustOverflow={false}
  387. overlayStyle={{ zIndex: 9999 }}
  388. onVisibleChange={visible => {
  389. this.setState({
  390. uploadVisible: visible
  391. });
  392. }}
  393. content={
  394. <div
  395. style={{
  396. width: 336, // 一行显示3张
  397. minHeight: 100,
  398. margin: "0 auto"
  399. }}
  400. >
  401. <Upload
  402. onRef={node => (this.uploadRef = node)}
  403. multiple={multiple}
  404. onChangeFileList={this.handleChangeFileList}
  405. onUpload={this.handleUpload}
  406. maxUpload={maxUpload}
  407. fileList={uploadFileList}
  408. showError={this.props.showError}
  409. onError={this.props.onError}
  410. />
  411. <div className="clearfix" />
  412. </div>
  413. }
  414. title={
  415. <div style={{ margin: "5px auto" }}>
  416. <span>
  417. {intl.get("editor.uploadTip")}
  418. {maxUpload >= 2 ? (
  419. <span style={{ color: "#666", fontWeight: 400 }}>
  420. {intl.get("editor.uploadCount", {
  421. count: maxUpload - uploadFileList.length
  422. })}
  423. </span>
  424. ) : null}
  425. </span>
  426. </div>
  427. }
  428. >
  429. {imageToolIcon ? (
  430. React.cloneElement(imageToolIcon, {
  431. onClick: () => this.handleShowUpload(true)
  432. })
  433. ) : (
  434. <Icon
  435. type="picture"
  436. className="comment-toolbar-icon"
  437. style={{ marginLeft: 20 }}
  438. onClick={() => this.handleShowUpload(true)}
  439. />
  440. )}
  441. </Popover>
  442. ) : null}
  443. </div>
  444. <div className="comment-toolbar-right">
  445. {button ? (
  446. React.cloneElement(button, {
  447. onClick: button.props.onClick || handleSubmit
  448. })
  449. ) : (
  450. <Button
  451. onClick={() => this.handleSubmit()}
  452. type="primary"
  453. loading={btnLoading}
  454. disabled={disabledSubmit}
  455. >
  456. {btnSubmitText}
  457. </Button>
  458. )}
  459. </div>
  460. </div>
  461. </div>
  462. </Fragment>
  463. ) : (
  464. <Fragment>
  465. <div className="comment-unlogin-tip">
  466. {intl.get("comment.unlogin")}
  467. </div>
  468. <div className="comment-unlogin-button">
  469. <Button
  470. type="primary"
  471. onClick={() => {
  472. window.location.href = `${app.LOGINLINK}?f=${window.location.href}`;
  473. }}
  474. >
  475. {intl.get("account.login")}
  476. </Button>
  477. </div>
  478. </Fragment>
  479. )}
  480. </div>
  481. );
  482. }
  483. }
  484. Editor.propTypes = {
  485. rows: PropTypes.number,
  486. placeholder: PropTypes.string,
  487. showEmoji: PropTypes.bool,
  488. emojiPopoverPlacement: PropTypes.string,
  489. showUpload: PropTypes.bool,
  490. uploadPopoverPlacement: PropTypes.string,
  491. uploadOverlayClassName: PropTypes.string,
  492. multiple: PropTypes.bool,
  493. closeUploadWhenBlur: PropTypes.bool,
  494. maxUpload: PropTypes.number,
  495. value: PropTypes.string,
  496. onChange: PropTypes.func,
  497. onSubmit: PropTypes.func,
  498. beforeSubmit: PropTypes.func,
  499. btnSubmitText: PropTypes.string,
  500. btnLoading: PropTypes.bool,
  501. btnDisabled: PropTypes.bool,
  502. button: PropTypes.node,
  503. emojiToolIcon: PropTypes.node,
  504. imageToolIcon: PropTypes.node,
  505. showError: PropTypes.bool,
  506. onError: PropTypes.func,
  507. maxLength: PropTypes.number,
  508. // Enter事件相关
  509. allowEnter: PropTypes.bool,
  510. onPressEnter: PropTypes.func
  511. };
  512. Editor.defaultProps = {
  513. rows: 5,
  514. // placeholder: "说点什么吧",
  515. showEmoji: true,
  516. showUpload: true,
  517. multiple: true,
  518. emojiPopoverPlacement: "bottomLeft",
  519. closeUploadWhenBlur: false,
  520. uploadPopoverPlacement: "bottomLeft",
  521. uploadOverlayClassName: "",
  522. maxUpload: 1,
  523. // btnSubmitText: "发表",
  524. btnLoading: false,
  525. btnDisabled: false,
  526. showError: true,
  527. maxLength: 5000,
  528. app: {},
  529. handleChangeFileList: () => {},
  530. // Enter事件相关
  531. allowEnter: false,
  532. onPressEnter: undefined
  533. };
  534. export default Comment(Editor);