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

Disallowing out of date range #9201

Open
wants to merge 12 commits into
base: develop
Choose a base branch
from

Conversation

Rishith25
Copy link
Contributor

@Rishith25 Rishith25 commented Nov 25, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features
    • Enhanced date selection component with improved logic for selecting dates, months, and years.
    • New validation methods ensure selections are within defined minimum and maximum limits.
    • Conditional disabling of selection buttons based on constraints.
    • Improved error handling provides user feedback for out-of-range selections.

@Rishith25 Rishith25 requested a review from a team as a code owner November 25, 2024 11:42
Copy link
Contributor

coderabbitai bot commented Nov 25, 2024

Walkthrough

The changes in this pull request enhance the DateInputV2 component by implementing constraints for date, month, and year selections based on min and max properties. New helper functions validate the selected values, and the component's rendering logic has been updated to disable navigation buttons when selections exceed the defined limits. Additionally, improved error handling provides user feedback for out-of-range selections, ensuring a more robust user experience.

Changes

File Path Change Summary
src/components/Common/DateInputV2.tsx Enhanced logic for date, month, and year selection; added isMonthWithinConstraints and isYearWithinConstraints methods; updated rendering logic to disable buttons based on constraints; improved error handling for out-of-range selections.

Assessment against linked issues

Objective Addressed Explanation
User should not be able to pick a month or year that is out of range (9030)

Possibly related PRs

Suggested labels

urgent, needs review, tested, P1

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐇 In the garden where dates bloom bright,
A rabbit hops with pure delight.
With months and years now in their place,
No more wrong turns in this joyful space!
Constraints in hand, we leap and play,
Selecting the right path, come what may! 🌼


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

netlify bot commented Nov 25, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 8d0073a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/675d929eaa476000085bd3d4
😎 Deploy Preview https://deploy-preview-9201--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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

🧹 Outside diff range and nitpick comments (5)
src/components/Common/DateInputV2.tsx (5)

99-101: Ensure decade navigation respects minimum year constraint

In the "year" view, the condition may prevent users from navigating to the decade containing the minimum year. Users should be able to view and select the minimum year when applicable.

Apply this diff to adjust the logic:

            if (
-              !min || year.getFullYear() - 10 >= min.getFullYear()
+              !min || year.getFullYear() - 10 >= min.getFullYear() ||
+              (year.getFullYear() > min.getFullYear() && year.getFullYear() - 10 < min.getFullYear())
            ) {
              setYear((prev) => dayjs(prev).subtract(10, "year").toDate());
            }

255-268: Provide user-friendly feedback when month selection is out of range

The error message "Cannot select month out of range" might not provide sufficient guidance to the user.

Consider customizing the error message to include the permissible range or suggest valid options.


272-285: Improve error message clarity for year selection

Similar to the month selection, enhancing the error message for out-of-range year selection can improve user experience.

Provide more detailed feedback to the user, possibly indicating the valid year range.


639-644: Simplify nested ternary operators for better readability

The nested ternary operators in the className prop reduce code clarity.

Refactor the class assignment using conditional statements:

let className = "w-1/4 rounded-lg px-2 py-4 text-center text-sm font-semibold";
if (isSelectedMonth(i)) {
  className += " bg-primary-500 text-white cursor-pointer";
} else if (isMonthWithinConstraints(i)) {
  className += " text-secondary-700 hover:bg-secondary-300 cursor-pointer";
} else {
  className += " !text-secondary-400 !cursor-not-allowed";
}

664-675: Improve readability of year selection class assignments

The class assignment for the year selection also uses nested ternary operators that can be simplified.

Apply a similar refactoring as suggested for the month selection to enhance code clarity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fdfc53d and 603eceb.

📒 Files selected for processing (1)
  • src/components/Common/DateInputV2.tsx (7 hunks)
🔇 Additional comments (3)
src/components/Common/DateInputV2.tsx (3)

220-233: Verify edge cases in isMonthWithinConstraints function

The isMonthWithinConstraints function appears to correctly validate months against the min and max constraints. Ensure that it handles edge cases where the month is exactly at the boundary of min or max.

