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: Allows triggers on dropdown and fixes filtering #2748

Merged
merged 3 commits into from
Dec 13, 2024
Merged

Conversation

perkinsjr
Copy link
Collaborator

@perkinsjr perkinsjr commented Dec 13, 2024

What does this PR do?

Fixes # (issue)

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Test A
  • Test B

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Enhanced user interaction within the Filter component for improved selection logic.
    • Updated dropdown menu triggers for various components to streamline user experience.
  • Bug Fixes

    • Resolved issues with unintended selections and dropdown interactions.
  • Documentation

    • Clarified usage of components in relation to dropdown menus and triggers.
  • Chores

    • General maintenance and updates to component structures while preserving core functionalities.

James Perkins added 3 commits December 13, 2024 10:51
Remove asChild to allow trigger from buttons
Removing as child to allow for correct triggers
Fix filter to work as expected
Copy link

changeset-bot bot commented Dec 13, 2024

⚠️ No Changeset found

Latest commit: 1fa0f81

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Dec 13, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard 🔄 Building (Inspect) Visit Preview 💬 Add feedback Dec 13, 2024 4:34pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 13, 2024 4:34pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 13, 2024 4:34pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 13, 2024 4:34pm

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request primarily involve modifications to various components within the dashboard application, particularly focusing on the DropdownMenuTrigger component. The asChild prop has been removed from several instances of this component across different files, affecting how dropdown menus are triggered and interact with child components. Additionally, some components have seen adjustments in their event handling logic, particularly regarding user interactions like clicks and selections. Overall, the functionality and structure of the components remain largely intact.

Changes

File Path Change Summary
apps/dashboard/app/(app)/audit/[bucket]/filter.tsx Modified Filter component: replaced onMouseDownCapture with onClick for PopoverTrigger.
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/filter.tsx Updated Filters component: DropdownMenuTrigger now wraps Button. Reset functionality adjusted for setSuccess.
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/menu.tsx Modified Menu component: removed asChild from DropdownMenuTrigger.
apps/dashboard/app/(app)/settings/user/update-user-email.tsx Updated UpdateUserEmail component: DropdownMenuTrigger now wraps Button. Error handling for email operations added.
apps/dashboard/components/dashboard/api-key-table/index.tsx Modified ApiKeyTable: removed asChild from DropdownMenuTrigger, updated DialogTrigger to use asChild.
apps/dashboard/components/dashboard/api-key-table/table.tsx Modified DataTable: removed asChild from DropdownMenuTrigger.
apps/dashboard/components/dashboard/root-key-table/index.tsx Modified RootKeyTable: removed asChild from DropdownMenuTrigger, updated DialogTrigger to use asChild.
apps/dashboard/components/dashboard/root-key-table/table.tsx Modified DataTable: removed asChild from DropdownMenuTrigger.
apps/dashboard/components/data-table/column-header.tsx Modified DataTableColumnHeader: removed asChild from DropdownMenuTrigger.
apps/dashboard/components/data-table/view-options.tsx Modified DataTableViewOptions: removed asChild from DropdownMenuTrigger.

Possibly related PRs

Suggested labels

Bug, 🕹️ oss.gg, :joystick: 150 points

Suggested reviewers

  • mcstepp
  • chronark
  • ogzhanolguncu

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.

Copy link
Contributor

github-actions bot commented Dec 13, 2024

Thank you for following the naming conventions for pull request titles! 🙏

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

🧹 Outside diff range and nitpick comments (8)
apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/menu.tsx (1)

Line range hint 23-42: Architectural Improvement: Consistent Dropdown Implementation

The systematic removal of asChild prop across dropdown triggers represents a positive architectural change that:

  1. Simplifies the component hierarchy
  2. Better aligns with Radix UI's recommended patterns
  3. Provides consistent behavior across different contexts (data tables, menus, filters)

This change should resolve the dropdown trigger issues mentioned in the PR objectives while maintaining proper functionality.

apps/dashboard/app/(app)/audit/[bucket]/filter.tsx (2)

Line range hint 75-83: Remove duplicate event handler logic

The onClick handler on the div duplicates the logic in the CommandItem's onSelect handler. This could potentially cause the selection logic to execute twice.

Remove the redundant onClick handler:

-                  <div
-                    onClick={() => {
-                      const next = isSelected
-                        ? selected.filter((v) => v !== option.value)
-                        : Array.from(new Set([...selected, option.value]));
-                      setSelected(next);
-                    }}
-                  >
+                  <div>

