import React , { createContext , ReactNode , useCallback , useMemo } from 'react' ; import { typedMemo } from '../../../../utils' ; import { useStore } from '../../hooks' ; import { Cell , WorksheetItem } from '../../types' ; export interface UpdateItemsContextType < T > { updateItems ( items , newValue ) : void ; } interface UpdateItemsProviderProps < Item > { children : ReactNode ; items : Item [ ] ; } export const UpdateItemsContext = createContext < UpdateItemsContextType < any > | null > ( null ) ; export const UpdateItemsProvider = typedMemo ( < T extends WorksheetItem > ( { children , items } ) => { const setRows = useStore ( ( state ) => state . setRows ) ; const addEditedCells = useStore ( ( state ) => state . addEditedCells ) ; const updateItems = useCallback ( ( cells , newValues ) => { setRows ( cells . reduce ( ( accum , cell , index ) => { const { hash , rowIndex } = cell ; if ( cell . value === newValues [ index ] ) { return accum ; } const row = accum [ rowIndex ] ; const updatedRow = { ... row , [ hash ] : newValues [ index ] } ; accum [ rowIndex ] = updatedRow ; return accum ; } , items ) ) ; addEditedCells ( cells . reduce < Array < Cell < any > > > ( ( accum , cell , index ) => { if ( cell . value === newValues [ index ] ) { return accum ; } return [ ... accum , { ... cell , value : newValues [ index ] } ] ; } , [ ] ) ) ; } , [ addEditedCells , items , setRows ] ) ; const providerValue = useMemo ( ( ) => ( { updateItems } ) , [ updateItems ] ) ; return < UpdateItemsContext . Provider value = { providerValue } > { children } < /UpdateItemsContext.Provider>; } ) ;