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 SearchDialog component #13

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

davidemarcoli
Copy link
Collaborator

@davidemarcoli davidemarcoli commented Feb 18, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced image handling now supports trusted external sources.
    • Introduced a new search interface within the navigation, offering an interactive search dialog with improved responsiveness and keyboard shortcut support.
    • Added modular components for command and dialog interactions to elevate user accessibility and streamline navigation.

Copy link

coderabbitai bot commented Feb 18, 2025

📝 Walkthrough

Walkthrough

This pull request introduces several enhancements and additions. A new image handling configuration is added to the Next.js config, allowing remote images from a specified host. Two new dependencies are added to the project. A new search dialog feature is integrated into the main navigation, with its implementation separated into its own component, featuring debounced input and API-based media search. In addition, new command and dialog UI components are created using Radix UI and cmdk libraries. Lastly, a custom debouncing hook is introduced to manage delayed state updates.

Changes

File(s) Change Summary
next.config.ts Added an images property with a remotePatterns array to allow images from https://image.tmdb.org to be handled by Next.js.
package.json Added two dependencies: @radix-ui/react-dialog (^1.1.6) and cmdk (^1.0.4).
src/components/main-nav.tsx
src/components/search-dialog.tsx
Integrated a new SearchDialog component into the main navigation and introduced a comprehensive search dialog with debounced input, local and API-based media searches, keyboard shortcuts, and conditional result rendering.
src/components/ui/command.tsx
src/components/ui/dialog.tsx
Added new UI components. In command.tsx, multiple components for a command interface (Command, CommandDialog, CommandInput, etc.) were created using cmdk. In dialog.tsx, a set of dialog components based on Radix UI (Dialog, DialogTrigger, DialogContent, etc.) were introduced with accessibility and animation features.
src/hooks/use-debounce.ts Introduced a generic useDebounce hook to debounce values with a configurable delay, replacing previous logic with simplified behavior.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant MN as MainNav
    participant SD as SearchDialog
    participant DB as useDebounce Hook
    participant API as Media API

    U->>MN: Clicks search icon
    MN->>SD: Opens SearchDialog
    U->>SD: Types search query
    SD->>DB: Sends query for debouncing
    DB-->>SD: Returns debounced query
    SD->>API: Sends debounced query
    API-->>SD: Returns search results
    SD->>U: Displays search results
    U->>SD: Selects a result
    SD->>MN: Triggers navigation via Next.js Router
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5e329e4 and dba254c.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • next.config.ts (1 hunks)
  • package.json (1 hunks)
  • src/components/main-nav.tsx (2 hunks)
  • src/components/search-dialog.tsx (1 hunks)
  • src/components/ui/command.tsx (1 hunks)
  • src/components/ui/dialog.tsx (1 hunks)
  • src/hooks/use-debounce.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/search-dialog.tsx

[error] 184-184: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 216-216: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

🪛 ESLint
src/components/search-dialog.tsx

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

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

src/components/ui/command.tsx

[error] 42-42: Unknown property 'cmdk-input-wrapper' found

(react/no-unknown-property)

🔇 Additional comments (6)
next.config.ts (1)

16-23:

✅ Verification successful

LGTM! Configuration for TMDB images looks correct.

The remote pattern configuration is properly set up to allow images from The Movie Database (TMDB).

Let's verify the TMDB API endpoint availability:


🏁 Script executed:

#!/bin/bash
# Description: Verify TMDB image endpoint availability
curl -I https://image.tmdb.org/t/p/original/example.jpg

Length of output: 965


TMDB Image Configuration Approved – Note on Test URL

LGTM! The remote patterns configuration for image.tmdb.org in next.config.ts is correctly set up as per Next.js guidelines.

Please note that the verification script returned an HTTP/2 400 status. This is most likely due to using a placeholder URL (example.jpg), which isn’t a valid image resource on TMDB. When tested with a proper image path, the configuration should work as expected.

src/components/main-nav.tsx (1)

42-44: LGTM! SearchDialog integration looks clean.

The SearchDialog is properly integrated into the navigation with appropriate spacing and responsive behavior.

src/hooks/use-debounce.ts (1)

3-13: LGTM! Clean and efficient debounce implementation.

The hook correctly implements debouncing with proper cleanup and type safety.

src/components/ui/dialog.tsx (1)

1-122: LGTM! Excellent dialog implementation with Radix UI.

The dialog components are well-implemented with:

  • Strong type safety using forwardRef
  • Proper accessibility features (aria labels, keyboard navigation)
  • Smooth animations with proper state transitions
  • Clean component organization
src/components/ui/command.tsx (1)

1-153: LGTM! Well-structured command interface implementation.

The component architecture is clean and follows React best practices:

  • Good use of React.forwardRef for component composition
  • Proper type definitions and prop handling
  • Consistent styling approach using the cn utility
🧰 Tools
🪛 ESLint

