fix: align single code block with the buttons#2154
Conversation
|
|
@DeepaPrasanna is attempting to deploy a commit to the Unkey Team on Vercel. A member of the Team first needs to authorize it. |
📝 Walkthrough📝 WalkthroughWalkthroughThe changes in this pull request primarily focus on the Changes
Assessment against linked issues
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
Thank you for following the naming conventions for pull request titles! 🙏 |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (2)
apps/www/components/blog/blog-code-block.tsx (2)
103-110: SyntaxHighlighter placement and configurationThe
SyntaxHighlightercomponent is now properly placed within the flex container, which should improve its alignment with the buttons. Thetrim()function applied toblock.children(line 109) is a good addition to remove any unnecessary whitespace.Consider adding a small right margin or padding to the
SyntaxHighlighterto ensure there's always some space between the code and the buttons, especially for longer code snippets:<SyntaxHighlighter language={block.className.replace(/language-/, "")} style={darkTheme} showLineNumbers={true} highlighter={"hljs"} + className="mr-2" > {block.children.trim()} </SyntaxHighlighter>
111-121: Button container and accessibility improvementThe buttons are now grouped in a flex container, which improves their alignment and spacing. The addition of the
aria-labelto the download button (line 115) is a great accessibility improvement.Consider adding a more descriptive
aria-labelfor the copy button as well. You can do this by passing it as a prop to theCopyButtoncomponent:- <CopyButton value={copyData} /> + <CopyButton value={copyData} aria-label="Copy code" />Also, for consistency, you might want to add the same
align-topclass to theCopyButtonthat you have on the download button:- <CopyButton value={copyData} /> + <CopyButton value={copyData} className="align-top" />
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- apps/www/components/blog/blog-code-block.tsx (1 hunks)
🔇 Additional comments (2)
apps/www/components/blog/blog-code-block.tsx (2)
101-102: Improved layout structure for better alignmentThe new structure using flex containers and padding improves the alignment of the code block with the buttons. This change directly addresses the issue mentioned in #2148.
101-121: Summary: Successful alignment of single line code blocks with buttonsThe changes made to the
BlogCodeBlockSinglecomponent successfully address the issue described in #2148. The new structure using flex containers improves the alignment of single line code blocks with the associated buttons, enhancing the overall visual appearance and user experience.Key improvements:
- Better layout structure using flex containers
- Proper alignment of the
SyntaxHighlighterwith buttons- Improved button grouping and spacing
- Added accessibility attribute (
aria-label) to the download buttonThese changes meet the PR objectives and provide a more balanced and visually appealing presentation of single line code blocks on the blog page.
To ensure that these changes don't negatively impact other parts of the codebase, please run the following verification script:
This script will help identify any potential conflicts or areas that might need adjustment due to these changes.
✅ Verification successful
Adjusting Verification Scripts for Proper File Type Recognition
The initial verification scripts encountered errors due to unrecognized file types. To resolve this, we'll modify the scripts to use file extensions directly.
[/run_scripts]
Verified: No conflicts detected with other usages or CSS classes
The verification confirms that
BlogCodeBlockSingleis only utilized withinapps/www/components/mdx-content.tsxandapps/www/components/blog/blog-code-block.tsx. Additionally, no conflicting CSS classes related toflex,items-center, orjustify-centerwere found. These results indicate that the recent changes do not adversely affect other parts of the codebase and meet the PR objectives without introducing new issues.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any other usage of BlogCodeBlockSingle that might be affected by these changes # Test: Search for other usages of BlogCodeBlockSingle rg --type typescript --type tsx "BlogCodeBlockSingle" # Test: Check for any CSS classes that might conflict with the new layout rg --type css --type scss "flex.*items-center.*justify-center"Length of output: 182
Script:
#!/bin/bash # Description: Check for any other usage of BlogCodeBlockSingle that might be affected by these changes # Test: Search for other usages of BlogCodeBlockSingle in .ts and .tsx files rg -g "*.ts" -g "*.tsx" "BlogCodeBlockSingle" # Test: Check for any CSS classes that might conflict with the new layout in .css and .scss files rg -g "*.css" -g "*.scss" "flex.*items-center.*justify-center"Length of output: 451
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (3)
apps/www/components/blog/suggested-blogs.tsx (3)
22-22: Approved: Good addition of thekeyprop, but consider removing the redundant key.The addition of the
keyprop to the outer<div>is a good practice and will help React's reconciliation process when rendering the list of blog posts. Usingpost.slugas the key is appropriate as it should be unique for each post.However, there's a redundant
keyprop on the inner<Link>component. Since the outer<div>now has a key, the inner one is unnecessary.Consider applying this small optimization:
<div key={post.slug} className={cn("flex flex-col w-full mt-8 prose", className)}> - <Link href={post.url} key={post.url}> + <Link href={post.url}>This change will remove the redundant key and slightly improve the component's efficiency.
Line range hint
1-43: Consider enhancing component robustness and flexibilityWhile the overall implementation looks good, here are some suggestions to improve the component:
Handle potential undefined values more safely:
Instead of using non-null assertion onpost?.date!, consider providing a fallback value or handling the case where date might be undefined.Make the default image path configurable:
Consider moving the hardcoded default image path to a constant or configuration file for easier management across different environments.Add error boundary and loading state:
Consider implementing error handling and a loading state to improve user experience in case of data fetching issues.Here's an example of how you might implement these suggestions:
import { DEFAULT_BLOG_IMAGE } from '@/config/constants'; // ... (rest of the imports) export function SuggestedBlogs({ className, currentPostSlug }: BlogListProps): JSX.Element { const [isLoading, setIsLoading] = React.useState(true); const [error, setError] = React.useState<Error | null>(null); const posts = React.useMemo(() => { try { setIsLoading(true); const filteredPosts = allPosts.filter((post: Post) => post.url !== currentPostSlug).slice(0, 3); setIsLoading(false); return filteredPosts; } catch (err) { setError(err instanceof Error ? err : new Error('An error occurred while fetching posts')); setIsLoading(false); return []; } }, [currentPostSlug]); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; if (posts.length === 0) return null; return ( <div> {posts.map((post) => ( <div key={post.slug} className={cn("flex flex-col w-full mt-8 prose", className)}> <Link href={post.url}> <div className="flex w-full"> <div className="flex flex-col gap-2"> <Frame size="sm"> <ImageWithBlur alt="Blog Image" src={post.image ?? DEFAULT_BLOG_IMAGE} width={600} height={400} /> </Frame> <p className="text-white">{post.title || 'Untitled'}</p> <p className="text-sm text-white/50"> {post.date ? format(new Date(post.date), "MMM dd, yyyy") : 'Date not available'} </p> </div> </div> </Link> </div> ))} </div> ); }This refactored version includes error handling, a loading state, and safer handling of potentially undefined values. It also suggests moving the default image path to a constants file for better configurability.
Line range hint
1-43: Optimize performance with memoizationTo improve the component's performance, consider the following optimizations:
- Memoize the filtered and sliced posts array using
useMemo.- Memoize the formatted date for each post using
useMemo.Here's how you can implement these optimizations:
import React, { useMemo } from 'react'; import { format } from 'date-fns'; // ... (other imports) export function SuggestedBlogs({ className, currentPostSlug }: BlogListProps): JSX.Element { const posts = useMemo(() => { return allPosts.filter((post: Post) => post.url !== currentPostSlug).slice(0, 3); }, [currentPostSlug]); if (posts.length === 0) { return <></>; } return ( <div> {posts.map((post) => ( <SuggestedBlogPost key={post.slug} post={post} className={className} /> ))} </div> ); } function SuggestedBlogPost({ post, className }: { post: Post; className?: string }) { const formattedDate = useMemo(() => { return post.date ? format(new Date(post.date), "MMM dd, yyyy") : 'Date not available'; }, [post.date]); return ( <div className={cn("flex flex-col w-full mt-8 prose", className)}> <Link href={post.url}> <div className="flex w-full"> <div className="flex flex-col gap-2"> <Frame size="sm"> <ImageWithBlur alt="Blog Image" src={post.image ?? "/images/blog-images/defaultBlog.png"} width={600} height={400} /> </Frame> <p className="text-white">{post.title}</p> <p className="text-sm text-white/50">{formattedDate}</p> </div> </div> </Link> </div> ); }These changes will ensure that:
- The posts are only filtered and sliced when
currentPostSlugchanges.- The date formatting only occurs when the post's date changes, not on every render.
By extracting the individual blog post rendering into a separate component, we can better isolate the memoization of the formatted date. This approach improves the overall performance of the
SuggestedBlogscomponent, especially when dealing with a large number of posts or frequent re-renders.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- apps/www/components/blog/blog-code-block.tsx (3 hunks)
- apps/www/components/blog/suggested-blogs.tsx (1 hunks)
- apps/www/components/mdx-content.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/www/components/blog/blog-code-block.tsx
🔇 Additional comments (1)
apps/www/components/mdx-content.tsx (1)
83-89: ApprovedThe updated
precomponent correctly uses theisSingleLineCodeBlockfunction to determine whether to render a single-line or multi-line code block. This enhances the flexibility of code block rendering based on content length.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (1)
apps/www/components/mdx-content.tsx (1)
114-121: Approved with a suggestion for type refinement.The
isSingleLineCodeBlockfunction is well-implemented and addresses the issues mentioned in the past review comments. It correctly accesses the code content and uses a reliable method to count lines.Consider refining the type annotation for the
contentparameter to be more specific:const isSingleLineCodeBlock = ( content: { children: ReactElement<{ children: string }> } ) => { const codeBlock = content.children.props.children; return codeBlock.split("\n").length < 2; };This more precise type annotation will help prevent potential misuse of the function and improve type safety.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- apps/www/components/mdx-content.tsx (3 hunks)
🔇 Additional comments (2)
apps/www/components/mdx-content.tsx (2)
Line range hint
1-121: Overall, the changes effectively address the PR objectives.The modifications to the
precomponent and the introduction of theisSingleLineCodeBlockfunction successfully resolve the alignment issue for single-line code blocks without affecting multi-line blocks. The implementation is clean and aligns well with the PR objectives.A few minor suggestions have been made to further improve type safety and verify the changes. These suggestions, if implemented, will enhance the robustness of the code without altering its core functionality.
Great job on addressing the issue and improving the code quality!
90-96: LGTM! Conditional rendering addresses the alignment issue.The updated
precomponent now correctly differentiates between single-line and multi-line code blocks, addressing the alignment issue mentioned in the PR objectives. This implementation should resolve the problem without affecting multi-line code blocks.To ensure this change doesn't introduce any regressions, please run the following script to check for any unexpected usage of
BlogCodeBlockSingleorBlogCodeBlock:This script will help identify any places where these components might be used directly, which could potentially bypass the new conditional logic.
✅ Verification successful
Verified: No unintended usages detected.
No direct usage of
BlogCodeBlockSingleorBlogCodeBlockwas found outside ofmdx-content.tsx. The conditional rendering implementation effectively centralizes their usage, ensuring the alignment issue is addressed without introducing any bypasses.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of BlogCodeBlockSingle and BlogCodeBlock components # Test: Search for direct usage of BlogCodeBlockSingle echo "Checking for direct usage of BlogCodeBlockSingle:" rg --type typescript --type tsx "BlogCodeBlockSingle" -g '!**/mdx-content.tsx' # Test: Search for direct usage of BlogCodeBlock echo "Checking for direct usage of BlogCodeBlock:" rg --type typescript --type tsx "BlogCodeBlock" -g '!**/mdx-content.tsx'Length of output: 427
Script:
#!/bin/bash # Description: Verify the usage of BlogCodeBlockSingle and BlogCodeBlock components # Test: Search for direct usage of BlogCodeBlockSingle echo "Checking for direct usage of BlogCodeBlockSingle:" rg --type tsx "BlogCodeBlockSingle" -g '!**/mdx-content.tsx' || rg --type ts "BlogCodeBlockSingle" -g '!**/mdx-content.tsx' # Test: Search for direct usage of BlogCodeBlock echo "Checking for direct usage of BlogCodeBlock:" rg --type tsx "BlogCodeBlock" -g '!**/mdx-content.tsx' || rg --type ts "BlogCodeBlock" -g '!**/mdx-content.tsx'Length of output: 794
perkinsjr
left a comment
There was a problem hiding this comment.
This code changes the core functionality.
In our current code we have two types of code blocks.
- A single code block.
- A code block that has multiple tabs.
The 2nd one allows a developer to add to do examples in multiple languages in a single code block with clickable tabs.
We only want to fix a single line of code when in either of these codeblocks to have correct alignment.
What you currently have done. Is now made all code blocks into tab based code blocks. Which in turn has now changed how all of the posts / changelogs and / templates work.
All that is required for this change is:
- Look for a single line in a code block and fix alignment.
- Make sure if there are more than one line of code in a codeblock that the copy and the download buttons don't shift.
No other changes are required outside of that, although fixing the key on the blog is welcomed.
Please make sure you are testing locally on all screen sizes, in the blog, changelog.
|
I am sorry. It was misunderstanding on my part. |
8fd5cca to
d6500b5
Compare
|
Awarding DeepaPrasanna: 150 points 🕹️ Well done! Check out your new contribution on oss.gg/DeepaPrasanna |
* fix: align single code block with the buttons * fix: add justify space between code line and buttons for singleBlockCode * fix: handle the key warning * fix: fix alignment of single code line









What does this PR do?
Updated styles to align the single line code block with the buttons.
Fixes #2148
Before:

After:

Type of change
How should this be tested?
Checklist
Required
pnpm buildpnpm fmtconsole.logsgit pull origin mainAppreciated
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Refactor