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: Update group postings in-place #10283

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

badkeyy
Copy link
Contributor

@badkeyy badkeyy commented Feb 6, 2025

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 principle of data economy for all client-server REST calls.
  • I strictly followed the client coding and design guidelines.
  • Following the theming guidelines, I specified colors only in the theming variable files and checked that the changes look consistent in both the light and the dark theme.
  • I added multiple integration tests (Jest) related to the features (with a high test coverage), while following the test guidelines.
  • I added authorities to all new routes and checked the course groups for displaying navigation elements (links, buttons).
  • I documented the TypeScript code using JSDoc style.
  • I added multiple screenshots/screencasts of my UI changes.
  • I translated all newly inserted strings into English and German.

Changes affecting Programming Exercises

  • High priority: I tested all changes and their related features with all corresponding user types on a test server configured with the integrated lifecycle setup (LocalVC and LocalCI).
  • I tested all changes and their related features with all corresponding user types on a test server configured with Gitlab and Jenkins.

Motivation and Context

Currently when a new post is published all post groupings get updated by completely recreating them. However this triggers the ngOnDestroy hook in the postings which results in the deletion mechanism to not work as expected (Fixes issue #10246).

Description

With this PR we now update groups in place (deletions, additions, new groups) which results in the ngOnDestroy hook not being called.

Steps for Testing

Prerequisites:

  • 1 Instructor
  1. Log in to Artemis
  2. Navigate to Course Communication
  3. Write at least 2 messages
  4. Delete both with a small delay in between the deletions
  5. Find the postings to be deleted consecutively and not at one
  6. (Optionally do the same and switch pages and find both postings to be instantly deleted)

Testserver States

You can manage test servers using Helios. Check environment statuses in the environment list. To deploy to a test server, go to the CI/CD page, find your PR or branch, and trigger the deployment.

Review Progress

Performance Review

  • I (as a reviewer) confirm that the client changes (in particular related to REST calls and UI responsiveness) are implemented with a very good performance even for very large courses with more than 2000 students.
  • I (as a reviewer) confirm that the server changes (in particular related to database calls) are implemented with a very good performance even for very large courses with more than 2000 students.

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Exam Mode Test

  • Test 1
  • Test 2

Performance Tests

  • Test 1
  • Test 2

Test Coverage

Screenshots

video

Summary by CodeRabbit

  • Refactor
    • Enhanced the organization of conversation messages for a clearer display. Pinned messages are now distinctly separated from others, while unpinned messages are chronologically sorted. This refined grouping delivers a more intuitive and efficient viewing experience in conversation threads.

@badkeyy badkeyy requested a review from a team as a code owner February 6, 2025 22:19
@github-actions github-actions bot added the client Pull requests that update TypeScript code. (Added Automatically!) label Feb 6, 2025
Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

The pull request refines the grouping logic within the ConversationMessagesComponent by modifying how posts are grouped. The changes include updating comments for clarity, switching from a “groups” array to an “updatedGroups” array, and incorporating a time difference check (using the diff method on creationDateDayjs) for consecutive posts. The grouping process now increments the groupedPosts array efficiently by updating and cleaning up excess groups. No changes were made to exported or public declarations.

Changes

File(s) Change Summary
src/.../conversation-messages.component.ts Refactored the grouping logic by replacing the old groups array with an updatedGroups array; updated comments for clarity; added a time difference check using diff(); and ensured incremental update of groupedPosts with removal of any excess groups.

Sequence Diagram(s)

sequenceDiagram
    participant CMP as ConversationMessagesComponent
    participant SP as SortedPosts
    participant UG as UpdatedGroups
    participant GP as GroupedPosts

    CMP->>SP: Check for available posts
    alt Posts exist
      CMP->>UG: Initialize grouping with the first post
      loop For each post in SP
        CMP->>UG: Compare time diff with previous post (using diff)
        alt Time difference within threshold
           CMP->>UG: Append post to current group
        else
           CMP->>UG: Start a new group
        end
      end
      CMP->>GP: Update groupedPosts using updatedGroups (remove excess groups)
    else No posts
      CMP->>GP: Skip grouping update
    end
Loading

Possibly related PRs

Suggested labels

client, small, bugfix, ready to merge, component:Communication

Suggested reviewers

  • HawKhiem
  • FelberMartin
  • krusche
  • asliayk
  • vinceclifford

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

🧹 Nitpick comments (2)
src/main/webapp/app/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts (2)

284-287: Extract time difference threshold to a constant.

The 5-minute threshold for grouping consecutive messages should be defined as a named constant for better maintainability.

+private readonly CONSECUTIVE_MESSAGE_TIME_THRESHOLD_MINUTES = 5;

-if (currentPost.author?.id === currentGroup.author?.id && timeDiff < 5 && timeDiff >= 0) {
+if (currentPost.author?.id === currentGroup.author?.id && timeDiff < this.CONSECUTIVE_MESSAGE_TIME_THRESHOLD_MINUTES && timeDiff >= 0) {

409-414: Add error handling for scroll operations.

The scroll operation could fail if the DOM elements are not ready. Consider adding try-catch blocks for robustness.

 scrollToBottomOfMessages() {
     // Use setTimeout to ensure the scroll happens after the new message is rendered
     requestAnimationFrame(() => {
+        try {
             this.content.nativeElement.scrollTop = this.content.nativeElement.scrollHeight;
+        } catch (error) {
+            console.error('Failed to scroll to bottom:', error);
+        }
     });
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc1e3cb and a3db1c8.

📒 Files selected for processing (1)
  • src/main/webapp/app/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/main/webapp/**/*.ts`: angular_style:https://angular.io/...

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/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Call Build Workflow / Build .war artifact
  • GitHub Check: Call Build Workflow / Build and Push Docker Image
  • GitHub Check: server-tests
  • GitHub Check: client-tests
  • GitHub Check: Analyse
🔇 Additional comments (3)
src/main/webapp/app/overview/course-conversations/layout/conversation-messages/conversation-messages.component.ts (3)

54-55: Consider the implications of ViewEncapsulation.None.

Using ViewEncapsulation.None makes the component's styles global, which could lead to style leaks and unintended side effects in other components. Consider using ViewEncapsulation.Emulated (default) or ViewEncapsulation.ShadowDom for better style encapsulation.


195-200: LGTM! Proper cleanup in ngOnDestroy.

The component correctly handles cleanup of subscriptions and event listeners, preventing memory leaks.


311-324: LGTM! Efficient in-place group updates.

The implementation efficiently updates groups in-place, preventing unnecessary recreation of post groups and avoiding the ngOnDestroy trigger issue mentioned in PR #10246.

Copy link

@HanyangXu0508 HanyangXu0508 left a comment

Choose a reason for hiding this comment

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

The 2 messages are deleted together but not as we want.

@badkeyy
Copy link
Contributor Author

badkeyy commented Feb 7, 2025

The 2 messages are deleted together but not as we want.

What do you mean? Does the behaviour differ to the video I made?

const lastPostInGroup = currentGroup.posts[currentGroup.posts.length - 1];
// Build updated groups for non-pinned posts.
const updatedGroups: PostGroup[] = [];
if (sortedPosts.length > 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
if (sortedPosts.length > 0) {
if (sortedPosts.length) {

Comment on lines +284 to +287
let timeDiff = Number.MAX_SAFE_INTEGER;
if (currentDate && lastDate) {
timeDiff = currentDate.diff(lastDate, 'minute');
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
let timeDiff = Number.MAX_SAFE_INTEGER;
if (currentDate && lastDate) {
timeDiff = currentDate.diff(lastDate, 'minute');
}
const timeDiff = currentDate && lastDate ? currentDate.diff(lastDate, 'minute') : Number.MAX_SAFE_INTEGER;


const currentDate = (currentPost as any).creationDateDayjs;
const lastDate = (lastPostInGroup as any).creationDateDayjs;
if (pinnedPosts.length > 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
if (pinnedPosts.length > 0) {
if (pinnedPosts.length) {

Comment on lines +305 to +309
const groupsEqual = (groupA: PostGroup, groupB: PostGroup): boolean => {
if (!groupA.author && !groupB.author) return true;
if (!groupA.author || !groupB.author) return false;
return groupA.author.id === groupB.author.id;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Could you transform it into a function and simplify it? Please rename it something the function is actually doing.

function isAuthorEqual(groupA: PostGroup, groupB: PostGroup): boolean {
    // Both groups are equal if neither has an author; otherwise, they are not
    if (!groupA.author || !groupB.author) {
        return !groupA.author && !groupB.author;
    }
    return groupA.author.id === groupB.author.id;
}

Comment on lines +311 to 324
for (let i = 0; i < updatedGroups.length; i++) {
if (this.groupedPosts[i] && groupsEqual(this.groupedPosts[i], updatedGroups[i])) {
this.groupedPosts[i].posts = updatedGroups[i].posts;
} else {
groups.push(currentGroup);
currentGroup = {
author: currentPost.author,
posts: [{ ...currentPost, isConsecutive: false }],
};
if (this.groupedPosts[i]) {
this.groupedPosts[i] = updatedGroups[i];
} else {
this.groupedPosts.push(updatedGroups[i]);
}
}
}

groups.push(currentGroup);

// Only add pinned group if pinned posts exist
if (pinnedPosts.length > 0) {
groups.unshift({ author: undefined, posts: pinnedPosts });
while (this.groupedPosts.length > updatedGroups.length) {
this.groupedPosts.pop();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

It's super hard to grasp what's happening in here.
Can you please improve this? Please use forEach instead of for(...) since there is no need for the for loop. Also, refactor it to avoid the nested if and else structure and avoid using the while loop. Feel free to ping me on Slack, and I'll discuss some ideas for improvement with you.

@HanyangXu0508
Copy link

HanyangXu0508 commented Feb 7, 2025 via email

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!)
Projects
Status: Ready For Review
Development

Successfully merging this pull request may close these issues.

3 participants