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

fix: table of contents links not working #3560

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

Conversation

cs7-shrey
Copy link

@cs7-shrey cs7-shrey commented Jan 9, 2025

Description

  • fixed the TOC component to allow navigation from table of contents

Related issue(s)
Fixes #3540

Summary by CodeRabbit

  • New Features
    • Enhanced table of contents (TOC) navigation by updating slug generation and tracking mechanism.
    • Improved content linking with more accurate scroll tracking, ensuring functionality even when slugs are absent.

Copy link

coderabbitai bot commented Jan 9, 2025

Walkthrough

The changes in the TOC.tsx component focus on modifying how the Scrollspy component processes the items prop and the href attributes for anchor elements. The items prop now conditionally checks for the presence of the slug property; if absent, it uses the slugWithATag property. This adjustment enhances the logic for scroll tracking and ensures that navigation links remain functional, improving the overall robustness of the TOC component.

Changes

File Change Summary
components/TOC.tsx - Updated Scrollspy items prop to conditionally use slug or slugWithATag
- Modified href attributes of anchor elements to reflect the new conditional logic

Assessment against linked issues

Objective Addressed Explanation
TOC links not working [#3540]
Smooth scrolling to sections Requires additional verification of scrolling behavior

Poem

🐰 A rabbit's tale of TOC delight,
Slugs transformed with coding might,
Links now dance across the page,
Scrolling smooth, a brand new stage!
Hop along, dear reader true, 🦊
Navigation's magic just for you!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 01c535f and 9792eb9.

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

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

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 9792eb9
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/6780305e91be21000861d864
😎 Deploy Preview https://deploy-preview-3560--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 9, 2025

⚡️ Lighthouse report for the changes in this PR:

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

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

Copy link

codecov bot commented Jan 9, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (50b2beb) to head (281d006).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #3560   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           19        19           
  Lines          668       668           
=========================================
  Hits           668       668           

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

Copy link

@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 (2)
components/TOC.tsx (2)

Line range hint 34-40: Enhance slug transformation for better compatibility

The current slug transformation might not handle all edge cases correctly. Consider these improvements:

  1. Handle consecutive spaces to avoid multiple hyphens
  2. Add support for non-ASCII characters
  3. Ensure compatibility with manually added anchor tags mentioned in the comment

Consider this enhanced transformation:

       slugWithATag: item.content
-        .replace(/[<>?!:`'."\\/=]/gi, '')
-        .replace(/\s/gi, '-')
-        .toLowerCase()
+        .normalize('NFKD')  // Normalize Unicode characters
+        .replace(/[\u0300-\u036f]/g, '')  // Remove diacritics
+        .replace(/[^a-zA-Z0-9\s-]/g, '')  // Keep only alphanumeric and spaces
+        .trim()
+        .replace(/\s+/g, '-')  // Replace one or more spaces with single hyphen
+        .toLowerCase()

Line range hint 34-93: Consider extracting slug transformation logic

The current implementation embeds the slug transformation logic directly in the component. For better maintainability and reusability, consider:

  1. Extracting this logic into a utility function
  2. Adding it to a shared utilities module
  3. Writing dedicated tests for the transformation logic

This would make it easier to maintain consistent slug generation across the application and improve test coverage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 50b2beb and 281d006.

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

78-78: LGTM! Consistent usage of transformed slugs

The change ensures that Scrollspy uses the same transformed slugs as the anchor links, maintaining consistency in navigation tracking.


88-88: Verify the fix for non-working TOC links

The change correctly uses the transformed slugs in anchor links. Let's verify that this matches the actual heading IDs in the rendered content.

✅ Verification successful

Slug transformation correctly matches heading IDs

The change to use slugWithATag is verified to be correct. The transformation logic follows standard markdown heading ID generation rules by removing special characters, converting spaces to hyphens, and making the text lowercase. This ensures the TOC links will correctly match the auto-generated heading IDs in the rendered content.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the heading IDs in MDX files match our transformed slugs

# Find all MDX files
echo "Checking heading patterns in MDX files..."
rg -A 1 '^#{1,6}\s+.*' --type md

# Check for manually added anchor tags in spec files
echo "Checking for manual anchor tags in spec files..."
rg '<a\s+name="[^"]*">' --type md

Length of output: 70547


Script:

#!/bin/bash
# Search for slug transformation logic in the codebase
echo "Searching for slug transformation code..."
rg -A 5 "slugWithATag" --type ts

echo "Searching for related slug utility functions..."
rg -A 5 "slug" --type ts --glob '!**/node_modules/**' --glob '!**/dist/**'

Length of output: 21610

Copy link

@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 (2)
components/TOC.tsx (2)

78-78: LGTM! Consider using nullish coalescing for clarity.

The fallback logic for handling missing slugs is correct. However, you could make it more explicit using the nullish coalescing operator.

-items={tocItems.map((item) => (item.slug ? item.slug : item.slugWithATag))}
+items={tocItems.map((item) => item.slug ?? item.slugWithATag)}

Line range hint 6-13: Update interface to reflect optional slug property.

The interface should indicate that slug might be undefined since the implementation handles missing slugs.

 interface ITOCProps {
   className?: string;
   cssBreakingPoint?: string;
   toc: {
     lvl: number;
     content: string;
-    slug: string;
+    slug?: string;
+    slugWithATag?: string;
   }[];
   contentSelector?: string;
   depth?: number;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4ad7f87 and 01c535f.

📒 Files selected for processing (1)
  • components/TOC.tsx (2 hunks)
🧰 Additional context used
🪛 eslint
components/TOC.tsx

[error] 88-88: Replace (item.slug·?·item.slug·:·item.slugWithATag) with item.slug·?·item.slug·:·item.slugWithATag

(prettier/prettier)

🪛 GitHub Actions: PR testing - if Node project
components/TOC.tsx

[error] 88-88: Prettier formatting error: Extra parentheses in expression '(item.slug ? item.slug : item.slugWithATag)'

@@ -85,7 +85,7 @@ export default function TOC({ className, cssBreakingPoint = 'xl', toc, contentSe
<a
className={`pl-${2 ** (item.lvl - 1)} font-normal mb-1 block font-sans text-sm
text-gray-900 antialiased transition duration-100 ease-in-out hover:underline`}
href={`#${item.slug}`}
href={`#${(item.slug ? item.slug : item.slugWithATag)}`}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unnecessary parentheses to fix formatting.

The conditional logic is correct, but the extra parentheses are causing formatting issues.

-href={`#${(item.slug ? item.slug : item.slugWithATag)}`}
+href={`#${item.slug ? item.slug : item.slugWithATag}`}
📝 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
href={`#${(item.slug ? item.slug : item.slugWithATag)}`}
href={`#${item.slug ? item.slug : item.slugWithATag}`}
🧰 Tools
🪛 eslint

[error] 88-88: Replace (item.slug·?·item.slug·:·item.slugWithATag) with item.slug·?·item.slug·:·item.slugWithATag

(prettier/prettier)

🪛 GitHub Actions: PR testing - if Node project

[error] 88-88: Prettier formatting error: Extra parentheses in expression '(item.slug ? item.slug : item.slugWithATag)'

@cs7-shrey
Copy link
Author

@coderabbitai review

Copy link

coderabbitai bot commented Jan 9, 2025

✅ 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.

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.

[BUG] Blog Table of contents links not working
2 participants