Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 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
7 changes: 7 additions & 0 deletions .changeset/green-rules-tickle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@primer/react': minor
---

The showPages prop on both Pagination components can now accept a responsive value.

<!-- Changed components: DataTable, Pagination -->
4 changes: 2 additions & 2 deletions generated/components.json
Original file line number Diff line number Diff line change
Expand Up @@ -2958,7 +2958,7 @@
"stories": [
{
"id": "components-pagination--default",
"code": "() => (\n <Pagination\n pageCount={15}\n currentPage={2}\n onPageChange={(e) => e.preventDefault()}\n />\n)"
"code": "() => (\n <Pagination\n pageCount={15}\n currentPage={2}\n onPageChange={(e) => e.preventDefault()}\n showPages={{\n narrow: false,\n }}\n />\n)"
}
],
"props": [
Expand Down Expand Up @@ -2996,7 +2996,7 @@
},
{
"name": "showPages",
"type": "boolean",
"type": "boolean | { narrow?: boolean, regular?: boolean, wide?: boolean }",
"defaultValue": "true",
"description": "Whether or not to show the individual page links."
},
Expand Down
56 changes: 50 additions & 6 deletions src/DataTable/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import {ChevronLeftIcon, ChevronRightIcon} from '@primer/octicons-react'
import React, {useState} from 'react'
import React, {useCallback, useState} from 'react'
import styled from 'styled-components'
import {get} from '../constants'
import {Button} from '../internal/components/ButtonReset'
import {LiveRegion, LiveRegionOutlet, Message} from '../internal/components/LiveRegion'
import {VisuallyHidden} from '../internal/components/VisuallyHidden'
import {warning} from '../utils/warning'
import {ResponsiveValue, viewportRanges} from '../hooks/useResponsiveValue'

const StyledPagination = styled.nav`
display: flex;
Expand Down Expand Up @@ -93,6 +94,22 @@ const StyledPagination = styled.nav`
min-height: 2rem;
user-select: none;
}

