通用评论

index.js 14KB

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