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

Communication: Fix an issue with link previews #9532

Merged
merged 3 commits into from
Oct 20, 2024

Conversation

pzdr7
Copy link
Contributor

@pzdr7 pzdr7 commented Oct 20, 2024

Checklist

General

Client

  • Important: I implemented the changes with a very good performance, prevented too many (unnecessary) REST calls and made sure the UI is responsive, even with large data (e.g. using paging).
  • I strictly followed the client coding and design guidelines.

Motivation and Context

Closes #9530

Currently, link previews carry over when switching between threads. This is due to a check from #6760 preventing the previews from being refreshed on changes.

Description

  • Removed the check. The previews now refresh for all messages, not just edited ones.
  • Improved the change detection with signals

Steps for Testing

Prerequisites:

  • 1 Student
  • 1 Course with communication enabled
  1. Navigate to the communication view of the course and open a channel.
  2. Post a message containing a link, e.g. https://github.com/ls1intum/scorpio
  3. Post a message not containing a link.
  4. For both messages, click "Reply in thread". Verify that the thread only shows the link preview if the message actually contains the link.
  5. Try this with the replies as well (as seen in Communication Embedded Links are duplicated #9530): post replies with / without a link and ensure they do not carry over from thread to thread.
  6. Make sure removing the preview still works:
    image

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

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

Unchanged

Class/File Line Coverage Confirmation (assert/expect)
link-preview-container.component.ts 97.5%

Screenshots

Screencast.from.20.10.2024.13.46.12.webm

Summary by CodeRabbit

  • New Features

    • Enhanced performance and maintainability of the Link Preview component through a transition to a reactive programming model.
    • Improved state management with dynamic property access for link previews and loading indicators.
  • Bug Fixes

    • Resolved issues related to component state updates by ensuring reactivity in property access.
  • Tests

    • Updated test cases to reflect changes in how properties are accessed and set within the Link Preview component.

@github-actions github-actions bot added tests client Pull requests that update TypeScript code. (Added Automatically!) labels Oct 20, 2024
@pzdr7 pzdr7 temporarily deployed to artemis-test3.artemis.cit.tum.de October 20, 2024 11:50 — with GitHub Actions Inactive
@pzdr7 pzdr7 temporarily deployed to artemis-test3.artemis.cit.tum.de October 20, 2024 12:20 — with GitHub Actions Inactive
@pzdr7 pzdr7 marked this pull request as ready for review October 20, 2024 12:26
@pzdr7 pzdr7 requested a review from a team as a code owner October 20, 2024 12:26
Copy link

coderabbitai bot commented Oct 20, 2024

Walkthrough

The pull request introduces significant changes to the LinkPreviewContainerComponent in an Angular application. It modifies property access patterns from direct references to function calls, enhancing reactivity. The component adopts Angular's ChangeDetectionStrategy.OnPush and transitions input properties to readonly signals. The test suite is updated to reflect these changes, ensuring that the component's functionality is validated with the new reactive model.

Changes

File Change Summary
src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.component.html Changed property access from direct references to function calls for linkPreviews, showLoadingsProgress, hasError, loaded, posting, isReply, and multiple.
src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.component.ts Updated component to use ChangeDetectionStrategy.OnPush, replaced @Input() with readonly properties using input(), transitioned state management to signals, modified lifecycle methods, and enhanced reactivity in reloadLinkPreviews and findPreviews.
src/test/javascript/spec/component/link-preview/link-preview-container.component.spec.ts Updated test suite to set data using fixture.componentRef.setInput, and changed property access to method calls for linkPreviews, hasError, loaded, and showLoadingsProgress.

Assessment against linked issues

Objective Addressed Explanation
Preview should only be in the thread where the link was posted (9530) The changes do not directly address the issue of link duplication in threads.

Possibly related PRs

Suggested labels

small, bugfix, component:Communication, ready for review

Suggested reviewers

  • krusche
  • SimonEntholzer
  • az108
  • HawKhiem

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 (6)
src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.component.html (1)

1-10: Summary: Effective refactoring to address link preview issues

The changes in this file effectively contribute to the PR's objective of fixing the issue with link previews persisting across different threads. By transitioning to signals and adopting the new Angular syntax, the component should now be more reactive to state changes. This increased reactivity should allow link previews to refresh correctly when switching between threads.

Key improvements:

  1. Adoption of the @for directive, enhancing performance and adhering to modern Angular practices.
  2. Consistent refactoring of property bindings to use function calls, likely leveraging signals for improved state management.
  3. Use of a trackBy function to optimize list rendering performance.

These changes, combined with the modifications in the component logic, should resolve the reported issue (#9530) of duplicated link previews across threads. The refactoring also aligns well with the goal of maintaining high performance and responsiveness, even with large datasets.

To further enhance the link preview functionality:

  1. Consider implementing lazy loading for link previews to improve initial load times, especially for threads with many links.
  2. Explore caching mechanisms for link preview data to reduce unnecessary network requests when revisiting threads.
src/test/javascript/spec/component/link-preview/link-preview-container.component.spec.ts (2)

55-59: Updated expectations for signal-based properties

The changes correctly reflect the transition to signal-based properties in the component. The use of function calls (e.g., component.linkPreviews()) instead of direct property access is appropriate.

However, we can make the expectation for linkPreviews more specific:

Consider using toContainEntries for a more precise assertion:

expect(component.linkPreviews()).toContainEntries([
  [0, expect.objectContaining(mockLinkPreviews[0])],
  [1, expect.objectContaining(mockLinkPreviews[1])]
]);

This approach verifies both the order and content of the linkPreviews array more explicitly.


80-80: Updated expectations for signal-based properties

The changes correctly reflect the transition to signal-based properties in the component. The use of function calls (e.g., component.linkPreviews()) instead of direct property access is appropriate.

However, we can improve the specificity of our expectations:

  1. For line 80, consider using a more reactive approach to update the signal:
component.linkPreviews.set([...component.linkPreviews(), existingLinkPreview]);
  1. For lines 87-88, consider using toContainEntries for a more precise assertion:
expect(component.linkPreviews()).toContainEntries([
  [0, expect.objectContaining(newLinkPreview)]
]);

This approach verifies both the length and content of the linkPreviews array more explicitly.

Also applies to: 84-88

src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.component.ts (3)

14-15: Consider using constructor injection for dependency injection

While the inject() function is valid in Angular 14 and later, the Angular Style Guide recommends using constructor injection for better readability and consistency across the codebase. Constructor injection makes dependencies explicit and easier to test.

Consider refactoring to use constructor injection:

-export class LinkPreviewContainerComponent implements OnInit, OnChanges {
-    private readonly linkPreviewService: LinkPreviewService = inject(LinkPreviewService);
-    private readonly linkifyService: LinkifyService = inject(LinkifyService);
+export class LinkPreviewContainerComponent implements OnInit, OnChanges {
+    constructor(
+        private readonly linkPreviewService: LinkPreviewService,
+        private readonly linkifyService: LinkifyService
+    ) {}

     // ...
 }

46-46: Address the TODO: Make the link preview limit configurable

There's a TODO comment indicating that the limit of 5 link previews should be configurable, possibly at the course level. Implementing this feature would enhance flexibility and allow different courses to set appropriate limits based on their needs.

Would you like assistance in implementing a configuration option for the link preview limit? I can help draft a solution or create a GitHub issue to track this enhancement.


Line range hint 51-71: Prevent potential memory leaks by managing subscriptions

In the findPreviews() method, you're subscribing to observables within a loop without unsubscribing. This can lead to memory leaks if the component is destroyed before all subscriptions complete. Ensure that you properly manage these subscriptions.

Consider using the takeUntil operator along with an ngOnDestroy lifecycle hook to manage unsubscription:

import { OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';

export class LinkPreviewContainerComponent implements OnInit, OnChanges, OnDestroy {
    private readonly destroy$ = new Subject<void>();

    // ...

    ngOnDestroy() {
        this.destroy$.next();
        this.destroy$.complete();
    }

    private findPreviews() {
        const links: Link[] = this.linkifyService.find(this.data() ?? '');
        // ...
        links.forEach((link) => {
            this.linkPreviewService.fetchLink(link.href)
                .pipe(takeUntil(this.destroy$))
                .subscribe({
                    next: (linkPreview) => {
                        // ...
                    },
                });
        });
    }
}

Ensure that you import takeUntil from 'rxjs/operators'.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f3a48ad and dfaf51c.

📒 Files selected for processing (3)
  • src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.component.html (1 hunks)
  • src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.component.ts (3 hunks)
  • src/test/javascript/spec/component/link-preview/link-preview-container.component.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.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/link-preview/components/link-preview-container/link-preview-container.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/link-preview/link-preview-container.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 (9)
src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.component.html (2)

1-1: Excellent use of new Angular syntax and optimization techniques!

The changes in this line demonstrate several good practices:

  1. Using the new @for directive as per our coding guidelines.
  2. Accessing linkPreviews as a function call, which aligns with the transition to signals mentioned in the component changes.
  3. Implementing a trackBy function (trackLinks) to optimize Angular's change detection for the list rendering.

These changes should improve the component's reactivity and performance.


5-10: Consistent refactoring to enhance reactivity

The changes on lines 5-10 demonstrate a systematic refactoring of property bindings:

  1. All properties (showLoadingsProgress, hasError, loaded, posting, isReply, multiple) are now accessed as function calls.
  2. This change aligns with the transition to signals mentioned in the component changes.
  3. Using function calls instead of direct property access can enhance reactivity and allow for computed properties.

These modifications should improve the component's ability to react to state changes efficiently. The consistent application of this pattern across all properties is commendable and shows attention to detail in the refactoring process.

src/test/javascript/spec/component/link-preview/link-preview-container.component.spec.ts (4)

40-40: Improved input property setting

The change from direct property assignment to fixture.componentRef.setInput() is a good improvement. This approach better aligns with Angular's change detection mechanism, especially when working with components using ChangeDetectionStrategy.OnPush and input properties defined as readonly signals.


60-62: Correct usage of boolean expectations

The updated expectations correctly use function calls for signal-based properties. The use of toBeFalse() and toBeTrue() for boolean assertions is in line with the provided coding guidelines and improves the readability of the test.


66-66: Consistent input property setting

The use of fixture.componentRef.setInput() is consistent with the earlier change and correctly reflects the component's use of readonly input properties.


Line range hint 1-90: Overall assessment of the changes

The modifications to this test file consistently reflect the transition to using signals in the LinkPreviewContainerComponent. The changes improve the alignment of the tests with Angular's latest practices and the component's new implementation.

Key improvements:

  1. Correct usage of fixture.componentRef.setInput() for setting input properties.
  2. Consistent use of function calls to access signal-based properties.
  3. Appropriate use of Jest matchers as per the coding guidelines.

While the changes are generally good, the suggestions provided in the previous comments will further enhance the test specificity and robustness. Consider implementing these suggestions to maximize the effectiveness of your test suite.

src/main/webapp/app/shared/link-preview/components/link-preview-container/link-preview-container.component.ts (3)

11-11: Verify the compatibility of using ChangeDetectionStrategy.OnPush

Implementing ChangeDetectionStrategy.OnPush can improve performance by optimizing change detection. However, ensure that all bindings and inputs are immutable or that you trigger change detection appropriately when mutable objects change. This will prevent any unexpected UI behavior due to Angular not detecting changes in mutable objects.


17-21: Usage of input() for @Input() properties may not align with standard practices

Defining input properties using the input() function is a new feature introduced in Angular 16 as part of the reactive signal model. While it offers advantages in certain scenarios, it's still in developer preview. Ensure that this approach is compatible with your project's Angular version and that all team members are aligned on using this new feature.

If you prefer to stick with the standard approach, consider reverting to using the @Input() decorator:

- readonly data = input<string>();
- readonly author = input<User>();
- readonly posting = input<Posting>();
- readonly isEdited = input<boolean>();
- readonly isReply = input<boolean>();
+ @Input() data?: string;
+ @Input() author?: User;
+ @Input() posting?: Posting;
+ @Input() isEdited?: boolean;
+ @Input() isReply?: boolean;

23-27: Ensure that using signal() aligns with your Angular version and project standards

The signal() function is part of Angular's new reactivity model introduced in Angular 16. It's still in developer preview and subject to change. Please verify that your project is using Angular 16 or later and that adopting signals fits within your project's guidelines.

@JanaNF JanaNF modified the milestone: tes Oct 20, 2024
@JanaNF JanaNF temporarily deployed to artemis-test1.artemis.cit.tum.de October 20, 2024 12:41 — with GitHub Actions Inactive
Copy link

@Cathy0123456789 Cathy0123456789 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 TS3. Works as expected. Tested for messages and replies:

  • Previews are only displayed in the thread they should appear in
  • Removing previews works, adding them back also works

Copy link
Contributor

@SimonEntholzer SimonEntholzer left a comment

Choose a reason for hiding this comment

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

Works on Ts1 👍

Copy link

@JanaNF JanaNF left a comment

Choose a reason for hiding this comment

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

Manual tested on TS1.

  • Did all the steps as you said.
  • Tested it on direct messages too.
  • When I edited the messages to other links, it changed the preview too.
  • Tried if it works with and without a / after the link (https://orf.at/, https://orf.at). It worked.

Problem: Some links do not work e.g. https://www.youtube.com/ , https://artemis.cit.tum.de/ , https://orf.de/

If that is not an issue from your side, just ignore my review.

@pzdr7
Copy link
Contributor Author

pzdr7 commented Oct 20, 2024

@JanaNF thanks for testing. I checked these links and they do not currently have a preview, so that should be unrelated to this PR.

@pzdr7 pzdr7 requested a review from JanaNF October 20, 2024 13:19
@krusche krusche added this to the 7.6.1 milestone Oct 20, 2024
Copy link
Member

@krusche krusche left a comment

Choose a reason for hiding this comment

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

Thanks for fixing the issue so quickly and for improving the code quality in the component 👍

@krusche krusche merged commit 97e17e6 into develop Oct 20, 2024
54 of 58 checks passed
@krusche krusche deleted the bugfix/communication/link-preview branch October 20, 2024 13:32
SimonEntholzer pushed a commit that referenced this pull request Oct 21, 2024
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!) ready for review tests
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

Communication Embedded Links are duplicated
5 participants