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: added pagination to bolgs #3579

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

Conversation

HarshithG0WDA
Copy link

@HarshithG0WDA HarshithG0WDA commented Jan 15, 2025

Description

  • Added pagination with appropriate styling
  • Added 12 posts per page for a aesthetics

Related issue(s)

Summary by CodeRabbit

  • New Features
    • Added pagination functionality to the blog index page.
    • Users can now navigate through blog posts with previous/next buttons.
    • Implemented page number selection with dynamic page range, including ellipses for skipped pages.
    • Displays 12 posts per page for improved readability.

Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

Walkthrough

The pull request introduces pagination functionality to the blog index page. The changes involve adding state variables for tracking the current page, page range, and posts per page. New methods are implemented to handle page navigation, including changing pages, moving to previous and next pages. The rendering logic is updated to display a subset of blog posts based on the current page, and a pagination control is added to allow users to navigate through different pages of blog posts.

Changes

File Change Summary
pages/blog/index.tsx - Added currentPage state variable initialized to 1
- Added pageRange state variable initialized to [1, 10]
- Added postsPerPage constant set to 12
- Implemented handlePageChange method for page navigation
- Implemented handlePrevious and handleNext methods
- Updated rendering logic to use paginated posts

Possibly related issues

  • asyncapi/website#3570: This PR directly addresses the feature request for introducing pagination on the blog page, matching the user's proposed solution of implementing page navigation with a configurable number of blogs per page.

Poem

🐰 Hop, hop, through pages we go,
Blogs lined up in a neat row
Click next, click prev, with glee
Pagination sets our content free!
A rabbit's guide to reading delight 📖✨


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 15, 2025

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 2ccaa9b
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/678cda7ca0ef360008ec3aaa
😎 Deploy Preview https://deploy-preview-3579--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

asyncapi-bot commented Jan 15, 2025

⚡️ Lighthouse report for the changes in this PR:

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

Lighthouse ran on https://deploy-preview-3579--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: 2

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

38-40: Consider performance optimizations and code organization improvements

  1. Move postsPerPage to a constants file for reusability across components.
  2. Consider using useMemo for derived state calculations.
+ import { POSTS_PER_PAGE } from '@/constants/pagination';
- const postsPerPage = 12;
+ const postsPerPage = POSTS_PER_PAGE;

+ const totalPages = useMemo(() => Math.ceil(posts.length / postsPerPage), [posts.length, postsPerPage]);

88-90: Optimize post slicing with memoization

The current posts calculation should be memoized to prevent unnecessary recalculations on re-renders.

- const indexOfLastPost = currentPage * postsPerPage;
- const indexOfFirstPost = indexOfLastPost - postsPerPage;
- const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
+ const currentPosts = useMemo(() => {
+   const indexOfLastPost = currentPage * postsPerPage;
+   const indexOfFirstPost = indexOfLastPost - postsPerPage;
+   return posts.slice(indexOfFirstPost, indexOfLastPost);
+ }, [posts, currentPage, postsPerPage]);

155-155: Add key prop based on unique identifier

Using array index as key prop might cause issues with React's reconciliation process if posts are reordered or filtered.

- {currentPosts.map((post, index) => (
-   <BlogPostItem key={index} post={post} />
- ))}
+ {currentPosts.map((post) => (
+   <BlogPostItem key={post.slug || post.id} post={post} />
+ ))}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 19c6b07 and c13f1b8.

📒 Files selected for processing (1)
  • pages/blog/index.tsx (4 hunks)
🧰 Additional context used
🪛 eslint
pages/blog/index.tsx

[error] 71-71: Expected blank line after variable declarations.

(newline-after-var)


[error] 72-72: Expected blank line before this statement.

(padding-line-between-statements)


[error] 175-175: Replace {·length:·Math.min(12,·Math.ceil(posts.length·/·postsPerPage)·-·pageRange[0]·+·1)·}, with ⏎··············{·length:·Math.min(12,·Math.ceil(posts.length·/·postsPerPage)·-·pageRange[0]·+·1)·},⏎·············

(prettier/prettier)


[error] 176-176: Insert ··

(prettier/prettier)


[error] 176-176: Expected blank line after variable declarations.

(newline-after-var)


[error] 177-177: Replace ·············· with ················

(prettier/prettier)


[error] 177-185: Expected blank line before this statement.

(padding-line-between-statements)


[error] 178-178: Insert ··

(prettier/prettier)


[error] 179-179: Replace ·················· with ····················

(prettier/prettier)


[error] 180-180: Insert ··

(prettier/prettier)


[error] 181-181: Replace ·················· with ····················

(prettier/prettier)


[error] 182-182: Insert ··

(prettier/prettier)


[error] 183-183: Insert ··

(prettier/prettier)


[error] 184-184: Insert ··

(prettier/prettier)


[error] 185-185: Replace ·············· with ················

(prettier/prettier)


[error] 186-186: Replace } with ··}⏎············

(prettier/prettier)

🪛 GitHub Actions: PR testing - if Node project
pages/blog/index.tsx

[error] 71-71: Expected blank line after variable declarations


[error] 72-72: Expected blank line before this statement


[warning] 169-169: Invalid Tailwind CSS classnames order