[error] 42-42: Unknown property 'cmdk-input-wrapper' found

(react/no-unknown-property)

package.json (1)

21-21:

❓ Verification inconclusive

Verify React version compatibility.

The project uses React 19.0.0, which seems to be an incorrect version number (latest stable is 18.x.x). Please verify the React version and ensure compatibility with the new dependencies.

Also applies to: 28-28, 35-35


🌐 Web query:

What is the latest stable version of React?

💡 Result:

The latest stable version of React is 19.0, released on December 5, 2024[1][3][4][5][8][9]. This major update introduced features like Actions, new hooks (useActionState, useFormStatus, useOptimistic), Server Components/Server Actions, improved Context API support, and enhanced hydration mechanisms[3][5].

Key details about React v19:

  • Follows Semantic Versioning principles[1]
  • Supported release channel: Latest[1]
  • Active support includes non-critical bug fixes and new features[1]
  • Security fixes backported to all minor releases of current major versions[1]

For production applications using older versions:

  • React 18.x remains under security support (latest patch: 18.3.1)[1][5]
  • Earlier major versions (17.x and below) only receive critical security patches[1]

Developers can upgrade using npm/yarn with react@19.0.0 and react-dom@19.0.0[8][9]. The official documentation at react.dev covers v19 features[6].

Citations:


React 19 Compatibility Assurance and Dependency Verification

Recent information confirms that React v19.0.0 is the latest stable release, so the current React version used in the project is correct. However, please verify that the newly added dependencies (e.g., @radix-ui/react-dialog@1.1.6 and cmdk@1.0.4) are fully compatible with React 19.0.0. This check should also cover the similar dependency updates noted on lines 28 and 35 in package.json.

Comment on lines +16 to +51
// export function useDebounce<T>(value: T, delay: number): T {
// const [debouncedValue, setDebouncedValue] = React.useState<T>(value)
// const timeoutRef = React.useRef<NodeJS.Timeout>(undefined)
// const previousValue = React.useRef<T>(value)

// React.useEffect(() => {
// // Only update if the value has changed
// if (value !== previousValue.current) {
// console.log('Value changed:', { previous: previousValue.current, current: value })

// // Clear any existing timeout
// if (timeoutRef.current) {
// console.log('Clearing previous timeout')
// clearTimeout(timeoutRef.current)
// }

// console.log(`Setting new timeout for ${delay}ms`)
// timeoutRef.current = setTimeout(() => {
// console.log('Timeout executed, updating debounced value:', value)
// setDebouncedValue(value)
// }, delay)

// previousValue.current = value
// }

// // Cleanup on unmount or delay change
// return () => {
// if (timeoutRef.current) {
// console.log('Cleaning up timeout on unmount/update')
// clearTimeout(timeoutRef.current)
// }
// }
// }, [value, delay])

// return debouncedValue
// }
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Remove commented code.

The old implementation with logging is no longer needed and should be removed to maintain code cleanliness.

