Skip to content

Commit

Permalink
feat: implement blur on fill
Browse files Browse the repository at this point in the history
  • Loading branch information
anday013 committed May 27, 2024
1 parent d7938f6 commit 2a78023
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/OtpInput/OtpInput.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
23 changes: 23 additions & 0 deletions src/OtpInput/__tests__/useOtpInput.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand All @@ -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();
});
});
});
2 changes: 2 additions & 0 deletions src/OtpInput/useOtpInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const useOtpInput = ({
numberOfDigits = 6,
disabled,
autoFocus = true,
blurOnFilled,
}: OtpInputProps) => {
const [text, setText] = useState("");
const [isFocused, setIsFocused] = useState(autoFocus);
Expand All @@ -28,6 +29,7 @@ export const useOtpInput = ({
onTextChange?.(value);
if (value.length === numberOfDigits) {
onFilled?.(value);
blurOnFilled && inputRef.current?.blur();
}
};

Expand Down

0 comments on commit 2a78023

Please sign in to comment.