import { useState , useEffect , useMemo , useRef } from 'react' ; import produce from 'immer' ; import useTabChange from './useTabChange' ; import computedEditColumns from './computedEditColumns' ; import { CellType } from './Cell' ; import { EditableColumn } from './Editable' ; const useProps = < T extends object > ( dataSource , columns , onCellChange , form ) => { const [ curCell , setCurCell ] = useState < CellType > ( null ) ; const { cacheSource , setCacheSource } = useDataSource ( dataSource , form ) ; const beforeCell = useRef < CellType > ( null ) ; const { editColumns , dataIndexMap } = useMemo ( ( ) => computedEditColumns ( columns , curCell , handleSetCurCell , form ) , [ columns , curCell ] ) ; const hasError = curCell && form . getFieldError ( `${ curCell ! . dataIndex }-${ curCell ! . rowIndex }` ) ; useTabChange ( curCell , handleSetCurCell , cacheSource , dataIndexMap ) ; useEffect ( ( ) => { if ( beforeCell && beforeCell . current ) { const { dataIndex , rowIndex } = beforeCell . current ; const value = form . getFieldValue ( `${ dataIndex }-${ rowIndex }` ) ; const nextSource = produce ( cacheSource , draft => { draft [ rowIndex ] [ dataIndex ] = value ; } ) ; setCacheSource ( nextSource ) ; onCellChange ( nextSource , value , cacheSource [ rowIndex ] [ dataIndex ] , rowIndex , dataIndex ) ; } beforeCell . current = curCell ; } , [ curCell ] ) ; function handleSetCurCell ( nextCell ) { if ( ! hasError ) { setCurCell ( nextCell ) ; } } return { cacheSource , editColumns , hasError , } ; } ; const useDataSource = ( dataSource , form ) => { const [ cacheSource , setCacheSource ] = useState ( dataSource ) ; useEffect ( ( ) => { setCacheSource ( dataSource ) ; form . resetFields ( ) ; } , [ dataSource ] ) ; return { cacheSource , setCacheSource , } ; } ; export default useProps ;