Skip to content

[f] VER-248 - Integrate related UI to the snippets#226

Merged
giahung68 merged 3 commits intomainfrom
features/248-integrate-related-snippet
Dec 10, 2024
Merged

[f] VER-248 - Integrate related UI to the snippets#226
giahung68 merged 3 commits intomainfrom
features/248-integrate-related-snippet

Conversation

@giahung68
Copy link
Collaborator

@giahung68 giahung68 commented Dec 10, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new component to display related snippets with enhanced UI elements.
    • Added functionality to fetch related snippets based on a snippet ID and language.
    • Enhanced the loading state presentation for comments.
  • Improvements

    • Refined the logic for displaying no snippets found based on additional filter states.
    • Updated translations for related snippets and comments in English and Spanish.
  • Bug Fixes

    • Improved error handling for the copy URL functionality in the related snippets component.
  • Style

    • Expanded the Tailwind CSS color palette with a new border color.
  • Chores

    • Updated the snippet fetching logic to include related snippets management.

@linear
Copy link

linear bot commented Dec 10, 2024

@coderabbitai
Copy link

coderabbitai bot commented Dec 10, 2024

Walkthrough

This pull request introduces several enhancements to the snippet management functionality within the application. A new function, fetchRelatedSnippets, is added to retrieve related snippets based on a snippet ID and language. Several components are updated to utilize this functionality, including SnippetDetail, which now fetches and displays related snippets. The RelatedSnippets component is created to present these snippets. Additionally, the translation files are updated to include new terms related to snippets and comments. Other minor adjustments include UI improvements and filtering logic refinements.

Changes

File Change Summary
src/apis/snippet.ts Added fetchRelatedSnippets(snippetId: string, language: string): Promise<RelatedSnippet[]>. Imported RelatedSnippet type.
src/components/LiveblocksComments.tsx Updated loading state rendering to use flexbox for centering the spinner.
src/components/NoSnippetsMessage.tsx Updated conditional rendering to check both searchTerm and isEmpty() from useSnippetFilters.
src/components/RelatedSnippets.tsx Introduced a new component to display related snippets, handling URL copying and navigation.
src/components/SnippetDetail.tsx Integrated useRelatedSnippets hook to fetch related snippets, added loading state, and updated rendering logic to include RelatedSnippets.
src/constants/translations.ts Added new translation entries for relatedSnippets, comment, and comments in English and Spanish.
src/hooks/useSnippetFilters.tsx Modified isEmpty logic to include upvotedBy in the emptiness check.
src/hooks/useSnippets.tsx Added useRelatedSnippets hook and updated snippetKeys for related snippets.
src/types/snippet.ts Introduced new RelatedSnippet interface with various properties.
tailwind.config.js Added new color entry 'border-gray-medium' to the Tailwind CSS configuration.

Assessment against linked issues

Objective Addressed Explanation
Integrate related snippets with UI (VER-248)

Possibly related PRs

🐰 In the land of snippets, hopping so bright,
Fetching related ones, a delightful sight.
With colors and comments, our joy will expand,
Together we'll share, hand in hand.
So gather your snippets, let’s make them shine,
In the world of code, everything's fine! 🌟


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. (Experiment)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@giahung68 giahung68 linked an issue Dec 10, 2024 that may be closed by this pull request
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: 6

🧹 Outside diff range and nitpick comments (10)
src/components/NoSnippetsMessage.tsx (1)

Line range hint 31-36: Move hard-coded translations to translation constants

The Spanish translations are hard-coded in the component. Consider moving them to the translations constant file for consistency and maintainability.

-        {language === 'spanish' ? 'No se encontraron snippets' : 'No snippets found'}
+        {t.noSnippetsFound}
...
-        {language === 'spanish'
-          ? 'Intenta ajustar tus filtros o busca algo diferente.'
-          : 'Try adjusting your filters or search for something different.'}
+        {t.tryAdjustingFilters}
🧰 Tools
🪛 eslint

[error] 9-9: Use object destructuring.

(prefer-destructuring)

src/components/LiveblocksComments.tsx (2)

45-48: Ensure consistent height for flex centering

The flex centering requires a defined height to work properly. Consider setting an explicit height or min-height if the parent container's height is not guaranteed.

-      <div className='flex h-full items-center justify-center'>
+      <div className='flex min-h-[200px] items-center justify-center'>

