通用评论

index.js 16KB

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