Consider adding unit tests to cover boundary cases, such as selecting the month equal to min.getMonth() or max.getMonth().


235-246: Validate logic in isYearWithinConstraints function

The isYearWithinConstraints function seems to correctly enforce the year constraints. Ensure that it accurately handles years at the boundaries defined by min and max.

Add unit tests to confirm that selecting the years exactly equal to min.getFullYear() and max.getFullYear() is handled as expected.


121-123: ⚠️ Potential issue

Correct year increment logic to respect maximum year

The current condition may allow users to navigate beyond the maximum year. The comparison should ensure that the new year does not exceed the maximum year.

Apply this diff to fix the logic:

            if (
-              !max || year.getFullYear() + 10 >= max.getFullYear()
+              !max || year.getFullYear() + 10 <= max.getFullYear()
            ) {
              setYear((prev) => dayjs(prev).add(10, "year").toDate());
            }

Likely invalid or redundant comment.

src/components/Common/DateInputV2.tsx Show resolved Hide resolved
src/components/Common/DateInputV2.tsx Show resolved Hide resolved
src/components/Common/DateInputV2.tsx Outdated Show resolved Hide resolved
src/components/Common/DateInputV2.tsx Outdated Show resolved Hide resolved
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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 603eceb and 8ade838.

📒 Files selected for processing (1)
  • src/components/Common/DateInputV2.tsx (7 hunks)
🔇 Additional comments (1)
src/components/Common/DateInputV2.tsx (1)

637-642: LGTM: Clear visual feedback for constrained options

The implementation effectively communicates date constraints to users through appropriate styling of disabled options.

Also applies to: 668-673

src/components/Common/DateInputV2.tsx Outdated Show resolved Hide resolved
src/components/Common/DateInputV2.tsx Outdated Show resolved Hide resolved
@Rishith25
Copy link
Contributor Author

@rithviknishad @nihal467 can you please review it.

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

🧹 Outside diff range and nitpick comments (1)
src/components/Common/DateInputV2.tsx (1)

223-248: LGTM! Consider adding JSDoc comments.

The constraint validation functions are well-implemented with proper edge case handling. Consider adding JSDoc comments to document the parameters and return values.

+/**
+ * Checks if the given month is within the min/max date constraints
+ * @param month - The month to check (0-11)
+ * @returns boolean indicating if the month is within constraints
+ */
 const isMonthWithinConstraints = (month: number) => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8ade838 and c7b7f85.

📒 Files selected for processing (1)
  • src/components/Common/DateInputV2.tsx (7 hunks)
🔇 Additional comments (2)
src/components/Common/DateInputV2.tsx (2)

257-289: LGTM! Robust implementation with proper edge case handling.

The implementation correctly:

  1. Validates selections before updating
  2. Adjusts dates for month transitions (e.g., March 31 -> February 28/29)
  3. Provides user feedback for invalid selections

Line range hint 643-679: LGTM! Clean implementation of constraint-based UI states.

The implementation properly handles:

  1. Visual feedback for selected items
  2. Disabled states for out-of-range options
  3. Proper cursor styles for interactive states

src/components/Common/DateInputV2.tsx Show resolved Hide resolved
@Rishith25
Copy link
Contributor Author

@Jacobjeevan I have done the changes and also suggested changes from coderabbitai

@Jacobjeevan
Copy link
Contributor

Something I noticed while testing, month selection to default to the min here (same happened for max as well).

image

@Rishith25
Copy link
Contributor Author

@Jacobjeevan Can you review the changes

@Jacobjeevan
Copy link
Contributor

Jacobjeevan commented Dec 5, 2024

@Jacobjeevan Can you review the changes

@Rishith25

Do the same for year as well. Test around with different parameters for min and max and check for weird behavior before requesting for review.

@Jacobjeevan Jacobjeevan removed their assignment Dec 5, 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

🧹 Outside diff range and nitpick comments (2)
src/components/Common/DateInputV2.tsx (2)

268-270: Consider extracting error messages to constants

For better maintainability and consistency, consider extracting the error messages to constants.