[error] 175-175: Formatting error: Incorrect spacing and line breaks


[error] 176-177: Expected blank line after variable declarations and incorrect indentation


[warning] 181-181: Invalid Tailwind CSS classnames order


[warning] 190-190: Invalid Tailwind CSS classnames order

⏰ Context from checks skipped due to timeout of 180000ms (1)
  • GitHub Check: Lighthouse CI

pages/blog/index.tsx Outdated Show resolved Hide resolved
pages/blog/index.tsx Outdated Show resolved Hide resolved
Copy link

codecov bot commented Jan 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (eb7e056) to head (2ccaa9b).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #3579   +/-   ##
=========================================
  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.

@HarshithG0WDA HarshithG0WDA changed the title feat: Added pagination to Blogs feat: added pagination to bolgs Jan 15, 2025
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

♻️ Duplicate comments (2)
pages/blog/index.tsx (2)

65-87: 🛠️ Refactor suggestion

Improve pagination handler implementation

Building upon previous feedback:

  1. Add input validation
  2. Extract magic numbers into named constants
  3. Add error handling for invalid page numbers
+ const PAGE_STEP = 3;
+ const PAGE_WINDOW = 9;

  const handlePageChange = (pageNumber: number) => {
+   const totalPages = Math.ceil(posts.length / POSTS_PER_PAGE);
+   if (pageNumber < 1 || pageNumber > totalPages) {
+     console.error(`Invalid page number: ${pageNumber}. Must be between 1 and ${totalPages}`);
+     return;
+   }

    setCurrentPage(pageNumber);
    if (pageNumber > pageRange[1] - 1) {
-     setPageRange([pageRange[0] + 3, pageRange[1] + 3]);
+     setPageRange([pageRange[0] + PAGE_STEP, pageRange[1] + PAGE_STEP]);
    } else if (pageNumber < pageRange[0] + 1) {
-     const newStart = Math.max(pageRange[0] - 3, 1);
-     const newEnd = newStart + 9;
+     const newStart = Math.max(pageRange[0] - PAGE_STEP, 1);
+     const newEnd = newStart + PAGE_WINDOW;

      setPageRange([newStart, newEnd]);
    }
  };

167-202: 🛠️ Refactor suggestion

Improve accessibility and maintainability of pagination controls

Building upon previous feedback:

  1. Add keyboard navigation
  2. Improve ARIA labels and roles
  3. Extract common CSS classes
+ const paginationButtonClass = (isActive: boolean) =>
+   `mx-1 rounded-md border px-3 py-1 ${isActive ? 'bg-gray-300' : 'bg-white'}`;

- <div className="mt-8 flex justify-center">
+ <nav className="mt-8 flex justify-center" role="navigation" aria-label="Pagination">
    <button
      onClick={handlePrevious}
-     className={`mx-1 rounded-md border px-3 py-1 ${currentPage === 1 ? 'bg-gray-300' : 'bg-white'}`}
+     className={paginationButtonClass(currentPage === 1)}
+     aria-label="Go to previous page"
      disabled={currentPage === 1}
+     onKeyDown={(e) => e.key === 'Enter' && handlePrevious()}
    >
      Previous
    </button>
    {/* ... */}
    <button
      key={pageNumber}
      onClick={() => handlePageChange(pageNumber)}
-     className={`mx-1 rounded-md border px-3 py-1 ${currentPage === pageNumber ? 'bg-gray-300' : 'bg-white'}`}
+     className={paginationButtonClass(currentPage === pageNumber)}
+     aria-label={`Go to page ${pageNumber}`}
+     aria-current={currentPage === pageNumber ? 'page' : undefined}
+     onKeyDown={(e) => e.key === 'Enter' && handlePageChange(pageNumber)}
    >
      {pageNumber}
    </button>
    {/* ... */}
- </div>
+ </nav>
🧹 Nitpick comments (2)
pages/blog/index.tsx (2)

38-40: Improve state management implementation

  1. Convert postsPerPage to a named constant
  2. Add TypeScript types for pageRange state
+ const POSTS_PER_PAGE = 12;
+ const INITIAL_PAGE_RANGE: [number, number] = [1, 10];

  const [currentPage, setCurrentPage] = useState(1);
- const [pageRange, setPageRange] = useState([1, 10]);
+ const [pageRange, setPageRange] = useState<[number, number]>(INITIAL_PAGE_RANGE);
- const postsPerPage = 12;

89-91: Optimize pagination calculations with memoization

The current implementation recalculates these values on every render. Consider using useMemo to optimize performance.

- const indexOfLastPost = currentPage * postsPerPage;
- const indexOfFirstPost = indexOfLastPost - postsPerPage;
- const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
+ const currentPosts = useMemo(() => {
+   const indexOfLastPost = currentPage * POSTS_PER_PAGE;
+   const indexOfFirstPost = indexOfLastPost - POSTS_PER_PAGE;
+   return posts.slice(indexOfFirstPost, indexOfLastPost);
+ }, [currentPage, posts, POSTS_PER_PAGE]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c13f1b8 and f171eb8.

📒 Files selected for processing (1)
  • pages/blog/index.tsx (4 hunks)

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.

2 participants