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(dashboard): "No bucket found" message position on Audit Logs page #2413

Merged

Conversation

unrenamed
Copy link
Contributor

@unrenamed unrenamed commented Oct 14, 2024

What does this PR do?

This PR includes several fixes to improve the Audit Logs section of the dashboard:

  • Moves the "bucket not found" placeholder under the Audit Logs filters for better UX.
  • Filters Audit Logs only by active keys and rate limits (deleted and expired options are omitted now)
  • Resolves a hydration error by replacing toLocaleDateString() with date-fns to ensure consistent date formatting between server and client, preventing rendering issues caused by time zone or locale differences.

Fixes #2220

image

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?

  • "Bucket Not Found" placeholder:
    • Go to Audit Logs.
    • Ensure "bucket not found" appears below the filters when no data is present.
  • Filter Audit Logs by active keys/rate limits:
    • Go to Audit Logs.
    • Remember the keys/rate limits filter options.
    • Go to Settings > Root Keys or Ratelimits pages and delete some records.
    • Reload the page (yes, there seems to be another bug related to cached data so this step is required now)
    • Ensure the filter options do NOT show deleted or expired records.
  • Date Formatting Consistency (Hydration Fix):
    • In dev mode, open DevTools, enable console errors and go to Audit Logs page.
    • Reload the page
    • Confirm no hydration errors in the console after page reload.

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

Summary by CodeRabbit

  • New Features
    • Added search functionality in the glossary for easier term lookup.
    • Enhanced display of glossary terms with responsive design for desktop and mobile.
  • Bug Fixes
    • Updated date formatting to consistently display as 'dd/MM/yyyy' for better readability.
  • Refactor
    • Streamlined import statements across various components for improved clarity.
    • Maintained overall structure and logic of components while reorganizing code.

…atting

Replace `toLocaleDateString()` with `date-fns` to ensure consistent date formatting between server and client. This prevents hydration mismatches caused by differing time zones or locale settings, ensuring stable rendering across environments.
Copy link

changeset-bot bot commented Oct 14, 2024

⚠️ No Changeset found

Latest commit: 4d2842a

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 Oct 14, 2024

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

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 28, 2024 0:06am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 28, 2024 0:06am
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 28, 2024 0:06am
workflows ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 28, 2024 0:06am
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 28, 2024 0:06am

Copy link

vercel bot commented Oct 14, 2024

@unrenamed is attempting to deploy a commit to the Unkey Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request implements changes across several components related to the glossary and audit logs. The Row component in the audit logs has been modified to enhance date and time rendering, consolidating the display format. In the database schema, new type exports for SelectAuditLog and SelectAuditLogTarget have been introduced. Additionally, the glossary components have undergone import reorganization and the addition of a search functionality via the FilterableCommand component, improving user interaction while maintaining existing logic and structure.

Changes

File Path Change Summary
apps/dashboard/app/(app)/audit/[bucket]/row.tsx Updated date and time rendering to use toLocaleDateString() for consistent formatting; added suppressHydrationWarning prop.
internal/db/src/schema/audit_logs.ts Introduced type exports SelectAuditLog and SelectAuditLogTarget for improved type safety.
apps/www/app/glossary/[slug]/page.tsx Added FilterableCommand and TermsRolodexDesktop components; reorganized import statements.
apps/www/app/glossary/client.tsx Adjusted import statements for Glossary and allGlossaries; no changes to logic.
apps/www/components/glossary/search.tsx Reordered import statements; no changes to core functionality.
apps/www/components/glossary/terms-rolodex-desktop.tsx Reordered import statements; core logic and functionality unchanged.

Possibly related PRs

Suggested labels

Feature, hacktoberfest

Suggested reviewers

  • mcstepp
  • chronark
  • perkinsjr

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 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 Oct 14, 2024

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

@unrenamed unrenamed changed the title Fix/no bucket msg position on audit logs page fix(dashboard): "No bucket found" message position on Audit Logs page Oct 14, 2024
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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a2797b1 and 853ea2a.

📒 Files selected for processing (2)
  • apps/dashboard/app/(app)/audit/[bucket]/page.tsx (3 hunks)
  • apps/dashboard/app/(app)/audit/[bucket]/row.tsx (2 hunks)
🧰 Additional context used
🔇 Additional comments (5)
apps/dashboard/app/(app)/audit/[bucket]/row.tsx (2)

8-8: LGTM: Good choice of date formatting library.

The addition of the format function from date-fns is a good choice. This library provides consistent date formatting across different environments, which aligns well with the PR objective of resolving hydration errors related to date formatting.


89-92: ⚠️ Potential issue

Consider preserving time information in the display.