-//   export function useDebounce<T>(value: T, delay: number): T {
-//     const [debouncedValue, setDebouncedValue] = React.useState<T>(value)
-//     const timeoutRef = React.useRef<NodeJS.Timeout>(undefined)
-//     const previousValue = React.useRef<T>(value)
-
-//     React.useEffect(() => {
-//       // Only update if the value has changed
-//       if (value !== previousValue.current) {
-//         console.log('Value changed:', { previous: previousValue.current, current: value })
-
-//         // Clear any existing timeout
-//         if (timeoutRef.current) {
-//           console.log('Clearing previous timeout')
-//           clearTimeout(timeoutRef.current)
-//         }
-
-//         console.log(`Setting new timeout for ${delay}ms`)
-//         timeoutRef.current = setTimeout(() => {
-//           console.log('Timeout executed, updating debounced value:', value)
-//           setDebouncedValue(value)
-//         }, delay)
-
-//         previousValue.current = value
-//       }
-
-//       // Cleanup on unmount or delay change
-//       return () => {
-//         if (timeoutRef.current) {
-//           console.log('Cleaning up timeout on unmount/update')
-//           clearTimeout(timeoutRef.current)
-//         }
-//       }
-//     }, [value, delay])
-
-//     return debouncedValue
-//   }
📝 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 function useDebounce<T>(value: T, delay: number): T {
// const [debouncedValue, setDebouncedValue] = React.useState<T>(value)
// const timeoutRef = React.useRef<NodeJS.Timeout>(undefined)
// const previousValue = React.useRef<T>(value)
// React.useEffect(() => {
// // Only update if the value has changed
// if (value !== previousValue.current) {
// console.log('Value changed:', { previous: previousValue.current, current: value })
// // Clear any existing timeout
// if (timeoutRef.current) {
// console.log('Clearing previous timeout')
// clearTimeout(timeoutRef.current)
// }
// console.log(`Setting new timeout for ${delay}ms`)
// timeoutRef.current = setTimeout(() => {
// console.log('Timeout executed, updating debounced value:', value)
// setDebouncedValue(value)
// }, delay)
// previousValue.current = value
// }
// // Cleanup on unmount or delay change
// return () => {
// if (timeoutRef.current) {
// console.log('Cleaning up timeout on unmount/update')
// clearTimeout(timeoutRef.current)
// }
// }
// }, [value, delay])
// return debouncedValue
// }

React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the custom attribute syntax.

The cmdk-input-wrapper attribute should use data- prefix for custom attributes to comply with HTML standards.

-  <div className="flex items-center border-b px-3" cmdk-input-wrapper="">
+  <div className="flex items-center border-b px-3" data-cmdk-input-wrapper="">
📝 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 border-b px-3" cmdk-input-wrapper="">
<div className="flex items-center border-b px-3" data-cmdk-input-wrapper="">
🧰 Tools
🪛 ESLint

[error] 42-42: Unknown property 'cmdk-input-wrapper' found

(react/no-unknown-property)

title: result.title,
media_type: '',
path: result.path,
excerpt: result.content.substring(0, 100) + '...',
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Use template literals instead of string concatenation.

Replace string concatenation with template literals for better readability.

-        excerpt: result.content.substring(0, 100) + '...',
+        excerpt: `${result.content.substring(0, 100)}...`,
-            ? item.overview.substring(0, 100) + '...'
+            ? `${item.overview.substring(0, 100)}...`

Also applies to: 216-216

🧰 Tools
🪛 Biome (1.9.4)

[error] 184-184: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

if (!response.ok) throw new Error('Search failed')

const data = await response.json()
console.log(`Got search results for "${debouncedQuery}":`, data)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove console.log statements.

Remove debug console.log statements before deploying to production.

-        console.log(`Got search results for "${debouncedQuery}":`, data)
-        console.log(`Set search results for "${debouncedQuery}":`, [...componentResults, ...mediaResults])

Also applies to: 224-224

setResults(componentResults)

// Then fetch media results
const response = await fetch(`/api/search/multi?query=${encodeURIComponent(debouncedQuery)}`)
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhance URL encoding security.

While encodeURIComponent is used, consider additional validation of the query parameter.

-        const response = await fetch(`/api/search/multi?query=${encodeURIComponent(debouncedQuery)}`)
+        const sanitizedQuery = debouncedQuery.trim().replace(/[^\w\s-]/g, '')
+        const response = await fetch(`/api/search/multi?query=${encodeURIComponent(sanitizedQuery)}`)
📝 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 response = await fetch(`/api/search/multi?query=${encodeURIComponent(debouncedQuery)}`)
const sanitizedQuery = debouncedQuery.trim().replace(/[^\w\s-]/g, '')
const response = await fetch(`/api/search/multi?query=${encodeURIComponent(sanitizedQuery)}`)

Comment on lines +211 to +222
const mediaResults = data.results.map((item: any) => ({
title: item.title || item.name || '',
media_type: mapMediaType(item.media_type),
path: `/${item.media_type}/${item.id}`,
excerpt: item.overview
? item.overview.substring(0, 100) + '...'
: 'No description available',
type: 'media' as const,
posterPath: item.poster_path
? `https://image.tmdb.org/t/p/w92${item.poster_path}`
: undefined
}))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace any type with a proper interface.

Using any type reduces type safety. Define a proper interface for the API response.

-        const mediaResults = data.results.map((item: any) => ({
+        interface SearchApiResult {
+          id: number
+          title?: string
+          name?: string
+          media_type: string
+          overview?: string
+          poster_path?: string
+        }
+        const mediaResults = data.results.map((item: SearchApiResult) => ({
📝 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 mediaResults = data.results.map((item: any) => ({
title: item.title || item.name || '',
media_type: mapMediaType(item.media_type),
path: `/${item.media_type}/${item.id}`,
excerpt: item.overview
? item.overview.substring(0, 100) + '...'
: 'No description available',
type: 'media' as const,
posterPath: item.poster_path
? `https://image.tmdb.org/t/p/w92${item.poster_path}`
: undefined
}))
interface SearchApiResult {
id: number
title?: string
name?: string
media_type: string
overview?: string
poster_path?: string
}
const mediaResults = data.results.map((item: SearchApiResult) => ({
title: item.title || item.name || '',
media_type: mapMediaType(item.media_type),
path: `/${item.media_type}/${item.id}`,
excerpt: item.overview
? item.overview.substring(0, 100) + '...'
: 'No description available',
type: 'media' as const,
posterPath: item.poster_path
? `https://image.tmdb.org/t/p/w92${item.poster_path}`
: undefined
}))
🧰 Tools
🪛 Biome (1.9.4)

[error] 216-216: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

🪛 ESLint

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

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

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.

1 participant