index.js 14.6 KB
Newer Older
周宏民's avatar
周宏民 committed
1
import { Image, message, Spin } from 'antd';
周宏民's avatar
周宏民 committed
2
import classNames from 'classnames';
周宏民's avatar
周宏民 committed
3
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
周宏民's avatar
周宏民 committed
4 5 6
import request from 'umi-request';
import FileListItem from './fileListItem';
import styles from './index.less';
7 8 9 10 11 12 13 14 15
import WangEditor from './wangEditor.js';

const baseUrl = '';
const API = {
  POST_UPLOADERFILES: `${baseUrl}/PandaWorkFlow/WorkFlow/AccountManage/UploaderFiles`,
  GET_DOWNLOADFILES: `${baseUrl}/PandaWorkFlow/WorkFlow/AccountManage/DownloadFiles`,
  GET_GETALLPERSONNELS: `${baseUrl}/PandaInformatization/PandaWork/MeetingTask/GetAllPersonnels`, // 获取人员
  GET_WORKHOURUSERLIST: `${baseUrl}/PandaInformatization/PandaWork/ProjectManage/GetWorkHourUserList`, //根据项目id获取项目参与人员
};
周宏民's avatar
周宏民 committed
16 17 18 19 20 21 22 23 24
let editor = null;
let range;
const selection = window.getSelection();
let startOffset;
let tempList = [];
let allPeople = []; // 全部人员
let selectPersonIndex;
let selectPerson = [];
const RichText = forwardRef((props, ref) => {
周宏民's avatar
周宏民 committed
25 26 27 28 29 30 31 32 33 34 35
  const [loading, setLoading] = useState(false);
  const [zIndex, setZIndex] = useState(500);
  const [selectIndex, setSelectIndex] = useState(null);
  const [selectList, setSelectList] = useState([]);
  const [selectSearchList, setSelectSearchList] = useState([]);
  const [fileList, setFileList] = useState([]);
  const [imgVisible, setImgVisible] = useState(false);
  const [imgPreviewSrc, setImgPreviewSrc] = useState('');
  const richTextRef = useRef();
  const selectBoxRef = useRef();
  const fileInputRef = useRef();
36 37 38 39 40 41 42
  const getData = () => {
    request(API.GET_WORKHOURUSERLIST, {
      method: 'get',
      params: { projectId: props.projectId },
    }).then((res) => {
      setSelectList(res.data || []);
    });
周宏民's avatar
周宏民 committed
43 44 45
  };
  // 获取全部人员信息
  const getAllPeople = async () => {
46 47 48 49
    request(API.GET_GETALLPERSONNELS, {
      method: 'get',
      params: {},
    }).then((res) => {
50
      allPeople = res?.data?.data || [];
51
    });
周宏民's avatar
周宏民 committed
52 53 54 55 56 57
  };
  // 图片上传
  const uploadImg = (file) => {
    const formData = new FormData();
    formData.append('file', file);
    setLoading(true);
58
    request(API.POST_UPLOADERFILES, {
周宏民's avatar
周宏民 committed
59 60 61 62
      method: 'POST',
      data: formData,
    })
      .then((res) => {
63 64 65 66
        if (!res.data) {
          setLoading(false);
          return;
        }
周宏民's avatar
周宏民 committed
67 68 69
        const img = res.data.replace(/[\\ \/=]/g, '/');
        const imgHtml = `
                    <img contenteditable="false" style="display: block;" width="50%" src="${API.GET_DOWNLOADFILES}?filePath=${img}" >
周宏民's avatar
周宏民 committed
70
                `;
周宏民's avatar
周宏民 committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
        editor.cmd.do('insertHTML', imgHtml);
        setLoading(false);
      })
      .catch((err) => {
        setLoading(false);
      });
  };
  const init = () => {
    const { BtnMenu } = WangEditor;
    editor = new WangEditor('#RichTextToolbar', '#RichTextContainer');
    // 自定义菜单
    const menuKey = 'fileMenuKey';
    if (props.onChangeFile) {
      class InsertABCMenu extends BtnMenu {
        constructor(editor) {
          const $elem = WangEditor.$(
            `<div class="w-e-menu">
周宏民's avatar
周宏民 committed
88 89 90
                            <i class="w-e-icon-link">
                            </i>
                        </div>`,
周宏民's avatar
周宏民 committed
91 92
          );
          super($elem, editor);
周宏民's avatar
周宏民 committed
93 94
        }

周宏民's avatar
周宏民 committed
95 96 97 98 99
        // 菜单点击事件
        clickHandler() {
          // 触发选择文件
          fileInputRef.current.click();
        }
周宏民's avatar
周宏民 committed
100

周宏民's avatar
周宏民 committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        // 菜单激活状态
        tryChangeActive() {
          // this.active(); // 菜单激活
        }
      }
      editor.menus.extend(menuKey, InsertABCMenu);
    }
    editor.config = Object.assign(
      {},
      editor.config,
      {
        placeholder: props.placeholder ?? '',
        focus: false,
        pasteFilterStyle: true, // 忽略粘贴样式
        pasteIgnoreImg: true, // 忽略粘贴的图片
        styleWithCSS: false,
        zIndex: 500,
        menus: [
          'bold',
          'fontSize',
          'italic',
          'underline',
          'strikeThrough',
          'foreColor',
          'backColor',
          'list',
          'justify',
          'table',
          menuKey,
          'undo',
          'redo',
          'image',
        ],
      },
      props.config || {},
    );
周宏民's avatar
周宏民 committed
137

周宏民's avatar
周宏民 committed
138 139 140 141
    setZIndex(Number(editor.config.zIndex));
    // 内容变更
    editor.config.onchange = (newHtml, e) => {
      props.onChange(newHtml);
周宏民's avatar
周宏民 committed
142
    };
周宏民's avatar
周宏民 committed
143 144 145 146
    // 粘贴前置处理
    editor.config.pasteTextHandle = (pasteStr) => pasteStr;
    editor.config.onblur = (newHtml) => {
      selectBoxRef.current.style.display = 'none';
周宏民's avatar
周宏民 committed
147
    };
周宏民's avatar
周宏民 committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161
    // 点击事件
    editor.txt.eventHooks.clickEvents.push((e) => {
      // 图片预览
      // 已弃用
      if (e.target.getAttribute('type') === 'preview') {
        const imgSrc = e.target?.parentNode?.parentNode
          ?.getElementsByTagName('img')?.[0]
          ?.getAttribute('src');
        setImgPreviewSrc(imgSrc);
        setImgVisible(true);
      }
      // 关闭选人的下拉框
      selectBoxRef.current.style.display = 'none';
    });
周宏民's avatar
周宏民 committed
162

周宏民's avatar
周宏民 committed
163 164 165 166 167 168 169
    editor.txt.eventHooks.onPreviewEvents.push((link) => {
      // 图片预览
      if (link) {
        setImgPreviewSrc(link);
        setImgVisible(true);
      }
    });
周宏民's avatar
周宏民 committed
170

171
    editor.txt.eventHooks.imgClickEvents.push((e) => {});
周宏民's avatar
周宏民 committed
172 173 174 175 176 177
    // 粘贴图片上传
    editor.txt.eventHooks.pasteEvents.push((e) => {
      const file = e?.clipboardData?.items[0]?.getAsFile() || null;
      if (!file) return;
      uploadImg(file);
    });
周宏民's avatar
周宏民 committed
178

周宏民's avatar
周宏民 committed
179 180 181 182 183 184 185 186 187 188
    editor.create();
    editor.txt.html(props.content || '');
    richTextRef.current.onkeydown = keyDownEvent;
    richTextRef.current.addEventListener('input', (e) => {
      if (range) {
        // 判断节点是否在选区及光标是否在@后面
        const type = selection.containsNode(selection.getRangeAt(0).commonAncestorContainer, false);
        if (!type || startOffset > selection.focusOffset) {
          closeList();
          return;
周宏民's avatar
周宏民 committed
189
        }
周宏民's avatar
周宏民 committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        range.setEnd(selection.getRangeAt(0).commonAncestorContainer, selection.focusOffset);
        // console.log('🚀 ~ range', range.toString(), tempList, selectList);
        const str = range.toString() || '';
        moveListBox();
        handleChange(str, tempList);
      }
      if (e.data !== '@') return;
      if (range) {
        closeList();
      }
      range = document.createRange();
      startOffset = selection.focusOffset;
      range.setStart(selection.getRangeAt(0).commonAncestorContainer, selection.focusOffset);
      selection.addRange(range);
      moveListBox();
      // 清空搜索
      handleChange('', tempList);
    });
  };
  // 跟据光标位置移动下拉框
  const moveListBox = () => {
    // 获取光标位置
    const cursor = window?.getSelection()?.getRangeAt(0)?.getBoundingClientRect() || null;
    const containerRect = document.querySelector('#RichText').getBoundingClientRect();
    selectBoxRef.current.style.display = 'block';
    selectBoxRef.current.style.left = `${parseInt(cursor.x - containerRect.x, 10) + 5}px`;
    selectBoxRef.current.style.top = `${parseInt(cursor.y - containerRect.y, 10) + 25}px`;
  };
  // 键盘事件
  const keyDownEvent = (evet) => {
    // 上下方向键
    if (evet.key === 'ArrowDown' || evet.key === 'ArrowUp') {
      if (selectBoxRef.current?.style?.display === 'block') {
223
        evet.preventDefault();
周宏民's avatar
周宏民 committed
224 225 226 227 228 229 230 231
        const max = selectBoxRef.current.querySelectorAll('.selectItem')?.length || 1000;
        let val = selectPersonIndex;
        if (evet.key === 'ArrowDown') {
          if (!val && val != 0) {
            val = 0;
          } else {
            val += 1;
          }
周宏民's avatar
周宏民 committed
232
        }
周宏民's avatar
周宏民 committed
233 234 235 236 237 238 239 240 241
        if (evet.key === 'ArrowUp') val -= 1;
        if (isNaN(val) || !val || val < 0) val = 0;
        if (val > max - 1) val = max - 1;
        selectPersonIndex = val;
        setSelectIndex(selectPersonIndex);
      }
    }
    if (evet.key === 'Enter') {
      // 解决无法回车换行的bug
242
      console.log(selectBoxRef.current.style.display === 'block');
243
      if (selectBoxRef.current.style.display === 'block') {
周宏民's avatar
周宏民 committed
244 245 246
        evet.preventDefault();
        if (selectPerson[selectPersonIndex]) {
          onSelect(selectPerson[selectPersonIndex]);
周宏民's avatar
周宏民 committed
247
        }
周宏民's avatar
周宏民 committed
248 249 250 251 252 253
        return false;
      }
    }
  };

  useEffect(() => {
254
    richTextRef.current && richTextRef.current.removeEventListener('input', (e) => {});
周宏民's avatar
周宏民 committed
255 256 257
    init();
    getAllPeople();
    return () => {
258
      richTextRef.current && richTextRef.current.removeEventListener('input', (e) => {});
周宏民's avatar
周宏民 committed
259 260
      editor && editor.destroy();
      editor = null;
周宏民's avatar
周宏民 committed
261
    };
周宏民's avatar
周宏民 committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  }, []);
  useEffect(() => {
    selectPersonIndex = null;
    setSelectIndex(null);
    selectPerson = selectSearchList || [];
  }, [selectSearchList]);
  useEffect(() => {
    if (props.projectId) getData();
  }, [props.projectId]);
  useEffect(() => {
    const keys = [];
    const arr = [];
    if (props.personList) {
      props.personList.forEach((i) => {
        i.userId = Number(i.userId);
        if (!keys.includes(i.userId)) {
          keys.push(i.userId);
          arr.push(i);
周宏民's avatar
周宏民 committed
280
        }
周宏民's avatar
周宏民 committed
281 282 283 284 285 286 287 288
      });
    }
    if (selectList) {
      selectList.forEach((i) => {
        i.userId = Number(i.userId);
        if (!keys.includes(i.userId)) {
          arr.push(i);
          keys.push(i.userId);
周宏民's avatar
周宏民 committed
289
        }
周宏民's avatar
周宏民 committed
290 291 292 293 294 295
      });
    }

    tempList = arr;
    setSelectSearchList(arr);
  }, [selectList, props.personList]);
296

周宏民's avatar
周宏民 committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  useEffect(() => {
    setFileList(props.fileList);
  }, [props.fileList]);
  const getHtml = (val) => editor.txt.html();
  // 获取文本,不含标签
  const getText = (val) => editor.txt.text();
  // 清除
  const onClear = () => {
    editor.txt.clear();
  };
  // 设置内容
  const setHtml = (val) => {
    editor.txt.html(val || '');
  };
  // 关闭人员下拉选框
  const closeList = () => {
    selectPersonIndex = null;
    setSelectIndex(null);
    selectBoxRef.current.style.display = 'none';
    if (range) {
      selection.removeRange(range);
      range = null;
    }
  };
  // @某人
  const onSelect = (item) => {
    if (range) {
      range.deleteContents();
      // 删除前一个@符号
      editor.cmd.do('delete');
      const _html = `<span><span data-userId="${item.userId}" data-type="person" >@${item.userName}</span><span>&nbsp;</span></span>`;
      editor.cmd.do('insertElem', _html);
      closeList();
      selection.collapseToEnd();
    }
  };
  let timer = null;
  const filterList = (val, list) => {
    if (!val) {
      if (list.length === 0) {
        selectBoxRef.current.style.display = 'none';
      }
      setSelectSearchList(list);
    } else {
      const arr = getArrayByName(val, allPeople);
      if (arr.length === 0) {
        selectBoxRef.current.style.display = 'none';
      }
      setSelectSearchList(arr);
    }
  };
  const handleChange = (val, list) => {
349
    console.log('🚀 ~ val', val);
周宏民's avatar
周宏民 committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null;
      filterList(val, list);
    }, 200);
    // filterList(val, list);
  };
  /**
   * 根据字符串模糊搜索返回符合条件的数据
   * name   搜索字符串
   * array  检索json数组
   */
  const getArrayByName = (name, array) => {
    const result = [];
    array.forEach((i) => {
      if (i.name.indexOf(name) != -1) result.push({ userName: i.name, userId: i.id, port: i.port });
    });
    return result;
  };
  const addFile = (e) => {
    if (e.target) {
373 374 375 376 377
      let file = e.target.files[0];
      const pattern =
        /[`~!@#$^\-&*()+=|{}':;',\\\[\]\<>\/?~!@#¥……&*()——|{}【】';:""'。,、?\s]/g;
      let name = file.name.replace(pattern, '');
      const renameFile = new File([file], name);
周宏民's avatar
周宏民 committed
378
      const formData = new FormData();
379
      formData.append('file', renameFile);
周宏民's avatar
周宏民 committed
380
      setLoading(true);
381
      request(API.POST_UPLOADERFILES, {
周宏民's avatar
周宏民 committed
382 383 384
        method: 'POST',
        data: formData,
      })
385 386 387 388 389 390 391 392 393 394 395 396 397 398
        .then((res) => {
          if (res.data) {
            const arr = [...fileList];
            const url = res.data.replace(/[\\ \/=]/g, '/');
            arr.unshift({
              name: file.name,
              type: file.type ? file.type.toLowerCase() : '',
              size: file.size,
              path: `${API.GET_DOWNLOADFILES}?filePath=${url}`,
            });
            // setFileList(arr);
            props.onChangeFile(arr);
            setLoading(false);
          } else {
399
            res && message.error(res.msg);
400 401 402
            setLoading(false);
          }
        })
周宏民's avatar
周宏民 committed
403 404
        .catch((err) => {
          setLoading(false);
周宏民's avatar
周宏民 committed
405
        });
周宏民's avatar
周宏民 committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    }
  };
  const onDelFile = (item) => {
    const arr = [];
    fileList.forEach((i) => {
      if (i.path !== item.path) {
        arr.push(i);
      }
    });
    // setFileList(arr);
    props.onChangeFile(arr);
  };
  useImperativeHandle(ref, () => ({
    setHtml,
    onClear,
    getHtml,
    getText,
  }));
  return (
    <div className={styles.RichText} id="RichText">
      {loading ? (
        <div className={styles.loadingWrap} style={{ zIndex: zIndex + 20 }}>
          <Spin spinning={loading} />
周宏民's avatar
周宏民 committed
429
        </div>
周宏民's avatar
周宏民 committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
      ) : null}
      <div id="RichTextToolbar" className={styles.RichTextToolbar} />
      <div ref={richTextRef} id="RichTextContainer" className={styles.RichTextContainer} />
      <div className={styles.RichTextFileList}>
        <FileListItem
          list={fileList}
          onDel={(val) => {
            onDelFile(val);
          }}
          type="edit"
          onPreview={(val) => {
            if (!val) return;
            setImgPreviewSrc(val.path);
            setImgVisible(true);
          }}
        />
      </div>
      <div
        ref={selectBoxRef}
        className={styles.selectBox}
        style={{ maxWidth: '300px', minWidth: '150px', zIndex: zIndex + 10 }}
      >
        {selectSearchList.length ? (
          <div className={styles.selectList}>
            {selectSearchList.map((item, index) => (
              <div
                key={item.userId}
                onClick={() => {
                  onSelect(item);
                }}
                className={classNames(
                  'selectItem',
                  styles.selectItem,
                  selectIndex === index ? styles.selectActiveItem : '',
                )}
              >
                {item.userName}
              </div>
            ))}
          </div>
        ) : null}
      </div>
      <input
        style={{ display: 'none' }}
        type="file"
        ref={fileInputRef}
        onChange={(e) => {
          addFile(e);
        }}
        name="file"
      />
      <Image
        width={200}
        style={{ display: 'none' }}
        src={imgPreviewSrc}
        preview={{
          visible: imgVisible,
          src: imgPreviewSrc,
          onVisibleChange: (value) => {
            setImgVisible(value);
            if (!value) setImgPreviewSrc('');
          },
        }}
      />
    </div>
  );
周宏民's avatar
周宏民 committed
496 497
});
export default RichText;