diff --git a/src/components/Pagination/Pagination.test.tsx b/src/components/Pagination/Pagination.test.tsx index b83a37f3..900103cd 100644 --- a/src/components/Pagination/Pagination.test.tsx +++ b/src/components/Pagination/Pagination.test.tsx @@ -92,6 +92,28 @@ describe("Pagination", () => { expect(onChange).toHaveBeenCalledTimes(0); }); + it("should not call onChange when input is greater than totalPages", () => { + const onChange = jest.fn(); + const { getByDisplayValue } = renderPagination({ + currentPage: 99, + totalPages: 100, + onChange, + }); + const pageInput = getByDisplayValue("99"); + fireEvent.input(pageInput, { + target: { + value: "100", + }, + }); + expect(onChange).toHaveBeenCalledTimes(1); + fireEvent.input(pageInput, { + target: { + value: "101", + }, + }); + expect(onChange).toHaveBeenCalledTimes(1); + }); + it("should call onPageSizeChange when pageSize option are selected", () => { const onPageSizeChange = jest.fn(); const { getByText } = renderPagination({ @@ -106,6 +128,7 @@ describe("Pagination", () => { fireEvent.click(getByText("250 rows")); expect(onPageSizeChange).toBeCalledTimes(1); }); + it("should disable input if the left and right button are disabled", () => { const onChange = jest.fn(); const { getByDisplayValue } = renderPagination({ diff --git a/src/components/Pagination/Pagination.tsx b/src/components/Pagination/Pagination.tsx index 06beeb65..54f3be9a 100644 --- a/src/components/Pagination/Pagination.tsx +++ b/src/components/Pagination/Pagination.tsx @@ -58,17 +58,37 @@ export const Pagination = ({ const formatNumber = (value: number) => { return new Intl.NumberFormat("en").format(value); }; + const leftButtonDisabled = currentPage <= 1; + const rightButtonDisabled = + (!!totalPages && currentPage === totalPages) || disableNextButton; + const onKeyDown: KeyboardEventHandler = e => { - if (e.key === "ArrowUp" || e.key === "ArrowRight") { + const isInputEnabled = !inputRef.current?.disabled; + if ( + (e.key === "ArrowUp" || e.key === "ArrowRight") && + isInputEnabled && + !rightButtonDisabled + ) { onChangeProp(currentPage + 1); - } else if (e.key === "ArrowDown" || e.key === "ArrowLeft") { - onChangeProp(currentPage - 1); + } else if ( + (e.key === "ArrowDown" || e.key === "ArrowLeft") && + isInputEnabled && + !leftButtonDisabled + ) { + const newPage = currentPage - 1; + if (newPage > 0) { + onChangeProp(newPage); + } } }; const onChange = (value: string) => { const valueToNumber = Number(value); - if (valueToNumber < 1 || inputRef.current?.disabled) { + if ( + valueToNumber < 1 || + inputRef.current?.disabled || + (typeof totalPages !== "undefined" ? valueToNumber > totalPages : false) + ) { return; } @@ -81,10 +101,6 @@ export const Pagination = ({ } }; - const leftButtonDisabled = currentPage <= 1; - const rightButtonDisabled = - (!!totalPages && currentPage === totalPages) || disableNextButton; - const onPrevClick: MouseEventHandler = useCallback( e => { if (leftButtonDisabled) {