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 video unit form component #9692

Merged

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 video-unit-form.component.ts (and thereby removed method calls in the template)

Steps for Testing

Prerequisites:

  1. Navigate to the Instructor lecture view (creating and editing)
  2. Click Units > Video to create a text lecture unit, verify the behavior is the same as on develop
  3. Verify Editing the video Unit works as on develop
  4. Create a Lecture in the guided mode, where you add a video Unit (make sure to select a competency to prevent known bug!)
  5. Verify Adding a video lecture unit works
  6. Verify the cancel button works for the video lecture unit

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

useSignalsInVideoUnitFormComponent-9692

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced form submission logic to improve validation before submission.
    • Updated cancel button functionality for better user experience.
  • Bug Fixes

    • Improved handling of form state, ensuring accurate reflection in the UI.
  • Tests

    • Streamlined input handling in test cases for better alignment with Angular's input binding.

These updates enhance the overall usability and reliability of the video unit form component.

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

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes involve significant updates to the VideoUnitFormComponent, enhancing its structure and reactivity by leveraging Angular's latest features. The component's form submission logic and cancel button handling have been modified for better clarity and functionality. Additionally, the testing suite has been updated to align with the new input handling methods, ensuring that the component behaves correctly under various conditions.

Changes

File Change Summary
src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component.html Updated form submission logic to use isFormValid() and modified cancel button condition to call hasCancelButton().
src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component.ts Refactored component to use Angular's reactive features, replacing decorators with input and output functions, and removed lifecycle methods in favor of an effect.
src/test/javascript/spec/component/lecture-unit/video-unit/video-unit-form.component.spec.ts Adjusted test suite to use setInput for component inputs, aligning with Angular's input binding mechanism.

Possibly related PRs

Suggested labels

lecture

Suggested reviewers

  • BBesrour
  • Feras797
  • krusche
  • sachmii

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 (7)
src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component.html (1)

Line range hint 110-117: Consider using a signal for the cancel button visibility.

While the changes align with moving logic to the component, using a method call hasCancelButton() in the template could lead to unnecessary re-evaluations during change detection cycles. Consider using a signal or computed property instead.

Example refactor:

- @if (hasCancelButton()) {
+ @if (showCancelButton()) {

In the component:

showCancelButton = computed(() => {
  // your cancel button logic here
});
src/test/javascript/spec/component/lecture-unit/video-unit/video-unit-form.component.spec.ts (3)

Line range hint 41-163: Consider refactoring repeated spy setup patterns.

The tests repeat the same spy setup pattern across multiple test cases:

jest.spyOn(videoUnitFormComponent, 'videoSourceUrlValidator').mockReturnValue(undefined);
jest.spyOn(videoUnitFormComponent, 'videoSourceTransformUrlValidator').mockReturnValue(undefined);

Consider extracting this into a helper method to improve maintainability:

function setupVideoValidatorSpies(component: VideoUnitFormComponent): void {
  jest.spyOn(component, 'videoSourceUrlValidator').mockReturnValue(undefined);
  jest.spyOn(component, 'videoSourceTransformUrlValidator').mockReturnValue(undefined);
}

Line range hint 119-163: Consider grouping URL transformation tests.

The URL transformation tests for YouTube and TUM-Live could be grouped under a describe block for better organization:

describe('URL transformations', () => {
  it('should correctly transform YouTube URL into embeddable format', () => {
    // existing test
  });

  it('should correctly transform TUM-Live URL without video only into embeddable format', () => {
    // existing test
  });
});

Line range hint 165-175: Input handling changes look good, consider additional test cases.

The migration to using setInput for component inputs is correct and aligns with the signal-based approach. However, consider adding test cases for:

  • Input change detection (when formData changes after initial setup)
  • Edge cases with null/undefined input values

Example additional test:

it('should update form when formData input changes', () => {
  videoUnitFormComponentFixture.componentRef.setInput('isEditMode', true);
  const initialData: VideoUnitFormData = {
    name: 'initial',
    description: 'initial desc',
    releaseDate: dayjs(),
    source: 'initial-source'
  };
  videoUnitFormComponentFixture.componentRef.setInput('formData', initialData);
  videoUnitFormComponentFixture.detectChanges();
  
  const updatedData: VideoUnitFormData = {
    name: 'updated',
    description: 'updated desc',
    releaseDate: dayjs(),
    source: 'updated-source'
  };
  videoUnitFormComponentFixture.componentRef.setInput('formData', updatedData);
  videoUnitFormComponentFixture.detectChanges();
  
  expect(videoUnitFormComponent.nameControl?.value).toEqual(updatedData.name);
  expect(videoUnitFormComponent.descriptionControl?.value).toEqual(updatedData.description);
});
src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component.ts (3)

90-95: Consider cleaning up the effect to prevent potential memory leaks

While Angular automatically handles the cleanup of effects within components, explicitly unsubscribing can prevent potential memory leaks and align with the coding guideline memory_leak_prevention:true.

You can store the effect cleanup function and call it in ngOnDestroy:

+ private readonly formEffectCleanup = effect(() => {
    if (this.isEditMode() && this.formData()) {
        untracked(() => this.setFormValues(this.formData()!));
    }
- });
+ });

