通用评论

index.js 14KB

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