Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add pagination feature in blog page #3595

Open
wants to merge 10 commits into
base: master
Choose a base branch
from

Conversation

priyanshuxkumar
Copy link

@priyanshuxkumar priyanshuxkumar commented Jan 21, 2025

Description
Add pagination feature in Blog page

Related issue(s)
Fixes #3570

update.mp4

Related issue(s)

Summary by CodeRabbit

Release Notes

  • New Features

    • Added pagination support for blog posts.
    • Implemented a flexible pagination system with page navigation.
    • Introduced a new PaginationItem component for individual page numbers.
    • Added "Next" and "Previous" icons for pagination controls.
  • Improvements

    • Introduced custom pagination hook for managing page-based content.
    • Added interactive pagination controls.
    • Improved user navigation experience for blog posts.

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Walkthrough

The pull request introduces a comprehensive pagination system for the blog page. The implementation includes creating helper functions like usePagination, developing reusable pagination components (Pagination and PaginationItem), and modifying the blog index page to incorporate pagination logic. The changes aim to improve user experience by limiting the number of blog posts displayed per page and providing intuitive navigation controls.

Changes

File Change Summary
components/helpers/applyFilter.ts Added conditional check to skip processing for 'page' property in onFilterApply function
components/helpers/usePagination.ts New custom React hook to manage pagination logic for array items
components/pagination/Pagination.tsx New component for rendering page navigation with dynamic page number generation
components/pagination/PaginationItem.tsx New component for rendering individual page number buttons
pages/blog/index.tsx Updated to use pagination hook, display current page items, and add pagination controls
components/icons/Next.tsx New component for rendering "Next" button icon
components/icons/Previous.tsx New component for rendering "Previous" button icon

Assessment against linked issues

Objective Addressed Explanation
Limit blogs per page
Provide "Next" and "Previous" buttons
Allow jumping to specific page
Improve performance
Enhance user experience

Suggested labels

ready-to-merge, bounty

Suggested reviewers

  • derberg
  • magicmatatjahu
  • anshgoyalevil
  • sambhavgupta0705
  • asyncapi-bot-eve
  • Mayaleeeee

Poem

🐰 Hop, hop, through pages we go,
Blogs lined up in a neat little row
No more scrolling till your eyes grow weary
Pagination makes reading less dreary!
A rabbit's guide to content so clear 📖✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Welcome to AsyncAPI. Thanks a lot for creating your first pull request. Please check out our contributors guide useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out this issue.

Copy link

netlify bot commented Jan 21, 2025

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit b514175
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/679724520c72730008e6af83
😎 Deploy Preview https://deploy-preview-3595--asyncapi-website.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@asyncapi-bot
Copy link
Contributor

Hello, @coderabbitai[bot]! 👋🏼

    I'm 🧞🧞🧞 Genie 🧞🧞🧞 from the magic lamp. Looks like somebody needs a hand!

    At the moment the following comments are supported in pull requests:

    - `/please-take-a-look` or `/ptal` - This comment will add a comment to the PR asking for attention from the reviewrs who have not reviewed the PR yet.
    - `/ready-to-merge` or `/rtm` - This comment will trigger automerge of PR in case all required checks are green, approvals in place and do-not-merge label is not added
    - `/do-not-merge` or `/dnm` - This comment will block automerging even if all conditions are met and ready-to-merge label is added
    - `/autoupdate` or `/au` - This comment will add `autoupdate` label to the PR and keeps your PR up-to-date to the target branch's future changes. Unless there is a merge conflict or it is a draft PR. (Currently only works for upstream branches.)
    - `/update` or `/u` - This comment will update the PR with the latest changes from the target branch. Unless there is a merge conflict or it is a draft PR. NOTE: this only updates the PR once, so if you need to update again, you need to call the command again.

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

@asyncapi-bot i'll start reviewing the changes for the pagination feature implementation.

🔗 analysis chain

🏁 scripts executed

the following scripts were executed for the analysis:

script:

#!/bin/bash
# get the pr diff to understand the changes
git diff --name-status head^..head

# get the actual diff
git diff head^..head

length of output: 9907

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

codecov bot commented Jan 21, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (c4b12e0) to head (b514175).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #3595   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           20        20           
  Lines          732       732           
=========================================
  Hits           732       732           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@asyncapi-bot
Copy link
Contributor

