Skip to content

Commit

Permalink
hide siblings on mobile pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
krystonen committed Oct 1, 2024
1 parent 5b7d59b commit ffb2888
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
21 changes: 21 additions & 0 deletions packages/react-pagination/hooks/usePagination.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,27 @@ describe("usePagination ", () => {

expect(result.current.page).toBe(1);
});

it("should handle siblings on mobile", () => {
const { result } = renderHook(() =>
usePagination({
pages: 20,
initialPage: 1,
siblings: 1,
boundaries: 1,
isMobile: true,
}),
);

expect(result.current.range).toEqual([[1, 2, 3], [20]]);

act(() => {
result.current.setPage(2);
});

// // The layout of the segments should still be the same.
expect(result.current.range).toEqual([[1, 2, 3], [20]]);
});
});

describe("Array-based pagination", () => {
Expand Down
16 changes: 13 additions & 3 deletions packages/react-pagination/hooks/usePagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ interface UsePaginationBaseProps {
boundaries: number;

gapSize?: number;
isMobile?: boolean;
}

export interface UsePaginationWithPagesProps extends UsePaginationBaseProps {
Expand Down Expand Up @@ -103,10 +104,12 @@ export function usePagination<T>(

const { boundaries = 1, siblings = 1, gapSize = 1 } = props;

const responsiveSiblings = props.isMobile ? 0 : siblings;

const range = useMemo(() => {
const segments: [number[], number[], number[]] = [
boundaries ? clampedSequence(1, boundaries) : [],
clampedSequence(page - siblings, page + siblings),
clampedSequence(page - responsiveSiblings, page + responsiveSiblings),
boundaries
? clampedSequence(computedPages + 1 - boundaries, computedPages)
: [],
Expand All @@ -115,11 +118,18 @@ export function usePagination<T>(
return formatSegments(
segments,
computedPages,
siblings,
responsiveSiblings,
boundaries,
gapSize,
);
}, [page, boundaries, siblings, clampedSequence, computedPages, gapSize]);
}, [
page,
boundaries,
responsiveSiblings,
clampedSequence,
computedPages,
gapSize,
]);

const currentItems = useMemo(
() =>
Expand Down

0 comments on commit ffb2888

Please sign in to comment.