Line range hint 84-91: Add error handling for state updates

The selection state update logic should include error handling to gracefully handle any potential failures.

Consider wrapping the state update in a try-catch block:

                    <CommandItem
                      key={option.value}
                      onSelect={() => {
+                       try {
                          const next = isSelected
                            ? selected.filter((v) => v !== option.value)
                            : Array.from(new Set([...selected, option.value]));
                          setSelected(next);
+                       } catch (error) {
+                         console.error('Failed to update selection:', error);
+                         // Consider showing a user-friendly error message
+                       }
                      }}
                    >
apps/dashboard/components/dashboard/root-key-table/index.tsx (1)

Line range hint 158-162: Consider adding rate limiting for key deletion operations

While the deletion confirmation dialog provides a good warning, additional security measures could help prevent accidental or malicious bulk deletions.

Consider implementing:

  1. Rate limiting for deletion operations
  2. A cool-down period between bulk deletions
  3. Additional confirmation for deleting multiple keys simultaneously
apps/dashboard/components/dashboard/api-key-table/table.tsx (1)

Line range hint 108-112: Remove @ts-ignore and fix type safety

The use of @ts-ignore masks potential type safety issues that should be addressed properly.

Consider fixing the type safety issue:

-                        // @ts-ignore
-                        .rows.map((row) => row.original.id as string);
+                        .rows.map((row) => {
+                          if (!row.original || typeof row.original !== 'object' || !('id' in row.original)) {
+                            throw new Error('Invalid row data structure');
+                          }
+                          return row.original.id as string;
+                        });
apps/dashboard/components/dashboard/api-key-table/index.tsx (1)

Line range hint 243-256: Good improvement in dropdown menu item handling

The addition of onSelect handlers with preventDefault() is a good practice that prevents unintended navigation when selecting menu items. The asChild prop on DialogTrigger is correctly used to maintain proper DOM structure.

Consider extracting the onSelect handler to avoid repetition:

+ const preventDefaultSelect = (e: Event) => e.preventDefault();
  <DropdownMenuItem
-   onSelect={(e) => {
-     e.preventDefault();
-   }}
+   onSelect={preventDefaultSelect}
  >
apps/dashboard/app/(app)/settings/user/update-user-email.tsx (2)

127-129: Add aria-label to improve accessibility.

The Button with MoreHorizontal icon should have an aria-label to improve screen reader experience.

-<Button variant="ghost">
+<Button variant="ghost" aria-label="Email options">
   <MoreHorizontal className="w-4 h-4" />
 </Button>

Line range hint 126-238: Consider refactoring error handling and loading states.

The dropdown menu actions contain repeated error handling patterns and multiple loading states that could be consolidated for better maintainability.

Consider these improvements:

  1. Create a reusable error handler:
const handleError = (error: unknown, customMessage?: string) => {
  const message = error instanceof Error ? error.message : customMessage ?? 'An error occurred';
  toast.error(message);
};
  1. Use a single loading state manager:
type LoadingAction = 'verification' | 'promotion' | 'removal';
const [loadingAction, setLoadingAction] = useState<LoadingAction | null>(null);
const isLoading = (action: LoadingAction) => loadingAction === action;

This would simplify the action handlers and make the code more maintainable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 580c165 and 1fa0f81.