The change to use date-fns for formatting resolves the hydration error, which is great. However, the current implementation uses the same format ('dd/MM/yyyy') for both date and time, resulting in a loss of time information.

Consider modifying the time format to include hours and minutes:

- {format(new Date(auditLog.time), 'dd/MM/yyyy')}
+ {format(new Date(auditLog.time), 'dd/MM/yyyy HH:mm')}

This change would preserve the time information while maintaining consistency across server and client rendering.

To ensure this change doesn't conflict with any existing time display logic, let's verify the usage:

✅ Verification successful

Date Formatting Change Verified Successfully

The modification to include time information in the date format ('dd/MM/yyyy HH:mm') in row.tsx does not conflict with other date formatting usages in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other occurrences of date formatting in the codebase

# Test: Search for date formatting patterns
rg --type typescript -e "format\(.*?new Date" -e "toLocaleString" -e "toLocaleDateString" -e "toLocaleTimeString"

Length of output: 144


Script:

#!/bin/bash
# Description: Check for other occurrences of date formatting in TypeScript files

# Test: Search for date formatting patterns in .ts and .tsx files
rg --glob '*.{ts,tsx}' -e "format\(.*?new Date" -e "toLocaleString" -e "toLocaleDateString" -e "toLocaleTimeString"

Length of output: 4492

apps/dashboard/app/(app)/audit/[bucket]/page.tsx (3)

46-46: Filtering out deleted rate limit namespaces

The addition of the where clause correctly filters out deleted rate limit namespaces, ensuring only active namespaces are included in the query.


150-159: Appropriate handling of missing buckets with user-friendly placeholder

The updated rendering logic provides a clear and informative message when a bucket is not found or inaccessible. This improves user experience by allowing users to understand the issue without navigating away from the page.


362-367: Correctly filtering out deleted and expired root keys

The where clause now properly excludes deleted and expired root keys, ensuring that only active keys are presented to the user for filtering.

apps/dashboard/app/(app)/audit/[bucket]/page.tsx Outdated Show resolved Hide resolved
…dability

The mapping logic within the <AuditLogTable> component is complex due to nested structures. Extracting this logic into a separate function or utility enhances readability and maintainability.
@chronark chronark self-assigned this Oct 16, 2024
Revert static datetime formatting using `date-fns` to `toLocaleDateString()` to better suit global users. Suppress the hydration mismatch warnings caused by differences between server and client-side rendered dates.

Co-authored-by: @chronark
PR: unkeyed#2413
@unrenamed
Copy link
Contributor Author

@chronark Just wanted to quickly check in about my recent PRs. I noticed the review activity has slowed down a bit, and I totally understand if there are other priorities right now or personal things that have come up.

I’m just a bit concerned about the upcoming hackathon deadline on October 31 and wanted to make sure the project is still actively participating. If you have time, I’d really appreciate a review before the deadline!

@unrenamed unrenamed requested a review from chronark October 25, 2024 10:03
@chronark chronark enabled auto-merge October 28, 2024 11:00
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 (10)
apps/www/components/glossary/search.tsx (2)

Line range hint 16-20: Consider adding ARIA attributes for better accessibility.

The component could benefit from additional accessibility attributes to improve screen reader support.

