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: Datetimepicker typecheck #244

Merged
merged 1 commit into from
Dec 2, 2024
Merged

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Dec 2, 2024

Summary by CodeRabbit

  • New Features

    • Improved error handling for date selection across multiple components, ensuring valid dates are used.
  • Bug Fixes

    • Enhanced robustness in the RolloutAndTiming, DateConditionRender, and DateTimePicker components to prevent null values from causing issues.
  • Chores

    • Cleaned up code by removing unnecessary comments related to ESLint rules.

Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing error handling for date selection across multiple components. The RolloutAndTiming, DateConditionRender, JobHistoryChart, and DateTimePicker components have been updated to include conditional checks that prevent null values from being processed. These modifications ensure that valid dates are always used, thereby improving the robustness of the date handling logic without altering the overall structure or functionality of the components involved.

Changes

File Change Summary
apps/webservice/src/app/[workspaceSlug]/(app)/_components/environment-policy-drawer/RolloutAndTiming.tsx Updated startTime and endTime handling to include null checks, defaulting to the current date if necessary.
apps/webservice/src/app/[workspaceSlug]/(app)/_components/filter/DateConditionRender.tsx Wrapped setDate in an arrow function with a null check before invocation.
apps/webservice/src/app/[workspaceSlug]/(app)/systems/JobHistoryChart.tsx Cast event parameter e to any in onClick handler to access the date property correctly.
packages/ui/src/date-time-picker/date-time-picker.tsx Modified onChange handler of TimeField to include a null check before setting the time value. Removed an ESLint rule comment.

Possibly related PRs

Suggested reviewers

  • jsbroks

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.

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

@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

🧹 Outside diff range and nitpick comments (4)
apps/webservice/src/app/[workspaceSlug]/(app)/systems/JobHistoryChart.tsx (1)

275-275: Type assertion is acceptable but needs documentation.

The any type assertion is a valid workaround for accessing the date property from Recharts' click event. However, to maintain code clarity:

  1. Add a comment explaining why this type assertion is necessary
  2. Consider creating proper type definitions for the event object
-                  const start = new Date((e as any).date);
+                  // TODO: Create proper type definitions for Recharts' click event
+                  // Using 'any' assertion as Recharts doesn't provide correct typings for the click event
+                  const start = new Date((e as any).date);
apps/webservice/src/app/[workspaceSlug]/(app)/_components/environment-policy-drawer/RolloutAndTiming.tsx (1)

Line range hint 151-173: Add validation for time range consistency

The current implementation doesn't validate that startTime is before endTime. Consider adding validation to ensure valid release windows.

You could:

  1. Add validation in the form schema:
const schema = z.object({
  releaseWindows: z.array(
    z.object({
      // ... existing fields ...
      startTime: z.date(),
      endTime: z.date(),
    }).refine(
      (data) => data.startTime < data.endTime,
      "End time must be after start time"
    ),
  ),
  // ... rest of the schema
});
  1. Or handle it in the onChange handlers to provide immediate feedback.
apps/webservice/src/app/[workspaceSlug]/(app)/_components/filter/DateConditionRender.tsx (2)

85-85: LGTM! Consider additional error handling.

The null check is good, but consider adding error handling for invalid date strings in the value prop.

Consider wrapping the date conversion in a try-catch:

<DateTimePicker
-  value={toZonedDateTime(new Date(value))}
+  value={(() => {
+    try {
+      return toZonedDateTime(new Date(value));
+    } catch (e) {
+      console.error('Invalid date string:', value);
+      return toZonedDateTime(new Date());
+    }
+  })()}
  onChange={(value) => value != null && setDate(value)}
  aria-label={type}
  variant="filter"
/>

Line range hint 14-41: Consider improving the robustness of toZonedDateTime utility.

The utility function could benefit from additional error handling and validation:

  1. Input validation for the Date object
  2. Fallback for unavailable timezone
  3. Simpler offset calculation

Consider this improved implementation:

const toZonedDateTime = (date: Date): ZonedDateTime => {
+  if (!(date instanceof Date) || isNaN(date.getTime())) {
+    throw new Error('Invalid Date object');
+  }

-  const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+  const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
-  const offset = -date.getTimezoneOffset() * ms("1m");
+  const offset = -date.getTimezoneOffset() * 60000; // Direct calculation in milliseconds

  // ... rest of the function
};
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8c72cc0 and da4635f.

