UNPKG

react-native-confirmation-code-field

Version:

A react-native component to input confirmation code for both Android and IOS

46 lines (45 loc) 1.53 kB
import { useCallback, useEffect, useRef } from 'react'; const findIndex = ({ locationX, locationY }, map) => { for (const index in map) { const layout = map[index]; if (layout.x < locationX && locationX < layout.xEnd && layout.y < locationY && locationY < layout.yEnd) { return parseInt(index, 10); } } return -1; }; export const useClearByFocusCellCommon = (params) => { 'use memo'; const paramsRef = useRef(params); const cellsLayouts = useRef({}); const callbackRef = useRef({}); useEffect(() => { paramsRef.current = params; }, [params]); const clearCodeByCoords = useCallback((coords) => { const index = findIndex(coords, cellsLayouts.current); if (index !== -1) { const { value, setValue } = paramsRef.current; const text = (value || '').slice(0, index); setValue(text); } }, []); const getCellOnLayoutHandler = useCallback((index) => { if (!callbackRef.current[index]) { callbackRef.current[index] = (event) => { const { width, height, x, y } = event.nativeEvent.layout; cellsLayouts.current[`${index}`] = { x, xEnd: x + width, y, yEnd: y + height, }; }; } return callbackRef.current[index]; }, []); return [clearCodeByCoords, getCellOnLayoutHandler]; };