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

Development: Use signals in date time picker #9694

Merged
merged 13 commits into from
Nov 9, 2024

Conversation

florian-glombik
Copy link
Contributor

@florian-glombik florian-glombik commented Nov 6, 2024

Checklist

General

Client

  • I strictly followed the client coding and design guidelines.
  • I added multiple integration tests (Jest) related to the features (with a high test coverage), while following the test guidelines.
  • I documented the TypeScript code using JSDoc style.
  • I added multiple screenshots/screencasts of my UI changes.

Motivation and Context

This PR introduces signals, and fixes code smells in components used for editing and updating lectures. This is a preparation for Lectures: Add status bar to lecture creation and edit mode #9655 and aims to keep #9655 at a manageable size of changes.

Description

  • Fixed code smells
  • Introduced signals in date-time-picker.component.ts (and thereby removed method calls in the template)

Steps for Testing

Prerequisites:

  • 1 Instructor

THIS PR DOES NOT HAVE CODE REVIEWS YET, YOU MIGHT WANT TO WAIT WITH MANUAL TESTS UNTIL THE CODE REVIEWS ARE PRESENT

  1. Navigate to the Instructor lecture view (creating and editing)
  2. Create and edit a lecture, verify that the datepickers work the same as on develop
  3. Create an exam and verify the datepickers work the same as on develop
  4. Create an exercise (of one type, not all exercise types) (except for programming) and verify the datepickers work the same as on develop
  5. If you know where one of the components below is in the UI, verify that the datepickeres works the same as on develop (take one component if possible with reasonable effort, you are not expected to test the whole list)

Please add your review comment on which component you have tested so other test reviews can consider it, and we can test different parts of the application.

  • the datepicker is used throughout the following components
    • system-notification-management-update.component.html
    • common-course-competency-form.component.html
    • course-update.component.html
    • exam-update.component.html
    • file-upload-exercise-update.component.html
    • modeling-exercise-update.component.html
    • programming-assessment-repo-export-dialog.component.html
    • quiz-exercise-update.component.html
    • quiz-re-evaluate.component.html
    • participation.component.html
    • submission-export-dialog.component.html
    • text-exercise-update.component.html
    • lecture-attachments.component.html
    • attachment-unit-form.component.html
    • attachment-units.component.html
    • online-unit-form.component.html
    • text-unit-form.component.html
    • video-unit-form.component.html
    • lecture-update.component.html
    • lecture-wizard-period.component.html
    • build-queue.component.html
    • vcs-access-token-settings.component.html

This is a refactoring PR that does not add functionality, so the behavior should not change in comparison to the develop branch.

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Performance Review

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Screenshots

UseSignalsInDateTimerPicker-9694

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced date-time picker component with improved reactivity and dynamic updates.
    • Introduced new signals and computed properties for better state management.
  • Bug Fixes

    • Updated validation logic for input fields to ensure accurate feedback on validity.
    • Improved test coverage by validating date calculations against expected outcomes.
    • Added tests for clearing the datepicker value to ensure proper functionality.

@florian-glombik florian-glombik requested a review from a team as a code owner November 6, 2024 20:49
@florian-glombik florian-glombik self-assigned this Nov 6, 2024
@github-actions github-actions bot added the client Pull requests that update TypeScript code. (Added Automatically!) label Nov 6, 2024
Copy link

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes in this pull request focus on enhancing the FormDateTimePickerComponent by transitioning from traditional property declarations to reactive properties using Angular's input and output functions. This includes modifying various properties to be reactive and introducing signals and computed properties for improved reactivity. The associated HTML template is updated to call these properties as functions, affecting the control flow and validation logic. Overall, the modifications aim to improve the component's responsiveness and maintainability through modern Angular practices.

Changes