Line range hint 51-51: Maintain consistent styling between loading and error states

The error message uses different margin classes (mx-6) compared to the loading state's centered layout. Consider using consistent styling for both states.

-    return <div className='mx-6'>Error loading comments: {error.message}</div>
+    return (
+      <div className='flex min-h-[200px] items-center justify-center text-red-500'>
+        Error loading comments: {error.message}
+      </div>
+    )
src/hooks/useSnippets.tsx (2)

50-56: Consider adding retry and error handling options

The useRelatedSnippets hook might benefit from additional error handling and retry options, especially for network failures.

 export function useRelatedSnippets({ snippetId, language }: { snippetId: string; language: string }) {
   return useQuery<RelatedSnippet[], Error>({
     queryKey: snippetKeys.related(snippetId, language),
     queryFn: () => fetchRelatedSnippets({ snippetId, language }),
-    enabled: !!snippetId
+    enabled: !!snippetId,
+    retry: 3,
+    retryDelay: 1000,
+    onError: (error) => {
+      console.error('Failed to fetch related snippets:', error);
+    }
   })
 }

7-7: Consider refactoring lists method parameters

The lists method has 5 parameters, which exceeds the recommended maximum of 3. Consider using a configuration object pattern.

+interface ListsConfig {
+  pageSize: number;
+  filters: SnippetFilters;
+  language: string;
+  orderBy: string;
+  searchTerm: string;
+}

-  lists: (pageSize: number, filters: any, language: string, orderBy: string, searchTerm: string) =>
+  lists: (config: ListsConfig) =>
-    [...snippetKeys.all, 'list', { pageSize, filters, language, orderBy, searchTerm }] as const,
+    [...snippetKeys.all, 'list', config] as const,
🧰 Tools
🪛 eslint

[error] 7-7: Method 'lists' has too many parameters (5). Maximum allowed is 3.

(@typescript-eslint/max-params)


[error] 7-7: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

src/types/snippet.ts (1)

129-129: Consider using a more specific type for similarity score

The similarity property might benefit from being more strictly typed (e.g., as a number between 0 and 1) to ensure valid similarity scores.

-  similarity: number
+  similarity: number & { __brand: 'NormalizedScore' }
src/apis/snippet.ts (1)

129-139: Enhance error handling and add input validation

While the implementation is functional, consider these improvements:

  1. Add input validation for snippetId and language
  2. Provide more descriptive error messages
 export const fetchRelatedSnippets = async ({
   snippetId,
   language
 }: {
   snippetId: string
   language: string
 }): Promise<RelatedSnippet[]> => {
+  if (!snippetId?.trim()) {
+    throw new Error('Invalid snippet ID provided')
+  }
+  if (!language?.trim()) {
+    throw new Error('Invalid language provided')
+  }
   const { data, error } = await supabase.rpc('search_related_snippets', { snippet_id: snippetId, p_language: language })
-  if (error) throw error
+  if (error) {
+    console.error('Error fetching related snippets:', error)
+    throw new Error(`Failed to fetch related snippets: ${error.message}`)
+  }
   return data
 }
src/hooks/useSnippetFilters.tsx (1)

91-94: LGTM! Consider simplifying the arrow function.

The logic changes look good. The upvotedBy check is consistent with other array checks.

Consider simplifying the arrow function body by removing the block statement:

-  const isEmpty = useCallback(() => {
-    return (
-      languages.length === 0 &&
-      states.length === 0 &&
-      sources.length === 0 &&
-      labels.length === 0 &&
-      labeledBy.length === 0 &&
-      starredBy.length === 0 &&
-      upvotedBy.length === 0 &&
-      !politicalSpectrum
-    )
-  }, [languages, states, sources, labels, labeledBy, starredBy, politicalSpectrum, upvotedBy])
+  const isEmpty = useCallback(
+    () =>
+      languages.length === 0 &&
+      states.length === 0 &&
+      sources.length === 0 &&
+      labels.length === 0 &&
+      labeledBy.length === 0 &&
+      starredBy.length === 0 &&
+      upvotedBy.length === 0 &&
+      !politicalSpectrum,
+    [languages, states, sources, labels, labeledBy, starredBy, politicalSpectrum, upvotedBy]
+  )
🧰 Tools
🪛 eslint

[error] 83-94: Unexpected block statement surrounding arrow body; move the returned value immediately after the =>.