+ ngOnDestroy() {
+     this.formEffectCleanup();
+ }

78-85: Simplify form control initialization by removing unnecessary type assertions

The type assertions using as Type | undefined are unnecessary since TypeScript can infer the types from the default values. This simplification enhances readability.

Update the form controls as follows:

- name: [undefined as string | undefined, [Validators.required, Validators.maxLength(255)]],
+ name: ['', [Validators.required, Validators.maxLength(255)]],

- description: [undefined as string | undefined, [Validators.maxLength(1000)]],
+ description: ['', [Validators.maxLength(1000)]],

- releaseDate: [undefined as dayjs.Dayjs | undefined],
+ releaseDate: [null as dayjs.Dayjs | null],

- source: [undefined as string | undefined, [Validators.required, this.videoSourceUrlValidator]],
+ source: ['', [Validators.required, this.videoSourceUrlValidator]],

- urlHelper: [undefined as string | undefined, this.videoSourceTransformUrlValidator],
+ urlHelper: ['', this.videoSourceTransformUrlValidator],

- competencyLinks: [undefined as CompetencyLectureUnitLink[] | undefined],
+ competencyLinks: [[], []],

87-87: Ensure method calls in templates adhere to performance best practices

Calling methods like isFormValid() in the template is acceptable when using signals. However, per the coding guideline methods_in_html:false, it's important to ensure these methods are efficient and do not negatively impact performance.

Consider storing isFormValid as a property if it doesn't need to recompute frequently or ensure that the computed signal is optimized.

- isFormValid = computed(() => this.statusChanges() === 'VALID');
+ readonly isFormValid = computed(() => this.statusChanges() === 'VALID');

Ensure that in the template, you're calling isFormValid() and that it doesn't trigger unnecessary re-evaluations.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

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

📒 Files selected for processing (3)
  • src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component.html (1 hunks)
  • src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component.ts (2 hunks)
  • src/test/javascript/spec/component/lecture-unit/video-unit/video-unit-form.component.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.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/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.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

src/test/javascript/spec/component/lecture-unit/video-unit/video-unit-form.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 (6)
src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component.html (1)

Line range hint 3-3: LGTM! Proper usage of new Angular control flow syntax.

The template correctly uses the new @if syntax throughout, replacing the older *ngIf directives. The form validation structure is well-organized and follows Angular best practices.

