Skip to content

Commit

Permalink
Fix pagination when there is only one page
Browse files Browse the repository at this point in the history
  • Loading branch information
pookmish committed Mar 8, 2024
1 parent 1964973 commit 7836a48
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 29 deletions.
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,8 @@ NEXT_PUBLIC_DRUPAL_BASE_URL=https://dev.next-drupal.org

# Change this to 'true' to fetch all pages and build each one.
# Recommended to enable this for production environment.
#BUILD_COMPLETE=false
#BUILD_COMPLETE=false

# Set this environment variable on the production environment only at launch. This will be used for the
# /sitemap.xml and allow search indexing on the site.
#NEXT_PUBLIC_DOMAIN=http://localhost:3000
2 changes: 1 addition & 1 deletion app/sitemap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const Sitemap = async (): Promise<MetadataRoute.Sitemap> => {
const sitemap: MetadataRoute.Sitemap = [];

nodes.map(node => sitemap.push({
url: `https://localhost:3000${node.path}`,
url: `${process.env.NEXT_PUBLIC_DOMAIN || ''}${node.path}`,
lastModified: new Date(node.changed.time),
priority: node.__typename === "NodeStanfordPage" ? 1 : .8,
changeFrequency: node.__typename === "NodeStanfordPage" ? "weekly": "monthly"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"tailwind-merge": "^2.2.1",
"tailwindcss": "^3.4.1",
"typescript": "^5.4.2",
"usehooks-ts": "^2.16.0",
"usehooks-ts": "^3.0.1",
"zustand": "^4.5.2"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion src/components/elements/load-more-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const LoadMoreList = ({buttonText, children, ulProps, liProps, itemsPerPage = 10
const {value: focusOnElement, setTrue: enableFocusElement, setFalse: disableFocusElement} = useBoolean(false)

const focusItemRef = useRef<HTMLLIElement>(null);
const [animationParent] = useAutoAnimate();
const [animationParent] = useAutoAnimate<HTMLUListElement>();

const showMoreItems = () => {
enableFocusElement();
Expand Down
49 changes: 29 additions & 20 deletions src/components/elements/paged-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,22 @@ type Props = HtmlHTMLAttributes<HTMLDivElement> & {
ulProps?: HtmlHTMLAttributes<HTMLUListElement>
liProps?: HtmlHTMLAttributes<HTMLLIElement>,
itemsPerPage?: number
pageKey?: string
}

const PagedList = ({children, ulProps, liProps, itemsPerPage = 10, ...props}: Props) => {
const PagedList = ({children, ulProps, liProps, itemsPerPage = 10, pageKey = 'page', ...props}: Props) => {
const items = Array.isArray(children) ? children : [children]

const router = useRouter();
const searchParams = useSearchParams()

// Use the GET param for page, but make sure that it is between 1 and the last page. If it's a string or a number
// outside the range, fix the value, so it works as expected.
const {count: page, setCount: setPage} = useCounter(Math.max(1, Math.min(Math.ceil(items.length / itemsPerPage), parseInt(searchParams.get('page') || '') || 1)))
const {count: page, setCount: setPage} = useCounter(Math.max(1, Math.min(Math.ceil(items.length / itemsPerPage), parseInt(searchParams.get(pageKey) || '') || 1)))
const {value: focusOnElement, setTrue: enableFocusElement, setFalse: disableFocusElement} = useBoolean(false)

const focusItemRef = useRef<HTMLLIElement>(null);
const [animationParent] = useAutoAnimate();
const [animationParent] = useAutoAnimate<HTMLUListElement>();

const goToPage = (page: number) => {
enableFocusElement();
Expand All @@ -40,12 +41,18 @@ const PagedList = ({children, ulProps, liProps, itemsPerPage = 10, ...props}: Pr
}, [focusOnElement, setFocusOnItem]);

useEffect(() => {
router.replace(page > 1 ? `?page=${page}` : '?', {scroll: false})
}, [router, page]);

// Use search params to retain any other parameters.
const params = new URLSearchParams(searchParams.toString());
if (page > 1) {
params.set(pageKey, `${page}`)
} else {
params.delete(pageKey)
}

router.replace(`?${params.toString()}`, {scroll: false})
}, [router, page, pageKey, searchParams]);
const paginationButtons = usePagination(items.length, page, itemsPerPage, 2);


return (
<div {...props}>
<ul {...ulProps} ref={animationParent}>
Expand All @@ -62,19 +69,21 @@ const PagedList = ({children, ulProps, liProps, itemsPerPage = 10, ...props}: Pr
)}
</ul>

<nav aria-label="Pager">
<ul className="list-unstyled flex justify-between">
{paginationButtons.map((pageNum, i) => (
<PaginationButton
key={`page-button-${pageNum}--${i}`}
page={pageNum}
currentPage={page}
total={Math.ceil(items.length / itemsPerPage)}
onClick={() => goToPage(pageNum)}
/>
))}
</ul>
</nav>
{paginationButtons.length > 1 &&
<nav aria-label="Pager">
<ul className="list-unstyled flex justify-between">
{paginationButtons.map((pageNum, i) => (
<PaginationButton
key={`page-button-${pageNum}--${i}`}
page={pageNum}
currentPage={page}
total={Math.ceil(items.length / itemsPerPage)}
onClick={() => goToPage(pageNum)}
/>
))}
</ul>
</nav>
}
</div>
)
}
Expand Down
1 change: 1 addition & 0 deletions src/components/views/stanford-news/news-list-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const NewsListView = async ({items = [], headingLevel}: Props) => {
<PagedList
ulProps={{className: "list-unstyled mb-20"}}
liProps={{className: "border-b border-black-20 last-of-type:border-0 pb-10 last:pb-0 pt-10 first:pt-0"}}
pageKey="news"
>
{items.map(item =>
<StanfordNewsListItem key={item.id} node={item} headingLevel={headingLevel}/>
Expand Down
10 changes: 5 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8605,7 +8605,7 @@ __metadata:
tailwindcss: "npm:^3.4.1"
tsconfig-paths-webpack-plugin: "npm:^4.1.0"
typescript: "npm:^5.4.2"
usehooks-ts: "npm:^2.16.0"
usehooks-ts: "npm:^3.0.1"
zustand: "npm:^4.5.2"
languageName: unknown
linkType: soft
Expand Down Expand Up @@ -17250,14 +17250,14 @@ __metadata:
languageName: node
linkType: hard

"usehooks-ts@npm:^2.16.0":
version: 2.16.0
resolution: "usehooks-ts@npm:2.16.0"
"usehooks-ts@npm:^3.0.1":
version: 3.0.1
resolution: "usehooks-ts@npm:3.0.1"
dependencies:
lodash.debounce: "npm:^4.0.8"
peerDependencies:
react: ^16.8.0 || ^17 || ^18
checksum: 10c0/0b7babf09b587cf7af71644dd603ee2efd820ec173c414af1c2afc2c61decc357738b093cabb6a881ac97d8a4e614723ee20096bddd459779f3a0786f4e6b2bf
checksum: 10c0/c1673758100251c35a62d8d50aafe375fdce253eaa4374e7f4686bfc68505bd1b24dfe1c605db6d2ddfbe3a4ac1eca826c52ce454c9e58d8da96a45c351e0e05
languageName: node
linkType: hard

Expand Down

0 comments on commit 7836a48

Please sign in to comment.