Consider adding these ARIA attributes:

 export function FilterableCommand(props: {
   placeholder: string;
   className?: string;
   terms: Array<Glossary>;
 }) {
// Add these props to the Command component
aria-label="Search glossary terms"
aria-expanded={open}
role="combobox"

Line range hint 31-38: Document the blur behavior more clearly.

The current comment explains the blur logic, but it could be more comprehensive to help future maintainers.

Consider expanding the comment:

-      // The `onBlur` event checks if the new focus target (relatedTarget) is within the Command component:
-      // - If it's not (i.e., clicking outside), it closes the list.
-      // - If it is (i.e., selecting an item), it keeps the list open, allowing the `onSelect` to handle the navigation.
+      // Focus management for the command list:
+      // 1. When focus leaves the input field, we check where it's going using `relatedTarget`
+      // 2. If the new focus target is outside the Command component:
+      //    - We close the list as the user is no longer interacting with the component
+      // 3. If the new focus target is inside the Command component:
+      //    - We keep the list open to allow item selection
+      //    - The `onSelect` handler will handle navigation when an item is chosen
+      // This prevents the list from closing prematurely when users try to select items
apps/www/components/glossary/terms-rolodex-desktop.tsx (2)

Line range hint 63-67: Consider enhancing accessibility for navigation buttons.

While the buttons have basic screen reader support, their accessibility could be improved with more descriptive labels.

Consider applying these changes to the scroll buttons:

 <Button
   variant="ghost"
   size="icon"
   onClick={() => handleScroll("up")}
   className={cn("p-0 transition-colors duration-150", {
     "cursor-not-allowed": terms.length <= visibleTerms.length,
   })}
   disabled={terms.length <= visibleTerms.length}
+  aria-label={`Scroll up through glossary terms. ${terms.length <= visibleTerms.length ? 'Disabled when all terms are visible' : ''}`}
 >
   <ChevronUpIcon className="w-4 h-4" />
-  <span className="sr-only">Scroll up</span>
 </Button>

Similar changes should be applied to the "down" button as well.

Also applies to: 89-93


Line range hint 29-39: Consider optimizing the terms wrapping logic.

The current implementation creates multiple copies of the terms array, which could be memory intensive for large lists. Consider using modulo arithmetic instead.

Here's a more efficient implementation:

 const getVisibleTerms = () => {
   const totalVisible = Math.min(7, terms.length);
   const halfVisible = Math.floor(totalVisible / 2);
 
-  const start = currentIndex - halfVisible;
-  const end = currentIndex + halfVisible + 1;
-
-  const wrappedTerms = [...terms, ...terms, ...terms];
-  const centerOffset = terms.length;
-
-  return wrappedTerms.slice(centerOffset + start, centerOffset + end);
+  return Array.from({ length: totalVisible }, (_, i) => {
+    const offset = i - halfVisible;
+    const index = ((currentIndex + offset) % terms.length + terms.length) % terms.length;
+    return terms[index];
+  });
 };

This approach:

  • Eliminates the need for array spreading
  • Uses less memory
  • Maintains the same visual behavior
apps/www/app/glossary/client.tsx (3)

Line range hint 89-95: Consider enhancing A-Z navigation accessibility.

The A-Z navigation bar could benefit from improved accessibility:

  1. Add aria-label to indicate this is an alphabetical navigation
  2. Consider adding keyboard navigation support
 <div className="justify-between flex border-b border-white/10 pb-8 mb-8">
+  <nav aria-label="Alphabetical glossary navigation">
   {alphabet.map((letter) =>
     groupedTerms[letter]?.length > 0 ? (
-      <Link key={letter} href={`#${letter}`} className="rounded hover:underline">
+      <Link
+        key={letter}
+        href={`#${letter}`}
+        className="rounded hover:underline"
+        role="link"
+        aria-label={`Jump to terms starting with ${letter}`}
+      >
         {letter}
       </Link>
     ) : (
-      <span key={letter} className="rounded text-white/30">
+      <span key={letter} className="rounded text-white/30" aria-hidden="true">
         {letter}
       </span>
     ),
   )}
+  </nav>
 </div>

Line range hint 183-201: Remove commented-out code.

The commented-out code at the bottom of the file should be removed as it:

  1. Adds unnecessary noise to the codebase
  2. Can be retrieved from version control if needed
  3. May become outdated and misleading over time

Line range hint 17-26: Consider performance optimizations.

The groupedTerms calculation could be optimized:

  1. Memoize the grouped terms to prevent unnecessary recalculations
  2. Consider moving the grouping logic outside the component
+import { useMemo } from "react";

 export function GlossaryClient() {
   const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
 
-  const groupedTerms = allGlossaries.reduce(
+  const groupedTerms = useMemo(() => allGlossaries.reduce(
     (acc, term) => {
       const firstLetter = term.title[0].toUpperCase();
       if (!acc[firstLetter]) {
         acc[firstLetter] = [];
       }
       acc[firstLetter].push(term);
       return acc;
     },
     {} as Record<string, Array<Glossary>>,
-  );
+  ), []);
apps/www/app/glossary/[slug]/page.tsx (3)

Line range hint 63-65: Consider initializing relatedTerms based on the current term.

The relatedTerms array is currently empty but used in the UI. Consider implementing logic to populate it with terms that share similar categories or tags with the current term.

Would you like me to help implement the related terms logic?


Line range hint 186-209: Replace hardcoded FAQ with dynamic content.

The FAQ section currently contains hardcoded questions about mime types, which may not be relevant for all glossary terms. Consider making the FAQ content dynamic based on the current term's category or topic.

Example approach:

const getFAQForTerm = (term: string, category: string): FAQ[] => {
  // Return relevant FAQs based on term and category
  return term.faqs || defaultFAQs[category] || [];
};

Line range hint 63-267: Consider adding error boundaries for component resilience.

The component handles the notFound() case but could benefit from error boundaries to gracefully handle runtime errors in the UI components.

Example implementation:

import { ErrorBoundary } from '@/components/error-boundary';

// Wrap the main content
<ErrorBoundary fallback={<ErrorFallback />}>
  <div className="prose sm:prose-sm md:prose-md sm:mx-6">
    {/* ... existing content ... */}
  </div>
</ErrorBoundary>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ba0c64a and 88aedd4.

📒 Files selected for processing (5)
  • apps/dashboard/app/(app)/audit/[bucket]/row.tsx (1 hunks)
  • apps/www/app/glossary/[slug]/page.tsx (1 hunks)
  • apps/www/app/glossary/client.tsx (1 hunks)
  • apps/www/components/glossary/search.tsx (2 hunks)
  • apps/www/components/glossary/terms-rolodex-desktop.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/dashboard/app/(app)/audit/[bucket]/row.tsx
🧰 Additional context used
📓 Learnings (1)
apps/www/components/glossary/search.tsx (1)
Learnt from: p6l-richard
PR: unkeyed/unkey#2085
File: apps/www/components/glossary/search.tsx:16-20
Timestamp: 2024-10-23T16:21:47.395Z
Learning: For the `FilterableCommand` component in `apps/www/components/glossary/search.tsx`, refactoring type definitions into an interface is not necessary at this time.
🔇 Additional comments (4)
apps/www/components/glossary/search.tsx (1)

Line range hint 3-14: LGTM! Clean import organization.

The imports are well-organized, following a logical pattern: types first, followed by components and utilities.

apps/www/components/glossary/terms-rolodex-desktop.tsx (1)

3-9: LGTM! Import organization follows a logical pattern.

The imports are now organized in a clear, logical order: types, components, utilities, icons, routing, and hooks.

Let's verify the integration with FilterableCommand as mentioned in the AI summary:

✅ Verification successful

Import organization is correct and components are properly integrated

The import organization in terms-rolodex-desktop.tsx follows a logical pattern, and the component is correctly integrated with FilterableCommand in the glossary page layout. Both components work together in the left sidebar where:

  • FilterableCommand provides the search functionality
  • TermsRolodexDesktop displays the scrollable list of terms below it
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of TermsRolodexDesktop with FilterableCommand
# Expected: Find where these components are used together in the glossary page

# Search for files that import both components
rg -l "TermsRolodexDesktop|FilterableCommand" | sort | uniq -d

# Show the context of how they're used together
ast-grep --pattern 'return (
  $$$
  <$_>
    $$$
    <TermsRolodexDesktop $$$/>
    $$$
    <FilterableCommand $$$/>
    $$$
  </$_>
)'

Length of output: 203


Script:

#!/bin/bash
# Let's try a different approach to verify the integration

# First, find all files that mention TermsRolodexDesktop
echo "=== Files containing TermsRolodexDesktop ==="
rg --type tsx --type jsx "TermsRolodexDesktop"

# Then, find all files that mention FilterableCommand
echo -e "\n=== Files containing FilterableCommand ==="
rg --type tsx --type jsx "FilterableCommand"

# Look for the actual component definition to understand its usage
echo -e "\n=== TermsRolodexDesktop component definition ==="
rg -A 5 "export (default )?function TermsRolodexDesktop" --type tsx

# Check if there are any recent changes related to glossary components
echo -e "\n=== Recent changes in glossary components ==="
fd . "apps/www/components/glossary" -t f -x ls -l {}

Length of output: 1016


Script:

#!/bin/bash
# Let's try without file type flags since tsx isn't recognized

# Search for TermsRolodexDesktop usage
echo "=== Files containing TermsRolodexDesktop ==="
rg "TermsRolodexDesktop"

# Search for FilterableCommand
echo -e "\n=== Files containing FilterableCommand ==="
rg "FilterableCommand"

# Look at the content of the search component which might integrate these
echo -e "\n=== Content of search.tsx ==="
cat "apps/www/components/glossary/search.tsx"

Length of output: 3121


Script:

#!/bin/bash
# Let's look at the glossary page to see how these components are used together

# Check the page where both components are imported
echo "=== Content of glossary/[slug]/page.tsx ==="
cat "apps/www/app/glossary/[slug]/page.tsx"

Length of output: 11903

apps/www/app/glossary/client.tsx (1)

5-5: Import reordering looks good.

Also applies to: 12-12

apps/www/app/glossary/[slug]/page.tsx (1)

4-5: LGTM: Import changes are well-organized.

The new imports for FilterableCommand and TermsRolodexDesktop are properly structured and follow Next.js conventions.

@chronark chronark added this pull request to the merge queue Oct 28, 2024
Merged via the queue into unkeyed:main with commit b652852 Oct 28, 2024
23 of 24 checks passed
Copy link

oss-gg bot commented Oct 28, 2024

Awarding unrenamed: 150 points 🕹️ Well done! Check out your new contribution on oss.gg/unrenamed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[🕹️] Audit Logs filtering by system shows no bucket message
2 participants