All files / src/form PageHeader.tsx

50.51% Statements 49/97
37.17% Branches 29/78
36.36% Functions 8/22
50.52% Lines 48/95

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 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                                          66x               6x   6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x     6x 1x         6x   1x     1x   1x           6x 1x 1x                             6x 1x 1x                           6x 1x       1x 1x 1x                                                                             6x 1x 1x       6x 6x                             6x                                                       6x                                         6x               6x                                           6x                                               6x               6x                             6x                                       6x                                   6x               6x               6x        
import React, { ReactElement, useEffect, useRef, useState } from "react";
import { Alert, Input, Popover, Space, Tag, Tooltip } from "antd";
import { PageHeader as AntdPageHeader } from '@ant-design/pro-layout';
import { useTranslation } from 'react-i18next';
import { filterDataAsync } from "@kernel/ClientSideFilter";
import { FileAddOutlined, FilterOutlined } from '@ant-design/icons';
import { fetchCanCreate, fetchFormIdAndExtInfoByName, fetchFormIdAndExtInfoByType } from "@utils/FetchUtils";
import { fullDomainNameToHumanReadable } from "@utils/StringUtils";
import { FormProps, PageHeaderProps } from "@props/RecordProps";
import { CsvOperateComponent } from "./csv";
import { CreateAction, ActionButtons, UpdateAction } from "./";
import { WEBSOCKET_SERVER_URL } from "@config/base";
import { stopPropagationAndPreventDefault } from "@utils/ObjectUtils";
import ReconnectableSocket, { SocketInterface } from "@utils/WebsocketUtils";
import { realtimeReducer, RealtimeWebsocketListenFunction, useConfig } from "../utils/hooks";
import {
  getDomainAutoRefreshService,
  UnsubscribeCallback
} from "@utils/DomainAutoRefreshUtils";
import DisplayStyleDropdown from "./DisplayStyleDropdown";
 
