index.tsx 22.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 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 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
import { CloseCircleFilled } from '@ant-design/icons';
import _ from 'lodash-es';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
import { handleHighlight } from '../qx-function-operation/components/var-picker';
import {
  domTagGen,
  flatten,
  reverseStr,
  strFill,
  widgetMapping,
} from '../qx-function-operation/util';
import './style.less';

import Cm from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/lib/codemirror.js';
import { UnControlled as CodeMirror } from 'react-codemirror2';
import './plugins/cm-extensions';

import 'codemirror/mode/javascript/javascript.js';
import 'codemirror/theme/idea.css';

import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/show-hint.js'; // ctrl代码提示补全

import 'codemirror/addon/selection/active-line.js'; // 光标代码高亮

import 'codemirror/addon/edit/matchbrackets.js';
import 'codemirror/addon/lint/javascript-lint.js';
import 'codemirror/addon/lint/lint.css';
import 'codemirror/addon/lint/lint.js'; // 错误提示
import beautify from 'js-beautify';
import { JSHINT } from 'jshint';
window.JSHINT = JSHINT;

type PositionProps = {
  s: number;
  e: number;
};

export type VariableProps = {
  variable: string;
  pos: PositionProps;
};

/**
 * 字符串中提取变量(${xxx})
 * @param code
 */
export const getAllVariable = (code: string) => {
  let codeLocal: string = _.clone(code);
  if (!codeLocal) {
    return [];
  }
  const variables: VariableProps[] = [];

  function loopGet() {
    const pos: PositionProps = {
      s: codeLocal.indexOf('${'),
      e: codeLocal.indexOf('}'),
    };
    if (pos.s === -1 && pos.e === -1) {
      return;
    }
    const variable = codeLocal.slice(pos.s, pos.e + 1);
    variables.push({ variable, pos });
    codeLocal = codeLocal.replace(variable, strFill(0, variable.length, 0));

    loopGet();
  }

  loopGet();
  return variables;
};

const getWidgetByType = (type?: string) => {
  let res: string;
  switch (type) {
    case 'TEXT':
      res = 'qxInput';
      break;
    case 'NUM':
      res = 'qxNumber';
      break;
    default:
      res = '';
  }
  // @ts-ignore
  return res;
};

type VarProps = {
  key: string;
  name?: string;
  type?: string;
};

type EditorProps = {
  cRef: any;
  // eg: 'hello ${v1} ${v2}!'
  value: string;
  // eg: {'${v1}': 'hehe', '${v2}': 'enen'}
  // variableObj: Record<string, string> | undefined;
  isUseFun: boolean;
  autofocus?: boolean;
  newVariable: VarProps;
  funcDataList: any[];
  varDataList: any[];
  className?: any;
  style?: any;
  readOnly?: boolean;
  from?: string;
  resetValue?: string;
  allowClear?: boolean | undefined;
  onChange: (code: string) => void;
  onFocusFunc: (funcName: string | null) => void;
};

