All files / src/form/update UpdateAction.tsx

51.78% Statements 58/112
48% Branches 24/50
44% Functions 11/25
51.35% Lines 57/111

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                              66x         64x 64x   64x 64x     64x       64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x   64x         64x 7x     64x 7x   7x           64x 11x 10x 10x 10x 16x       10x       11x 2x 2x 1x   1x     9x   8x 8x               64x                     64x               64x     64x           64x           64x             64x 10x                   54x                                                                         54x                                                                                               54x 54x   54x                         54x                               54x          
import React, { useEffect, useState, useContext } from 'react';
import { useLocation } from 'react-router-dom';
import { FormOutlined, EyeOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { ContinueOperate, FormExtInfoProps, SaveRecordProps, TableMetaProps, UpdateProps } from '@props/RecordProps';
import { Alert, Modal, Popover, Space } from "antd";
import UpdateComponent from "./App";
import { fetchDomainMeta, fetchFormExtInfo, fetchFormIdAndExtInfoByType } from "@utils/FetchUtils";
import { modalPropsBuilder, SaveLoadingButtonType } from '../';
import { LargeSpin } from "../../components";
import { hasDetailPanel } from '@utils/ColumnsUtils';
import { useDomainPermit } from '@utils/DomainPermitUtils';
import { useHotkeys } from 'react-hotkeys-hook';
import { ModalLockContext } from '@utils/context';
 
export const UpdateAction: React.FC<UpdateProps> = (props: UpdateProps) => {
  const {
    domainName, id, ownerClass, ownerId, showIconAndText, columnNameInOwnerClass,
    callback, errorMsg, formId, initShowEditModal, zIndex, onCancelCallback,
    queryParameters, refererUrl, readonly, switchEditable, fetchType,
  } = props;
  const { t } = useTranslation();
 
  const [loading, setLoading] = useState<boolean>(true);
  const [showModal, setShowModal] = useState<boolean>(
    initShowEditModal != null ? initShowEditModal : false
  );
  const [updateFormId, setUpdateFormId] = useState<number>();
  // 触发保存操作是通过每次将 triggerSave 这个 state 变量设置为不同的随机值
  // 进而触发 UpdateComponent 组件的刷新, 然后在 UpdateComponent 组件中,
  // 会判断 triggerSave 的值如果不是 false, 则表示需要触发保存操作
  const [triggerSave, setTriggerSave] = useState<false | number>(false);
  const [continueOperate, setContinueOperate] = useState<ContinueOperate>(false);
  const [columns, setColumns] = useState<Array<TableMetaProps>>();
  const [hasAnyDetailPanel, setHasAnyDetailPanel] = useState<boolean>(false);
  const [needToRefreshListPage, setNeedToRefreshListPage] = useState<boolean>(false);
  const [isValid, setIsValid] = useState<boolean>(true);
  const [saveLoadingButton, setSaveLoadingButton] = useState<SaveLoadingButtonType>(undefined);
  const location = useLocation();
  const currentUrl = refererUrl ?? location.pathname;
  const domainPermit = useDomainPermit(domainName, id);
  const [readonlyState, setReadonlyState] = useState<boolean>(readonly ?? false);
  const { acquireLock, releaseLock, hasLock } = useContext(ModalLockContext);
  const [lockId, setLockId] = useState(0);
  const [cancelConfirmMessage, setCancelConfirmMessage] = useState<string | undefined>();
  const [extInfo, setExtInfo] = useState<FormExtInfoProps>();
 
  const switchEditableWrap = (editable: boolean): void => {
    setReadonlyState(editable);
    switchEditable?.(editable);
  };
 
  useEffect(() => {
    console.log("Current lockId: ", lockId);
  }, [lockId]);
 
  useEffect(() => {
    Iif (showModal && lockId === 0) {
      setLockId(acquireLock());
    } else Iif (!showModal && lockId !== 0) {
      releaseLock(lockId);
      setLockId(0);
    }
  }, [showModal, lockId, acquireLock, releaseLock]);
 
  useEffect(() => {
    const setAllInfo = (fId: number): void => {
      setUpdateFormId(fId);
      fetchDomainMeta(domainName, fId).then((meta: Array<TableMetaProps>) => {
        setColumns(meta);
        setHasAnyDetailPanel(meta?.filter(c => hasDetailPanel(c)).length > 0);
      }).catch((e) => {
        console.error(e);
      }).finally(() => {
        setLoading(false);
      });
    };
 
    if (formId != null) {
      setAllInfo(formId);
      fetchFormExtInfo(formId).then(json => {
        setExtInfo(json.extInfo);
      }).catch(e => {
        console.error(`Failed to get form(${formId}) meta of domain ${domainName} form: ${e}`);
      });
    } else {
      fetchFormIdAndExtInfoByType(domainName, "Update")
        .then(json => {
          setAllInfo(json?.id);
          setExtInfo(json.extInfo);
        })
        .catch(e => {
          console.error(`Failed to get Update form id of ${domainName}: ${e}`);
        });
    }
  }, [domainName, formId, loading]);
 
  const onSaveAndClose = (): void => {
    setCancelConfirmMessage(undefined);
    setNeedToRefreshListPage(true);
    setContinueOperate(false);
    setTriggerSave(Math.random());
    setSaveLoadingButton("saveClose");
    if (hasLock(lockId)) {
      releaseLock(lockId);
    }
  };
 
  const onSaveAndContinue = (): void => {
    setCancelConfirmMessage(undefined);
    setNeedToRefreshListPage(true);
    setContinueOperate("edit");
    setTriggerSave(Math.random());
    setSaveLoadingButton("saveContinueEdit");
  };
 
  const useHotKeysConfig = {
    enableOnFormTags: true
  };
  useHotkeys('shift+ctrl+s, shift+cmd+s', () => {
    if (!hasLock(lockId)) {
      console.log('Shortcut shift+ctrl+s ignored due to global lock.');
    }
    onSaveAndContinue();
  }, useHotKeysConfig);
  useHotkeys('ctrl+enter, cmd+enter', () => {
    if (!hasLock(lockId)) {
      console.log('Shortcut ctrl+enter ignored due to global lock.');
    }
    onSaveAndClose();
  }, useHotKeysConfig);
  useHotkeys('shift+ctrl+e, shift+cmd+e', () => {
    if (!hasLock(lockId)) {
      console.log('Shortcut shift+ctrl+e ignored due to global lock.');
    }
    switchEditableWrap(!readonlyState);
  }, useHotKeysConfig);
 
  if (errorMsg != null) {
    return (
      <Popover
        trigger="click"
        title={<Alert message="Error" type="error" showIcon />}
        content={<pre>{errorMsg}</pre>}
      >
        <span><FormOutlined style={{ color: "red" }} /> Edit</span>
      </Popover>
    );
  } else {
    const modalParams = modalPropsBuilder({
      hasRelateObjectField: hasAnyDetailPanel,
      mode: "edit", t,
      open: showModal,
      isValid,
      domainName,
      onSaveAndClose,
      onSaveAndContinue,
      onDelete: () => {
        setCancelConfirmMessage(undefined);
        setShowModal(false);
        callback?.();
        if (hasLock(lockId)) {
          releaseLock(lockId);
        }
      },
      onCancel: () => {
        setCancelConfirmMessage(undefined);
        setShowModal(false);
        onCancelCallback?.();
        if (needToRefreshListPage) {
          callback?.();
        }
        if (hasLock(lockId)) {
          releaseLock(lockId);
        }
      },
      zIndex: zIndex + 1,
      ownerClass, ownerId, id, saveLoadingButton,
      columnNameInOwnerClass,
      refererUrl: currentUrl,
      readonly: readonlyState,
      updatable: domainPermit?.canUpdate,
      switchEditable: switchEditableWrap,
      cancelConfirmMessage,
      modalTitle: extInfo?.domainTitle,
    });
    const componentParams: UpdateProps = {
      formId: updateFormId,
      domainName,
      id,
      callback: (props: {
        continueOperate: ContinueOperate;
        data?: SaveRecordProps;
        status?: "fail" | "success";
      }) => {
        const { continueOperate, status } = props;
        const saveSuccess = (status !== 'fail');
        saveSuccess && setTriggerSave(false);
        setContinueOperate(continueOperate);
        //Only refresh after return to list panel to avoid duplicate API call
        //(continueOperate === false)
        if (continueOperate === false) {
          saveSuccess && callback?.();
          onCancelCallback?.();
        }
        setSaveLoadingButton(undefined);
      },
      columnNameInOwnerClass,
      ownerClass,
      ownerId,
      triggerSave,
      continueOperate,
      columns,
      validationCallback: (v: boolean) => {
        setIsValid(v);
 
        //如果 valid 是 true, 则重置 button 的 loading 状态的逻辑由 saveCallback 处理
        //此处只处理 valid 是 false 的状态
        if (!v) {
          setSaveLoadingButton(undefined);
        }
 
        setTimeout(() => {
          setIsValid(true);
        }, 2000);
      },
      zIndex: zIndex + 1,
      queryParameters,
      readonly: readonlyState,
      refererUrl: currentUrl,
      switchEditable: switchEditableWrap,
      fetchType,
      setCancelConfirmMessage,
    };
    const title = readonly ? t("Show details") : t("Edit current object");
    const icon = readonly ? <EyeOutlined /> : <FormOutlined />;
 
    const iconAndText = (<a
      title={title}
      href="/#"
      style={{ cursor: "pointer" }}
      onClick={() => {
        setShowModal(true);
      }}>
      <Space size={8}>
        {icon}
        {title}
      </Space>
    </a>);
    const modal = (
      <Modal {...modalParams}>
        {loading &&
          <div style={{
            textAlign: "center",
            margin: "auto",
            width: "100%",
            padding: "1rem"
          }}>
            <LargeSpin />
          </div>
        }
        {/* eslint-disable-next-line @typescript-eslint/ban-ts-comment */}
        {/* @ts-ignore */}
        {!loading && (<UpdateComponent {...componentParams} />)}
      </Modal>
    );
    return (<> {showIconAndText ? iconAndText : (<></>)} {modal} </>);
  }
};
 
export default UpdateAction;