Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

refactor: optimize date range picker component #3592

Merged
merged 7 commits into from
Feb 7, 2025

Conversation

Innocent-Akim
Copy link
Contributor

@Innocent-Akim Innocent-Akim commented Feb 5, 2025

  • Extract PredefinedRanges into a separate component for better maintainability
  • Implement createRangeHelper factory function to reduce code duplication
  • Add memoization for predefined ranges to prevent unnecessary recalculations
  • Improve type safety with DateRangeGetter type
  • Standardize date comparison using startOfDay
  • Enhance UI with consistent button styling and layout

Performance improvements:

  • Reduce redundant date calculations
  • Prevent unnecessary re-renders with useMemo
  • Centralize date range creation logic

Technical improvements:

  • Better type safety
  • More maintainable code structure
  • Consistent date handling

Description

Please include a summary of the changes and the related issues.

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my code
  • I have commented on my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings

Previous screenshots

Please add here videos or images of the previous status

Current screenshots

Please add here videos or images of the current (new) status

Summary by CodeRabbit

  • Refactor
    • Enhanced the date range picker functionality to provide more accurate day-level selection and improved performance through modularization.
  • Style
    • Refined layout and class styling in the timesheet detail view for a more consistent and cleaner visual presentation.
  • Chores
    • Added "Ipredefine" to the spell-checking dictionary for improved accuracy in text validation.

Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

Walkthrough

This pull request refactors the predefined date range logic in the DateRangePicker component by introducing a new functional component—PredefinedRanges—along with a helper function to streamline range action creation and selection checks. Additionally, cosmetic improvements have been made in the TimesheetDetailModal component, where JSX formatting and class name order have been updated for better readability. A new entry has also been added to the spell check configuration.

Changes

File(s) Summary
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx - Removed inline predefined ranges and replaced them with a new PredefinedRanges component.
- Introduced createRangeHelper for generating range actions and selection checks.
- Utilized React.useMemo and imported startOfDay from date-fns to improve date comparison logic.
- Added new types/interfaces: PredefinedRangeProps and DateRangeGetter.
apps/web/app/[locale]/timesheet/[memberId]/components/TimesheetDetailModal.tsx - Updated JSX formatting by removing extra whitespace and reordering class names for consistency.
- Adjusted component styling without altering the underlying functionality.
.cspell.json - Added the word "Ipredefine" to the spell check configuration.

Sequence Diagram(s)

sequenceDiagram
    participant DRP as DateRangePicker
    participant PR as PredefinedRanges
    participant CH as createRangeHelper
    participant DF as date-fns (startOfDay & isEqual)
    
    DRP->>PR: Pass date range handler & current range
    PR->>CH: Request generation of range actions
    CH->>DF: Compute startOfDay & perform isEqual check
    DF-->>CH: Return computed date comparisons
    CH-->>PR: Provide range actions with selection logic
    PR-->>DRP: Return optimized predefined ranges
Loading

Possibly related PRs

  • [Feat]: Implement dynamic date range picker for timesheet filtering #3213: The changes in the main PR, which involve the restructuring of the DateRangePicker component and the introduction of a new PredefinedRanges component, are related to the modifications in the retrieved PR that implements a dynamic date range picker for filtering timesheet entries, as both involve enhancements to date range selection functionality.
  • [Feat]: Date picker settings init #3586: The changes in the main PR are related to the modifications in the date-range-picker.tsx file, specifically involving the use of the startOfDay function from date-fns, which is also referenced in the retrieved PR.

Suggested labels

WEB, Improvement, Timesheets

Suggested reviewers

  • evereq

Poem

I'm a rabbit hopping through a field of code,
New components bloom, and helper functions are bestowed.
The ranges are now defined with care and light,
Predefined logic sparkling, a delightful sight.
With whitespace tamed and class names in a row,
I celebrate these changes with a joyful, happy glow!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/web/app/[locale]/timesheet/[memberId]/components/TimesheetDetailModal.tsx