const CodeEditor: React.FC<EditorProps> = ({
  cRef,
  funcDataList,
  varDataList,
  isUseFun,
  autofocus,
  readOnly,
  allowClear,
  resetValue,
  value,
  newVariable,
  from,
  className,
  onChange,
  onFocusFunc,
}) => {
  const [isInitDone, setIsInitDone] = useState<boolean>(false);
  const [valueLocal, setValueLocal] = useState<string>();
  const [editor, setEditor] = useState<any>(null);
  const formatRef = useRef(false); // 代码格式化引起的变化
  // 定义匹配括号的正则表达式
  const bracketRegex = /[(){}\[\]]/g;

  useEffect(() => {
    if (!editor) return;
    editor.on('mousedown', (_cm: any, event: any) => {
      // 1 = 鼠标左键,2 = 鼠标右键,4 = 鼠标中键
      if (event.buttons === 1) {
        const element = event.target as Element;
        if (element.classList.contains('funcName')) {
          const funcName = element.getAttribute('data-widget');
          const funcData = funcDataListFlatten.current.find(
            (data: any) => data.funcNameEg === funcName,
          );
          if (funcData && typeof onFocusFunc === 'function') {
            onFocusFunc(funcData);
          }
        }
      }
    });
    // 添加占位符功能
    const placeholderText = editor.getOption('placeholder');
    const placeholderElement = document.createElement('div');
    placeholderElement.className = 'CodeMirror-placeholder';
    placeholderElement.textContent = placeholderText;
    editor.getWrapperElement().appendChild(placeholderElement);

    const handleChange = () => {
      const value = editor.getValue();
      if (value?.length) {
        placeholderElement.style.display = 'none';
      } else {
        placeholderElement.style.display = 'block';
      }
      const lastLine = editor.lastLine();
      editor.scrollIntoView(
        { line: lastLine, ch: 0, margin: { bottom: 50 } },
        100,
      );

      setTimeout(() => {
        // 获取编辑器的包装元素
        const wrapperElements =
          document.getElementsByClassName('CodeMirror-widget');
        // 将 cm-ignore-events 的值设为 false
        for (let i = 0; i < (wrapperElements || []).length; i++) {
          wrapperElements[i].setAttribute('cm-ignore-events', 'false');
        }
      }, 100);

      // 在内容中查找匹配的括号
      let match: any;
      while ((match = bracketRegex.exec(value))) {
        const from = { line: 0, ch: match.index };
        const to = { line: 0, ch: match.index + 1 };

        // 标记匹配的括号并应用 CSS 类名
        editor.markText(from, to, { className: 'bracket-mark' });
      }

      // const processedContent = value.replace(/(\(|\)|\[|\]|\{|\})/g, '<span class="custom-paren">$1</span>');
      // editor.setValue(processedContent);
    };
    handleChange();

    // 监听编辑器的输入事件
    editor.on('change', handleChange);
  }, [editor]);

  // 扁平化dataSource
  const funcDataListFlatten: any = useRef([]);
  if (!funcDataListFlatten.current.length && funcDataList.length) {
    flatten(funcDataList, funcDataListFlatten.current);
  }
  const funcDataListSimple: any = {};
  funcDataListFlatten.current.forEach((item: any) => {
    Object.assign(funcDataListSimple, { [item.title]: item.title });
  });
  // 以变量字符长度排序,确保`DATAIF`比`IF`优先匹配
  const funcDataListSort = funcDataListFlatten.current;

  useEffect(() => {
    if (funcDataListSort.length) {
      setTimeout(() => {
        cmUtils.variableRender();
      }, 100);
    }
  }, [JSON.stringify(funcDataListSort)]);

  // const varDataListFlatten: any[] = [];
  const varDataListFlatten = useRef<any[]>([]);
  if (!varDataListFlatten.current.length && varDataList.length) {
    flatten(varDataList, varDataListFlatten.current);
  }
  // flatten(varDataList, varDataListFlatten);
  const varDataListSimple: any = {};
  varDataListFlatten.current.forEach((item) => {
    Object.assign(varDataListSimple, { [item.key]: item.titleStr });
    if (item.attrs) {
      item.attrs.forEach((attrItem: any) =>
        Object.assign(varDataListSimple, {
          [attrItem.key]: `${item.titleStr}.${attrItem.titleStr}`,
        }),
      );
    }
  });

  // 插入的变量在函数内,并且前面也是变量
  const isInFunc = (id: number, code: string) => {
    let left1: number = 0;
    let left2: number = 0;
    let right1: number = 0;
    let right2: number = 0;
    // 前面是否是变量
    const beforeVar = code.split('')[id - 1] === '}';
    code.split('').forEach((item, index) => {
      if (index < id) {
        if (item === '(') {
          left1++;
        } else if (item === ')') {
          left2++;
        }
      } else {
        if (item === '(') {
          right1++;
        } else if (item === ')') {
          right2++;
        }
      }
    });
    return left1 > left2 && right1 < right2 && beforeVar;
  };

  const cmUtils: {
    insert: (variable: string, isFormula: boolean) => void;
    variableRender: () => void;
  } = {
    // 插入变量
    insert: (variable: string, isFormula: boolean = false) => {
      // 光标位置插入新值(变量)
      // editor.replaceSelection(variable);

      // "公式"类型变量时
      if (isFormula) {
        // 光标位置固定插入内容
        editor.replaceSelection(variable + '()');
        // 光标左移
        editor.execCommand('goCharLeft');
      } else {
        const pos = editor.getCursor()?.ch;
        const inFunc = isInFunc(pos, editor.getValue());
        if (inFunc) {
          editor.replaceSelection(',' + variable);
        } else {
          editor.replaceSelection(variable);
        }
      }
      cmUtils.variableRender();
      // 让编辑器聚集
      editor.focus();
    },

    // 替换变量(变量示例:${xxx})
    variableRender: () => {
      const code = _.cloneDeep(editor.getValue());
      // 换行分隔
      const codeArr = code.split('\n');

      const makeText = (
        line: number,
        sIndex: number,
        eIndex: number,
        variable: string,
        text: string,
        hasError: boolean,
        type?: string,
      ) => {
        editor.markText(
          {
            line: line,
            ch: sIndex,
          },
          {
            line: line,
            ch: eIndex,
          },
          {
            replacedWith: domTagGen(
              variable,
              text,
              hasError ? 'red' : '#026be1',
              type,
            ),
            inclusiveRight: false,
            readOnly: false,
          },
        );
      };

      const replacement = (
        line: number,
        regexp: any,
        refObj: any,
        type?: string,
      ) => {
        const lineStr = codeArr[line];
        let match: any;
        while ((match = regexp.exec(lineStr)) !== null) {
          const variable = match[0];
          const sIndex = match.index;
          const eIndex = sIndex + variable.length;
          const text: string = refObj[variable] || '(已缺失)';
          if (!type || (type === 'function' && lineStr[eIndex] === '(')) {
            const hasError: boolean = refObj[variable] === undefined;
            makeText(line, sIndex, eIndex, variable, text, hasError, type);
            codeArr[line] = codeArr[line].replace(
              variable,
              strFill(0, variable.length, 0),
            );
          }
        }
      };

      const funcRegexp = new RegExp(
        funcDataListSort
          .map((data: any) => {
            return '\\b' + data.title + '\\b';
          })
          .join('|'),
        'g',
      );

      for (let i = 0; i < editor.doc.size; i++) {
        // 替换变量名称
        const regexp = /\$\{.*?\}/g;
        replacement(i, regexp, varDataListSimple);
        if (Boolean(isUseFun) && funcDataListSort.length > 0) {
          // 替换函数公式名称
          replacement(i, funcRegexp, funcDataListSimple, 'function');
        }
      }
    },
  };

  const getFuncId = (name: string) => {
    return funcDataListFlatten.current.find(
      (item: any) => item.funcNameEg === name,
    )?.id;
  };

  useEffect(() => {
    if (value && !isInitDone) {
      // 限制初始值只设置一次
      setValueLocal(value);
    }
  }, [value]);

  useEffect(() => {
    // 消息提醒 新增模板时  触发方式变为"定时触发"时 需要将消息内容中的表单字段值清除
    if (resetValue) {
      setValueLocal(resetValue);
    }
  }, [resetValue]);

  useEffect(() => {
    if (newVariable) {
      cmUtils.insert(newVariable.key, newVariable.type === 'fun');
    }
  }, [newVariable]);

  // 编辑器内容变化响应
  const onHandleChange = (editor: any, data: any, value: string) => {
    cmUtils.variableRender();
    onChange(value);
    setIsInitDone(true);
    if (!formatRef.current) {
      editor.showHint();
    }
    formatRef.current = false;
    // 函数补全时,光标左移
    if (data.origin === 'complete' && data.text?.[0]?.endsWith('()')) {
      editor.execCommand('goCharLeft');
      const funcName = data.text?.[0].slice(0, -2);
      const funcData = funcDataListFlatten.current.find(
        (data: any) => data.funcNameEg === funcName,
      );
      if (funcData && typeof onFocusFunc === 'function') {
        onFocusFunc(funcData);
      }
    }
    if (value === '') {
      onFocusFunc(null);
    }
  };

  // 光标移动响应
  // const onHandleCursor = (editor: any, cursor: any) => {
  //   const lineStr = editor.getLine(cursor.line);
  //   const funcName = getLegalVaribleNameFromIndex(lineStr, cursor.ch);
  //   const funcData = funcDataListFlatten.find(
  //     (data) => data.title === funcName,
  //   );
  //   if (funcData && typeof onFocusFunc === 'function') {
  //     onFocusFunc(funcData);
  //   }
  // };

  // 格式化code文本
  const autoFormatSelection = () => {
    const code = editor.getValue(); // 获取编辑器中的代码
    let beautifiedCode = beautify(code); // 使用代码美化工具(如 js-beautify)美化代码
    beautifiedCode = beautifiedCode.replace(
      /\$\s*\{\s*(.*?)\s*\}/g,
      function (a, b) {
        return '${' + b + '}';
      },
    );
    formatRef.current = true;
    editor.setValue(beautifiedCode); // 将美化后的代码设置回编辑器
  };

  // 代码提示
  const hintCompletion = (cm: any, options: any) => {
    const funRegex = /[a-zA-Z0-9_\u4e00-\u9fff]/;
    const dotRegex = /\./;
    const varRegex = /^\.(\}.*?\{\$)/;
    const comp = funcDataListSort.map((data: any) => data.title);
    return new Promise((accept) => {
      setTimeout(() => {
        const cursor = cm.getCursor();
        const line = cm.getLine(cursor.line);
        let start = cursor.ch;
        let end = cursor.ch;
        let completions = [];
        while (start && funRegex.test(line.charAt(start - 1))) --start;
        while (end < line.length && funRegex.test(line.charAt(end))) ++end;
        const word = line.slice(start, end);
        if (start && dotRegex.test(line.charAt(start - 1))) {
          // 提示对象.属性
          if (word === '') {
            const lineReverse = reverseStr(line.slice(0, start));
            const matched = varRegex.exec(lineReverse);
            const word = matched ? reverseStr(matched[1]) : '';
            const findVar = varDataListFlatten.current.find(
              (item: any) => item.key === word,
            );
            if (findVar && findVar.attrs) {
              completions.push(
                ...findVar.attrs.map((attrItem: any) => ({
                  text: attrItem.key,
                  displayText: attrItem.titleStr,
                  from: Cm.Pos(cursor.line, start - word.length - 1),
                  to: Cm.Pos(cursor.line, end),
                  customInfo: {
                    widget: getWidgetByType(attrItem.fieldGroupType),
                  },
                })),
              );
            }
          }
        } else {
          // 提示公式函数名、变量
          if (word) {
            for (let i = 0; i < comp.length; i++) {
              if (comp[i].toLowerCase().indexOf(word.toLowerCase()) > -1) {
                completions.push(comp[i]);
              }
            }
            for (let i = 0; i < varDataListFlatten.current.length; i++) {
              const it = varDataListFlatten.current[i];
              if (it.titleStr.indexOf(word) > -1) {
                completions.push({
                  text: it.key,
                  displayText: it.titleStr,
                });
              }
            }
          }
        }

        // const firstFieldIndex = completions.findIndex(item => typeof item !== 'string');
        completions = completions.map((item: any, index) => {
          if (typeof item === 'string') {
            return {
              text: item + '()',
              displayText: item,
              render: (element: any, self: any, data: any) => {
                const container = document.createElement('div');
                container.className = 'hint-line';
                const top = document.createElement('div');
                // @ts-ignore
                const jsxEl: React.ReactElement = handleHighlight(
                  item,
                  word,
                  'fx',
                );
                ReactDOM?.render(jsxEl, top);
                // top.innerHTML = <span>122</span>;
                top.className = 'hint-line_left';
                const bottom = document.createElement('div');
                bottom.className = 'hint-line_right';
                // @ts-ignore
                const desc =
                  funcDataListFlatten.current.find(
                    (it: any) => it.funcNameEg === item,
                  )?.funcName || '';
                bottom.innerHTML = desc;
                container.appendChild(top);
                container.appendChild(bottom);
                element.appendChild(container);
                element.addEventListener('click', function () {
                  self.complete(); // 选择当前提示项并插入到编辑器中
                  self.close(); // 关闭代码提示列表
                });
              },
            };
          } else {
            return {
              text: item.text,
              displayText: item.displayText,
              ...(item.from && {
                from: item.from,
                to: item.to,
              }),
              render: (element: any, self: any) => {
                element.style.padding = '5px';
                const DIV = document.createElement('div');
                DIV.style.display = 'flex';
                DIV.style.justifyContent = 'space-between';
                const LEFT = document.createElement('span');
                // @ts-ignore
                const jsxEl: React.ReactElement = handleHighlight(
                  item.displayText,
                  word,
                );
                ReactDOM?.render(jsxEl, LEFT);
                // LEFT.innerHTML = item.displayText;
                const variable = varDataListFlatten.current.find(
                  (it) => it.key === item.text,
                );
                let RIGHT;
                if (variable?.widget) {
                  const { name, color, bgColor } =
                    widgetMapping[variable.widget] || {};
                  RIGHT = document.createElement('span');
                  RIGHT.className = 'tag';
                  RIGHT.innerHTML = name;
                  RIGHT.style.color = color;
                  RIGHT.style.backgroundColor = bgColor;
                } else if (item.customInfo?.widget) {
                  const { name, color, bgColor } =
                    widgetMapping[item.customInfo?.widget] || {};
                  RIGHT = document.createElement('span');
                  RIGHT.className = 'tag';
                  RIGHT.innerHTML = name;
                  RIGHT.style.color = color;
                  RIGHT.style.backgroundColor = bgColor;
                }
                DIV.appendChild(LEFT);
                if (RIGHT) DIV.appendChild(RIGHT);
                // if (firstFieldIndex === index) {
                //   const TITLE = document.createElement('div');
                //   TITLE.innerHTML = '当前表单字段';
                //   TITLE.style.padding = '5px';
                //   element.appendChild(TITLE)
                // }
                element.appendChild(DIV);
                element.addEventListener('click', function () {
                  self.complete(); // 选择当前提示项并插入到编辑器中
                  self.close(); // 关闭代码提示列表
                });
              },
            };
          }
        });

        if (completions.length) {
          return accept({
            list: completions,
            from: Cm.Pos(cursor.line, start),
            to: Cm.Pos(cursor.line, end),
          });
        } else {
          return accept(null);
        }
      }, 50);
    });
  };

  // 清除组件内容
  const onHandleClear = () => {
    editor.doc.setValue('');
  };

  useImperativeHandle(cRef, () => ({
    autoFormatSelection,
    // 获取编辑器使用到的函数公式名称, eg: [IF, SUM, CONCAT]
    getUsedFuncList() {
      const usedFuncList = [];
      const codeArr = _.cloneDeep(editor.getValue()).split('\n');
      if (Boolean(isUseFun) && funcDataListSort.length > 0) {
        const funcRegexp = new RegExp(
          funcDataListSort
            .map((data: any) => {
              return '\\b' + data.title + '\\b';
            })
            .join('|'),
          'g',
        );
        for (let i = 0; i < editor.doc.size; i++) {
          const lineStr = codeArr[i];
          let match: any;
          while ((match = funcRegexp.exec(lineStr)) !== null) {
            const variable = match[0];
            if (lineStr[match['index'] + variable.length] === '(') {
              const funcId = getFuncId(variable);
              if (funcDataListSimple[variable] && funcId) {
                usedFuncList.push(funcId);
              }
            }
          }
        }
      }
      return usedFuncList;
    },
    getEditor() {
      return editor;
    },
  }));

  function customLint() {
    return [];
  }

  return (
    <div
      className={
        from === 'copySend'
          ? 'qx-copy-send-cm ' + className
          : 'qx-formula-cm ' + className
      }
    >
      {/* @ts-ignore */}
      <CodeMirror
        editorDidMount={(editor) => {
          setEditor(editor);
          editor.addKeyMap({
            'Ctrl-f': autoFormatSelection,
          });
        }}
        value={(valueLocal || '').toString()}
        options={{
          mode: 'javascript', // 语言
          theme: 'idea',
          placeholder: '请输入函数',
          extraKeys: { Ctrl: 'autocomplete' }, //ctrl+空格自动提示配置
          hintOptions: {
            completeSingle: false,
            hint: hintCompletion,
            className: 'myCodeMirrorHint',
          },
          autofocus, //自动获取焦点
          matchBrackets: true, // 匹配括号
          autoCloseBrackets: true,
          lint: {
            getAnnotations: customLint,
          },
          readOnly: Boolean(readOnly),
          cursorHeight: Boolean(readOnly) ? 0 : 'auto',
          // 滚动(false,默认)或自动换行
          lineWrapping: true,
          styleActiveLine: true, // 光标行代码高亮
        }}
        // onKeyEvent={handleKeyEvent}
        // onBeforeChange={handleBeforeChange}
        // onCursorActivity={handleCursorActivity}
        // onCursor={onHandleCursor}
        onChange={onHandleChange}
      />
      {allowClear && value && (
        <CloseCircleFilled
          className={'qx-field-setter__clear'}
          onClick={onHandleClear}
        />
      )}
    </div>
  );
};
export default CodeEditor;