Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/table-pagination-shrinking-count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@primer/react": patch
---

DataTable: Keep pagination on an available page when the total number of rows decreases.
51 changes: 42 additions & 9 deletions packages/react/src/DataTable/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {ChevronLeftIcon, ChevronRightIcon} from '@primer/octicons-react'
import type React from 'react'
import {useCallback, useMemo, useState} from 'react'
import {useCallback, useEffect, useMemo, useRef, useState} from 'react'
import {Button} from '../internal/components/ButtonReset'
import {AriaStatus} from '../live-region'
import {VisuallyHidden} from '../VisuallyHidden'
Expand Down Expand Up @@ -179,7 +179,7 @@ type RangeProps = {
}

function Range({pageStart, pageEnd, totalCount}: RangeProps) {
const start = pageStart + 1
const start = totalCount === 0 ? 0 : pageStart + 1
const end = pageEnd
return (
<>
Expand Down Expand Up @@ -322,10 +322,15 @@ type PaginationResult = {

function usePagination(config: PaginationConfig): PaginationResult {
const {defaultPageIndex, onChange, pageSize, totalCount} = config
const pageCount = Math.ceil(totalCount / pageSize)
const calculatedPageCount = Math.ceil(totalCount / pageSize)
const pageCount = Number.isFinite(calculatedPageCount) ? calculatedPageCount : 0
const validDefaultPageIndex =
defaultPageIndex !== undefined &&
defaultPageIndex >= 0 &&
(defaultPageIndex < pageCount || (defaultPageIndex === 0 && pageCount === 0))
const [defaultIndex, setDefaultIndex] = useState(() => {
if (defaultPageIndex !== undefined) {
if (defaultPageIndex >= 0 && defaultPageIndex < pageCount) {
if (validDefaultPageIndex) {
return defaultPageIndex
}

Expand All @@ -342,13 +347,39 @@ function usePagination(config: PaginationConfig): PaginationResult {

return 0
})
const [pageIndex, setPageIndex] = useState(defaultIndex)
const validDefaultPageCount = defaultPageIndex !== undefined && defaultPageIndex >= 0 && defaultPageIndex < pageCount
if (validDefaultPageCount && defaultIndex !== defaultPageIndex) {
const [storedPageIndex, setPageIndex] = useState(defaultIndex)
const previousPageIndex = useRef(storedPageIndex)
const previousDefaultIndex = useRef(defaultIndex)
const lastClampedPageIndex = useRef<number | undefined>(undefined)
const defaultPageIndexChanged = validDefaultPageIndex && defaultIndex !== defaultPageIndex
const pageIndex = defaultPageIndexChanged ? defaultPageIndex : Math.min(storedPageIndex, Math.max(0, pageCount - 1))
Comment thread
tay1orjones marked this conversation as resolved.
Resolved
if (defaultPageIndexChanged) {
setDefaultIndex(defaultPageIndex)
setPageIndex(defaultPageIndex)
onChange?.({pageIndex: defaultPageIndex})
}
if (pageIndex !== storedPageIndex) {
setPageIndex(pageIndex)
Comment thread
tay1orjones marked this conversation as resolved.
Resolved
}
Comment thread
tay1orjones marked this conversation as resolved.
Resolved
useEffect(() => {
// Prop changes can update parent state only after this component commits.
if (previousPageIndex.current !== pageIndex || previousDefaultIndex.current !== defaultIndex) {
Comment thread
tay1orjones marked this conversation as resolved.
Resolved
const pageChanged = previousPageIndex.current !== pageIndex
const defaultChanged = previousDefaultIndex.current !== defaultIndex
// The parent can echo the last clamped index through defaultPageIndex.
const echoedClamp = defaultChanged && !pageChanged && defaultIndex === lastClampedPageIndex.current
Comment thread
tay1orjones marked this conversation as resolved.
Resolved
previousPageIndex.current = pageIndex
previousDefaultIndex.current = defaultIndex
lastClampedPageIndex.current = pageChanged && !defaultChanged && onChange ? pageIndex : undefined
// eslint-disable-next-line react-you-might-not-need-an-effect/no-event-handler
if (!echoedClamp) {
// eslint-disable-next-line react-you-might-not-need-an-effect/no-pass-live-state-to-parent, react-you-might-not-need-an-effect/no-pass-data-to-parent
onChange?.({pageIndex})
}
} else {
// Only suppress an echo during the next commit after a clamp.
lastClampedPageIndex.current = undefined
}
})

const pageStart = pageIndex * pageSize
const pageEnd = Math.min((pageIndex + 1) * pageSize, totalCount)
const hasNextPage = pageIndex + 1 < pageCount
Expand All @@ -357,6 +388,8 @@ function usePagination(config: PaginationConfig): PaginationResult {
function selectPage(newPageIndex: number) {
if (pageIndex !== newPageIndex) {
setPageIndex(newPageIndex)
previousPageIndex.current = newPageIndex
lastClampedPageIndex.current = undefined
onChange?.({pageIndex: newPageIndex})
}
}
Expand Down
226 changes: 226 additions & 0 deletions packages/react/src/DataTable/__tests__/Pagination.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {page, userEvent} from 'vitest/browser'
import {beforeEach, describe, expect, it, vi} from 'vitest'
import {Pagination} from '../Pagination'
import {act, fireEvent, render} from '@testing-library/react'
import {StrictMode, useCallback, useState} from 'react'

describe('Table.Pagination', () => {
beforeEach(async () => {
Expand All @@ -20,6 +21,231 @@ describe('Table.Pagination', () => {
.toBeInTheDocument()
})

it('keeps the current page in bounds when the row count shrinks', () => {
const {rerender} = render(<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={100} />)
expect(getCurrentPage()).toHaveTextContent('4')
rerender(<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={40} />)
expect(getCurrentPage()).toHaveTextContent('2')
rerender(<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={0} />)
expect(getPages().some(button => button.hasAttribute('aria-current'))).toBe(false)
expect(getPageRange()).toEqual('0 through 0 of 0')
expect(page.getByText('Showing 0 through 0 of 0', {exact: true}).element()).toBeInTheDocument()
})

it.each([
{totalCount: 0, pageSize: 0},
{totalCount: 25, pageSize: 0},
{totalCount: Number.NaN, pageSize: 25},
])('does not re-render indefinitely for an invalid page count: $totalCount / $pageSize', props => {
render(<Pagination aria-label="Pagination" {...props} />)
expect(page.getByRole('navigation', {name: 'Pagination', exact: true}).element()).toBeInTheDocument()
expect(getPages()).toHaveLength(0)
})

it('notifies the parent after clamping so it can display the remaining rows', () => {
const onChange = vi.fn()
function PaginatedRows({totalCount}: {totalCount: number}) {
const [pageIndex, setPageIndex] = useState(3)
const rows = Array.from({length: totalCount}, (_, index) => `Row ${index + 1}`)
return (
<>
<div>{rows.slice(pageIndex * 25, (pageIndex + 1) * 25).join(', ')}</div>
<Pagination
aria-label="Pagination"
defaultPageIndex={3}
totalCount={totalCount}
onChange={state => {
onChange(state)
setPageIndex(state.pageIndex)
}}
/>
</>
)
}

const {rerender} = render(
<StrictMode>
<PaginatedRows totalCount={100} />
</StrictMode>,
)
expect(page.getByText('Row 76', {exact: false}).element()).toBeInTheDocument()
rerender(
<StrictMode>
<PaginatedRows totalCount={40} />
</StrictMode>,
)
expect(onChange).toHaveBeenCalledTimes(1)
expect(onChange).toHaveBeenLastCalledWith({pageIndex: 1})
expect(page.getByText('Row 26', {exact: false}).element()).toBeInTheDocument()
expect(getCurrentPage()).toHaveTextContent('2')

rerender(
<StrictMode>
<PaginatedRows totalCount={0} />
</StrictMode>,
)
expect(onChange).toHaveBeenCalledTimes(2)
expect(onChange).toHaveBeenLastCalledWith({pageIndex: 0})

rerender(
<StrictMode>
<PaginatedRows totalCount={100} />
</StrictMode>,
)
expect(onChange).toHaveBeenCalledTimes(2)
expect(
page.getByText(Array.from({length: 25}, (_, index) => `Row ${index + 1}`).join(', '), {exact: true}).element(),
).toBeInTheDocument()
expect(getCurrentPage()).toHaveTextContent('1')
})

it('does not report a clamped index again when the parent echoes it as the default', () => {
const onChange = vi.fn()
function PaginationWithEcho({totalCount}: {totalCount: number}) {
const [pageIndex, setPageIndex] = useState(3)
return (
<Pagination
aria-label="Pagination"
defaultPageIndex={pageIndex}
totalCount={totalCount}
onChange={state => {
onChange(state)
setPageIndex(state.pageIndex)
}}
/>
)
}

const {rerender} = render(
<StrictMode>
<PaginationWithEcho totalCount={100} />
</StrictMode>,
)
rerender(
<StrictMode>
<PaginationWithEcho totalCount={40} />
</StrictMode>,
)
expect(onChange).toHaveBeenCalledExactlyOnceWith({pageIndex: 1})
expect(getCurrentPage()).toHaveTextContent('2')

rerender(
<StrictMode>
<PaginationWithEcho totalCount={0} />
</StrictMode>,
)
expect(onChange).toHaveBeenCalledTimes(2)
expect(onChange).toHaveBeenLastCalledWith({pageIndex: 0})

rerender(
<StrictMode>
<PaginationWithEcho totalCount={100} />
</StrictMode>,
)
expect(onChange).toHaveBeenCalledTimes(2)
expect(getCurrentPage()).toHaveTextContent('1')
})

it('reports a later default change to the clamped page after an unrelated commit', () => {
const onChange = vi.fn()
const {rerender} = render(
<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={100} onChange={onChange} />,
)
rerender(<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={40} onChange={onChange} />)
rerender(
<Pagination aria-label="Pagination" id="updated" defaultPageIndex={3} totalCount={40} onChange={onChange} />,
)
rerender(
<Pagination aria-label="Pagination" id="updated" defaultPageIndex={1} totalCount={40} onChange={onChange} />,
)

expect(onChange.mock.calls).toEqual([[{pageIndex: 1}], [{pageIndex: 1}]])
})

it('accepts an empty-table default before returning to a later page', () => {
const onChange = vi.fn()
const {rerender} = render(
<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={100} onChange={onChange} />,
)
rerender(<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={0} onChange={onChange} />)
rerender(<Pagination aria-label="Pagination" defaultPageIndex={0} totalCount={0} onChange={onChange} />)
expect(onChange).toHaveBeenCalledExactlyOnceWith({pageIndex: 0})

rerender(<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={100} onChange={onChange} />)
expect(getCurrentPage()).toHaveTextContent('4')
expect(onChange).toHaveBeenLastCalledWith({pageIndex: 3})
})

it('accepts page zero as the default for an empty table', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
render(<Pagination aria-label="Pagination" defaultPageIndex={0} totalCount={0} />)
expect(warn).not.toHaveBeenCalled()
})

it('reports a clamp when selecting a page also shrinks the row count', async () => {
const onChange = vi.fn()
function PaginationWithShrinkingRows() {
const [totalCount, setTotalCount] = useState(50)
const [parentPageIndex, setParentPageIndex] = useState(0)
const handleChange = useCallback((state: {pageIndex: number}) => {
onChange(state)
setParentPageIndex(state.pageIndex)
setTotalCount(25)
}, [])
return (
<>
<div>Parent page {parentPageIndex + 1}</div>
<Pagination aria-label="Pagination" totalCount={totalCount} onChange={handleChange} />
</>
)
}

render(<PaginationWithShrinkingRows />)
await userEvent.click(getPage(1))

expect(onChange.mock.calls).toEqual([[{pageIndex: 1}], [{pageIndex: 0}]])
expect(page.getByText('Parent page 1', {exact: true}).element()).toBeInTheDocument()
expect(getCurrentPage()).toHaveTextContent('1')
})

it('applies a valid default page reset when the row count shrinks at the same time', () => {
const onChange = vi.fn()
const {rerender} = render(
<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={100} onChange={onChange} />,
)

rerender(<Pagination aria-label="Pagination" defaultPageIndex={0} totalCount={40} onChange={onChange} />)

expect(getCurrentPage()).toHaveTextContent('1')
expect(getPageRange()).toEqual('1 through 25 of 40')
expect(onChange).toHaveBeenCalledExactlyOnceWith({pageIndex: 0})
})

it('reports an independent default page reset after clamping', () => {
const onChange = vi.fn()
const {rerender} = render(
<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={100} onChange={onChange} />,
)
rerender(<Pagination aria-label="Pagination" defaultPageIndex={3} totalCount={40} onChange={onChange} />)
rerender(<Pagination aria-label="Pagination" defaultPageIndex={0} totalCount={40} onChange={onChange} />)

expect(onChange.mock.calls).toEqual([[{pageIndex: 1}], [{pageIndex: 0}]])
expect(getCurrentPage()).toHaveTextContent('1')
})

it('notifies when the default page changes to the selected page', async () => {
const onChange = vi.fn()
const {rerender} = render(
<Pagination aria-label="Pagination" defaultPageIndex={0} totalCount={100} onChange={onChange} />,
)
await userEvent.click(getPage(1))
onChange.mockClear()

rerender(<Pagination aria-label="Pagination" defaultPageIndex={1} totalCount={100} onChange={onChange} />)

expect(onChange).toHaveBeenCalledExactlyOnceWith({pageIndex: 1})
})

it('should set the initial selected page to the first page', () => {
render(<Pagination aria-label="Pagination" totalCount={100} />)
expect(getCurrentPage()).toEqual(getFirstPage())
Expand Down
Loading