From 2a78023d1267e82acde1120a9cb23973e8b5102d Mon Sep 17 00:00:00 2001 From: anday013 Date: Mon, 27 May 2024 11:02:13 +0200 Subject: [PATCH] feat: implement blur on fill --- src/OtpInput/OtpInput.types.ts | 1 + src/OtpInput/__tests__/useOtpInput.test.ts | 23 ++++++++++++++++++++++ src/OtpInput/useOtpInput.ts | 2 ++ 3 files changed, 26 insertions(+) diff --git a/src/OtpInput/OtpInput.types.ts b/src/OtpInput/OtpInput.types.ts index f1ecd96..8620b6c 100644 --- a/src/OtpInput/OtpInput.types.ts +++ b/src/OtpInput/OtpInput.types.ts @@ -6,6 +6,7 @@ export interface OtpInputProps { focusColor?: ColorValue; onTextChange?: (text: string) => void; onFilled?: (text: string) => void; + blurOnFilled?: boolean; hideStick?: boolean; focusStickBlinkingDuration?: number; secureTextEntry?: boolean; diff --git a/src/OtpInput/__tests__/useOtpInput.test.ts b/src/OtpInput/__tests__/useOtpInput.test.ts index 1327730..e7007b7 100644 --- a/src/OtpInput/__tests__/useOtpInput.test.ts +++ b/src/OtpInput/__tests__/useOtpInput.test.ts @@ -153,6 +153,7 @@ describe("useOtpInput", () => { expect(mockSetState).toHaveBeenCalledWith(true); }); }); + test("handleBlur() should set hasCurrentFocus to false", () => { const mockSetState = jest.fn(); jest.spyOn(React, "useState").mockImplementation(() => [true, mockSetState]); @@ -163,4 +164,26 @@ describe("useOtpInput", () => { expect(mockSetState).toHaveBeenCalledWith(false); }); }); + + test("should blur the input when filled if blurOnFilled is 'true'", () => { + jest.spyOn(React, "useRef").mockReturnValue({ current: { blur: jest.fn() } } as any); + + const { result } = renderUseOtInput({ blurOnFilled: true }); + result.current.actions.handleTextChange("123456"); + + act(() => { + expect(result.current.models.inputRef.current?.blur).toHaveBeenCalled(); + }); + }); + + test("should NOT blur the input when filled if blurOnFilled is 'true'", () => { + jest.spyOn(React, "useRef").mockReturnValue({ current: { blur: jest.fn() } } as any); + + const { result } = renderUseOtInput(); + result.current.actions.handleTextChange("123456"); + + act(() => { + expect(result.current.models.inputRef.current?.blur).not.toHaveBeenCalled(); + }); + }); }); diff --git a/src/OtpInput/useOtpInput.ts b/src/OtpInput/useOtpInput.ts index 2874601..a995bfb 100644 --- a/src/OtpInput/useOtpInput.ts +++ b/src/OtpInput/useOtpInput.ts @@ -8,6 +8,7 @@ export const useOtpInput = ({ numberOfDigits = 6, disabled, autoFocus = true, + blurOnFilled, }: OtpInputProps) => { const [text, setText] = useState(""); const [isFocused, setIsFocused] = useState(autoFocus); @@ -28,6 +29,7 @@ export const useOtpInput = ({ onTextChange?.(value); if (value.length === numberOfDigits) { onFilled?.(value); + blurOnFilled && inputRef.current?.blur(); } };