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 | 66x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 4x 1x 1x 1x 4x 2x 2x 2x 2x 4x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 1x 4x 4x 4x | import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Empty } from "antd"; import { ApiErrorStatusType, ContinueOperate, GroupMetaProps, RecordProps, SaveOptionProps, SaveRecordProps, TableMetaProps, UpdateProps } from "@props/RecordProps"; import { fetchCurrentValue, fetchDomainMeta, onFinishFailed, fetchFormFieldGroups, fetchFormIdAndExtInfoByType, populateDomainData } from '@utils/FetchUtils'; import { FieldsToHideOnEditPage } from '@config/base'; import { DataCollectForm } from "../"; import { callSaveDomainWithCallback, getLastTrigger, setLastTrigger } from '@utils/SaveDomainUtils'; import { pureObjectIsEmpty } from "@utils/ObjectUtils"; import { LargeSpin } from '../../components'; import { humanReadableTitle, removePackagePart } from "@utils/StringUtils"; import { transformRecord } from '@kernel/DisplayComponentsMapping'; import { emptyMethod } from "@utils/Constants"; import { getAllOnSavedCallback, getFormFieldsValue, useCustomHookForm } from "@utils/FormUtils"; const UpdateComponent: React.FC<UpdateProps> = (props: UpdateProps) => { const { formId, domainName, id, callback, validationCallback, readonly, columnNameInOwnerClass, ownerClass, ownerId, triggerSave, continueOperate, columns: initColumns, hideDetailPanel, zIndex, hideHeaderTitle, hideHeader, displayMode, formType, queryParameters, showBottomSaveButton, page, fetchType, setCancelConfirmMessage, } = props; const [columns, setColumns] = useState<Array<TableMetaProps>>([] as TableMetaProps[]); const [updateFormGroups, setUpdateFormGroups] = useState<Array<GroupMetaProps>>(); const [record, setRecord] = useState<RecordProps>(); const form = useCustomHookForm(); const [loading, setLoading] = useState<boolean>(true); const [groupLoading, setGroupLoading] = useState<boolean>(true); /** 如果父组件没有传递 formId 过来,本组件会往后台请求获取 formId */ const [internalFormId, setInternalFormId] = useState<number | undefined>(formId); const [errorStatusCode, setErrorStatusCode] = useState<ApiErrorStatusType>(); const [previousId, setPreviousId] = useState<number>(); const path = `/Update|${domainName}`; const saveOptions = useMemo<SaveOptionProps>(() => ({ arrayColumnOptions: {}, dynamicTemplateAttributesFieldOptions: {}, }), []); const finishCallbackRef = useRef<() => void>(emptyMethod); const idChanged = (previousId !== id); const onSaveCallback = useCallback((res: { continueOperate: ContinueOperate; data?: SaveRecordProps; status: "fail" | "success"; }) => { getAllOnSavedCallback(form).forEach(it => it(res)); callback?.(res); const { data } = res; if (res.status === 'success' && data && 'id' in data) { const transformedRecord = transformRecord(columns, data as RecordProps); setRecord(transformedRecord); form.setFieldsValue(transformedRecord); console.info( `Domain ${domainName} has been saved, backend return ${JSON.stringify(data)}` ); } }, [columns, callback, form, domainName]); finishCallbackRef.current = () => { const values = getFormFieldsValue(form); if (values != null && !pureObjectIsEmpty(values)) { callSaveDomainWithCallback({ callback: onSaveCallback, values, continueOperate, domainName, columns, options: saveOptions }); } else { console.error(`Form values is null when save ${domainName}(${id})`); } }; useEffect(() => { Eif (page != 'master-detail' && page != 'detail-drawer') { const url = `/${formId}/${domainName}/${id}/${readonly ? 'show' : 'update'}`; window.history.pushState('', '', url); } }, [formId, domainName, id, readonly, page]); useEffect(() => { // 如果 Props 中传递的 formId 为空,则到后台去获取 formId 并保存在 state 中 Iif (formId == null && internalFormId == null) { const formType = (id == null) ? "Create" : "Update"; fetchFormIdAndExtInfoByType(domainName, formType) .then(json => { setInternalFormId(json?.id); }); } else Eif (formId != null) { //如果 Props 中传递的 formId 不为空则直接设置 internalFormId setInternalFormId(formId); } }, [domainName, id, formId, internalFormId]); useEffect(() => { // 如果数据(record) 已经准备好,元数据也已经准备好 // 1. formId 不为 -1 且字段分组信息已经获取到 // 2. formId 为 -1, 表示使用默认的 domainMeta 来渲染表单,肯定没有 group // 则设置 loading 为 false const useDefaultForm = (internalFormId === -1); const groupInfoRetrieved = (!useDefaultForm && updateFormGroups != null); const dataIsReady = (record != null); Iif ((loading === true && dataIsReady) && (groupInfoRetrieved || useDefaultForm)) { setLoading(false); } }, [internalFormId, loading, record, updateFormGroups]); useEffect(() => { if (!idChanged || internalFormId == null) { return; } const fetchInitValue = async ( domainName: string, domainMeta: Array<TableMetaProps>, id: number ): Promise<void> => { try { // setColumns(domainMeta); let record = await fetchCurrentValue(domainName, id, fetchType, formId); if (formId && domainMeta.some(meta => !!meta.transient)) { record = (await populateDomainData({ formId, domainName, objects: [record], }))[0]; } // 支持从 URL 中传递参数,用于初始化表单 // 将从 queryParameters 中获取的参数合并到后台返回的 record 中 if (queryParameters != null && Object.keys(queryParameters).length > 0) { Object.keys(queryParameters).forEach(key => { record[key] = queryParameters[key]; }); } const columnsWithDynamicFields = domainMeta.filter(meta => !meta.isDynamicTemplateAttributeField); if (record.extInfo?.dynamicFields) { const { dynamicFields } = record.extInfo; columnsWithDynamicFields.push(...dynamicFields); } const transformed = transformRecord(columnsWithDynamicFields, record); setColumns(columnsWithDynamicFields); setRecord(transformed); form.setFieldsValue(transformed); if (internalFormId != null) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore fetchFormFieldGroups(domainName, internalFormId, id) .then(g => { setUpdateFormGroups((g?.length > 0) ? g : []); }).catch(e => { console.warn(`Failed to get form ${internalFormId} group: ${JSON.stringify(e)}`); setUpdateFormGroups([]); }).finally(() => setGroupLoading(false)); } else { setGroupLoading(false); } } catch (error) { console.error(`Error get current value[${domainName}][${id}]for update: , ${error}`); setErrorStatusCode((error as { status: ApiErrorStatusType }).status); } finally { setLoading(false); } }; Eif (record == null || idChanged) { setPreviousId(id); Iif (initColumns != null && idChanged) { fetchInitValue(domainName, initColumns, id); } else Eif (initColumns == null || idChanged) { fetchDomainMeta(domainName, internalFormId) .then((domainMeta: Array<TableMetaProps>) => { return domainMeta; }).then((domainMeta: Array<TableMetaProps>) => { fetchInitValue(domainName, domainMeta, id); }).catch(e => { console.warn(`Failed to get ${domainName} domain meta: ${JSON.stringify(e)}`); }); } } }, [ internalFormId, domainName, id, form, initColumns, loading, record, formId, columns, groupLoading, previousId, idChanged, updateFormGroups, queryParameters, fetchType ]); useEffect(() => { Iif (!!triggerSave && (readonly !== true) && getLastTrigger() !== triggerSave) { setLastTrigger(triggerSave); const values = form.getFieldsValue(); setRecord(values); form.validateFields().then(finishCallbackRef.current); } // Only include triggerSave to avoid duplicate API call // eslint-disable-next-line react-hooks/exhaustive-deps }, [triggerSave]); Iif (errorStatusCode != null) { const domainTitle = `${humanReadableTitle(removePackagePart(domainName) ?? "")}`; const ErrorStatusToMsgMap: { [propName: number]: string; } = { 403: `You don't have permission to view or edit ${domainTitle} with id [${id}]`, 404: `${domainTitle} with id [${id}] does not exist`, 500: `Error to getting data of ${domainTitle} with id [${id}]]`, }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return <Empty style={{ paddingTop: "calc(.30 * 100vh)" }} description={ErrorStatusToMsgMap[errorStatusCode]} />; } const stillLoading = (loading || groupLoading); return (stillLoading) ? <LargeSpin /> : ( <DataCollectForm hideHeaderTitle={hideHeaderTitle} columns={columns} groups={updateFormGroups ?? []} domainName={domainName} onFinish={finishCallbackRef.current} onFinishFailed={(e) => { onFinishFailed(e); }} onChange={emptyMethod} form={form} record={record} operation="update" ownerClass={ownerClass} columnNameInOwnerClass={columnNameInOwnerClass} ownerId={ownerId} validationCallback={validationCallback} hideFields={FieldsToHideOnEditPage} readonly={readonly} hideDetailPanel={hideDetailPanel} zIndex={zIndex} deleteCallback={() => { callback(); }} updateCallback={() => { callback(); }} hideHeader={hideHeader} displayMode={displayMode} formType={formType} showBottomSaveButton={showBottomSaveButton} setColumns={setColumns} saveOptions={saveOptions} page={page ?? "edit"} setCancelConfirmMessage={setCancelConfirmMessage} path={path} />); }; export default UpdateComponent; |