Skip to content

feat: keys create wizard#3156

Merged
perkinsjr merged 47 commits intomainfrom
keys-create-menu
Apr 29, 2025
Merged

feat: keys create wizard#3156
perkinsjr merged 47 commits intomainfrom
keys-create-menu

Conversation

@ogzhanolguncu
Copy link
Contributor

@ogzhanolguncu ogzhanolguncu commented Apr 21, 2025

What does this PR do?

This PR adds new key creation multi step dialog, refactors dialog component for better composability and styles Select component with our own colors similar to Input and InputArea.

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
image image image image image image

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive multi-step dialog for API key creation with sections for general settings, rate limits, usage credits, expiration, and metadata.
    • Added form state persistence, advanced validation schemas, and dynamic step validation with visual status indicators.
    • Delivered new UI components including toggles for feature enabling, secret key display with masking, JSON metadata editing, and success confirmation dialogs.
    • Added a reusable navigable dialog system and enhanced dialog container with customizable headers, footers, and close warning behavior.
    • Expanded the icon set with new scalable icons and improved icon sizing support.
  • Improvements

    • Enhanced select and switch components with variant styling, icon support, and dark mode compatibility.
    • Improved dialog and popover components for flexibility, accessibility, and user interaction control.
    • Updated input and textarea components for better dark mode theming using gray alpha color scales.
    • Restricted date-time pickers in logs and related components to disallow future dates.
    • Refined calendar component to support multiple disabled date ranges.
    • Improved alignment and styling of icons in form input descriptions.
  • Bug Fixes

    • Improved validation consistency and state synchronization across all form sections.
  • Chores

    • Removed deprecated key creation pages and components, consolidating functionality into the new dialog.
    • Refactored codebase for modularity, maintainability, and reuse, including reorganizing dialog parts and hooks.
    • Replaced deprecated dialog container implementation with a new centralized component and re-exports for backward compatibility.

@vercel
Copy link

vercel bot commented Apr 21, 2025

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

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 13 resolved Apr 28, 2025 7:12pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
engineering ⬜️ Ignored (Inspect) Visit Preview Apr 28, 2025 7:12pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 21, 2025

📝 Walkthrough

Walkthrough

This change introduces a new modular, multi-step dialog system for creating API keys within the dashboard application. The previous monolithic key creation page and related components are removed and replaced with a dialog-based workflow, leveraging new reusable React components for each configuration section (general, rate limit, credits, expiration, metadata). Validation schemas are refactored and centralized using Zod, and a new form persistence hook is added. The dialog supports step-by-step navigation, persistent form state, granular validation, and displays a success dialog with key details upon creation. Supporting UI components, icons, and utilities are also introduced or updated for consistency and enhanced user experience.

Changes