Oops! Something went wrong! :(

ESLint: 8.46.0

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/apps/web/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx

Oops! Something went wrong! :(

ESLint: 8.46.0

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/apps/web/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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

🧹 Nitpick comments (1)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (1)

174-257: Update component name to match interface name.

After renaming the interface to PredefinedRangeProps, update the component implementation for consistency.

Apply this diff:

-const PredefinedRanges = ({ handleDateRangeChange, t, dateRange }: IpredefineRange) => {
+const PredefinedRanges = ({ handleDateRangeChange, t, dateRange }: PredefinedRangeProps) => {

Otherwise, the implementation looks good:

  • Proper use of useMemo for performance optimization
  • Consistent button styling
  • Well-structured predefined ranges
🧰 Tools
🪛 GitHub Check: Cspell

[warning] 174-174:
Unknown word (Ipredefine)

🪛 GitHub Actions: Check Spelling and Typos with cspell

[warning] 174-174: Unknown word (Ipredefine)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 796a9b8 and 86b8011.

📒 Files selected for processing (2)
  • apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (3 hunks)
  • apps/web/app/[locale]/timesheet/[memberId]/components/TimesheetDetailModal.tsx (9 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/app/[locale]/timesheet/[memberId]/components/TimesheetDetailModal.tsx
🧰 Additional context used
🪛 GitHub Check: Cspell
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx

[warning] 141-141:
Unknown word (Ipredefine)


[warning] 174-174:
Unknown word (Ipredefine)

🪛 GitHub Actions: Check Spelling and Typos with cspell
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx

[warning] 141-141: Unknown word (Ipredefine)


[warning] 174-174: Unknown word (Ipredefine)


[error] 2 spelling issues found in 1 of the 2 files checked.

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: deploy
🔇 Additional comments (3)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (3)

20-21: LGTM! Import changes support the refactoring goals.

The added imports enhance type safety and date comparison consistency.

Also applies to: 26-26


101-101: LGTM! Good separation of concerns.

Extracting predefined ranges into a separate component improves modularity and maintainability.


149-172: LGTM! Well-structured helper function.

The createRangeHelper function:

  • Reduces code duplication
  • Ensures consistent date comparison
  • Properly handles edge cases

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 (2)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (2)

149-172: Consider memoizing createRangeHelper results.

While the factory pattern effectively reduces code duplication, consider memoizing the results to prevent unnecessary recreations of action and isSelected functions.

 const createRangeHelper = (handleDateRangeChange: (range: DateRange | undefined) => void) => {
-	return (getRange: DateRangeGetter) => {
+	return React.useCallback((getRange: DateRangeGetter) => {
 		const range = getRange();
 		return {
 			action: () => {
@@ -169,6 +169,6 @@
 			}
 		};
-	};
+	}, [handleDateRangeChange]);
 };

174-256: Consider memoizing weekOptions.

The component is well-implemented with good performance optimizations. Consider memoizing weekOptions to prevent unnecessary recreations.

 const PredefinedRanges = ({ handleDateRangeChange, t, dateRange }: PredefinedRangeProps) => {
 	const createRange = createRangeHelper(handleDateRangeChange);
-	const weekOptions = { weekStartsOn: 1 as const };
+	const weekOptions = React.useMemo(() => ({ weekStartsOn: 1 as const }), []);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 86b8011 and 7fa1be2.

📒 Files selected for processing (2)
  • .cspell.json (1 hunks)
  • apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .cspell.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: deploy
🔇 Additional comments (3)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (3)

20-21: LGTM! Import changes enhance date comparison accuracy.

The addition of startOfDay and isEqual from date-fns, along with the TranslationHooks type, improves date comparison precision and type safety.

Also applies to: 26-26


101-101: LGTM! Good separation of concerns.

Extracting predefined ranges into a separate component improves code organization and maintainability.


141-145: Follow TypeScript naming conventions for interfaces.

The interface name PredefinedRangeProps should be used to follow TypeScript naming conventions.

@evereq
Copy link
Member

evereq commented Feb 6, 2025

@Innocent-Akim please resolve merge conflicts

- Extract PredefinedRanges into a separate component for better maintainability
- Implement createRangeHelper factory function to reduce code duplication
- Add memoization for predefined ranges to prevent unnecessary recalculations
- Improve type safety with DateRangeGetter type
- Standardize date comparison using startOfDay
- Enhance UI with consistent button styling and layout

Performance improvements:
- Reduce redundant date calculations
- Prevent unnecessary re-renders with useMemo
- Centralize date range creation logic

Technical improvements:
- Better type safety
- More maintainable code structure
- Consistent date handling
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 (2)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (2)

165-188: Consider memoizing the range object.

While the implementation is correct, the range object could be memoized to prevent unnecessary object creation on each selection check.

 const createRangeHelper = (handleDateRangeChange: (range: DateRange | undefined) => void) => {
 	return (getRange: DateRangeGetter) => {
-		const range = getRange();
+		const range = React.useMemo(() => getRange(), []);
 		return {
 			action: () => {
 				const newRange = {

190-277: Consider moving weekOptions outside the component.

The weekOptions object is static and doesn't need to be recreated on each render. Consider moving it outside the component scope.

+const weekOptions = { weekStartsOn: 1 as const };
+
 const PredefinedRanges = ({ handleDateRangeChange, t, dateRange }: PredefinedRangeProps) => {
-	const weekOptions = { weekStartsOn: 1 as const };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7fa1be2 and 0fc2b38.

📒 Files selected for processing (3)
  • .cspell.json (1 hunks)
  • apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (3 hunks)
  • apps/web/app/[locale]/timesheet/[memberId]/components/TimesheetDetailModal.tsx (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • .cspell.json
  • apps/web/app/[locale]/timesheet/[memberId]/components/TimesheetDetailModal.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: deploy
🔇 Additional comments (2)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/date-range-picker.tsx (2)

129-130: LGTM! Good separation of concerns.

The extraction of predefined ranges into a separate component improves code organization and maintainability.


157-164: LGTM! Good type definitions.

The interface and type definitions enhance type safety and follow TypeScript naming conventions.

@evereq evereq merged commit 59ab502 into develop Feb 7, 2025
12 of 13 checks passed
@evereq evereq deleted the refactor/optimize-date-range-picker branch February 7, 2025 06:36
@Innocent-Akim Innocent-Akim self-assigned this Feb 7, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants