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 dropdown menu behavior for links to allow default browser options #9832

Merged

Conversation

asliayk
Copy link
Contributor

@asliayk asliayk commented Nov 20, 2024

Checklist

General

Client

Motivation and Context

When a user right-clicks on a link within a message, the dropdown menu opens instead of displaying the browser's default context menu (e.g., option to open the link in a new tab).
(Closes #9776)

Description

The dropdown menu is now disabled when the user right-clicks on a link, allowing the browser's default options to be displayed.

Steps for Testing

Prerequisites:

  • 1 Instructor
  • 1 Course with Communication enabled
  1. Log in to Artemis.
  2. Navigate to the Communication section of a course.
  3. Post a message in a channel containing a link, such as: "Here is the link www.google.com".
  4. Right-click on the link and verify that the dropdown menu does not appear, and the browser's default context menu is shown.
  5. Right-click on any other part of the text and confirm that the dropdown menu opens as expected.

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

Class/File Line Coverage Confirmation (assert/expect)
answer-post.component.ts 96.22% ✅ ❌
post.component.ts 95.28% ✅ ❌

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced right-click interactions in both the AnswerPost and Post components, ensuring dropdown behavior is contextually appropriate based on cursor style.
  • Bug Fixes

    • Improved handling of right-click events to prevent default actions when the cursor is not a pointer.
  • Tests

    • Added new test cases for the onRightClick method in both the AnswerPost and Post components to validate behavior under different cursor styles.

@asliayk asliayk added tests client Pull requests that update TypeScript code. (Added Automatically!) small bugfix component:Communication labels Nov 20, 2024
@asliayk asliayk self-assigned this Nov 20, 2024
@asliayk asliayk requested a review from a team as a code owner November 20, 2024 13:40
@asliayk asliayk changed the title updated open dropdown function to disable it when there is link Communication: Fix dropdown menu behavior for links to allow default browser options Nov 20, 2024
Copy link

coderabbitai bot commented Nov 20, 2024

Walkthrough

The changes primarily involve modifications to the onRightClick methods in the AnswerPostComponent and PostComponent classes. These modifications introduce checks for the cursor style of the target element before preventing the default context menu from appearing. The AnswerPostComponent has also been updated to implement the OnDestroy lifecycle interface, adding the ngOnDestroy method for cleanup purposes. Additionally, new test cases have been added to both components to validate the behavior of the onRightClick method under different cursor styles, enhancing test coverage without altering existing functionalities.

Changes

File Change Summary
src/main/webapp/app/shared/metis/answer-post/answer-post.component.ts Updated AnswerPostComponent to implement OnDestroy, added ngOnDestroy and cleanupActiveDropdown, refined onRightClick method.
src/main/webapp/app/shared/metis/post/post.component.ts Modified onRightClick method to include cursor style check; updated isConsecutive property declaration.
src/test/javascript/spec/component/shared/metis/answer-post/answer-post.component.spec.ts Added test case for onRightClick method to validate behavior based on cursor styles.
src/test/javascript/spec/component/shared/metis/post/post.component.spec.ts Introduced test case for onRightClick method to check functionality under various cursor conditions.

Assessment against linked issues

Objective Addressed Explanation
Get standard drop down menu when right clicking a link (#9776)

Possibly related PRs

Suggested labels

ready to merge

Suggested reviewers

  • sachmii
  • HawKhiem
  • Cathy0123456789
  • florian-glombik
  • PaRangger
  • ItsaaaMeMario

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6b5f153 and e32c071.

📒 Files selected for processing (4)
  • src/main/webapp/app/shared/metis/answer-post/answer-post.component.ts (4 hunks)
  • src/main/webapp/app/shared/metis/post/post.component.ts (1 hunks)
  • src/test/javascript/spec/component/shared/metis/answer-post/answer-post.component.spec.ts (2 hunks)
  • src/test/javascript/spec/component/shared/metis/post/post.component.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/webapp/app/shared/metis/post/post.component.ts
  • src/test/javascript/spec/component/shared/metis/answer-post/answer-post.component.spec.ts
  • src/test/javascript/spec/component/shared/metis/post/post.component.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
src/main/webapp/app/shared/metis/answer-post/answer-post.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

🔇 Additional comments (4)
src/main/webapp/app/shared/metis/answer-post/answer-post.component.ts (4)

10-10: LGTM: Good practice implementing OnDestroy

The addition of the OnDestroy interface follows Angular best practices for component lifecycle management and memory leak prevention.

Also applies to: 40-40


123-129: LGTM: Robust cursor style check implementation

The implementation correctly determines if the element is a link by checking the cursor style, with proper error handling and fallback. This effectively solves the original issue by allowing default browser context menu for links.


132-149: 🛠️ Refactor suggestion

Consider avoiding static property for dropdown state management

Using static activeDropdownPost to manage dropdown state across component instances can lead to unexpected behavior when multiple instances exist. Consider managing the state at the instance level instead.

-static activeDropdownPost: AnswerPostComponent | null = null;
+@Input() isActiveDropdown = false;

 onRightClick(event: MouseEvent) {
     // ... cursor style check ...
     if (!isPointerCursor) {
         event.preventDefault();
-        if (AnswerPostComponent.activeDropdownPost !== this) {
-            AnswerPostComponent.cleanupActiveDropdown();
-        }
-        AnswerPostComponent.activeDropdownPost = this;
+        this.closeOtherDropdowns.emit();
+        this.isActiveDropdown = true;
         // ... rest of the method
     }
 }

+@Output() closeOtherDropdowns = new EventEmitter<void>();

170-174: 🛠️ Refactor suggestion

Enhance component cleanup in ngOnDestroy

While the dropdown cleanup is good, consider adding comprehensive cleanup:

  1. Event listener cleanup (document click listener)
  2. Subscription cleanup
+private subscriptions = new Subscription();
+private clickListener: () => void;

 constructor(
     public changeDetector: ChangeDetectorRef,
     public renderer: Renderer2,
     @Inject(DOCUMENT) private document: Document,
 ) {
     super();
+    this.clickListener = this.renderer.listen('document', 'click', () => this.onClickOutside());
 }

 ngOnDestroy(): void {
     if (AnswerPostComponent.activeDropdownPost === this) {
         AnswerPostComponent.cleanupActiveDropdown();
     }
+    if (this.clickListener) {
+        this.clickListener();
+    }
+    this.subscriptions.unsubscribe();
 }

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

🧹 Outside diff range and nitpick comments (9)
src/main/webapp/app/shared/metis/answer-post/answer-post.component.ts (2)

103-104: Consider a more robust link detection approach

While using cursor style to detect interactive elements works, consider combining it with additional checks for better reliability:

-        const isPointerCursor = window.getComputedStyle(targetElement).cursor === 'pointer';
+        const computedStyle = window.getComputedStyle(targetElement);
+        const isLink = targetElement.tagName.toLowerCase() === 'a' || 
+                      targetElement.closest('a') !== null;
+        const isPointerCursor = computedStyle.cursor === 'pointer';
+        const isInteractive = isLink || isPointerCursor;

117-120: Consider adding boundary checks for dropdown positioning

The dropdown position calculation should include vertical boundary checks to ensure the dropdown remains within viewport:

     this.dropdownPosition = {
         x: event.clientX,
         y: event.clientY,
     };
+    
+    // Ensure dropdown stays within viewport vertically
+    const dropdownHeight = 200; // Approximate height
+    const screenHeight = window.innerHeight;
+    if (this.dropdownPosition.y + dropdownHeight > screenHeight) {
+        this.dropdownPosition.y = screenHeight - dropdownHeight - 10;
+    }
src/test/javascript/spec/component/shared/metis/answer-post/answer-post.component.spec.ts (3)

180-193: Consider adding more cursor style test cases.

The test cases cover 'pointer' and 'default' cursors, but should also include other common cursor styles like 'text' to ensure comprehensive coverage of the right-click behavior.

 const testCases = [
     {
         cursor: 'pointer',
         preventDefaultCalled: false,
         showDropdown: false,
         dropdownPosition: { x: 0, y: 0 },
     },
     {
         cursor: 'default',
         preventDefaultCalled: true,
         showDropdown: true,
         dropdownPosition: { x: 100, y: 200 },
     },
+    {
+        cursor: 'text',
+        preventDefaultCalled: true,
+        showDropdown: true,
+        dropdownPosition: { x: 100, y: 200 },
+    },
 ];

201-203: Use more specific type for mock return value.

The current mock implementation uses a partial type. Consider using a more complete mock object to prevent potential type-related issues.

-jest.spyOn(window, 'getComputedStyle').mockReturnValue({
-    cursor,
-} as CSSStyleDeclaration);
+const mockStyle = {
+    cursor,
+    getPropertyValue: (prop: string) => prop === 'cursor' ? cursor : '',
+    setProperty: jest.fn(),
+} as unknown as CSSStyleDeclaration;
+jest.spyOn(window, 'getComputedStyle').mockReturnValue(mockStyle);

195-208: Consider extracting test setup to a helper function.

The test setup code is quite lengthy. Consider extracting it to a helper function to improve readability and maintainability.

+const setupRightClickTest = (cursor: string) => {
+    const event = new MouseEvent('contextmenu', { clientX: 100, clientY: 200 });
+    const targetElement = document.createElement('div');
+    Object.defineProperty(event, 'target', { value: targetElement });
+    
+    const mockStyle = {
+        cursor,
+        getPropertyValue: (prop: string) => prop === 'cursor' ? cursor : '',
+        setProperty: jest.fn(),
+    } as unknown as CSSStyleDeclaration;
+    jest.spyOn(window, 'getComputedStyle').mockReturnValue(mockStyle);
+    
+    const preventDefaultSpy = jest.spyOn(event, 'preventDefault');
+    
+    return { event, preventDefaultSpy };
+};

 testCases.forEach(({ cursor, preventDefaultCalled, showDropdown, dropdownPosition }) => {
-    const event = new MouseEvent('contextmenu', { clientX: 100, clientY: 200 });
-    const targetElement = document.createElement('div');
-    Object.defineProperty(event, 'target', { value: targetElement });
-    
-    jest.spyOn(window, 'getComputedStyle').mockReturnValue({
-        cursor,
-    } as CSSStyleDeclaration);
-    
-    const preventDefaultSpy = jest.spyOn(event, 'preventDefault');
+    const { event, preventDefaultSpy } = setupRightClickTest(cursor);
     
     component.onRightClick(event);
src/main/webapp/app/shared/metis/post/post.component.ts (2)

124-125: Consider using a more robust link detection method

While checking the cursor style works, it might be more reliable to directly check if the clicked element is a link or contains a link in its parent chain.

-const isPointerCursor = window.getComputedStyle(targetElement).cursor === 'pointer';
+const isLink = (element: HTMLElement): boolean => {
+    if (!element) return false;
+    return element.tagName === 'A' || (element.parentElement ? isLink(element.parentElement) : false);
+};
+const shouldDisableDropdown = isLink(targetElement);

124-146: Consider enhancing keyboard accessibility

While the right-click handling is improved, consider adding keyboard navigation support for the custom dropdown menu when it is shown.

// Add keyboard event handling
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
    if (this.showDropdown) {
        switch(event.key) {
            case 'Escape':
                this.showDropdown = false;
                this.enableBodyScroll();
                break;
            // Add more keyboard navigation as needed
        }
    }
}
src/test/javascript/spec/component/shared/metis/post/post.component.spec.ts (2)

315-351: Test implementation looks good but could be more comprehensive.

The test case effectively verifies the onRightClick behavior for different cursor styles. However, consider these improvements:

  1. Add specific test cases for link elements (<a> tags) since they are the main focus of the PR
  2. Include additional cursor values that might appear on links (e.g., 'text', 'help')
  3. Consider testing the interaction with actual link text and href attributes

Here's a suggested enhancement:

 it('should handle onRightClick correctly based on cursor style', () => {
     const testCases = [
         {
             cursor: 'pointer',
+            element: 'a',
+            href: 'https://example.com',
             preventDefaultCalled: false,
             showDropdown: false,
             dropdownPosition: { x: 0, y: 0 },
         },
         {
             cursor: 'default',
+            element: 'div',
             preventDefaultCalled: true,
             showDropdown: true,
             dropdownPosition: { x: 100, y: 200 },
         },
+        {
+            cursor: 'text',
+            element: 'a',
+            href: 'https://example.com',
+            preventDefaultCalled: false,
+            showDropdown: false,
+            dropdownPosition: { x: 0, y: 0 },
+        },
     ];

-    testCases.forEach(({ cursor, preventDefaultCalled, showDropdown, dropdownPosition }) => {
+    testCases.forEach(({ cursor, element, href, preventDefaultCalled, showDropdown, dropdownPosition }) => {
         const event = new MouseEvent('contextmenu', { clientX: 100, clientY: 200 });

-        const targetElement = document.createElement('div');
+        const targetElement = document.createElement(element);
+        if (href) {
+            (targetElement as HTMLAnchorElement).href = href;
+        }
         Object.defineProperty(event, 'target', { value: targetElement });

349-349: Consider moving mock restoration to afterEach.

Instead of calling jest.restoreAllMocks() within the test, move it to the afterEach block where other cleanup is performed. This ensures consistent cleanup across all tests and follows Jest best practices.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e3ed347 and 523c56e.

📒 Files selected for processing (4)
  • src/main/webapp/app/shared/metis/answer-post/answer-post.component.ts (1 hunks)
  • src/main/webapp/app/shared/metis/post/post.component.ts (1 hunks)
  • src/test/javascript/spec/component/shared/metis/answer-post/answer-post.component.spec.ts (1 hunks)
  • src/test/javascript/spec/component/shared/metis/post/post.component.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
src/main/webapp/app/shared/metis/answer-post/answer-post.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/main/webapp/app/shared/metis/post/post.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/shared/metis/answer-post/answer-post.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}}

src/test/javascript/spec/component/shared/metis/post/post.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/metis/answer-post/answer-post.component.spec.ts (1)

209-211: 🛠️ Refactor suggestion

Use more specific Jest matchers.

According to the coding guidelines, use more specific Jest matchers for boolean and object comparisons.

-expect(component.showDropdown).toBe(showDropdown);
-expect(component.dropdownPosition).toEqual(dropdownPosition);
+expect(component.showDropdown).toBeTrue();
+expect(component.dropdownPosition).toContainEntries(Object.entries(dropdownPosition));

Likely invalid or redundant comment.

src/main/webapp/app/shared/metis/post/post.component.ts (1)

127-146: LGTM! The implementation handles dropdown state correctly

The code properly:

  • Prevents default behavior only when necessary
  • Manages dropdown state and positioning
  • Handles cleanup of previous dropdowns
  • Updates change detection appropriately

This aligns well with Angular's OnPush change detection strategy and maintains proper component state management.

Please verify that:

  1. The dropdown is disabled for all types of links (text links, button links, etc.)
  2. The browser's context menu appears correctly for links
  3. The custom dropdown still works for non-link elements

@asliayk asliayk changed the title Communication: Fix dropdown menu behavior for links to allow default browser options Communication: Fix dropdown menu behavior for links to allow default browser options Nov 20, 2024
@HawKhiem HawKhiem temporarily deployed to artemis-test6.artemis.cit.tum.de November 20, 2024 17:11 — 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 TS6. Works as described.

HawKhiem
HawKhiem previously approved these changes Nov 20, 2024
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 TS5. Everything works as expected!

@asliayk asliayk dismissed stale reviews from PaRangger and coderabbitai[bot] via e32c071 November 27, 2024 21:34
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.

Reapprove, Re-tested on TS1 👍

Copy link
Contributor

@FelberMartin FelberMartin left a comment

Choose a reason for hiding this comment

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

Tested in both Firefox and Chrome, works as described

Copy link
Contributor

@cremertim cremertim 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 ts1, works as expected

Copy link

@julian-wls julian-wls 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 TS1, works as expected.

@krusche krusche merged commit e5ca593 into develop Nov 30, 2024
66 of 70 checks passed
@krusche krusche deleted the bugfix/communication/disable-dropdown-when-there-is-link branch November 30, 2024 08:15
AjayvirS pushed a commit that referenced this pull request Dec 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix client Pull requests that update TypeScript code. (Added Automatically!) component:Communication ready to merge small tests
Projects
Status: Merged
Development

Successfully merging this pull request may close these issues.

Communication: Get standard drop down menu when right clicking a link