index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import React, { PureComponent, Fragment } from "react";
  2. import { apiUrl } from "@/utils/sldconfig.js";
  3. import { emojiRegex } from "@/utils/regex";
  4. import { message } from "antd";
  5. export default class SldUEditor extends PureComponent {
  6. constructor(props) {
  7. super(props);
  8. this.state = {};
  9. }
  10. componentDidMount() {
  11. this.initEditor();
  12. }
  13. componentWillReceiveProps(nextProps, nextContext) {
  14. if (nextProps.getContentFlag && !this.props.getContentFlag) {
  15. let con = UE.getEditor(nextProps.id).getContent();
  16. this.props.getEditorContent(con);
  17. }
  18. }
  19. componentWillUnmount() {
  20. UE.delEditor(this.props.id);
  21. }
  22. initEditor = () => {
  23. const { id, initEditorContent } = this.props;
  24. console.info();
  25. const ueEditor = UE.getEditor(id, {
  26. serverUrl:
  27. `${apiUrl}v3/oss/ueditor/upload?configPath=config.json&storeId=` +
  28. localStorage.getItem("storeId"),
  29. });
  30. ueEditor.ready((editor) => {
  31. if (!editor) {
  32. UE.delEditor(id);
  33. this.initEditor();
  34. } else {
  35. if (initEditorContent) {
  36. UE.getEditor(id).setContent(initEditorContent);
  37. }
  38. // 监听输入内容变化
  39. ueEditor.addListener("contentChange", () => {
  40. const content = ueEditor.getContentTxt(); // 纯文本
  41. if (this.hasEmoji(content)) {
  42. message.warn("监测到输入表情符号,已自动去除");
  43. ueEditor.body.innerHTML = ueEditor.body.innerHTML.replace(
  44. emojiRegex,
  45. ""
  46. );
  47. ueEditor.focus();
  48. const range = ueEditor.selection.getRange();
  49. const body = ueEditor.body;
  50. // 找到最后一个文本节点或者元素节点
  51. let lastNode = body.lastChild;
  52. // 如果最后一个是元素节点,尝试找到它的最后一个文本节点
  53. function getLastTextNode(node) {
  54. if (node.nodeType === 3) return node; // 文本节点
  55. if (!node.hasChildNodes()) return null;
  56. return getLastTextNode(node.lastChild);
  57. }
  58. const lastTextNode = getLastTextNode(lastNode) || lastNode;
  59. // 如果找到文本节点,光标放在文本末尾
  60. if (lastTextNode && lastTextNode.nodeType === 3) {
  61. range.setStart(lastTextNode, lastTextNode.nodeValue.length);
  62. } else {
  63. // 否则放在最后元素后面
  64. range.setStartAfter(lastNode);
  65. }
  66. range.collapse(true);
  67. range.select();
  68. }
  69. });
  70. }
  71. });
  72. };
  73. hasEmoji = (str) => {
  74. return emojiRegex.test(str);
  75. };
  76. render() {
  77. const { id } = this.props;
  78. return <div id={id} name="content" type="text/plain" />;
  79. }
  80. }