File Change Summary
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html Updated expressions to use function calls for properties like labelName, disabled, and isValid. Adjusted logic for invalid feedback message and bindings for ngClass and ng-invalid.
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts Transitioned properties to reactive inputs and outputs using input<T>() and output<T>(). Introduced signals isInputValid and dateInputValue, and a computed property isValid. Updated methods to call updateSignals for state management.
src/test/javascript/spec/component/shared/date-time-picker.component.spec.ts Modified tests to use calculated values for properties min, max, and startAt. Updated assertions to validate computed dates from methods instead of static assignments.

Possibly related PRs

  • Development: Use signals in lecture online and text unit #9658: The changes in this PR involve the introduction of signals in components, similar to the main PR's focus on converting properties to function calls and enhancing reactivity in the date-time-picker component. Both PRs aim to improve the responsiveness and maintainability of Angular components.

Suggested labels

ready for review

Suggested reviewers

  • JohannesWt
  • SimonEntholzer
  • az108
  • BBesrour

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 or @coderabbitai title 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

@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 (4)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html (2)

22-23: Consider consolidating validation classes

There appears to be redundant validation styling with both:

[ngClass]="{ 'is-invalid': isValid() }"
[class.ng-invalid]="!isValid()"

Consider using just one approach for validation styling to improve maintainability.


43-44: Consider extracting the validation condition to a computed signal

While the implementation is correct, the condition dateInput.invalid || (requiredField() && !dateInput.value) could be moved to a computed signal in the component for better readability and reusability.

Example:

readonly showValidationError = computed(() => {
  return this.dateInput?.invalid || (this.requiredField() && !this.dateInput?.value);
});

Then in template:

@if (showValidationError()) {
  <div class="invalid-feedback">...</div>
}
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (2)

29-29: Consistent use of signal-based input() and specify precise type for value property

For consistency with other input properties and improved type safety, consider converting the value input to use the input<T>() function with a more specific type.

Apply this diff to align value with the other signal-based inputs:

-    @Input() value: any;
+    value = input<dayjs.Dayjs | Date | undefined>();

49-49: Remove redundant Boolean call in updateSignals() method

The explicit use of Boolean is unnecessary, as the value will already be coerced to a boolean.

Apply this diff to simplify the expression:

-    this.isInputValid.set(!Boolean(this.dateInput?.invalid));
+    this.isInputValid.set(!this.dateInput?.invalid);
🧰 Tools
🪛 Biome

[error] 49-49: Avoid redundant Boolean call

It is not necessary to use Boolean call when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant Boolean call

(lint/complexity/noExtraBooleanCast)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fdc2501 and 9b954b2.

📒 Files selected for processing (2)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html (3 hunks)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html (1)

Pattern src/main/webapp/**/*.html: @if and @for are new and valid Angular syntax replacing *ngIf and *ngFor. They should always be used over the old style.

src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

🪛 Biome
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts

[error] 49-49: Avoid redundant Boolean call

It is not necessary to use Boolean call when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant Boolean call

(lint/complexity/noExtraBooleanCast)

🔇 Additional comments (5)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html (5)

1-10: LGTM! Proper usage of @if and signal functions

The changes correctly implement the new @if syntax and properly call the signal functions for labelName() and labelTooltip().


Line range hint 11-17: LGTM! Correct implementation of timezone warning

The timezone warning section properly implements @if with the signal function and maintains correct translation usage.


25-27: LGTM! Proper implementation of signal functions

The disabled, min, and max bindings correctly use their respective signal functions.


41-41: LGTM! Correct usage of startDate signal

The startDate() function call is properly implemented.


Line range hint 46-51: LGTM! Proper warning implementation

The warning section correctly uses @if with the signal function and maintains proper translation usage.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 6, 2024
Copy link

@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 (2)
src/test/javascript/spec/component/shared/date-time-picker.component.spec.ts (2)

105-107: Consider testing edge cases for input signals.

While the happy path is covered, consider adding test cases for:

  • Invalid date inputs
  • Undefined inputs
  • Null inputs

Example test cases to add:

it('should handle invalid date inputs', () => {
    fixture.componentRef.setInput('min', dayjs('invalid'));
    expect(component.minDate()).toBeNull();
});

