All files / src/form PredefinedFilters.tsx

38% Statements 19/50
20.93% Branches 9/43
20% Functions 2/10
38.77% Lines 19/49

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                                                    66x                   31x 30x 30x 30x   30x           30x   30x     30x           30x                       30x                         30x     30x 30x 30x                                                                                                         30x     30x     30x         30x        
import React, { ReactElement, useState } from 'react';
import {
  getAppliedSearchConditionsForDomain, getCurrentFilterId, removeObsoleteConditions,
  setSearchConditions
} from '@kernel/ServerSideSearcher';
import { DynamicFilterResponseProps, FetchSearchResultProps, SearchConditions, TableMetaProps } from '@props/RecordProps';
import { Tag, Tooltip } from 'antd';
import { useTranslation } from 'react-i18next';
import { isEqual } from 'lodash';
import { DynamicIcon, CloseIcon } from '../components';
import { stopPropagationAndPreventDefault } from "@utils/ObjectUtils";
import { useFilter } from '@utils/hooks';
import { getUserId } from '@utils/TokenUtils';
import SaveDynamicFilterPopover from '../components/filters/SaveDynamicFilterPopover';
 
export interface PredefinedFiltersProps {
  domainName: string;
  fetchDataCallback: () => void;
  fullTextFetchDataCallback?: (fullTextSearchConditions?: FetchSearchResultProps) => void;
  columns: Array<TableMetaProps>;
  displayStyle: 'inline' | 'block';
  displayDefault?: boolean;
  zIndex: number;
  fullTextSearchConditions?: FetchSearchResultProps;
}
 
const PredefinedFilters = (props: PredefinedFiltersProps): ReactElement => {
  const {
    columns,
    fetchDataCallback,
    domainName,
    displayStyle,
    displayDefault,
    zIndex,
    fullTextSearchConditions,
    fullTextFetchDataCallback
  } = props;
  const { t } = useTranslation();
  const [refresh, setRefresh] = useState<number>(0);
  const [dynamicFilters, defaultFilter] = useFilter(domainName, displayDefault, refresh);
 
  const refreshCallback = (): void => {
    setRefresh(refresh + 1);
  };
 
  // 如果该方法返回 undefined,
  // 则 apply 系统定义的 isDefault 为 true 的 DynamicFilter
  const conditionSaved = getAppliedSearchConditionsForDomain(domainName);
 
  const { changed, conditions } = (conditionSaved === undefined) ?
    { changed: false, conditions: undefined } : removeObsoleteConditions(conditionSaved, columns);
 
  Iif (changed && !fullTextFetchDataCallback) {
    setSearchConditions(domainName, conditions);
    fetchDataCallback();
  }
 
  // 如果当前保存的搜索条件为 null 则默认使用 defaultFilter 来进行过滤
  Iif (defaultFilter != null && conditions == null) {
    const cond = JSON.parse(defaultFilter.conditions);
    defaultFilter.parsedConditions = cond;
    if (fullTextFetchDataCallback != null) {
      setSearchConditions(domainName, cond.searchConditions ?? {}, defaultFilter.id);
      fullTextFetchDataCallback(cond);
    } else {
      setSearchConditions(domainName, cond, defaultFilter.id);
      fetchDataCallback();
    }
  }
 
  const applyPredefinedFilter = (filter: DynamicFilterResponseProps): void => {
    const parsedCondition = filter.parsedConditions ?? {};
    if (fullTextFetchDataCallback != null) {
      const c = (parsedCondition as unknown as FetchSearchResultProps);
      setSearchConditions(domainName, c.searchConditions, filter.id);
      fullTextFetchDataCallback(c);
    } else {
      const c = (parsedCondition as unknown as SearchConditions);
      setSearchConditions(domainName, c, filter.id);
      fetchDataCallback();
    }
  };
 
  const userId = getUserId();
 
  function blockRender(): ReactElement {
    const entries = [] as ReactElement[];
    const nonEmptyDefaultFilter = defaultFilter ?? {} as DynamicFilterResponseProps;
    dynamicFilters?.forEach((f: DynamicFilterResponseProps, idx: number) => {
      f.parsedConditions = JSON.parse(f.conditions);
      //const isCurrent = isEqual(f.parsedConditions, conditions) || isEqual(f.parsedConditions, fullTextSearchConditions);
      const isCurrent = isEqual(f.id, getCurrentFilterId(domainName));
      const isDefault = isEqual(f, defaultFilter);
      const onClick = (): void => applyPredefinedFilter(isCurrent ? nonEmptyDefaultFilter : f);
      const isMyFilter = (f.owner != null && userId != null && f.owner === parseInt(userId));
      const userDefinedClass = isMyFilter ? "user-defined-filter-tag" : "";
      const className = isCurrent ?
        `current-filter-tag filter-${f.name}-active ${userDefinedClass}` :
        `filter-tag filter-${f.name}-inactive ${userDefinedClass}`;
      entries.push(
        <Tooltip
          title={t(f.description ?? "")}
          key={f.name}
          placement={(idx === dynamicFilters?.length - 1) ? "bottom" : "top"}
          mouseEnterDelay={0.5}
        >
          <Tag
            onClick={onClick}
            className={className}
            icon={f.icon == null ? undefined : <DynamicIcon type={f.icon} />}
          >
            <span>{t(f.label)}</span>
            <span>
              {isMyFilter &&
                <SaveDynamicFilterPopover
                  domainName={domainName}
                  zIndex={zIndex + 1}
                  filter={f}
                  updateCallback={() => refreshCallback()}
                  fullTextSearchConditions={fullTextSearchConditions}
                />
              }
            </span>
            <span>
              {isCurrent &&
                <a href="/#"
                  onClick={(e) => stopPropagationAndPreventDefault(e)}
                  title={t("Remove this filter")}
                >
                  <CloseIcon
                    noLinkWrap={true}
                    onClick={() => applyPredefinedFilter(isDefault ?
                      {} as DynamicFilterResponseProps : nonEmptyDefaultFilter)}
                  />
                </a>
              }
            </span>
          </Tag>
        </Tooltip>
      );
    });
    return entries.length > 0 ? (<>{entries}</>) : (<></>);
  }
 
  const inlineRender = (): ReactElement => {
    return blockRender();
  };
  const renderByDisplayStyle = {
    inline: inlineRender,
    block: blockRender
  };
 
  return renderByDisplayStyle[displayStyle]();
};
 
export default PredefinedFilters;