All files / src/kernel ClientSideFilter.tsx

81.81% Statements 72/88
78.43% Branches 40/51
57.14% Functions 8/14
82.35% Lines 70/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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              66x                                                                                               8x 88x       8x 3x   18x 18x       5x             5x 5x 5x 55x   5x 5x   5x 5x 5x 5x     5x 20x 20x       5x 5x 15x 15x     15x 80x 80x     5x   5x 30x   30x 294x     294x 294x 54x   240x 240x     240x 240x 240x 240x   240x 240x 240x   240x 30x 30x 30x 30x 30x 5x   5x 2x                     210x 90x 90x 90x 9x   9x 6x                     120x 5x 5x 6x                       30x 30x 15x   30x     5x            
import { isEnumColumn, isObjectType } from "@utils/ColumnsUtils";
import { EnumValues, ObjectValues, RecordProps, TableMetaProps } from "../props/RecordProps";
import React, { ReactElement } from "react";
import Highlighter from "react-highlight-words";
import { FilterMinimalKeywordLength, TRIGGER_CLIENT_SIDE_FILTER_MINIMAL_TIME_MS } from '@config/base';
 
let latestValue: string;
let timeout: ReturnType<typeof setTimeout> | undefined = undefined;
 
export async function filterDataAsync(
  data: Array<RecordProps>,
  columns: Array<TableMetaProps>,
  enumValues: EnumValues,
  objectValues: ObjectValues,
  keyword: string
): Promise<{ data: Array<RecordProps>; total: number }> {
  latestValue = keyword;
 
  //控制在 TRIGGER_CLIENT_SIDE_FILTER_MINIMAL_TIME_MS 内只搜索一次
  const x = (): Promise<string> => {
    return new Promise((resolve) => {
      if (timeout != null) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(() => resolve('done!'),
        TRIGGER_CLIENT_SIDE_FILTER_MINIMAL_TIME_MS);
    });
  };
 
  return x().then(() => {
    return new Promise((resolve) => {
      const result = filterData(data, columns, enumValues, objectValues, latestValue);
      resolve(result);
    });
  });
}
 
/**
 * 在客户端过滤表格中的内容,使用大小写不敏感的匹配方式,使用界面上用户看到的所有信息进行匹配
 * @param data 表格中的数据内容
 * @param columns 表格的列的元数据
 * @param enumValues 表格中包含的枚举值列表
 * @param objectValues 表格中包含的对象值列表
 * @param keyword 过滤的关键字
 */
export function filterData(
  data: Array<RecordProps>,
  columns: Array<TableMetaProps>,
  enumValues: EnumValues,
  objectValues: ObjectValues,
  keyword: string): {
    data: Array<RecordProps>;
    total: number;
  } {
  //Reset all render to clear last round serach keyword highlight
  columns.forEach(column => {
    column.render = column.backupRender;
  });
 
  // If keyword is empty, display all data
  if (keyword == null || keyword === '') {
    return {
      data: data.map(row => {
        row.clientSideShow = true;
        return row;
      }),
      total: data.length
    };
  } Iif (keyword != null && keyword !== ''
    && keyword.length < FilterMinimalKeywordLength) {
    return {
      data, total: data.length
    };
  } else {
    //Loop over every line of data
    const upperCaseKeyword: string = keyword.toUpperCase();
    const columnMetaByKey: { [propName: string]: TableMetaProps } = {};
    columns.forEach(c => {
      columnMetaByKey[c.key] = c;
    });
    const isEnumColumnCache: { [propName: string]: boolean } = {};
    const isObjectColumnCache: { [propName: string]: boolean } = {};
 
    const flatEnumValuesCache: { [propName: string]: string } = {};
    for (const evName in enumValues) {
      const evValueLabelPairs = enumValues[evName];
      Iif (!Object.prototype.hasOwnProperty.call(enumValues, evName)) {
        continue;
      }
      for (let i = 0; i < evValueLabelPairs.length; i++) {
        const vlPair = evValueLabelPairs[i];
        flatEnumValuesCache[`${evName}_${vlPair.value}`] = vlPair.label;
      }
    }
 
    const flatObjectValuesCache: { [propName: string]: string } = {};
    for (const objName in objectValues) {
      const idLabelPairs = objectValues[objName];
      Iif (!Object.prototype.hasOwnProperty.call(objectValues, objName)) {
        continue;
      }
      for (let i = 0; i < idLabelPairs.length; i++) {
        const vlPair = idLabelPairs[i];
        flatObjectValuesCache[`${objName}_${vlPair.value}`] = vlPair.label;
      }
    }
    let matchedNumber = 0;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const filteredData = data.map((row, idx) => {
      let match = false;
      //Loop over every column of each line of data to match
      for (const property in row) {
        Iif (!Object.prototype.hasOwnProperty.call(row, property)) {
          continue;
        }
        const columnMeta = columnMetaByKey[property];
        if (columnMeta == null) {
          continue;
        }
        const rowValue = row[property];
        Iif (rowValue == null || rowValue === '') {
          continue;
        }
        const { type } = columnMeta;
        const isEnumFromCache = isEnumColumnCache[type];
        const isEnum = (isEnumFromCache != null) ? isEnumFromCache : isEnumColumn(type);
        isEnumColumnCache[type] = isEnum;
 
        const isObjectFromCache = isObjectColumnCache[type];
        const isObject = (isObjectFromCache != null) ? isObjectFromCache : isObjectType(type);
        isObjectColumnCache[type] = isObject;
 
        if (isEnum) {
          const enumValue = enumValues[property];
          Eif (null != enumValue && enumValue.length > 0) {
            const enumCacheKey = `${property}_${rowValue}`;
            const matchLabel = flatEnumValuesCache[enumCacheKey];
            if (matchLabel.toUpperCase()?.includes(upperCaseKeyword)) {
              match = true;
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              columnMeta.render = (text: string): ReactElement => {
                return (
                  <Highlighter
                    highlightClassName="highlight-word"
                    searchWords={[keyword]}
                    autoEscape
                    textToHighlight={matchLabel ? matchLabel : ''}
                  />
                );
              };
            }
          }
        } else if (isObject) {
          const objectCacheKey = `${type}_${rowValue.id}`;
          const matchLabel = flatObjectValuesCache[objectCacheKey];
          if (matchLabel?.toUpperCase().includes(upperCaseKeyword)) {
            match = true;
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            columnMeta.render = (text: string): ReactElement => {
              return (
                <Highlighter
                  highlightClassName="highlight-word"
                  searchWords={[keyword]}
                  autoEscape
                  textToHighlight={matchLabel ? matchLabel : ''}
                />
              );
            };
          }
        } else {
          if ((rowValue != null && rowValue.toString().toUpperCase().includes(upperCaseKeyword))) {
            match = true;
            columnMeta.render = (text: string): ReactElement => {
              return (
                <Highlighter
                  highlightClassName="highlight-word"
                  searchWords={[keyword]}
                  autoEscape
                  textToHighlight={text ? text.toString() : ''}
                />
              );
            };
          }
        }
      }
      row.clientSideShow = match;
      if (match) {
        matchedNumber += 1;
      }
      return row;
    });
 
    return {
      data: filteredData,
      total: matchedNumber
    };
  }
}