${
// Hides pages based on the viewport range passed to `showPages`
Object.keys(viewportRanges)
.map(viewportRangeKey => {
return `
@media (${viewportRanges[viewportRangeKey as keyof typeof viewportRanges]}) {
.TablePaginationStep[data-hidden-viewport-ranges*='${viewportRangeKey}'],
.TablePaginationStep[data-hidden-viewport-ranges*='${viewportRangeKey}'] + .TablePaginationTruncationStep {
display: none;
}
}
`
})
.join('')
}
`

export type PaginationProps = Omit<React.ComponentPropsWithoutRef<'nav'>, 'onChange'> & {
Expand Down Expand Up @@ -123,6 +140,11 @@ export type PaginationProps = Omit<React.ComponentPropsWithoutRef<'nav'>, 'onCha
*/
pageSize?: number

/**
* Whether to show the page numbers
*/
showPages?: boolean | ResponsiveValue<boolean>

/**
* Specify the total number of items within the collection
*/
Expand All @@ -141,6 +163,7 @@ export function Pagination({
id,
onChange,
pageSize = 25,
showPages = {narrow: false},
totalCount,
}: PaginationProps) {
const {
Expand Down Expand Up @@ -171,6 +194,19 @@ export function Pagination({
const offsetEndIndex = offsetStartIndex + truncatedPageCount - 1
const hasLeadingTruncation = offsetStartIndex >= 2
const hasTrailingTruncation = pageCount - 1 - offsetEndIndex > 1
const getViewportRangesToHidePages = useCallback(() => {
if (typeof showPages !== 'boolean') {
return Object.keys(showPages).filter(key => !showPages[key as keyof typeof viewportRanges]) as Array<
keyof typeof viewportRanges
>
}

if (showPages) {
return []
} else {
return Object.keys(viewportRanges) as Array<keyof typeof viewportRanges>
}
}, [showPages])

return (
<LiveRegion>
Expand Down Expand Up @@ -202,7 +238,7 @@ export function Pagination({
</Button>
</Step>
{pageCount > 0 ? (
<Step>
<Step hiddenViewportRanges={getViewportRangesToHidePages()}>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the hiddenViewportRanges prop something that can be placed on TablePaginationSteps? Would be great to calculate this once and place it on the outermost node and then target it e.g.

  @media ${viewportRanges.narrow} {
    .TablePaginationSteps[data-hidden-viewport-ranges*='narrow'] > *:not(:first-child):not(:last-child) {
      display: none;
    }

    .TablePaginationSteps[data-hidden-viewport-ranges*='narrow'] > *:first-child {
      margin-inline-end: 0;
    }
  }

If not, I think this is something we should calculate once instead of as a function and just pass its value to each Step instead of messing around with useCallback() and calling it for each step.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh good catch! Ok, I'll refactor 👍

<Page
active={pageIndex === 0}
onClick={() => {
Expand All @@ -229,7 +265,7 @@ export function Pagination({

const page = offsetStartIndex + i
return (
<Step key={i}>
<Step key={i} hiddenViewportRanges={getViewportRangesToHidePages()}>
<Page
active={pageIndex === page}
onClick={() => {
Expand All @@ -246,7 +282,7 @@ export function Pagination({
})
: null}
{pageCount > 1 ? (
<Step>
<Step hiddenViewportRanges={getViewportRangesToHidePages()}>
<Page
active={pageIndex === pageCount - 1}
onClick={() => {
Expand Down Expand Up @@ -317,12 +353,20 @@ function TruncationStep() {
)
}

function Step({children}: React.PropsWithChildren) {
return <li className="TablePaginationStep">{children}</li>
function Step({
children,
hiddenViewportRanges,
}: React.PropsWithChildren & {hiddenViewportRanges?: Array<keyof typeof viewportRanges>}) {
return (
<li className="TablePaginationStep" data-hidden-viewport-ranges={hiddenViewportRanges?.join(' ')}>
{children}
</li>
)
}

type PageProps = React.PropsWithChildren<{
active: boolean
hiddenViewportRanges?: Array<keyof typeof viewportRanges>
onClick: () => void
}>

Expand Down
2 changes: 1 addition & 1 deletion src/Pagination/Pagination.docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
},
{
"name": "showPages",
"type": "boolean",
"type": "boolean | { narrow?: boolean, regular?: boolean, wide?: boolean }",
"defaultValue": "true",
"description": "Whether or not to show the individual page links."
},
Expand Down
13 changes: 13 additions & 0 deletions src/Pagination/Pagination.features.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ export const HidePageNumbers = () => (
<Pagination pageCount={15} currentPage={5} showPages={false} onPageChange={e => e.preventDefault()} />
)

export const HidePageNumbersByViewport = () => (
<>
<Pagination pageCount={15} currentPage={5} showPages={{narrow: false}} onPageChange={e => e.preventDefault()} />
<p>Page numbers are hidden on narrow viewports.</p>
</>
)

HidePageNumbersByViewport.parameters = {
viewport: {
defaultViewport: 'small',
},
}

export const HigherSurroundingPageCount = () => (
<Pagination pageCount={15} currentPage={5} surroundingPageCount={4} onPageChange={e => e.preventDefault()} />
)
38 changes: 35 additions & 3 deletions src/Pagination/Pagination.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,38 @@ export default {
component: Pagination,
} as Meta<ComponentProps<typeof Pagination>>

export const Default = () => <Pagination pageCount={15} currentPage={2} onPageChange={e => e.preventDefault()} />
const parseShowPagesArg = (value: boolean | string) => {
if (typeof value === 'boolean') {
return value
}

export const Playground: Story<ComponentProps<typeof Pagination>> = args => (
<Pagination onPageChange={e => e.preventDefault()} {...args} />
if (value === 'hide at narrow') {
return {narrow: false}
}

if (value === 'hide at regular') {
return {regular: false}
}

if (value === 'hide at wide') {
return {wide: false}
}
}

export const Default = () => (
<Pagination pageCount={15} currentPage={2} onPageChange={e => e.preventDefault()} showPages={{narrow: false}} />
)

export const Playground: Story<ComponentProps<typeof Pagination>> = ({showPages, ...args}) => {
return (
<Pagination
onPageChange={e => e.preventDefault()}
showPages={parseShowPagesArg(showPages as boolean | string)}
{...args}
/>
)
}

Playground.args = {
currentPage: 5,
marginPageCount: 1,
Expand All @@ -22,6 +48,12 @@ Playground.args = {
surroundingPageCount: 2,
}
Playground.argTypes = {
showPages: {
control: {
type: 'radio',
},
options: [true, false, 'hide at narrow', 'hide at regular', 'hide at wide'],
},
hrefBuilder: {
control: false,
table: {
Expand Down
23 changes: 20 additions & 3 deletions src/Pagination/Pagination.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {get} from '../constants'
import sx, {SxProp} from '../sx'
import getGlobalFocusStyles from '../internal/utils/getGlobalFocusStyles'
import {buildComponentData, buildPaginationModel} from './model'
import {ResponsiveValue, viewportRanges} from '../hooks/useResponsiveValue'

const Page = styled.a`
display: inline-block;
Expand Down Expand Up @@ -78,6 +79,22 @@ const Page = styled.a`
background-color: transparent;
}

${
// Hides pages based on the viewport range passed to `showPages`
Object.keys(viewportRanges)
.map(viewportRangeKey => {
return `
@media (${viewportRanges[viewportRangeKey as keyof typeof viewportRanges]}) {
&[data-hidden-viewport-ranges*='${viewportRangeKey}'],
&[data-hidden-viewport-ranges*='${viewportRangeKey}'] + .paginationBreak {
display: none;
}
}
`
})
.join('')
}

@supports (clip-path: polygon(50% 0, 100% 50%, 50% 100%)) {
&[rel='prev']::before,
&[rel='next']::after {
Expand Down Expand Up @@ -130,7 +147,7 @@ type UsePaginationPagesParameters = {
onPageChange: (e: React.MouseEvent, n: number) => void
hrefBuilder: (n: number) => string
marginPageCount: number
showPages?: boolean
showPages?: PaginationProps['showPages']
surroundingPageCount: number
}

Expand All @@ -147,7 +164,7 @@ function usePaginationPages({
const pageChange = React.useCallback((n: number) => (e: React.MouseEvent) => onPageChange(e, n), [onPageChange])

const model = React.useMemo(() => {
return buildPaginationModel(pageCount, currentPage, !!showPages, marginPageCount, surroundingPageCount)
return buildPaginationModel(pageCount, currentPage, marginPageCount, surroundingPageCount, showPages)
}, [pageCount, currentPage, showPages, marginPageCount, surroundingPageCount])

const children = React.useMemo(() => {
Expand Down Expand Up @@ -178,7 +195,7 @@ export type PaginationProps = {
onPageChange?: (e: React.MouseEvent, n: number) => void
hrefBuilder?: (n: number) => string
marginPageCount?: number
showPages?: boolean
showPages?: boolean | ResponsiveValue<boolean>
surroundingPageCount?: number
}

Expand Down
28 changes: 25 additions & 3 deletions src/Pagination/model.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
import {viewportRanges} from '../hooks/useResponsiveValue'
import {PaginationProps} from './Pagination'

export function buildPaginationModel(
pageCount: number,
currentPage: number,
showPages: boolean,
marginPageCount: number,
surroundingPageCount: number,
showPages?: PaginationProps['showPages'],
) {
const pages = []

if (showPages) {
const getViewportRangesToHidePages = () => {
if (showPages && typeof showPages !== 'boolean') {
return Object.keys(showPages).filter(key => !showPages[key as keyof typeof viewportRanges]) as Array<
keyof typeof viewportRanges
>
}

if (showPages) {
return []
} else {
return Object.keys(viewportRanges) as Array<keyof typeof viewportRanges>
}
}

if (showPages !== false) {
const pageNums: Array<number> = []
const addPage = (n: number) => {
if (n >= 1 && n <= pageCount) {
Expand Down Expand Up @@ -85,6 +102,7 @@ export function buildPaginationModel(
num,
selected,
precedesBreak,
hiddenViewportRanges: getViewportRangesToHidePages(),
})
} else {
if (lastDelta === 1) {
Expand All @@ -93,6 +111,7 @@ export function buildPaginationModel(
num,
selected,
precedesBreak,
hiddenViewportRanges: getViewportRangesToHidePages(),
})
} else {
// We skipped some, so add a break
Expand All @@ -105,6 +124,7 @@ export function buildPaginationModel(
num,
selected,
precedesBreak: false,
hiddenViewportRanges: getViewportRangesToHidePages(),
})
}
}
Expand Down Expand Up @@ -132,6 +152,7 @@ type PageType = {
disabled?: boolean
selected?: boolean
precedesBreak?: boolean
hiddenViewportRanges?: Array<keyof typeof viewportRanges>
}

export function buildComponentData(
Expand Down Expand Up @@ -185,13 +206,14 @@ export function buildComponentData(
'aria-label': `Page ${page.num}${page.precedesBreak ? '...' : ''}`,
onClick,
'aria-current': page.selected ? 'page' : undefined,
'data-hidden-viewport-ranges': page.hiddenViewportRanges?.join(' '),
})
break
}
case 'BREAK': {
key = `page-${page.num}-break`
content = '…'
Object.assign(props, {as: 'span', role: 'presentation'})
Object.assign(props, {as: 'span', role: 'presentation', className: 'paginationBreak'})
}
}

Expand Down
Loading