(arrow-body-style)

src/components/RelatedSnippets.tsx (2)

126-129: Consider improving the comment count button accessibility.

The disabled button showing comment count could be improved for better accessibility.

Consider using a more semantic element since it's not interactive:

-<Button variant='ghost' size='sm' className='gap-1 px-2 text-xs' disabled>
+<div className='flex items-center gap-1 px-2 text-xs text-muted-foreground' role="status">
   <MessageSquare className='h-4 w-4' />
   {snippet.comment_count} {snippet.comment_count < 2 ? t.comment : t.comments}
-</Button>
+</div>

63-65: Consider showing a message when no related snippets exist.

Instead of returning null, consider showing a message to improve user experience.

 if (isEmpty(snippets)) {
-  return null;
+  return (
+    <div className="text-muted-foreground text-sm mt-4">
+      No related snippets found
+    </div>
+  );
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b29d1ed and 1e4089f.

📒 Files selected for processing (10)
  • src/apis/snippet.ts (2 hunks)
  • src/components/LiveblocksComments.tsx (1 hunks)
  • src/components/NoSnippetsMessage.tsx (1 hunks)
  • src/components/RelatedSnippets.tsx (1 hunks)
  • src/components/SnippetDetail.tsx (5 hunks)
  • src/constants/translations.ts (2 hunks)
  • src/hooks/useSnippetFilters.tsx (1 hunks)
  • src/hooks/useSnippets.tsx (2 hunks)
  • src/types/snippet.ts (1 hunks)
  • tailwind.config.js (1 hunks)
🧰 Additional context used
🪛 eslint
src/hooks/useSnippetFilters.tsx

[error] 83-94: Unexpected block statement surrounding arrow body; move the returned value immediately after the =>.

(arrow-body-style)

src/components/NoSnippetsMessage.tsx

[error] 9-9: Use object destructuring.

(prefer-destructuring)

src/components/RelatedSnippets.tsx

[error] 2-2: Missing file extension for "@/components/ui/card"

(import/extensions)


[error] 3-3: Missing file extension for "@/components/ui/button"

(import/extensions)


[error] 4-4: Missing file extension for "@/components/ui/badge"

(import/extensions)


[error] 5-5: Missing file extension for "@/components/ui/label"

(import/extensions)


[error] 10-10: Missing file extension for "@/hooks/use-toast"

(import/extensions)


[error] 11-11: Missing file extension for "@/components/ui/popover"

(import/extensions)


[error] 12-12: Missing file extension for "@/components/ui/tooltip"

(import/extensions)


[error] 14-14: Missing file extension for "@/constants/translations"

(import/extensions)


[error] 15-15: Missing file extension for "@/providers/language"

(import/extensions)


[error] 30-30: 'id' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 83-83: Handler function for onClick prop key must be a camelCase name beginning with 'on' only

(react/jsx-handler-names)


[error] 119-119: Do not use Array index in keys

(react/no-array-index-key)

src/components/SnippetDetail.tsx

[error] 22-22: Missing file extension for "@/hooks/useSnippets"

(import/extensions)

src/types/snippet.ts

[error] 123-126: Array type using 'Array' is forbidden. Use 'T[]' instead.

(@typescript-eslint/array-type)

src/hooks/useSnippets.tsx

[error] 2-2: Missing file extension for "@/apis/snippet"

(import/extensions)


[error] 3-3: All imports in the declaration are only used as types. Use import type.

(@typescript-eslint/consistent-type-imports)


[error] 3-3: Missing file extension for "@/types/snippet"

(import/extensions)


[error] 7-7: Method 'lists' has too many parameters (5). Maximum allowed is 3.

(@typescript-eslint/max-params)


[error] 7-7: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

🔇 Additional comments (8)
src/components/NoSnippetsMessage.tsx (1)

12-12: Consider clarifying the condition logic

The condition searchTerm && !isEmpty() might be counterintuitive. It suggests showing the "no results" message when there's a search term AND filters are not empty, which seems opposite to what we'd expect.

Let's verify the intended behavior:

tailwind.config.js (1)

68-69: LGTM: Color addition follows conventions

The new color definition follows the existing pattern and uses semantic naming.

src/apis/snippet.ts (1)

136-136: Verify the RPC function name and parameters

Ensure that the Supabase RPC function search_related_snippets exists and accepts the correct parameters.

src/constants/translations.ts (1)

73-76: LGTM! Translations are consistent and well-structured.

The new translations for related snippets and comments are properly implemented in both English and Spanish, following the existing naming conventions.

Also applies to: 149-152

src/components/SnippetDetail.tsx (4)

22-22: LGTM: Import changes align with related snippets integration

The new imports for useRelatedSnippets and RelatedSnippets component are appropriately added to support the related snippets feature.

Also applies to: 38-38

🧰 Tools
🪛 eslint

[error] 22-22: Missing file extension for "@/hooks/useSnippets"

(import/extensions)


51-54: LGTM: Related snippets hook implementation

The useRelatedSnippets hook is properly implemented with appropriate parameters and loading state management.


240-240: LGTM: Improved card spacing

The addition of bottom margin (mb-8) provides better visual separation between the main card and related snippets.


446-446: Verify RelatedSnippets component implementation

Let's verify the existence and proper typing of the RelatedSnippets component.

✅ Verification successful

RelatedSnippets component is properly implemented and typed

The RelatedSnippets component is correctly implemented in src/components/RelatedSnippets.tsx with proper typing:

  • Component is properly typed with RelatedSnippetsProps interface that expects snippets: RelatedSnippet[]
  • Component is correctly imported and used in SnippetDetail.tsx
  • Integration includes proper loading state handling
  • Related snippets data is fetched through a properly typed custom hook useRelatedSnippets
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify RelatedSnippets component implementation and typing

# Check for RelatedSnippets component definition
ast-grep --pattern 'const RelatedSnippets: $_ = ({ snippets }: $_) => $_'

# Check for RelatedSnippets type definitions
rg -A 5 'type.*RelatedSnippets.*Props'

Length of output: 116


Script:

#!/bin/bash
# Let's try a broader search for RelatedSnippets component
rg -A 10 "RelatedSnippets"

# Also search for any file containing RelatedSnippets in its name
fd "RelatedSnippets"

Length of output: 6260

Comment on lines 7 to 8
lists: (pageSize: number, filters: any, language: string, orderBy: string, searchTerm: string) =>
[...snippetKeys.all, 'list', { pageSize, filters, language, orderBy, searchTerm }] as const,
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace 'any' type with a proper interface

Using any type reduces type safety. Consider creating a proper interface for the filters parameter.

+interface SnippetFilters {
+  upvotedBy?: string[];
+  // add other filter properties
+}

-  lists: (pageSize: number, filters: any, language: string, orderBy: string, searchTerm: string) =>
+  lists: (pageSize: number, filters: SnippetFilters, language: string, orderBy: string, searchTerm: string) =>

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

🧰 Tools
🪛 eslint

[error] 7-7: Method 'lists' has too many parameters (5). Maximum allowed is 3.

(@typescript-eslint/max-params)


[error] 7-7: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

Comment on lines +123 to +126
labels: Array<{
text: string
text_spanish: string
}>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix array type syntax to follow TypeScript best practices

Replace Array<T> with T[] syntax as per TypeScript guidelines.

-  labels: Array<{
+  labels: {
     text: string
     text_spanish: string
-  }>
+  }[]
📝 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
labels: Array<{
text: string
text_spanish: string
}>
labels: {
text: string
text_spanish: string
}[]
🧰 Tools
🪛 eslint

[error] 123-126: Array type using 'Array' is forbidden. Use 'T[]' instead.

(@typescript-eslint/array-type)

Comment on lines +117 to +124
{snippet.labels.map((label, index) => (
<Badge
key={index}
variant='secondary'
className='flex h-8 items-center space-x-1 rounded-full border-none bg-blue-light px-3 text-blue-accent hover:bg-blue-200'>
{label.text}
</Badge>
))}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using array index as key for labels.

Using array indices as keys can lead to rendering issues if the array items change.

Consider using a unique identifier from the label object:

-{snippet.labels.map((label, index) => (
+{snippet.labels.map(label => (
   <Badge
-    key={index}
+    key={label.id || label.text}
     variant='secondary'
     className='flex h-8 items-center space-x-1 rounded-full border-none bg-blue-light px-3 text-blue-accent hover:bg-blue-200'>
     {label.text}
   </Badge>
 ))}

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

🧰 Tools
🪛 eslint

[error] 119-119: Do not use Array index in keys

(react/no-array-index-key)

Comment on lines +30 to +57
const handleCopy = async (e: React.MouseEvent, id: string) => {
e.stopPropagation()
try {
if (navigator.clipboard) {
await navigator.clipboard.writeText(publicUrl)
} else {
const textArea = document.createElement('textarea')
textArea.value = publicUrl
document.body.appendChild(textArea)
textArea.select()
document.execCommand('copy')
document.body.removeChild(textArea)
}
setCopied(true)
setOpen(true)
setTimeout(() => {
setCopied(false)
setOpen(false)
}, 1000)
} catch (err) {
console.error('Failed to copy:', err)
toast({
variant: 'destructive',
title: 'Error',
description: 'Failed to copy link. Please try again.'
})
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider enhancing clipboard operation error handling.

The clipboard operation implementation could be improved for better error handling and user experience.

Consider these improvements:

 const handleCopy = async (e: React.MouseEvent, id: string) => {
   e.stopPropagation()
   try {
-    if (navigator.clipboard) {
+    if (navigator.clipboard && window.isSecureContext) {
       await navigator.clipboard.writeText(publicUrl)
     } else {
+      // Fallback for non-HTTPS or unsupported browsers
       const textArea = document.createElement('textarea')
       textArea.value = publicUrl
+      textArea.style.position = 'fixed'
+      textArea.style.opacity = '0'
       document.body.appendChild(textArea)
       textArea.select()
       document.execCommand('copy')
       document.body.removeChild(textArea)
     }
     setCopied(true)
     setOpen(true)
     setTimeout(() => {
       setCopied(false)
       setOpen(false)
     }, 1000)
   } catch (err) {
     console.error('Failed to copy:', err)
     toast({
       variant: 'destructive',
       title: 'Error',
-      description: 'Failed to copy link. Please try again.'
+      description: 'Failed to copy link. Please try again or copy manually.'
     })
   }
 }
📝 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
const handleCopy = async (e: React.MouseEvent, id: string) => {
e.stopPropagation()
try {
if (navigator.clipboard) {
await navigator.clipboard.writeText(publicUrl)
} else {
const textArea = document.createElement('textarea')
textArea.value = publicUrl
document.body.appendChild(textArea)
textArea.select()
document.execCommand('copy')
document.body.removeChild(textArea)
}
setCopied(true)
setOpen(true)
setTimeout(() => {
setCopied(false)
setOpen(false)
}, 1000)
} catch (err) {
console.error('Failed to copy:', err)
toast({
variant: 'destructive',
title: 'Error',
description: 'Failed to copy link. Please try again.'
})
}
}
const handleCopy = async (e: React.MouseEvent, id: string) => {
e.stopPropagation()
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(publicUrl)
} else {
// Fallback for non-HTTPS or unsupported browsers
const textArea = document.createElement('textarea')
textArea.value = publicUrl
textArea.style.position = 'fixed'
textArea.style.opacity = '0'
document.body.appendChild(textArea)
textArea.select()
document.execCommand('copy')
document.body.removeChild(textArea)
}
setCopied(true)
setOpen(true)
setTimeout(() => {
setCopied(false)
setOpen(false)
}, 1000)
} catch (err) {
console.error('Failed to copy:', err)
toast({
variant: 'destructive',
title: 'Error',
description: 'Failed to copy link. Please try again or copy manually.'
})
}
}
🧰 Tools
🪛 eslint

[error] 30-30: 'id' is defined but never used.

(@typescript-eslint/no-unused-vars)

Comment on lines +83 to +109
<div className='flex items-center gap-2 space-y-0' onClick={e => e.stopPropagation()}>
<Popover modal>
<PopoverTrigger asChild>
<Button variant='ghost' className='size-icon'>
<Share2 className='h-4 w-4' />
</Button>
</PopoverTrigger>
<PopoverContent hideWhenDetached align='end' className='z-40 w-[300px]'>
<div className='flex-col items-start'>
<div className='mb-2 text-sm font-medium'>Share snippet</div>
<div className='flex w-full items-center gap-2'>
<code className='flex-1 truncate rounded bg-muted px-2 py-1'>{publicUrl}</code>
<Tooltip open={open}>
<TooltipTrigger asChild>
<Button variant='outline' size='sm' onClick={e => handleCopy(e, snippet.id)}>
{copied ? <Check className='h-4 w-4' /> : <Copy className='h-4 w-4' />}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{copied ? 'Copied!' : 'Copy link'}</p>
</TooltipContent>
</Tooltip>
</div>
</div>
</PopoverContent>
</Popover>
</div>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve event handling and accessibility.

The share button implementation needs improvements for accessibility and event handling.

Consider these enhancements:

-<div className='flex items-center gap-2 space-y-0' onClick={e => e.stopPropagation()}>
+<div className='flex items-center gap-2 space-y-0'>
   <Popover modal>
     <PopoverTrigger asChild>
-      <Button variant='ghost' className='size-icon'>
+      <Button 
+        variant='ghost' 
+        className='size-icon'
+        aria-label='Share snippet'
+        onClick={e => e.stopPropagation()}>
         <Share2 className='h-4 w-4' />
       </Button>
     </PopoverTrigger>
📝 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
<div className='flex items-center gap-2 space-y-0' onClick={e => e.stopPropagation()}>
<Popover modal>
<PopoverTrigger asChild>
<Button variant='ghost' className='size-icon'>
<Share2 className='h-4 w-4' />
</Button>
</PopoverTrigger>
<PopoverContent hideWhenDetached align='end' className='z-40 w-[300px]'>
<div className='flex-col items-start'>
<div className='mb-2 text-sm font-medium'>Share snippet</div>
<div className='flex w-full items-center gap-2'>
<code className='flex-1 truncate rounded bg-muted px-2 py-1'>{publicUrl}</code>
<Tooltip open={open}>
<TooltipTrigger asChild>
<Button variant='outline' size='sm' onClick={e => handleCopy(e, snippet.id)}>
{copied ? <Check className='h-4 w-4' /> : <Copy className='h-4 w-4' />}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{copied ? 'Copied!' : 'Copy link'}</p>
</TooltipContent>
</Tooltip>
</div>
</div>
</PopoverContent>
</Popover>
</div>
<div className='flex items-center gap-2 space-y-0'>
<Popover modal>
<PopoverTrigger asChild>
<Button
variant='ghost'
className='size-icon'
aria-label='Share snippet'
onClick={e => e.stopPropagation()}>
<Share2 className='h-4 w-4' />
</Button>
</PopoverTrigger>
<PopoverContent hideWhenDetached align='end' className='z-40 w-[300px]'>
<div className='flex-col items-start'>
<div className='mb-2 text-sm font-medium'>Share snippet</div>
<div className='flex w-full items-center gap-2'>
<code className='flex-1 truncate rounded bg-muted px-2 py-1'>{publicUrl}</code>
<Tooltip open={open}>
<TooltipTrigger asChild>
<Button variant='outline' size='sm' onClick={e => handleCopy(e, snippet.id)}>
{copied ? <Check className='h-4 w-4' /> : <Copy className='h-4 w-4' />}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{copied ? 'Copied!' : 'Copy link'}</p>
</TooltipContent>
</Tooltip>
</div>
</div>
</PopoverContent>
</Popover>
</div>
🧰 Tools
🪛 eslint

[error] 83-83: Handler function for onClick prop key must be a camelCase name beginning with 'on' only

(react/jsx-handler-names)

Comment on lines +441 to +447
{isRelatedSnippetsLoading ? (
<div className='flex h-full items-center justify-center'>
<Spinner />
</div>
) : (
<RelatedSnippets snippets={relatedSnippets || []} />
)}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error state handling for related snippets

While loading state is properly handled, there's no error state handling for the related snippets section. Consider adding error handling to improve user experience when fetching related snippets fails.

-        {isRelatedSnippetsLoading ? (
+        {isRelatedSnippetsLoading && (
           <div className='flex h-full items-center justify-center'>
             <Spinner />
           </div>
-        ) : (
+        )}
+        {!isRelatedSnippetsLoading && error && (
+          <div className='text-center text-red-500'>
+            <p>{t.errorLoadingRelatedSnippets}</p>
+          </div>
+        )}
+        {!isRelatedSnippetsLoading && !error && (
           <RelatedSnippets snippets={relatedSnippets || []} />
         )}

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

Copy link
Collaborator Author

@giahung68 giahung68 left a comment

Choose a reason for hiding this comment

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

LGTM

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.

Integrate related snippets Change "Upvote" filter label to "Upvoted"

1 participant