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 when referencing lectures that contain brackets in title #9528

Merged
merged 2 commits into from
Oct 19, 2024

Conversation

PaRangger
Copy link
Contributor

@PaRangger PaRangger commented Oct 19, 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.
  • 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.

Motivation and Context

Currently, it is possible to reference lectures, attachments, and attachment units that include brackets in their names. However, since round and square brackets are used for markdown syntax in the Monaco editor, their presence in names causes the generated links to break and become non-functional.

Description

I have implemented a function in the frontend that automatically removes both round and square brackets from reference titles and names. This ensures that users cannot inadvertently include brackets in their references, preventing potential issues with broken links.

Steps for Testing

Prerequisites:

  • 1 Instructor
  • 1 Course with communication enabled
  1. Log in to Artemis
  2. Navigate to course management
  3. Click on the course
  4. Go to lectures and create a lecture with attachments and pdf file units. Make sure to include brackets in all their names.
  5. Navigate to communication
  6. Select a channel
  7. Reference the created attachments and lectures
  8. Verify only the brackets that are used to link to the given resource are present

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

Statements : 87.44% ( 55105/63015 )
Branches : 73.63% ( 20722/28142 )
Functions : 82.03% ( 12343/15046 )
Lines : 87.5% ( 52622/60136 )

Screenshots

Bildschirmaufnahme 2024-10-19 um 15 54 30

Summary by CodeRabbit

  • New Features

    • Enhanced string handling for markdown references by sanitizing input to remove specific syntax symbols.
  • Bug Fixes

    • Improved formatting of references to attachments and lectures to ensure they do not include brackets when special characters are present.
  • Tests

    • Added new integration tests to validate the correct formatting of references in various scenarios, including edge cases.

@github-actions github-actions bot added tests client Pull requests that update TypeScript code. (Added Automatically!) labels Oct 19, 2024
@PaRangger PaRangger added component:Communication communication Pull requests that affect the corresponding module small deploy:artemis-test1 labels Oct 19, 2024
@PaRangger PaRangger temporarily deployed to artemis-test1.artemis.cit.tum.de October 19, 2024 14:06 — with GitHub Actions Inactive
@PaRangger PaRangger marked this pull request as ready for review October 19, 2024 14:38
@PaRangger PaRangger requested a review from a team as a code owner October 19, 2024 14:38
Copy link

coderabbitai bot commented Oct 19, 2024

Walkthrough

The changes in this pull request involve modifications to the LectureAttachmentReferenceAction class to include a new private method, sanitizeStringForMarkdownEditor, which sanitizes strings by removing specific markdown syntax symbols. This method is used in several existing methods to ensure that references are formatted correctly when inserted into the editor. Additionally, the integration tests for the MonacoEditorCommunicationAction component have been updated to include new test cases that validate the formatting of references, particularly focusing on handling special characters and ensuring proper error handling for nonexistent references.

Changes