asyncapi-bot commented Jan 21, 2025

⚡️ Lighthouse report for the changes in this PR:

Category Score
🔴 Performance 41
🟢 Accessibility 98
🟢 Best practices 92
🟢 SEO 100
🔴 PWA 33

Lighthouse ran on https://deploy-preview-3595--asyncapi-website.netlify.app/

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
components/helpers/applyFilter.ts (1)

140-142: Consider filtering out pagination params before processing.

While the current implementation works correctly by skipping the 'page' parameter, consider a more maintainable approach by filtering out pagination-related parameters before processing.

Here's a suggested improvement:

export const onFilterApply = (
  inputData: DataObject[],
  onFilter: (result: DataObject[], query: Filter) => void,
  query: Filter
): void => {
  let result = inputData;

  if (query && Object.keys(query).length >= 1) {
-   Object.keys(query).forEach((property) => {
-     if (property === 'page') {
-       return;
-     }
+   // Filter out pagination params
+   const filterParams = Object.keys(query).filter(key => key !== 'page');
+   filterParams.forEach((property) => {
      const res = result.filter((e) => {
        // ... rest of the filtering logic
      });

      result = res;
    });
  }
  onFilter(result, query);
};

This approach:

  1. Makes the intention clearer by explicitly filtering out pagination params
  2. Avoids using early returns within forEach
  3. Is more extensible if more pagination-related params need to be excluded in the future
components/pagination/PaginationItem.tsx (1)

4-5: Remove unnecessary eslint-disable comment.

The empty eslint-disable comment can be removed as it serves no purpose.

-  // eslint-disable-next-line prettier/prettier
components/helpers/usePagination.ts (1)

14-30: Add input validation for edge cases.

While the implementation is solid, consider adding validation for:

  • Negative or zero itemsPerPage
  • Empty items array
 export function usePagination<T>(items: T[], itemsPerPage: number) {
+  if (itemsPerPage <= 0) {
+    throw new Error('itemsPerPage must be greater than 0');
+  }
+
   const [currentPage, setCurrentPage] = useState(1);
-  const maxPage = Math.ceil(items.length / itemsPerPage);
+  const maxPage = items.length ? Math.ceil(items.length / itemsPerPage) : 1;
components/pagination/Pagination.tsx (2)

6-7: Remove unnecessary eslint-disable comment.

The empty eslint-disable comment can be removed as it serves no purpose.

-  // eslint-disable-next-line prettier/prettier

55-75: Enhance accessibility and reduce CSS duplication.

  1. Add aria-labels to SVG elements for better accessibility
  2. Extract duplicate button styles to a common class
+const commonButtonStyles = `
+  font-normal flex h-[34px] items-center justify-center gap-2 rounded bg-white px-4
+  py-[7px] text-sm leading-[17px] tracking-[-0.01em]
+`;

 {/* Previous button */}
 <button
   onClick={() => handlePageChange(currentPage - 1)}
   disabled={currentPage === 1}
-  className={`
-    font-normal flex h-[34px] items-center justify-center gap-2 rounded bg-white px-4
-    py-[7px] text-sm leading-[17px] tracking-[-0.01em]
+  className={`${commonButtonStyles}
     ${currentPage === 1 ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'}
   `}
+  aria-label="Previous page"
 >
   <svg
     width='20'
     height='20'
     viewBox='0 0 24 24'
     fill='none'
     xmlns='http://www.w3.org/2000/svg'
     className='stroke-current'
+    aria-hidden="true"
   >

 {/* Next button */}
 <button
   onClick={() => handlePageChange(currentPage + 1)}
   disabled={currentPage === totalPages}
-  className={`
-    font-normal flex h-[34px] items-center justify-center gap-2 rounded bg-white px-4
-    py-[7px] text-sm leading-[17px] tracking-[-0.01em]
+  className={`${commonButtonStyles}
     ${currentPage === totalPages ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'}
   `}
+  aria-label="Next page"
 >

Also applies to: 99-119

pages/blog/index.tsx (1)

43-56: Add scroll to top behavior on page change.

When navigating between pages, consider scrolling to the top for better user experience.

 const handlePageChange = (page: number) => {
   setCurrentPage(page);

   const currentFilters = { ...router.query, page: page.toString() };

   router.push(
     {
       pathname: router.pathname,
       query: currentFilters
     },
     undefined,
     { shallow: true }
-  );
+  ).then(() => {
+    window.scrollTo({ top: 0, behavior: 'smooth' });
+  });
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cf3ca64 and af0e6a1.

📒 Files selected for processing (5)
  • components/helpers/applyFilter.ts (1 hunks)
  • components/helpers/usePagination.ts (1 hunks)
  • components/pagination/Pagination.tsx (1 hunks)
  • components/pagination/PaginationItem.tsx (1 hunks)
  • pages/blog/index.tsx (3 hunks)
🔇 Additional comments (3)
components/pagination/PaginationItem.tsx (1)

19-31: Great implementation with accessibility in mind!

The component is well-structured with:

  • Clear prop types and documentation
  • Proper accessibility attributes (aria-current)
  • Semantic button element with appropriate styling
components/pagination/Pagination.tsx (1)

21-122: Well-implemented pagination logic!

The component demonstrates:

  • Smart handling of different page number scenarios
  • Clean separation of concerns
  • Proper validation in handlePageChange
pages/blog/index.tsx (1)

154-168: Well-integrated pagination system!

The pagination integration demonstrates:

  • Clean integration with the existing blog page
  • Proper state management
  • Good user experience with loading states

Comment on lines 58 to 64
useEffect(() => {
const pageFromQuery = parseInt(router.query.page as string, 10);

if (!Number.isNaN(pageFromQuery) && pageFromQuery >= 1 && pageFromQuery !== currentPage) {
setCurrentPage(pageFromQuery);
}
}, [router.query.page]);
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 21, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for invalid page numbers.

When an invalid page number is provided in the URL, the code should handle it gracefully.

 useEffect(() => {
   const pageFromQuery = parseInt(router.query.page as string, 10);

-  if (!Number.isNaN(pageFromQuery) && pageFromQuery >= 1 && pageFromQuery !== currentPage) {
+  if (!Number.isNaN(pageFromQuery)) {
+    if (pageFromQuery >= 1 && pageFromQuery <= maxPage && pageFromQuery !== currentPage) {
       setCurrentPage(pageFromQuery);
+    } else {
+      // Reset to page 1 for invalid page numbers
+      handlePageChange(1);
+    }
   }
-  }, [router.query.page]);
+  }, [router.query.page, maxPage]);

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Author

Choose a reason for hiding this comment

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

Thank you for the suggestion to add error handling for invalid page numbers. I implemented the proposed code, but I am encountering an issue where navigating to any page (e.g., ?page=2) redirects me back to ?page=1.

It seems like the handlePageChange(1) function is being triggered unnecessarily, even when the pageFromQuery is valid.

Copy link
Contributor

Choose a reason for hiding this comment

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

@priyanshuxkumar I understand the issue. The problem occurs because we're validating against maxPage before it's properly initialized. Let's modify the code to ensure we only validate when we have a valid maxPage:

useEffect(() => {
  const pageFromQuery = parseInt(router.query.page as string, 10);

  if (!Number.isNaN(pageFromQuery) && maxPage > 0) {
    if (pageFromQuery >= 1 && pageFromQuery <= maxPage && pageFromQuery !== currentPage) {
      setCurrentPage(pageFromQuery);
    } else if (pageFromQuery < 1 || pageFromQuery > maxPage) {
      // Only reset to page 1 if the page number is actually invalid
      handlePageChange(1);
    }
  }
}, [router.query.page, maxPage, currentPage]);

This should fix the issue by:

  1. Only performing validation when maxPage is properly initialized (maxPage > 0)
  2. Only resetting to page 1 when the page number is actually out of bounds

Let me know if this resolves the issue!

Copy link
Author

Choose a reason for hiding this comment

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

yes its resolved

Copy link
Contributor

Choose a reason for hiding this comment

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

@priyanshuxkumar Great to hear that the pagination is working correctly now! 🎉


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
pages/blog/index.tsx (3)

40-41: Consider moving postsPerPage to configuration.

The hardcoded value of 9 posts per page would be better managed as a configuration constant, making it easier to adjust across different viewports or requirements.

+// Add to src/config/blog.ts or similar
+export const POSTS_PER_PAGE = 9;
+
 // In BlogIndexPage
-  const postsPerPage = 9;
+  const postsPerPage = POSTS_PER_PAGE;

164-168: Improve loader condition logic.

The current loader condition might show unnecessarily when currentItems is empty but posts exist. Consider checking both arrays.

-            {Object.keys(currentItems).length > 0 && !isClient && (
+            {Object.keys(posts).length > 0 && !isClient && (

169-173: Enhance pagination container accessibility.

Add appropriate ARIA attributes to improve accessibility for screen readers.

-              <div className='mt-8 w-full'>
+              <div className='mt-8 w-full' role="navigation" aria-label="Blog posts pagination">
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between af0e6a1 and 1873828.

📒 Files selected for processing (1)
  • pages/blog/index.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 180000ms (1)
  • GitHub Check: Test NodeJS PR - macos-13
🔇 Additional comments (2)
pages/blog/index.tsx (2)

4-4: LGTM! Import statements are well-organized.

The new imports for pagination components follow the existing import structure and use proper path aliases.

Also applies to: 10-10


43-69: Well-implemented page change handling and URL synchronization!

The code effectively:

  • Updates page state
  • Synchronizes URL query parameters
  • Handles invalid page numbers gracefully
  • Uses shallow routing for better performance

Comment on lines 140 to 142
if (property === 'page') {
return;
}
Copy link
Member

Choose a reason for hiding this comment

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

Can't we handle filters in a better approach?

Think in an approach where we look for some specific variables from query params here, not all.

Copy link
Author

Choose a reason for hiding this comment

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

` const nonFilterableKeys = ['page'];

if (query && Object.keys(query).length >= 1) {
Object.keys(query).forEach((property) => {
if (nonFilterableKeys.includes(property)) {
return; // Skip non-filterable keys like 'page'
}
`

Dynamically handles filters while explicitly excluding non-filterable keys like 'page'

* @returns {T[]} currentItems - Items for the current page
* @returns {number} maxPage - Total number of pages
*/
export function usePagination<T>(items: T[], itemsPerPage: number) {
Copy link
Member

@akshatnema akshatnema Jan 25, 2025

Choose a reason for hiding this comment

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

What is T here?

Copy link
Author

Choose a reason for hiding this comment

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

It takes a prop of items(all items) and returns the only item that has to be displayed on the current page

Comment on lines 27 to 50
const getPageNumbers = () => {
const pages = [];

if (totalPages <= 7) {
for (let i = 1; i <= totalPages; i++) pages.push(i);
} else {
pages.push(1);
if (currentPage > 3) {
pages.push('ellipsis1');
}

for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
pages.push(i);
}

if (currentPage < totalPages - 2) {
pages.push('ellipsis2');
}

pages.push(totalPages);
}

return pages;
};
Copy link
Member

Choose a reason for hiding this comment

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

Can you please explain the else part of this logic? It seems to be very weird.

Copy link
Author

Choose a reason for hiding this comment

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

i have updated this . basically it return the number of pages for display on pagination -
Screenshot from 2025-01-26 10-54-33

Comment on lines 55 to 63
<button
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
className={`
font-normal flex h-[34px] items-center justify-center gap-2 rounded bg-white px-4
py-[7px] text-sm leading-[17px] tracking-[-0.01em]
${currentPage === 1 ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'}
`}
>
Copy link
Member

Choose a reason for hiding this comment

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

We have existing Button element, can't we use that?

Copy link
Author

Choose a reason for hiding this comment

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

Yes, i updated it

Comment on lines 64 to 73
<svg
width='20'
height='20'
viewBox='0 0 24 24'
fill='none'
xmlns='http://www.w3.org/2000/svg'
className='stroke-current'
>
<path d='M15 18L9 12L15 6' strokeWidth='2' strokeLinecap='round' strokeLinejoin='round' />
</svg>
Copy link
Member

Choose a reason for hiding this comment

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

Add this SVG image as part of icons. Don't add the SVG code directly in the components.

Copy link
Author

Choose a reason for hiding this comment

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

yes, i have fixed it

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
components/icons/Previous.tsx (1)

9-18: Enhance SVG accessibility

Add appropriate ARIA attributes and descriptive elements for screen readers.

 <svg
   width='20'
   height='20'
   viewBox='0 0 24 24'
   fill='none'
   xmlns='http://www.w3.org/2000/svg'
   className='stroke-current'
+  role="img"
+  aria-label="Previous page"
 >
+  <title>Previous page</title>
   <path d='M15 18L9 12L15 6' strokeWidth='2' strokeLinecap='round' strokeLinejoin='round' />
 </svg>
components/pagination/Pagination.tsx (3)

11-12: Remove unnecessary empty eslint-disable comment

This empty prettier/eslint disable comment can be removed as it serves no purpose.


26-31: Add input validation for props

Add validation to ensure totalPages is positive and currentPage is within valid range.

 export default function Pagination({ totalPages, currentPage, onPageChange }: PaginationProps) {
+  if (totalPages < 1) {
+    throw new Error('totalPages must be positive');
+  }
+  if (currentPage < 1 || currentPage > totalPages) {
+    throw new Error('currentPage must be between 1 and totalPages');
+  }
+
   const handlePageChange = (page: number) => {

36-61: Extract magic numbers into named constants

The pagination logic uses magic numbers (7, 3, 2) which should be extracted into named constants for better maintainability.

+const MAX_VISIBLE_PAGES = 7;
+const BOUNDARY_PAGES = 3;
+const SIBLING_PAGES = 1;
+
 const getPageNumbers = (): (number | string)[] => {
-  if (totalPages <= 7) {
+  if (totalPages <= MAX_VISIBLE_PAGES) {
     return Array.from({ length: totalPages }, (_, i) => i + 1);
   }

   const pages: (number | string)[] = [1];

-  if (currentPage > 3) {
+  if (currentPage > BOUNDARY_PAGES) {
     pages.push('ellipsis1');
   }

-  const start = Math.max(2, currentPage - 1);
-  const end = Math.min(totalPages - 1, currentPage + 1);
+  const start = Math.max(2, currentPage - SIBLING_PAGES);
+  const end = Math.min(totalPages - 1, currentPage + SIBLING_PAGES);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1873828 and 458ca3e.

📒 Files selected for processing (4)
  • components/helpers/applyFilter.ts (1 hunks)
  • components/icons/Next.tsx (1 hunks)
  • components/icons/Previous.tsx (1 hunks)
  • components/pagination/Pagination.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/icons/Next.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/helpers/applyFilter.ts

/**
* @description Icons for Previous button in pagination
*/
export default function IconPrevios() {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in component name: IconPreviosIconPrevious

The component name has a typo that should be corrected for clarity and consistency.

-export default function IconPrevios() {
+export default function IconPrevious() {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export default function IconPrevios() {
export default function IconPrevious() {

currentPage === 1 ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
}`}
text='Previous'
icon={<IconPrevios />}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update import to use corrected icon name

Once the IconPrevios component is renamed to IconPrevious, update this import reference.

-icon={<IconPrevios />}
+icon={<IconPrevious />}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
icon={<IconPrevios />}
icon={<IconPrevious />}

Comment on lines 63 to 107
return (
<div className='font-inter flex items-center justify-center gap-8'>
{/* Previous button */}
<Button
onClick={() => handlePageChange(currentPage - 1)}
className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
currentPage === 1 ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
}`}
text='Previous'
icon={<IconPrevios />}
iconPosition={ButtonIconPosition.LEFT}
/>

{/* Page numbers */}
<div className='flex gap-2'>
{getPageNumbers().map((page) =>
typeof page === 'number' ? (
<PaginationItem
key={page}
pageNumber={page}
isActive={page === currentPage}
onPageChange={handlePageChange}
/>
) : (
<span
key={page}
className='font-inter flex size-10 items-center justify-center text-sm font-semibold text-[#6B6B6B]'
>
...
</span>
)
)}
</div>

{/* Next button */}
<Button
onClick={() => handlePageChange(currentPage + 1)}
className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
currentPage === totalPages ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
}`}
text='Next'
icon={<IconNext />}
/>
</div>
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance accessibility and extract styles

The pagination component needs accessibility improvements and style cleanup:

  1. Add ARIA labels for navigation
  2. Extract complex conditional styles into utility classes or CSS modules
  3. Add keyboard navigation support
 return (
-  <div className='font-inter flex items-center justify-center gap-8'>
+  <nav
+    role="navigation"
+    aria-label="Pagination"
+    className='font-inter flex items-center justify-center gap-8'
+  >
     {/* Previous button */}
     <Button
       onClick={() => handlePageChange(currentPage - 1)}
+      disabled={currentPage === 1}
       className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
         currentPage === 1 ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
       }`}
       text='Previous'
       icon={<IconPrevios />}
       iconPosition={ButtonIconPosition.LEFT}
+      aria-label="Go to previous page"
     />

     {/* Page numbers */}
-    <div className='flex gap-2'>
+    <div className='flex gap-2' role="list">
       {getPageNumbers().map((page) =>
         typeof page === 'number' ? (
           <PaginationItem
             key={page}
             pageNumber={page}
             isActive={page === currentPage}
             onPageChange={handlePageChange}
+            aria-label={`Go to page ${page}`}
+            aria-current={page === currentPage ? 'page' : undefined}
           />
         ) : (
           <span
             key={page}
             className='font-inter flex size-10 items-center justify-center text-sm font-semibold text-[#6B6B6B]'
+            aria-hidden="true"
           >
             ...
           </span>
         )
       )}
     </div>

     {/* Next button */}
     <Button
       onClick={() => handlePageChange(currentPage + 1)}
+      disabled={currentPage === totalPages}
       className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
         currentPage === totalPages ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
       }`}
       text='Next'
       icon={<IconNext />}
+      aria-label="Go to next page"
     />
-  </div>
+  </nav>
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return (
<div className='font-inter flex items-center justify-center gap-8'>
{/* Previous button */}
<Button
onClick={() => handlePageChange(currentPage - 1)}
className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
currentPage === 1 ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
}`}
text='Previous'
icon={<IconPrevios />}
iconPosition={ButtonIconPosition.LEFT}
/>
{/* Page numbers */}
<div className='flex gap-2'>
{getPageNumbers().map((page) =>
typeof page === 'number' ? (
<PaginationItem
key={page}
pageNumber={page}
isActive={page === currentPage}
onPageChange={handlePageChange}
/>
) : (
<span
key={page}
className='font-inter flex size-10 items-center justify-center text-sm font-semibold text-[#6B6B6B]'
>
...
</span>
)
)}
</div>
{/* Next button */}
<Button
onClick={() => handlePageChange(currentPage + 1)}
className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
currentPage === totalPages ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
}`}
text='Next'
icon={<IconNext />}
/>
</div>
);
return (
<nav
role="navigation"
aria-label="Pagination"
className='font-inter flex items-center justify-center gap-8'
>
{/* Previous button */}
<Button
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
currentPage === 1 ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
}`}
text='Previous'
icon={<IconPrevios />}
iconPosition={ButtonIconPosition.LEFT}
aria-label="Go to previous page"
/>
{/* Page numbers */}
<div className='flex gap-2' role="list">
{getPageNumbers().map((page) =>
typeof page === 'number' ? (
<PaginationItem
key={page}
pageNumber={page}
isActive={page === currentPage}
onPageChange={handlePageChange}
aria-label={`Go to page ${page}`}
aria-current={page === currentPage ? 'page' : undefined}
/>
) : (
<span
key={page}
className='font-inter flex size-10 items-center justify-center text-sm font-semibold text-[#6B6B6B]'
aria-hidden="true"
>
...
</span>
)
)}
</div>
{/* Next button */}
<Button
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === totalPages}
className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
currentPage === totalPages ? 'cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
}`}
text='Next'
icon={<IconNext />}
aria-label="Go to next page"
/>
</nav>
);

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (5)
components/pagination/Pagination.tsx (5)

11-12: Remove unnecessary eslint-disable comment.

The empty eslint-disable comment for prettier/prettier can be safely removed as it serves no purpose.

-  // eslint-disable-next-line prettier/prettier
-

23-25: Enhance component documentation.

The current JSDoc could be more descriptive. Consider adding:

 /**
  * This is the Pagination component. It displays a list of page numbers that can be clicked to navigate.
+ *
+ * @param {Object} props
+ * @param {number} props.totalPages - Total number of pages to display
+ * @param {number} props.currentPage - Currently active page number
+ * @param {Function} props.onPageChange - Callback function triggered when page changes
+ * @returns {JSX.Element} Pagination navigation component
+ *
+ * @example
+ * <Pagination
+ *   totalPages={10}
+ *   currentPage={1}
+ *   onPageChange={(page) => setCurrentPage(page)}
+ * />
  */

33-35: Improve helper function documentation.

The current JSDoc should better describe the function's behavior and return value format.

 /**
- * @returns number of pages shows in Pagination.
+ * Generates an array of page numbers and ellipsis markers for pagination display.
+ * For <= 7 pages, returns all page numbers.
+ * For > 7 pages, returns a subset with ellipsis markers.
+ *
+ * @returns {(number|string)[]} Array containing page numbers and 'ellipsis1'/'ellipsis2' strings
+ * @example
+ * // Returns [1, 2, 3, 4, 5] for totalPages=5
+ * // Returns [1, 'ellipsis1', 4, 5, 6, 'ellipsis2', 10] for totalPages=10, currentPage=5
  */

36-61: Extract magic numbers into named constants.

The function uses several magic numbers that should be constants for better maintainability and clarity.

+const MAX_VISIBLE_PAGES = 7;
+const ELLIPSIS_THRESHOLD = 3;
+const VISIBLE_PAGES_AROUND_CURRENT = 1;

 const getPageNumbers = (): (number | string)[] => {
-  if (totalPages <= 7) {
+  if (totalPages <= MAX_VISIBLE_PAGES) {
     return Array.from({ length: totalPages }, (_, i) => i + 1);
   }

   const pages: (number | string)[] = [1];

-  if (currentPage > 3) {
+  if (currentPage > ELLIPSIS_THRESHOLD) {
     pages.push('ellipsis1');
   }

-  const start = Math.max(2, currentPage - 1);
-  const end = Math.min(totalPages - 1, currentPage + 1);
+  const start = Math.max(2, currentPage - VISIBLE_PAGES_AROUND_CURRENT);
+  const end = Math.min(totalPages - 1, currentPage + VISIBLE_PAGES_AROUND_CURRENT);

   for (let i = start; i <= end; i++) {
     pages.push(i);
   }

-  if (currentPage < totalPages - 2) {
+  if (currentPage < totalPages - ELLIPSIS_THRESHOLD + 1) {
     pages.push('ellipsis2');
   }

   pages.push(totalPages);
   return pages;
 };

69-71: Extract common button styles into Tailwind components.

The button styles are duplicated between Previous and Next buttons. Consider extracting them into Tailwind components.

Add these classes to your Tailwind CSS file:

@layer components {
  .pagination-button {
    @apply font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em];
  }
  
  .pagination-button-enabled {
    @apply text-[#141717] hover:bg-gray-50;
  }
  
  .pagination-button-disabled {
    @apply cursor-not-allowed text-gray-300 hover:bg-gray-white;
  }
}

Then simplify the button classes:

-        className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
-          currentPage === totalPages
-            ? 'cursor-not-allowedtext-gray-300 hover:bg-gray-white text-gray-300'
-            : 'text-[#141717] hover:bg-gray-50'
-        }`}
+        className={`pagination-button ${
+          currentPage === totalPages
+            ? 'pagination-button-disabled'
+            : 'pagination-button-enabled'
+        }`}

Also applies to: 106-110

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 458ca3e and 66b9af3.

📒 Files selected for processing (2)
  • components/icons/Previous.tsx (1 hunks)
  • components/pagination/Pagination.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/icons/Previous.tsx

Comment on lines 107 to 109
currentPage === totalPages
? 'cursor-not-allowedtext-gray-300 hover:bg-gray-white text-gray-300'
: 'text-[#141717] hover:bg-gray-50'
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix CSS class concatenation in Next button's disabled state.

There's a typo in the class concatenation that might affect styling.

-            ? 'cursor-not-allowedtext-gray-300 hover:bg-gray-white text-gray-300'
+            ? 'cursor-not-allowed text-gray-300 hover:bg-gray-white'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
currentPage === totalPages
? 'cursor-not-allowedtext-gray-300 hover:bg-gray-white text-gray-300'
: 'text-[#141717] hover:bg-gray-50'
currentPage === totalPages
? 'cursor-not-allowed text-gray-300 hover:bg-gray-white'
: 'text-[#141717] hover:bg-gray-50'

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
components/pagination/Pagination.tsx (4)

11-12: Remove unnecessary eslint-disable comment.

The empty eslint-disable comment can be safely removed as it serves no purpose.

-  // eslint-disable-next-line prettier/prettier
-

27-31: Add input validation for page numbers.

While the bounds checking is good, consider adding type validation and handling edge cases.

   const handlePageChange = (page: number) => {
+    // Handle NaN and non-integer values
+    if (!Number.isInteger(page)) {
+      console.warn('Invalid page number:', page);
+      return;
+    }
     if (page >= 1 && page <= totalPages) {
       onPageChange(page);
     }
   };

36-61: Improve code maintainability with constants and better documentation.

The pagination logic could be more maintainable with named constants and improved documentation.

+  // Constants for pagination configuration
+  const MAX_VISIBLE_PAGES = 7;
+  const ELLIPSIS_START = 'ellipsis_start';
+  const ELLIPSIS_END = 'ellipsis_end';
+
   const getPageNumbers = (): (number | string)[] => {
-    if (totalPages <= 7) {
+    // Show all pages if total pages is less than or equal to maximum visible pages
+    if (totalPages <= MAX_VISIBLE_PAGES) {
       return Array.from({ length: totalPages }, (_, i) => i + 1);
     }

     const pages: (number | string)[] = [1];

     if (currentPage > 3) {
-      pages.push('ellipsis1');
+      pages.push(ELLIPSIS_START);
     }

+    // Calculate the range of visible page numbers around the current page
     const start = Math.max(2, currentPage - 1);
     const end = Math.min(totalPages - 1, currentPage + 1);

     for (let i = start; i <= end; i++) {
       pages.push(i);
     }

     if (currentPage < totalPages - 2) {
-      pages.push('ellipsis2');
+      pages.push(ELLIPSIS_END);
     }

     pages.push(totalPages);
     return pages;
   };

63-115: Optimize button styles and reduce duplication.

The Previous and Next button styles are duplicated. Consider extracting common styles and simplifying the conditional classes.

+  // Extract common button styles
+  const getButtonStyles = (isDisabled: boolean) => `
+    font-normal flex h-[34px] items-center justify-center 
+    rounded bg-white px-3 py-[7px] text-sm leading-[17px] 
+    tracking-[-0.01em] ${
+      isDisabled 
+        ? 'hover:bg-gray-white cursor-not-allowed text-gray-300' 
+        : 'text-[#141717] hover:bg-gray-50'
+    }
+  `;

   return (
     <nav role='navigation' aria-label='Pagination' className='font-inter flex items-center justify-center gap-8'>
       {/* Previous button */}
       <Button
         onClick={() => handlePageChange(currentPage - 1)}
         disabled={currentPage === 1}
-        className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
-          currentPage === 1 ? 'hover:bg-gray-white cursor-not-allowed text-gray-300' : 'text-[#141717] hover:bg-gray-50'
-        }`}
+        className={getButtonStyles(currentPage === 1)}
         text='Previous'
         icon={<IconPrevious />}
         iconPosition={ButtonIconPosition.LEFT}
         aria-label='Go to previous page'
       />

       {/* ... page numbers ... */}

       {/* Next button */}
       <Button
         onClick={() => handlePageChange(currentPage + 1)}
         disabled={currentPage === totalPages}
-        className={`font-normal flex h-[34px] items-center justify-center rounded bg-white px-3 py-[7px] text-sm leading-[17px] tracking-[-0.01em] ${
-          currentPage === totalPages
-            ? 'hover:bg-gray-white cursor-not-allowed text-gray-300'
-            : 'text-[#141717] hover:bg-gray-50'
-        }`}
+        className={getButtonStyles(currentPage === totalPages)}
         text='Next'
         icon={<IconNext />}
         aria-label='Go to next page'
       />
     </nav>
   );
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 66b9af3 and 454dd35.

📒 Files selected for processing (1)
  • components/pagination/Pagination.tsx (1 hunks)
🔇 Additional comments (1)
components/pagination/Pagination.tsx (1)

26-26: Add prop validation for edge cases.

Consider adding validation for the component props to handle edge cases gracefully.

 export default function Pagination({ totalPages, currentPage, onPageChange }: PaginationProps) {
+  // Validate props
+  if (totalPages < 1) {
+    console.warn('totalPages must be greater than 0');
+    return null;
+  }
+  if (currentPage < 1 || currentPage > totalPages) {
+    console.warn('currentPage must be between 1 and totalPages');
+    return null;
+  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[FEATURE] Introduce Pagination on Blog Page
3 participants