Also applies to: 8-8, 14-14, 15-15, 16-16, 17-17, 18-18, 19-19, 20-20, 21-21, 22-22, 23-23, 24-24, 25-25, 26-26, 27-27, 28-28, 29-29, 30-30, 31-31, 32-32, 33-33, 34-34, 35-35, 36-36, 37-37, 38-38, 39-39, 40-40, 41-41, 42-42, 43-43, 44-44, 45-45, 46-46, 47-47, 48-48, 49-49, 50-50, 51-51, 52-52, 53-53, 54-54, 55-55, 56-56, 57-57, 58-58, 59-59, 60-60, 61-61, 62-62, 63-63, 64-64, 65-65, 66-66, 67-67, 68-68, 69-69, 70-70, 71-71, 72-72, 73-73, 74-74, 75-75, 76-76, 77-77, 78-78, 79-79, 80-80, 81-81, 82-82, 83-83, 84-84, 85-85, 86-86, 87-87, 88-88, 89-89, 90-90, 91-91, 92-92, 93-93, 94-94, 95-95, 96-96, 97-97, 98-98, 99-99, 100-100, 101-101, 102-102, 103-103, 104-104, 105-105, 106-106, 107-107, 108-108, 109-109

src/test/javascript/spec/component/lecture-unit/video-unit/video-unit-form.component.spec.ts (1)

Line range hint 1-39: Test setup follows best practices!

The configuration demonstrates good practices:

  • Proper use of NgMocks for mocking components and pipes
  • Focused imports without unnecessary dependencies
  • Clean TestBed configuration without schemas
src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component.ts (4)

65-65: Usage of inject() aligns with Angular best practices

The use of inject(FormBuilder) is appropriate and leverages Angular's dependency injection in a functional way. This aligns with modern Angular patterns.


86-87: Conversion of statusChanges to a signal is correct

Transforming form.statusChanges into a signal using toSignal is a valid approach for reactive form handling with signals. This ensures that isFormValid updates automatically based on form validity.


92-92: Confirm the necessity of untracked within the effect

Using untracked prevents the setFormValues method from creating additional dependencies that could retrigger the effect unnecessarily. Ensure this is intentional and does not skip updates that should be tracked.

Please verify that untracked is necessary here and doesn't omit any required reactive updates.


72-73: Usage of input and output signals is appropriate

Defining hasCancelButton and onCancel using input and output functions modernizes the component and leverages Angular's signal APIs effectively.

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

github-actions bot commented Nov 6, 2024

⚠️ Unable to deploy to test servers ⚠️

Testserver "artemis-test3.artemis.cit.tum.de" is already in use by PR #9691.

@github-actions github-actions bot added the deployment-error Added by deployment workflows if an error occured label Nov 6, 2024
@florian-glombik florian-glombik removed the deployment-error Added by deployment workflows if an error occured label Nov 6, 2024
Copy link
Contributor

@az108 az108 left a comment

Choose a reason for hiding this comment

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

Overall, Code looks good to me but can you please check out the failing client test. Will approve after that.

@florian-glombik
Copy link
Contributor Author

@anditurdiu #9692 (review) Which failing client test are you referring to? https://bamboo.ase.in.tum.de/browse/ARTEMIS-TESTS7337-TSTEST-1

The GitHub Action tasks are flaky, as far as I know that's why they did not replace the Bamboo pipelines yet.

az108
az108 previously approved these changes Nov 6, 2024
Copy link
Contributor

@az108 az108 left a comment

Choose a reason for hiding this comment

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

@florian-glombik alright then its fine from my side if its flaky 👍

JohannesWt
JohannesWt previously approved these changes Nov 7, 2024
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 👍

kevinfischer4
kevinfischer4 previously approved these changes Nov 7, 2024
Copy link

@kevinfischer4 kevinfischer4 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 TS2, works as described.

@github-actions github-actions bot removed the lecture Pull requests that affect the corresponding module label Nov 8, 2024
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.

Reapprove 🇹🇭

@krusche krusche merged commit bfebf27 into develop Nov 8, 2024
23 of 30 checks passed
@krusche krusche deleted the chore/lectures/use-signals-in-video-unit-form-component branch November 8, 2024 12:12
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
Status: Merged
Development

Successfully merging this pull request may close these issues.

6 participants