File(s) Change Summary
apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/credits-setup.tsx, .../expiration-setup.tsx, .../general-setup.tsx, .../key-created-success-dialog.tsx, .../metadata-setup.tsx, .../protection-switch.tsx, .../ratelimit-setup.tsx, .../secret-key.tsx, .../section-label.tsx Introduced new modular, form-driven React components for each key creation section (credits, expiration, general, metadata, rate limit, secret key display, section label, protection switch, and success dialog).
apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/hooks/use-create-key.tsx, .../use-validate-steps.ts Added custom React hooks for API key creation mutation and multi-step dialog validation management.
apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/types.ts Added type definitions for section names and validation states.
apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/create-key.constants.tsx, .../create-key.schema.ts, .../create-key.utils.ts Added constants, Zod validation schemas, and utility functions for the new dialog workflow and form transformation.
apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/index.tsx Added the main CreateKeyDialog component implementing the multi-step dialog UI and workflow.
apps/dashboard/app/(app)/apis/[apiId]/api-id-navbar.tsx Replaced old key creation button with the new dialog-based component and updated badge styling.
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/client.tsx, .../navigation.tsx, .../page.tsx, .../validation.ts Removed the old monolithic key creation page, navigation, and validation schema.
apps/dashboard/components/dialog-container.tsx, .../dialog-container/dialog-container.tsx, .../dialog-container/dialog-parts.tsx, .../dialog-container/navigable-dialog.tsx Refactored dialog container: moved implementation, added new default dialog parts, and introduced a generic navigable dialog system.
apps/dashboard/components/logs/datetime/datetime-popover.tsx Extended the date-time popover to support a custom header for use in expiration setup.
apps/dashboard/components/ui/select.tsx, .../switch.tsx Refactored select and switch UI components to support new styling, variants, and features for the dialog.
apps/dashboard/components/ui/dialog.tsx Enhanced dialog overlay/content to support a "close warning" mode, intercepting close attempts for confirmation dialogs.
apps/dashboard/hooks/use-persisted-form.tsx Added a hook for form state persistence in local, session, or memory storage.
apps/dashboard/lib/trpc/routers/key/create.ts Updated key creation endpoint to use new input schema, support multiple rate limits, and return the key name.
internal/icons/src/icons/arrow-right.tsx, .../calendar-clock.tsx, .../chart-pie.tsx, .../code.tsx, .../eye-slash.tsx, .../eye.tsx, .../key-2.tsx Added new SVG icon components for use in the new dialog UI.
internal/icons/src/icons/check.tsx, .../gauge.tsx, .../xmark.tsx Updated existing icon components to support dynamic sizing.
internal/icons/src/index.ts Exported new and updated icons.
apps/dashboard/lib/trpc/trpc.ts Minor formatting change to error construction (no logic change).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CreateKeyDialog
    participant FormSectionComponent
    participant usePersistedForm
    participant useCreateKey
    participant API

    User->>CreateKeyDialog: Open dialog
    CreateKeyDialog->>usePersistedForm: Initialize/load form state
    loop For each section
        CreateKeyDialog->>FormSectionComponent: Render section UI
        User->>FormSectionComponent: Input data/toggle features
        FormSectionComponent->>usePersistedForm: Update form state
    end
    User->>CreateKeyDialog: Submit form
    CreateKeyDialog->>useCreateKey: Trigger key creation mutation
    useCreateKey->>API: Call createKey endpoint
    API-->>useCreateKey: Return key data
    useCreateKey-->>CreateKeyDialog: onSuccess callback
    CreateKeyDialog->>User: Show success dialog with key details
Loading

Possibly related PRs

Suggested labels

Feature, Dashboard

Suggested reviewers

  • perkinsjr
  • mcstepp
  • chronark
  • MichaelUnkey
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@github-actions
Copy link
Contributor

github-actions bot commented Apr 21, 2025

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

@changeset-bot
Copy link

changeset-bot bot commented Apr 22, 2025

⚠️ No Changeset found

Latest commit: c3690b7

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

@ogzhanolguncu ogzhanolguncu marked this pull request as ready for review April 22, 2025 11:40
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

🧹 Nitpick comments (1)
internal/ui/src/components/date-time/components/calendar.tsx (1)

149-173: Consider memoizing the disabled date matcher function.

The getDisabledMatcher function creates new arrays and objects on each render, which could impact performance if the component re-renders frequently or if there are many disabled date ranges.