📒 Files selected for processing (10)
  • apps/dashboard/app/(app)/audit/[bucket]/filter.tsx (2 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/filter.tsx (1 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/menu.tsx (1 hunks)
  • apps/dashboard/app/(app)/settings/user/update-user-email.tsx (1 hunks)
  • apps/dashboard/components/dashboard/api-key-table/index.tsx (1 hunks)
  • apps/dashboard/components/dashboard/api-key-table/table.tsx (1 hunks)
  • apps/dashboard/components/dashboard/root-key-table/index.tsx (1 hunks)
  • apps/dashboard/components/dashboard/root-key-table/table.tsx (1 hunks)
  • apps/dashboard/components/data-table/column-header.tsx (1 hunks)
  • apps/dashboard/components/data-table/view-options.tsx (1 hunks)
🔇 Additional comments (8)
apps/dashboard/components/data-table/view-options.tsx (1)

Line range hint 23-28: LGTM! Dropdown trigger implementation follows Radix UI best practices.

The removal of asChild prop is correct here as the Button is properly wrapped by DropdownMenuTrigger, ensuring proper event handling and accessibility.

Let's verify this component's integration:

✅ Verification successful

Both implementations are valid for their specific use cases

The chart component uses asChild with ghost buttons that only contain icons, while our view-options component correctly implements a standard dropdown trigger with a labeled button. Both approaches follow Radix UI patterns:

  • With asChild: When the trigger is a simple icon button (like in chart.tsx)
  • Without asChild: When the trigger is a fully styled button with text and icon (like in our view-options)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for consistent dropdown trigger implementation across the codebase
rg -l "DropdownMenuTrigger.*asChild" --type tsx

Length of output: 77


Script:

#!/bin/bash
# Check for consistent dropdown trigger implementation across the codebase
# Using ripgrep without file type restriction first to find all instances
rg -l "DropdownMenuTrigger.*asChild"

# Also search for general usage of DropdownMenuTrigger for comparison
rg -l "DropdownMenuTrigger"

Length of output: 1064


Script:

#!/bin/bash
# Let's check the implementation in the one file that uses asChild
rg "DropdownMenuTrigger.*asChild" -A 3 "apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/chart.tsx"

# Also check the implementation in our component under review for comparison
rg "DropdownMenuTrigger" -A 3 "apps/dashboard/components/data-table/view-options.tsx"

Length of output: 1110

apps/dashboard/components/data-table/column-header.tsx (1)

Line range hint 30-42: LGTM! Consistent dropdown implementation with proper sort state handling.

The dropdown trigger implementation correctly wraps the Button component while maintaining the dynamic sort indicator rendering.

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/menu.tsx (1)

Line range hint 32-36: LGTM! Dropdown trigger implementation aligns with PR objectives.

The dropdown trigger correctly wraps the Button component, and the implementation properly supports the filtering functionality mentioned in the PR objectives.

Let's verify the filtering functionality:

✅ Verification successful

Let me also check the menu component implementation:

And let's verify the query state management with nuqs:


LGTM! Filtering functionality is properly implemented in the menu component

The menu component correctly implements the filtering functionality using nuqs query state management:

  • Uses useQueryState hook with proper parsing and default options
  • Implements "Filter for identifier" action that sets the identifier filter through setIdentifier([identifier])
  • Integrates with the broader filtering system as evidenced by the shared query state usage across related components (filter.tsx)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for consistent filter implementation across rate limit logs
rg -A 5 "setIdentifier.*identifier" --type tsx

Length of output: 76


Script:

#!/bin/bash
# Check for filtering implementation in rate limits logs
rg -t ts -t tsx "setIdentifier|identifier.*filter" apps/

Length of output: 86


Script:

#!/bin/bash
# Check the menu component implementation
ast-grep --pattern $'const Menu = () => {
  $$$
}'  apps/dashboard/app/\(app\)/ratelimits/\[namespaceId\]/logs/menu.tsx

Length of output: 117


Script:

#!/bin/bash
# Check query state management
rg -t ts -t tsx "useQueryState" apps/dashboard/app/\(app\)/ratelimits/\[namespaceId\]/logs/

Length of output: 117


Script:

#!/bin/bash
# Let's try without file type specifications
rg "useQueryState|setIdentifier|identifier.*filter" apps/dashboard/app/

# And check the menu component content
cat apps/dashboard/app/\(app\)/ratelimits/\[namespaceId\]/logs/menu.tsx

Length of output: 5595

apps/dashboard/components/dashboard/api-key-table/table.tsx (1)

Line range hint 136-140: LGTM: Dropdown trigger implementation looks correct

The implementation aligns with the PR's objective of fixing dropdown triggers.

apps/dashboard/components/dashboard/root-key-table/table.tsx (1)

136-139: Verify dropdown trigger accessibility

The removal of asChild prop from DropdownMenuTrigger changes how the trigger is rendered in the DOM. While this fixes the dropdown trigger issues, we should verify that it maintains proper accessibility.

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/filter.tsx (1)

Line range hint 89-93: LGTM! Changes align with fixing dropdown triggers

The removal of asChild prop from DropdownMenuTrigger is consistent with the PR's objective, and the filter functionality remains intact with proper state management.

apps/dashboard/components/dashboard/api-key-table/index.tsx (1)

Line range hint 238-242: LGTM! Dropdown trigger changes are consistent

The removal of asChild prop from DropdownMenuTrigger is consistent with the changes in other files, maintaining a uniform approach to fixing dropdown triggers.

apps/dashboard/app/(app)/settings/user/update-user-email.tsx (1)

126-129: LGTM! Improved dropdown trigger implementation.

The direct wrapping of the Button component within DropdownMenuTrigger improves the dropdown's behavior while maintaining proper keyboard accessibility.

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