const PageHeader = (props: PageHeaderProps): ReactElement => {
  const {
    domainName, data, selectedData, columns, tableMode, objectValues,
    enumValues, setData, fetchDataCallback, initialCanCreate, ownerClass, extra,
    ownerColumn, ownerId, columnNameInOwnerClass, readonly, setTableMode,
    initShowCreateModal, initDomainId, initDomainPage, zIndex, isCurrentActiveTab,
    displayLabel, hide, listForm, dataState, dataDispatch, disableSearch, disableCSV,
    createFormName,
  } = props;
 
  const { t } = useTranslation();
  const [canCreate, setCanCreate] = useState<boolean>(false);
  const [createFormId, setCreateFormId] = useState<number>();
  const [canCreateErrorMsg, setCanCreateErrorMsg] = useState<string | undefined>(undefined);
  const domainTitle = fullDomainNameToHumanReadable(listForm?.extInfo?.domainTitle ?? domainName);
  const [matchedNumber, setMatchedNumber] = useState<number>();
  const [filterKeyword, setFilterKeyword] = useState<string>();
  const [visiblePopover, setVisiblePopover] = useState<string>();
  const [websocket, setWebsocket] = useState<SocketInterface>();
  /** 查看详情的 Modal 的只读状态,在查看详情的 Modal 中,可以点击编辑按钮,将其状态修改为编辑状态 */
  const [detailModalReadonly, setDetailModalReadonly] = useState<boolean>(initDomainPage === 'detail');
  const { value: useNewWebsocketService } = useConfig("debugDynamicLogic.enableNewDomainChangePushService");
  const domainChangeUnsubscribeCallbackRef = useRef<UnsubscribeCallback>();
 
  /** 如果不是当前的激活页签,则隐藏所有的 Popover 控件 */
  useEffect(() => {
    Iif (isCurrentActiveTab === false) {
      setVisiblePopover(undefined);
    }
  }, [isCurrentActiveTab]);
 
  useEffect(() => {
    let promise: Promise<FormProps>;
    Iif (createFormName) {
      promise = fetchFormIdAndExtInfoByName(domainName, createFormName);
    } else {
      promise = fetchFormIdAndExtInfoByType(domainName, "Create");
    }
    promise.then(json => setCreateFormId(json.id))
      .catch(e => {
        console.warn(`Failed to get create form id of domain ${domainName}: ${e}`);
      });
  }, [createFormName, domainName]);
 
  useEffect(() => {
    if (initialCanCreate != null) {
      setCanCreate(initialCanCreate);
    } else E{
      fetchCanCreate(domainName).then(json => {
        if (json.error === 1) {
          setCanCreate(false);
          setCanCreateErrorMsg(json.createErrorMsg);
        } else {
          setCanCreate(json.create);
        }
      }).catch(
        (e) => console.warn(`Failed to get canCreate for ${domainName}: ${JSON.stringify(e)}`)
      );
    }
  }, [domainName, initialCanCreate]);
 
  useEffect(() => {
    Eif (useNewWebsocketService !== 'true') {
      return;
    }
    const domainAutoRefreshService = getDomainAutoRefreshService();
    if (dataState.refreshMode === 'realtime') {
      domainChangeUnsubscribeCallbackRef.current = domainAutoRefreshService.subscribe(domainName, () => fetchDataCallback(false));
    } else if (dataState.refreshMode === 'manual' || dataState.refreshMode == null) {
      domainChangeUnsubscribeCallbackRef.current?.();
    }
    return () => {
      domainChangeUnsubscribeCallbackRef.current?.();
    };
  }, [domainName, dataState.refreshMode, useNewWebsocketService, fetchDataCallback]);
 
  // deprecated
  useEffect(() => {
    Iif (useNewWebsocketService === 'true') {
      return;
    }
    //console.log("websocket: ", websocket, " dataState.data: ", dataState.data, " refreshModeState: ", dataState.refreshMode);
    const { data } = dataState;
    Eif (websocket == null || data == null) {
      return;
    }
    let listenFunc: RealtimeWebsocketListenFunction | undefined;
    // 只在第一次 websocket 连接时候,注册监听函数,后续数据变化了,无需再注册或者刷新监听函数
    if (websocket.numberOfMessageListeners() === 0) {
      if (dataState.refreshMode === 'realtime') {
        listenFunc = realtimeReducer({
          type: 'initConnection', payload: {
            domainName, data, dataDispatch, websocket, fetchDataCallback
          }
        });
        websocket.onStateChange((isOpen: boolean) => {
          //on websocket reconnect, send current listen id to backend
          if (isOpen) {
            realtimeReducer({
              type: 'transferIds', payload: {
                domainName, data, dataDispatch, websocket, fetchDataCallback
              }
            });
          }
        });
      } else if (dataState.refreshMode === 'manual' || dataState.refreshMode == null) {
        realtimeReducer({
          type: 'close', payload: {
            domainName, data, dataDispatch, websocket, fetchDataCallback
          }
        });
      }
      if (listenFunc != null) {
        console.log("Replace websocket listen func with new data: ", dataState.data);
        websocket.replaceOn(listenFunc());
      }
    }
  }, [
    dataDispatch, dataState.data, domainName, dataState.refreshMode, websocket,
    fetchDataCallback, dataState, websocket?.isConnected, useNewWebsocketService,
  ]);
 
  // Reset the websocket connection when domainName changes
  useEffect(() => {
    websocket?.close();
    setWebsocket(undefined);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [domainName]);
 
  const actionMode = (selectedData.length > 0) ? "multiple" : "class";
  const actionButtons = (<ActionButtons
    visiblePopover={visiblePopover}
    setVisiblePopoverCallback={(key?: string) => setVisiblePopover(key)}
    domainName={domainName}
    fetchDataCallback={fetchDataCallback}
    mode={actionMode}
    selectedData={selectedData}
    zIndex={zIndex}
    displayLabel={displayLabel}
    ownerClass={ownerClass}
    ownerId={ownerId}
    columnNameInOwnerClass={columnNameInOwnerClass}
    labelField={listForm?.labelField}
  />);
 
  const csvOperations = disableCSV ? (
    <></>
  ) : (
    <CsvOperateComponent
      visiblePopover={visiblePopover}
      setVisiblePopoverCallback={(key, e) => {
        if (e != null) {
          stopPropagationAndPreventDefault(e);
        }
        setVisiblePopover(key);
      }}
      domainName={domainName}
      columns={columns}
      selectedData={selectedData}
      enumValues={enumValues}
      objectValues={objectValues}
      allData={data ?? []}
      fetchDataCallback={fetchDataCallback}
      ownerClass={ownerClass}
      ownerId={ownerId}
      columnNameInOwnerClass={columnNameInOwnerClass}
      showUpload={canCreate}
      ownerColumn={ownerColumn}
      readonly={readonly}
      zIndex={zIndex}
    />
  );
 
  const createIcon = canCreate ? (
    <div>
      <CreateAction
        initShowCreateModal={initShowCreateModal}
        formId={createFormId ?? undefined}
        domainName={domainName}
        ownerId={ownerId}
        ownerClass={ownerClass}
        columnNameInOwnerClass={columnNameInOwnerClass}
        callback={() => fetchDataCallback(true)}
        initialCanCreate={canCreate}
        zIndex={zIndex + 1}
        showIconAndText={true}
        formName={createFormName}
      />
    </div>
  ) : (
    <></>
  );
 
  const createAndImportWrapper = (
    <Space>
      {createIcon}
      {csvOperations}
    </Space>
  );
 
 
  const changeDisplayStyleElem = (
    <DisplayStyleDropdown
      key="change-display-style"
      setTableMode={setTableMode}
      tableMode={tableMode}
      fetchDataCallback={fetchDataCallback}
      refreshMode={dataState.refreshMode}
      setRefreshMode={(mode: string) => {
        dataDispatch({ type: "set", payload: { refreshMode: mode } });
        if (mode === 'realtime') {
          const socket: SocketInterface = (websocket == null || !websocket.isConnected()) ?
            ReconnectableSocket(`${WEBSOCKET_SERVER_URL}/websocket/domainData`) : websocket;
          setWebsocket(socket);
        } else {
          if (websocket != null) {
            websocket.close();
            setWebsocket(undefined);
          }
        }
      }}
    />
  );
 
  const textFilterElement = (<Input
    key="search-form"
    placeholder={t("Type to filter table content")}
    allowClear
    prefix={<FilterOutlined style={{ paddingRight: "8px" }} />}
    suffix={(filterKeyword != null && filterKeyword !== '' && matchedNumber != null) &&
      <Tooltip
        title={t("FilterTableContentTooltip", {
          numOfRow: data.length, matchedNumber,
          isAre: matchedNumber > 1 ? 'are' : 'is'
        })}
      >
        <Tag className="filter-number-tag">{`${matchedNumber}/${data.length}`}</Tag>
      </Tooltip>}
    onChange={(e) => {
      const { value } = e.target;
      setFilterKeyword(value);
      filterDataAsync(data, columns, enumValues, objectValues, value)
        .then(result => {
          setData(result.data);
          setMatchedNumber(result.total);
        });
    }} />);
 
  const masterExtra = (<>
    {extra}
    {disableSearch ? (<></>) : [
      changeDisplayStyleElem,
      textFilterElement,
    ]}
  </>);
 
  const canCreateErrorElement = ((canCreateErrorMsg != null) &&
    <Popover
      title={<Alert message="Error" type="error" showIcon />}
      content={<pre>{canCreateErrorMsg}</pre>}
    >
      <Tooltip
        title={`Create new ${domainTitle} (Backend configuration error)`}
      >
        <FileAddOutlined
          className="link-icon"
          style={{ color: "red" }} />
      </Tooltip>
    </Popover>
  );
 
  const initDomainUpdateActionElement = (initDomainId != null) && (
    <div style={{ display: "none" }}>
      <UpdateAction
        id={initDomainId}
        domainName={domainName}
        ownerClass={ownerClass}
        ownerId={ownerId}
        initShowEditModal={initDomainId != null}
        callback={() => fetchDataCallback()}
        zIndex={zIndex + 1}
        readonly={detailModalReadonly}
        switchEditable={() => {
          setDetailModalReadonly(!detailModalReadonly);
        }}
      /></div>
  );
 
  // 如果父对象传递了 initDomainId 表示页面打开的时候就需要
  // 打开编辑页面
  const masterHeader = (
    <AntdPageHeader
      className="site-page-header"
      backIcon={false}
      title={domainTitle}
      subTitle={<Space
        direction="horizontal"
        size={"small"}
      >
        {!readonly && canCreate && canCreateErrorMsg == null && createAndImportWrapper}
        {!canCreate && canCreateErrorElement}
        {actionButtons}
        {initDomainUpdateActionElement}
      </Space>}
      extra={masterExtra}
    />
  );
 
  const detailHeader = (
    <Space
      className="detail-page-action-space"
      direction="horizontal"
      size="middle">
      {!readonly && createAndImportWrapper}
      {actionButtons}
    </Space>
  );
  const TableModeHeaderMapping = {
    "simple-list": masterHeader,
    "table-list": masterHeader,
    "card-list": masterHeader,
    "detail-drawer": detailHeader,
    "detail": detailHeader,
    "finder": (<div />),
  };
  return (hide === true) ? (<div style={{ height: "80px" }} />) : TableModeHeaderMapping[tableMode];
};
 
export default PageHeader;