it('should handle undefined inputs', () => {
    fixture.componentRef.setInput('min', undefined);
    expect(component.minDate()).toBeNull();
});

100-114: Improve test organization and readability.

The current test structure in the "should have working getters" block is testing multiple behaviors in a single test. Consider splitting it into separate, focused test cases.

Example refactor:

describe('date signals', () => {
    it('should handle minDate signal', () => {
        const expectedMinDate = normalDate.subtract(2, 'day');
        fixture.componentRef.setInput('min', expectedMinDate);
        expect(dayjs(component.minDate()).toEqual(expectedMinDate)).toBeTrue();
    });

    it('should handle maxDate signal', () => {
        const expectedMaxDate = normalDate.add(2, 'day');
        fixture.componentRef.setInput('max', expectedMaxDate);
        expect(dayjs(component.maxDate()).toEqual(expectedMaxDate)).toBeTrue();
    });

    it('should handle startDate signal', () => {
        const expectedStartDate = normalDate.add(1, 'day');
        fixture.componentRef.setInput('startAt', expectedStartDate);
        expect(dayjs(component.startDate()).toEqual(expectedStartDate)).toBeTrue();
    });
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9b954b2 and afed090.

📒 Files selected for processing (1)
  • src/test/javascript/spec/component/shared/date-time-picker.component.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/test/javascript/spec/component/shared/date-time-picker.component.spec.ts (1)

Pattern src/test/javascript/spec/**/*.ts: jest: true; mock: NgMocks; bad_practices: avoid_full_module_import; perf_improvements: mock_irrelevant_deps; service_testing: mock_http_for_logic; no_schema: avoid_NO_ERRORS_SCHEMA; expectation_specificity: true; solutions: {boolean: toBeTrue/False, reference: toBe, existence: toBeNull/NotNull, undefined: toBeUndefined, class_obj: toContainEntries/toEqual, spy_calls: {not_called: not.toHaveBeenCalled, once: toHaveBeenCalledOnce, with_value: toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith}}

🔇 Additional comments (2)
src/test/javascript/spec/component/shared/date-time-picker.component.spec.ts (2)

101-104: LGTM: Clear and descriptive test setup.

The test setup uses meaningful variable names and clear date manipulations.


111-113: 🛠️ Refactor suggestion

Align assertions with coding guidelines.

The assertions should use more specific matchers according to the coding guidelines.

Consider this refactor:

-expect(dayjs(component.minDate())).toEqual(expectedMinDate);
-expect(dayjs(component.maxDate())).toEqual(expectedMaxDate);
-expect(dayjs(component.startDate())).toEqual(expectedStartDate);
+expect(dayjs(component.minDate()).toEqual(expectedMinDate)).toBeTrue();
+expect(dayjs(component.maxDate()).toEqual(expectedMaxDate)).toBeTrue();
+expect(dayjs(component.startDate()).toEqual(expectedStartDate)).toBeTrue();

Likely invalid or redundant comment.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 6, 2024
Copy link

@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 (3)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (3)

43-46: Simplify the isValid computed logic.

The current implementation can be made more readable by breaking down the conditions.

-    isValid = computed(() => {
-        const isInvalid = this.error() || !this.isInputValid() || (this.requiredField() && !this.dateInputValue()) || this.warning();
-        return !isInvalid;
-    });
+    isValid = computed(() => {
+        if (this.error() || this.warning()) {
+            return false;
+        }
+        if (this.requiredField() && !this.dateInputValue()) {
+            return false;
+        }
+        return this.isInputValid();
+    });

40-41: Consider adding type safety to dateInputValue signal.

The dateInputValue signal should explicitly declare its type to prevent potential type-related issues.

-    protected dateInputValue = signal<string>('');
+    protected dateInputValue = signal<string | null>('');

109-119: Consider memoizing date conversion results.

The computed properties for dates might recalculate unnecessarily. Consider memoizing the conversion results if the input hasn't changed.

+    private lastStartAt?: dayjs.Dayjs;
+    private memoizedStartDate?: Date | null;

    startDate = computed(() => {
+        const currentStartAt = this.startAt?.();
+        if (currentStartAt === this.lastStartAt) {
+            return this.memoizedStartDate;
+        }
+        this.lastStartAt = currentStartAt;
+        this.memoizedStartDate = this.convertToDate(currentStartAt ?? dayjs().startOf('minutes'));
+        return this.memoizedStartDate;
    });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between afed090 and dcd52fd.

📒 Files selected for processing (2)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html (3 hunks)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html
🧰 Additional context used
📓 Path-based instructions (1)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

🪛 Biome
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts

[error] 49-49: Avoid redundant Boolean call

It is not necessary to use Boolean call when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant Boolean call

(lint/complexity/noExtraBooleanCast)

🔇 Additional comments (2)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (2)

Line range hint 1-18: LGTM! Clean component setup with signals.

The component setup follows Angular best practices with proper imports and ControlValueAccessor implementation.


Line range hint 1-136: Verify signal implementation impact.

The transition to signals looks good, but we should verify that this refactoring doesn't affect the component's behavior in the parent components.

✅ Verification successful

Let me analyze the usage of the date-time-picker component to verify the impact of the signal implementation.


Based on the analysis of the template and the search results, I can now provide a final response:

Signal implementation is safe and backward compatible

The changes to signals are safe because:

  • The component is self-contained and only used within its own directory
  • The template correctly uses the new signal syntax with parentheses ()
  • The component maintains its ControlValueAccessor interface, ensuring form integration
  • The ngModel binding in the template is preserved, maintaining compatibility with parent components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components using this date-time-picker
echo "Searching for usage of date-time-picker component..."
rg -l "jhi-date-time-picker" --type ts

# Search for potential ngModel bindings that might be affected
echo "Checking for ngModel bindings..."
rg "\[(ngModel)\].*=.*" --type html

Length of output: 11449


Script:

#!/bin/bash
# Check the template file to understand how the component is used
echo "Checking date-time-picker template..."
cat src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html

# Check if there are any direct references to properties that were converted to signals
echo "Checking for direct property references..."
rg "FormDateTimePickerComponent\." --type ts -A 2 -B 2

Length of output: 2391

🧰 Tools
🪛 Biome

[error] 49-49: Avoid redundant Boolean call

It is not necessary to use Boolean call when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant Boolean call

(lint/complexity/noExtraBooleanCast)

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 6, 2024
Copy link

@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 (2)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (2)

43-46: Simplify the isValid computed logic for better readability.

The current implementation can be simplified by grouping related conditions.

    isValid = computed(() => {
-        const isInvalid = this.error() || !this.isInputValid() || (this.requiredField() && !this.dateInputValue()) || this.warning();
-        return !isInvalid;
+        return !(
+            this.error() ||
+            !this.isInputValid() ||
+            (this.requiredField() && !this.dateInputValue()) ||
+            this.warning()
+        );
    });

Line range hint 66-74: Enhance type safety in writeValue method.

The method accepts any type and could benefit from more specific typing and null checks.

-    writeValue(value: any) {
+    writeValue(value: dayjs.Dayjs | Date | null | undefined) {
         // convert dayjs to date, because owl-date-time only works correctly with date objects
-        if (dayjs.isDayjs(value)) {
+        if (!value) {
+            this.value.set(null);
+        } else if (dayjs.isDayjs(value)) {
             this.value.set((value as dayjs.Dayjs).toDate());
         } else {
             this.value.set(value);
         }
         this.updateSignals();
     }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dcd52fd and 25d9d1d.

📒 Files selected for processing (3)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html (3 hunks)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (7 hunks)
  • src/test/javascript/spec/component/shared/date-time-picker.component.spec.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.html
  • src/test/javascript/spec/component/shared/date-time-picker.component.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

🪛 Biome
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts

[error] 49-49: Avoid redundant Boolean call

It is not necessary to use Boolean call when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant Boolean call

(lint/complexity/noExtraBooleanCast)

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 7, 2024
Copy link

@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 (3)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (3)

43-46: Simplify validation logic and improve error handling.

The validation logic in isValid could be more maintainable and might lead to confusing UX when both warnings and errors are present.

Consider restructuring the validation:

-    isValid = computed(() => {
-        const isInvalid = this.error() || !this.isInputValid() || (this.requiredField() && !this.dateInputValue()) || this.warning();
-        return !isInvalid;
-    });
+    isValid = computed(() => {
+        if (this.error()) {
+            return false;
+        }
+        if (this.requiredField() && !this.dateInputValue()) {
+            return false;
+        }
+        return this.isInputValid();
+    });
+
+    hasWarning = computed(() => {
+        return this.warning() && this.isValid();
+    });

109-111: Enhance date handling in computed properties.

The computed properties for dates could benefit from more robust null checking and validation.

Consider this enhanced implementation:

     startDate = computed(() => {
-        return this.convertToDate(this.startAt?.() ?? dayjs().startOf('minutes'));
+        const startAt = this.startAt?.();
+        return this.convertToDate(startAt ?? dayjs().startOf('minutes'));
     });

     minDate = computed(() => {
-        return this.convertToDate(this.min?.());
+        const minValue = this.min?.();
+        return minValue ? this.convertToDate(minValue) : null;
     });

     maxDate = computed(() => {
-        return this.convertToDate(this.max?.());
+        const maxValue = this.max?.();
+        return maxValue ? this.convertToDate(maxValue) : null;
     });

Also applies to: 113-115, 117-119


97-99: Consider adding validation in updateField.

The updateField method should validate the new value before updating and triggering changes.

Consider adding validation:

     updateField(newValue: dayjs.Dayjs) {
+        if (!newValue || !dayjs.isDayjs(newValue)) {
+            return;
+        }
         this.value.set(newValue);
         this.onChange?.(dayjs(this.value()));
         this.valueChanged();
     }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 25d9d1d and aee3f41.

📒 Files selected for processing (1)
  • src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

📓 Learnings (1)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (1)
Learnt from: florian-glombik
PR: ls1intum/Artemis#9694
File: src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts:29-29
Timestamp: 2024-11-07T00:36:51.500Z
Learning: In the Angular `FormDateTimePickerComponent` in `src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts`, the `value` model property may sometimes be a `string` because the component is used in multiple places where a `string` is passed. Therefore, changing its type from `any` to a more specific type could cause issues.
🪛 Biome
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts

[error] 49-49: Avoid redundant Boolean call

It is not necessary to use Boolean call when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant Boolean call

(lint/complexity/noExtraBooleanCast)

🔇 Additional comments (1)
src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts (1)

1-1: LGTM: Clean import organization.

The imports are well-organized and include all necessary signal-related functions from @angular/core.

Copy link
Contributor

@edkaya edkaya left a comment

Choose a reason for hiding this comment

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

Code lgtm

Copy link
Contributor

@JohannesWt JohannesWt left a comment

Choose a reason for hiding this comment

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

Code 🧑‍💻

Copy link
Contributor

@PaRangger PaRangger left a comment

Choose a reason for hiding this comment

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

Tested on TS4. Date Picker works fine and no related errors in the console. Code LGTM.

Copy link
Contributor

@asliayk asliayk left a comment

Choose a reason for hiding this comment

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

code lgtm

Copy link

@HawKhiem HawKhiem left a comment

Choose a reason for hiding this comment

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

Tested on TS4. Works as expected

Copy link

@JerroyTan JerroyTan left a comment

Choose a reason for hiding this comment

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

Tested on TS4, Date picker functionalities worked fine.

@krusche krusche merged commit 0d01a40 into develop Nov 9, 2024
25 of 38 checks passed
@krusche krusche deleted the chore/general/use-signals-in-date-time-picker branch November 9, 2024 15:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
client Pull requests that update TypeScript code. (Added Automatically!) code quality ready for review ready to merge refactoring small tests
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

8 participants