📒 Files selected for processing (4)
  • apps/webservice/src/app/[workspaceSlug]/(app)/_components/environment-policy-drawer/RolloutAndTiming.tsx (2 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(app)/_components/filter/DateConditionRender.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(app)/systems/JobHistoryChart.tsx (1 hunks)
  • packages/ui/src/date-time-picker/date-time-picker.tsx (1 hunks)
🔇 Additional comments (1)
packages/ui/src/date-time-picker/date-time-picker.tsx (1)

73-73: LGTM! Type guard improves runtime safety.

The added null check is a good defensive programming practice that prevents potential runtime issues.

Let's verify if this null check is necessary by checking React Aria's TimeField documentation and implementation:

✅ Verification successful

The null check is necessary and correct

The null check is justified because:

  1. The TimeField component uses React Aria's useTimeField hook which works with the TimeValue type from react-aria
  2. The DateTimePicker's state management is handled by useDatePickerState from react-stately, where timeValue and setTimeValue are part of the state
  3. The type guard ensures type safety between these two different state management systems
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for TimeField implementation details and null value handling
rg -A 5 "TimeField.*onChange.*null" --type ts

Length of output: 47


Script:

#!/bin/bash
# Let's check the TimeField usage and implementation in the codebase
ast-grep --pattern 'TimeField'

# Also check the imports to understand which TimeField we're using
rg "import.*TimeField" --type ts

Length of output: 839


Script:

#!/bin/bash
# Let's examine the time-field.tsx implementation to understand the value handling
cat packages/ui/src/date-time-picker/time-field.tsx

Length of output: 1314


Script:

#!/bin/bash
# Let's check the DateTimePicker implementation to understand the full context
cat packages/ui/src/date-time-picker/date-time-picker.tsx

Length of output: 2704

Comment on lines +151 to +157
startTime:
t != null
? t.toDate(
Intl.DateTimeFormat().resolvedOptions()
.timeZone,
)
: new Date(),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reconsider the default fallback for null dates

While the null check is good, defaulting to the current date when t is null might mask errors or create unexpected behavior. Consider either:

  1. Preserving the existing date value instead of defaulting to current date
  2. Implementing proper form validation to handle null dates
-                                startTime:
-                                  t != null
-                                    ? t.toDate(
-                                        Intl.DateTimeFormat().resolvedOptions()
-                                          .timeZone,
-                                      )
-                                    : new Date(),
+                                startTime: t?.toDate(
+                                  Intl.DateTimeFormat().resolvedOptions()
+                                    .timeZone,
+                                ) ?? value.startTime,
📝 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
startTime:
t != null
? t.toDate(
Intl.DateTimeFormat().resolvedOptions()
.timeZone,
)
: new Date(),
startTime: t?.toDate(
Intl.DateTimeFormat().resolvedOptions()
.timeZone,
) ?? value.startTime,

Comment on lines +167 to +173
endTime:
t != null
? t.toDate(
Intl.DateTimeFormat().resolvedOptions()
.timeZone,
)
: new Date(),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Apply consistent handling for endTime

Apply the same improvement as suggested for startTime to maintain consistency.

-                                endTime:
-                                  t != null
-                                    ? t.toDate(
-                                        Intl.DateTimeFormat().resolvedOptions()
-                                          .timeZone,
-                                      )
-                                    : new Date(),
+                                endTime: t?.toDate(
+                                  Intl.DateTimeFormat().resolvedOptions()
+                                    .timeZone,
+                                ) ?? value.endTime,
📝 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
endTime:
t != null
? t.toDate(
Intl.DateTimeFormat().resolvedOptions()
.timeZone,
)
: new Date(),
endTime: t?.toDate(
Intl.DateTimeFormat().resolvedOptions()
.timeZone,
) ?? value.endTime,

@adityachoudhari26 adityachoudhari26 merged commit d9d948e into main Dec 2, 2024
7 of 8 checks passed
@adityachoudhari26 adityachoudhari26 deleted the datetimepicker-typecheck branch December 2, 2024 18:29
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