-  const getDisabledMatcher = (): Matcher | Matcher[] | undefined => {
+  const getDisabledMatcher = React.useMemo((): Matcher | Matcher[] | undefined => {
     const matchers: Matcher[] = [];
 
     if (minDate) {
       matchers.push({ before: minDate });
     }
 
     if (maxDate) {
       matchers.push({ after: maxDate });
     }
 
     if (disabledDates && disabledDates.length > 0) {
       disabledDates.forEach((dateRange) => {
         if (dateRange.from && dateRange.to) {
           matchers.push({ from: dateRange.from, to: dateRange.to });
         } else if (dateRange.before) {
           matchers.push({ before: dateRange.before });
         } else if (dateRange.after) {
           matchers.push({ after: dateRange.after });
         }
       });
     }
 
     return matchers.length > 0 ? matchers : undefined;
-  };
+  }, [minDate, maxDate, disabledDates]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2032a5a and 594e8a5.

📒 Files selected for processing (13)
  • apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/expiration-setup.tsx (1 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/ratelimit-setup.tsx (1 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/_overview/components/controls/components/logs-datetime/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/apis/_components/controls/components/logs-datetime/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/audit/components/controls/components/logs-datetime/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/logs/components/controls/components/logs-datetime/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/_overview/components/controls/components/logs-datetime/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-datetime/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/ratelimits/_components/controls/components/logs-datetime/index.tsx (1 hunks)
  • apps/dashboard/components/logs/datetime/datetime-popover.tsx (7 hunks)
  • internal/ui/src/components/date-time/components/calendar.tsx (4 hunks)
  • internal/ui/src/components/date-time/date-time.tsx (3 hunks)
  • internal/ui/src/components/form/form-input.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • apps/dashboard/app/(app)/ratelimits/_components/controls/components/logs-datetime/index.tsx
  • internal/ui/src/components/form/form-input.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/ratelimit-setup.tsx
  • apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/expiration-setup.tsx
  • apps/dashboard/components/logs/datetime/datetime-popover.tsx
🧰 Additional context used
🧬 Code Graph Analysis (2)
internal/ui/src/components/date-time/date-time.tsx (1)
internal/ui/src/components/date-time/components/time-split.tsx (1)
  • TimeUnit (10-14)
internal/ui/src/components/date-time/components/calendar.tsx (2)
apps/dashboard/components/ui/calendar.tsx (1)
  • CalendarProps (10-10)
internal/ui/src/components/date-time/date-time.tsx (1)
  • useDateTimeContext (123-123)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Test Go API Local / Test (Shard 8/8)
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Go API Local / Test (Shard 6/8)
  • GitHub Check: Test Go API Local / Test (Shard 5/8)
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Build / Build
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (15)
apps/dashboard/app/(app)/logs/components/controls/components/logs-datetime/index.tsx (1)

31-31: Good addition of date validation constraint

Adding maxDate={new Date()} improves the user experience by preventing users from selecting future dates for logs, which wouldn't contain any data. This is a sensible constraint that aligns with the data availability.

apps/dashboard/app/(app)/apis/[apiId]/_overview/components/controls/components/logs-datetime/index.tsx (1)

32-32: Good addition of date validation constraint

Adding maxDate={new Date()} appropriately restricts date selection to past and current dates, which is consistent with the available log data. This prevents users from selecting invalid future dates.

apps/dashboard/app/(app)/audit/components/controls/components/logs-datetime/index.tsx (1)

31-31: Good addition of date validation constraint

Adding maxDate={new Date()} is a good user experience improvement that prevents users from selecting future dates in the audit logs, where no data would exist.

apps/dashboard/app/(app)/ratelimits/[namespaceId]/_overview/components/controls/components/logs-datetime/index.tsx (1)

31-31: Good addition of date validation constraint

Adding maxDate={new Date()} ensures users can only select dates up to the current time, which is appropriate for rate limit logs since future data doesn't exist yet.

apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/components/controls/components/logs-datetime/index.tsx (1)

31-31: Good addition of date constraint.

Adding the maxDate prop limits date selection to the current date and earlier, which is a logical constraint for log viewing.

apps/dashboard/app/(app)/apis/_components/controls/components/logs-datetime/index.tsx (1)

31-31: Good addition of date constraint.

Adding the maxDate prop limits date selection to the current date and earlier, which is a logical constraint for log viewing.

internal/ui/src/components/date-time/date-time.tsx (4)

3-4: Linter comment update looks good.

The updated comment format is appropriate.


11-12: Good rename for better semantic clarity.

Renaming from minDateRange/maxDateRange to minDate/maxDate improves naming clarity, as these represent individual date constraints rather than ranges.


48-55: API update for DateTime component looks good.

The function signature now properly includes the new props, maintaining consistency with the interface changes.


102-104: Context value updated correctly.

The context provider value properly uses the renamed props.

internal/ui/src/components/date-time/components/calendar.tsx (5)

6-12: Improved import statement structure.

The named imports provide better clarity and the addition of the Matcher type is necessary for the new disabled date functionality.


76-76: Improved styling for disabled days.

The styling specification makes disabled days more visually distinct while maintaining consistency with the overall design language.


85-91: Good enhancement with flexible date disabling API.

The new disabledDates array allows for specifying multiple date ranges or boundaries to be disabled, which significantly improves the component's flexibility.


101-101: Correct context usage with renamed props.

The destructuring now properly uses the renamed minDate and maxDate props from context.


185-185: Good implementation of disabled date handling.

Using the aggregated matcher from the new function ensures all date constraints are properly applied.

Copy link
Contributor Author

We are ready for round 2

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: 2

🧹 Nitpick comments (5)
apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/expiration-setup.tsx (5)

72-72: Inconsistent comments about minimum time constraint

There's a discrepancy between the comment on line 96 which says "at least 2 minutes in the future" and the actual implementation on line 72 which sets minValidDate to 10 minutes from now.

- // Check if the date is valid (at least 2 minutes in the future)
+ // Check if the date is valid (at least 10 minutes in the future)

Also applies to: 96-96


95-102: Improve user feedback for invalid date selections

When a user selects a date too close to the current time, the code silently adjusts it to the minimum valid date without notifying the user. This could be confusing.

Consider adding explicit user feedback when dates are auto-adjusted:

if (newDate < minValidDate) {
  // If date is too soon, set it to minimum valid date
  setValue("expiration.data", minValidDate);
+ // You could add a toast notification here:
+ // toast.info("Expiration date must be at least 10 minutes in the future. Adjusted automatically.");
} else {
  setValue("expiration.data", newDate);
}

50-50: Ensure selected title synchronization

The component initializes selectedTitle to "1 day", but doesn't update it when the form initializes with a different value. This could cause UI inconsistency.

Consider synchronizing the initial title with the actual form value:

- const [selectedTitle, setSelectedTitle] = useState<string>("1 day");
+ const [selectedTitle, setSelectedTitle] = useState<string>(
+   currentExpiryDate ? 
+     (EXPIRATION_OPTIONS.find(opt => {
+       if (opt.value === undefined) return false; // Skip custom option
+       const now = new Date();
+       let optionDate = new Date();
+       switch (opt.value) {
+         case "1d": optionDate = addDays(now, 1); break;
+         case "7d": optionDate = addDays(now, 7); break;
+         case "30d": optionDate = addDays(now, 30); break;
+       }
+       return Math.abs(optionDate.getTime() - currentExpiryDate.getTime()) < 60000; // Within a minute
+     })?.display || "Custom") 
+     : "1 day"
+ );

Also applies to: 153-153


133-133: Clarify timezone handling in UI

The description mentions UTC, but there's no explicit timezone handling in the code. This could lead to confusion for users in different timezones.

Consider making the timezone handling more explicit in both the code and UI. For example:

- return "The key will be automatically disabled at the specified date and time (UTC).";
+ return "The key will be automatically disabled at the specified date and time in UTC timezone.";

You could also consider showing both local and UTC time to prevent confusion.


152-159: Consider adding error handling for date selection

The DatetimePopover component doesn't have explicit error handling if something goes wrong during date selection.

Consider adding error handling for the DatetimePopover:

<DatetimePopover
  initialTitle={selectedTitle}
  initialTimeValues={getInitialTimeValues()}
  onSuggestionChange={setSelectedTitle}
  onDateTimeChange={handleDateTimeChange}
+ onError={(error) => {
+   console.error("Error in date selection:", error);
+   // Optionally show error to user
+ }}
  customOptions={EXPIRATION_OPTIONS}
  customHeader={<ExpirationHeader />}
  singleDateMode
  minDate={minValidDate} // Set minimum date to 2 minutes from now
>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f91fe79 and c3690b7.

📒 Files selected for processing (1)
  • apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/expiration-setup.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Test Go API Local / Test (Shard 8/8)
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Go API Local / Test (Shard 6/8)
  • GitHub Check: Test Go API Local / Test (Shard 5/8)
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Build / Build
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/expiration-setup.tsx (2)

11-40: LGTM! Well-structured expiration options

The expiration options are well-defined with clear labels and descriptions.


42-61: Good use of react-hook-form and form state management

The component correctly uses react-hook-form hooks and properly manages form state. The toggle switch implementation is clean and handles state changes appropriately.

Also applies to: 136-145

Comment on lines +125 to +134
const isExpiringVerySoon =
currentExpiryDate &&
new Date(currentExpiryDate).getTime() - new Date().getTime() < 60 * 60 * 1000;

const getExpiryDescription = () => {
if (isExpiringVerySoon) {
return "This key will expire very soon (less than 1 hour). Consider setting a longer expiration time.";
}
return "The key will be automatically disabled at the specified date and time (UTC).";
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix expiration warning when expiration is disabled

Per PR comments, an expiration warning appears even when the date field is disabled. This is because isExpiringVerySoon can be true even when expirationEnabled is false.

// Calculate date for showing warning about close expiry (less than 1 hour)
const isExpiringVerySoon =
- currentExpiryDate &&
+ expirationEnabled && currentExpiryDate &&
  new Date(currentExpiryDate).getTime() - new Date().getTime() < 60 * 60 * 1000;

const getExpiryDescription = () => {
  if (isExpiringVerySoon) {
    return "This key will expire very soon (less than 1 hour). Consider setting a longer expiration time.";
  }
  return "The key will be automatically disabled at the specified date and time (UTC).";
};
📝 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 isExpiringVerySoon =
currentExpiryDate &&
new Date(currentExpiryDate).getTime() - new Date().getTime() < 60 * 60 * 1000;
const getExpiryDescription = () => {
if (isExpiringVerySoon) {
return "This key will expire very soon (less than 1 hour). Consider setting a longer expiration time.";
}
return "The key will be automatically disabled at the specified date and time (UTC).";
};
const isExpiringVerySoon =
expirationEnabled && currentExpiryDate &&
new Date(currentExpiryDate).getTime() - new Date().getTime() < 60 * 60 * 1000;
const getExpiryDescription = () => {
if (isExpiringVerySoon) {
return "This key will expire very soon (less than 1 hour). Consider setting a longer expiration time.";
}
return "The key will be automatically disabled at the specified date and time (UTC).";
};

Comment on lines +147 to +173
<Controller
control={control}
name="expiration.data"
render={({ field }) => (
<DatetimePopover
initialTitle={selectedTitle}
initialTimeValues={getInitialTimeValues()}
onSuggestionChange={setSelectedTitle}
onDateTimeChange={handleDateTimeChange}
customOptions={EXPIRATION_OPTIONS}
customHeader={<ExpirationHeader />}
singleDateMode
minDate={minValidDate} // Set minimum date to 2 minutes from now
>
<FormInput
label="Expiry Date"
description={getExpiryDescription()}
readOnly
disabled={!expirationEnabled}
value={formatExpiryDate(field.value)}
className="cursor-pointer w-full"
variant={expirationEnabled && isExpiringVerySoon ? "warning" : undefined}
error={errors.expiration?.data?.message}
/>
</DatetimePopover>
)}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Validate and clear form errors correctly

Per PR comments, the date field is automatically marked as invalid and selecting a valid date doesn't clear the validation error. This may be related to how form validation is handled.

Check if the form validation is properly updated when dates change. Consider logging the validation in the handleDateTimeChange function:


🏁 Script executed:

#!/bin/bash
# Search for form validation schema for expiration
rg -A 10 -B 10 "expiration.*schema|schema.*expiration" --glob="*.{ts,tsx}"

Length of output: 76


🏁 Script executed:

#!/bin/bash
# Locate where handleDateTimeChange is defined/used
rg -n "handleDateTimeChange" -A 5 -B 5 --glob="*.{ts,tsx}"

# Check if clearErrors is ever called in relation to expiration
rg -n "clearErrors" -A 5 -B 5 --glob="*.{ts,tsx}"

Length of output: 6363


🏁 Script executed:

#!/bin/bash
# Inspect handleDateTimeChange implementation in expiration-setup.tsx and related form methods
file="apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/expiration-setup.tsx"

# Show the function body
rg -n -A30 -B0 "const handleDateTimeChange" -- "$file"

# Check how the form state is updated
rg -n "setValue" -- "$file"

# Verify if errors are cleared or set
rg -n "clearErrors" -- "$file"
rg -n "setError" -- "$file"

Length of output: 1890


Clear or re-validate the expiry field when the date changes

The handleDateTimeChange helper updates expiration.data via setValue but never clears or re-validates the field, so any prior validation error remains. To fix this, update the logic in expiration-setup.tsx as follows:

• Destructure and call clearErrors("expiration.data") inside handleDateTimeChange immediately after you call setValue for a valid date.
• Alternatively, invoke setValue("expiration.data", newDate, { shouldValidate: true }) to re-trigger validation and clear errors automatically.
• You can also leverage the Controller’s field.onChange callback instead of setValue directly, so React Hook Form runs its built-in validation flow.

Locations to update:

  • apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/components/expiration-setup.tsx
    handleDateTimeChange (lines 75–103)

Copy link
Member

@perkinsjr perkinsjr left a comment

Choose a reason for hiding this comment

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

Approved. Let's merge on Tuesday

Copy link
Contributor Author

I'll let you merge tomorrow. I'll rebase my other PR from this one 🫡

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