+const ERROR_MESSAGES = {
+  MONTH_OUT_OF_RANGE: "Cannot select month out of range",
+  YEAR_OUT_OF_RANGE: "Cannot select year out of range",
+} as const;

 Notification.Error({
-  msg: outOfLimitsErrorMessage ?? "Cannot select month out of range",
+  msg: outOfLimitsErrorMessage ?? ERROR_MESSAGES.MONTH_OUT_OF_RANGE,
 });

 Notification.Error({
-  msg: outOfLimitsErrorMessage ?? "Cannot select year out of range",
+  msg: outOfLimitsErrorMessage ?? ERROR_MESSAGES.YEAR_OUT_OF_RANGE,
 });

Also applies to: 294-296


437-443: Consider extracting button disable conditions to helper functions

The disable conditions for navigation buttons are complex and repeated. Consider extracting them to helper functions for better readability and maintainability.

+const isDecrementDisabled = (type: DatePickerType) => {
+  switch (type) {
+    case "date":
+      return !isDateWithinConstraints(
+        getLastDay(),
+        datePickerHeaderDate.getMonth() - 1,
+        datePickerHeaderDate.getFullYear(),
+      );
+    case "month":
+      return min && datePickerHeaderDate.getFullYear() <= min.getFullYear();
+    case "year":
+      return min && year.getFullYear() - 1 < min.getFullYear();
+    default:
+      return false;
+  }
+};

+const isIncrementDisabled = (type: DatePickerType) => {
+  switch (type) {
+    case "date":
+      return !isDateWithinConstraints(
+        getLastDay(),
+        datePickerHeaderDate.getMonth(),
+        datePickerHeaderDate.getFullYear(),
+      );
+    case "month":
+      return max && datePickerHeaderDate.getFullYear() >= max.getFullYear();
+    case "year":
+      return max && year.getFullYear() + 1 > max.getFullYear();
+    default:
+      return false;
+  }
+};

-disabled={!isDateWithinConstraints(/*...*/)}
+disabled={isDecrementDisabled("date")}

-disabled={min && datePickerHeaderDate.getFullYear() <= min.getFullYear()}
+disabled={isDecrementDisabled("month")}

-disabled={min && year.getFullYear() - 10 < min.getFullYear()}
+disabled={isDecrementDisabled("year")}

-disabled={!isDateWithinConstraints(/*...*/)}
+disabled={isIncrementDisabled("date")}

-disabled={max && datePickerHeaderDate.getFullYear() >= max.getFullYear()}
+disabled={isIncrementDisabled("month")}

-disabled={max && year.getFullYear() + 10 > max.getFullYear()}
+disabled={isIncrementDisabled("year")}

Also applies to: 457-461, 476-479, 516-522, 536-540, 555-558

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a52b0a2 and 9d3e0d2.

📒 Files selected for processing (1)
  • src/components/Common/DateInputV2.tsx (7 hunks)
🔇 Additional comments (2)
src/components/Common/DateInputV2.tsx (2)

222-247: LGTM! Well-implemented validation functions

The validation functions are well-designed with thorough checks:

  • isMonthWithinConstraints: Properly validates both the first and last day of the month
  • isYearWithinConstraints: Correctly handles year boundaries

651-656: LGTM! Well-structured UI rendering logic

The UI rendering logic for month and year selection is well-implemented:

  • Uses classNames utility effectively for conditional classes
  • Properly handles selected, enabled, and disabled states

Also applies to: 682-687

src/components/Common/DateInputV2.tsx Show resolved Hide resolved
@Rishith25
Copy link
Contributor Author

Hey @Jacobjeevan , I have made changes to the min and max limits. The min and max limits for both year and month are now working fine. I have tested all scenarios, and no unusual behavior has been observed. It is ready for review.

@nihal467
Copy link
Member

nihal467 commented Dec 9, 2024

@Jacobjeevan can you check the PR

@Jacobjeevan Jacobjeevan removed their assignment Dec 10, 2024
@nihal467
Copy link
Member

LGTM

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

Successfully merging this pull request may close these issues.

Disallow picking out of range month or year from month/year selector in date input dropdown
4 participants