File Change Summary
src/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.ts - Added method: `private sanitizeStringForMarkdownEditor(str: string
src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts - New import: Attachment from app/entities/attachment.model
- New test cases added for handling attachments and lectures without brackets.
- Tests validate formatting and error handling for references.

Possibly related PRs

Suggested labels

bugfix

Suggested reviewers

  • JohannesStoehr
  • florian-glombik
  • az108
  • egekurt123
  • krusche

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

🧹 Outside diff range and nitpick comments (9)
src/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.ts (5)

112-115: LGTM with a minor suggestion for readability.

The changes look good and address the PR objective of fixing issues with brackets in titles. The use of the sanitizeStringForMarkdownEditor method ensures that the lecture title is properly sanitized before being inserted into the editor.

Consider extracting the string template into a separate constant for improved readability:

const lectureReferenceTemplate = `[lecture]${this.sanitizeStringForMarkdownEditor(lecture.title)}(${this.metisService.getLinkForLecture(lecture.id.toString())})[/lecture]`;
this.replaceTextAtCurrentSelection(editor, lectureReferenceTemplate);

This change would make the code more readable and easier to maintain.


120-120: LGTM with a minor suggestion for readability.

The changes look good and address the PR objective of fixing issues with brackets in attachment names. The use of the sanitizeStringForMarkdownEditor method ensures that the attachment name is properly sanitized before being inserted into the editor.

Consider extracting the string template into a separate constant for improved readability:

const attachmentReferenceTemplate = `[attachment]${this.sanitizeStringForMarkdownEditor(attachment.name)}(${shortLink})[/attachment]`;
this.replaceTextAtCurrentSelection(editor, attachmentReferenceTemplate);

This change would make the code more readable and easier to maintain.


127-130: LGTM with a minor suggestion for readability.

The changes look good and address the PR objective of fixing issues with brackets in attachment unit names. The use of the sanitizeStringForMarkdownEditor method ensures that the attachment unit name is properly sanitized before being inserted into the editor.

Consider extracting the string template into a separate constant for improved readability:

const slideReferenceTemplate = `[slide]${this.sanitizeStringForMarkdownEditor(attachmentUnit.name)} Slide ${slide.slideNumber}(${shortLinkWithoutFileName})[/slide]`;
this.replaceTextAtCurrentSelection(editor, slideReferenceTemplate);

This change would make the code more readable and easier to maintain.


135-136: LGTM with a minor suggestion for readability.

The changes look good and address the PR objective of fixing issues with brackets in attachment unit names. The use of the sanitizeStringForMarkdownEditor method ensures that the attachment unit name is properly sanitized before being inserted into the editor.

Consider extracting the string template into a separate constant for improved readability:

const attachmentUnitReferenceTemplate = `[lecture-unit]${this.sanitizeStringForMarkdownEditor(attachmentUnit.name)}(${shortLink})[/lecture-unit]`;
this.replaceTextAtCurrentSelection(editor, attachmentUnitReferenceTemplate);

This change would make the code more readable and easier to maintain.


138-154: LGTM with a minor optimization suggestion.

The new sanitizeStringForMarkdownEditor method effectively addresses the PR objective by removing brackets from the input string. The implementation is concise, handles undefined input, and follows TypeScript best practices.

Consider using a regular expression for a more efficient implementation:

private sanitizeStringForMarkdownEditor(str: string | undefined): string | undefined {
    if (str === undefined) {
        return str;
    }

    return str.replace(/[\(\)\[\]]/g, '');
}

This change would achieve the same result with a single replace operation, potentially improving performance for longer strings.

src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts (4)

Line range hint 23-23: Avoid full module import of 'monaco-editor'

Importing the entire monaco-editor module can increase bundle size and affect performance. Consider importing only the necessary members to optimize the build.

Apply this diff to import only the required parts:

-import * as monaco from 'monaco-editor';
+import { languages, Position } from 'monaco-editor';

Ensure that all references to monaco in the code are updated accordingly.


298-299: Use robust methods for extracting the short link

Using split('attachments/') to extract shortLink may be fragile if the URL structure changes. Consider using URL parsing utilities or regular expressions to reliably extract the desired part of the link.

For example:

const url = new URL(newAttachment.link!, 'http://localhost');
const shortLink = url.pathname.split('/attachments/')[1];

This approach reduces the dependency on the exact format of the link.


312-315: Avoid mutating shared objects in tests

Directly modifying lecture.title and then restoring it can lead to unintended side effects if other tests rely on the original value. To prevent this, create a copy of the lecture object with the modified title.

Apply this change:

-const lecture = lectureAttachmentReferenceAction.lecturesWithDetails[0];
-const previousTitle = lecture.title;
-lecture.title = lectureNameWithBrackets;
+const lecture = { ...lectureAttachmentReferenceAction.lecturesWithDetails[0], title: lectureNameWithBrackets };

This ensures that the original lecture object remains unmodified.


328-335: Avoid mutating shared objects in tests

Changing attachmentUnit.name directly may affect other tests. Consider cloning the attachmentUnit object before modifying it to avoid side effects.

Apply this change:

-const attachmentUnit = lecture.attachmentUnits![0];
-const previousName = attachmentUnit.name;
-attachmentUnit.name = attachmentUnitNameWithBrackets;
+const attachmentUnit = { ...lecture.attachmentUnits![0], name: attachmentUnitNameWithBrackets };

This creates a new attachmentUnit instance for this test case.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f0d60cb and aa6421c.

📒 Files selected for processing (2)
  • src/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.ts (1 hunks)
  • src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.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/monaco-editor/monaco-editor-communication-action.integration.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/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.ts (1)

Line range hint 1-154: Overall implementation looks great!

The changes in this file effectively address the PR objective of fixing issues with brackets in lecture titles, attachment names, and other references. The new sanitizeStringForMarkdownEditor method is well-implemented and used consistently throughout the class.

Key points:

  1. The sanitization logic prevents broken links in the Monaco editor by removing problematic characters.
  2. The changes are consistent across all reference insertion methods.
  3. The implementation follows TypeScript best practices and coding guidelines.

The minor suggestions for readability (extracting string templates) and optimization (using a regex in the sanitization method) would further improve the code quality, but the current implementation is already solid and meets the requirements.

Great job on addressing this issue and improving the robustness of the reference insertion functionality!

src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts (1)

29-30: Imports are appropriate

The additions of Attachment and dayjs imports are necessary for the new test cases and are correctly implemented.

Copy link

⚠️ Unable to deploy to test servers ⚠️

Testserver "artemis-test1.artemis.cit.tum.de" is already in use by PR #9522.

@github-actions github-actions bot added the deployment-error Added by deployment workflows if an error occured label Oct 19, 2024
@HawKhiem HawKhiem added deploy:artemis-test1 and removed deployment-error Added by deployment workflows if an error occured labels Oct 19, 2024
@HawKhiem HawKhiem temporarily deployed to artemis-test1.artemis.cit.tum.de October 19, 2024 19:12 — with GitHub Actions Inactive
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.

Code looks good to me 👍

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!) communication Pull requests that affect the corresponding module component:Communication ready for review small tests
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

5 participants