All files / chat-messages si-chat-container.component.ts

54.66% Statements 41/75
45.83% Branches 11/24
58.82% Functions 10/17
54.66% Lines 41/75

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222                                                                                            1x 20x 20x   20x   20x 20x 20x               20x           20x 4x       20x 19x 19x 19x           20x       21x     21x 20x   21x 20x         20x       20x 20x       20x 20x                                                         19x       19x 19x       19x       19x       19x       19x 19x       19x       19x               1x 1x       1x 1x 1x         1x                                                                    
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { isPlatformBrowser } from '@angular/common';
import {
  AfterContentInit,
  Component,
  effect,
  ElementRef,
  input,
  OnDestroy,
  PLATFORM_ID,
  viewChild,
  inject
} from '@angular/core';
 
/**
 * A declarative container component for displaying a chat interface with automatic scroll-to-bottom behavior.
 *
 * This component provides the layout and styling for a chat interface, managing scrolling behavior
 * to keep the newest messages visible while respecting user scrolling actions. It automatically
 * scrolls to the bottom when new content is added, unless the user has scrolled up to view older messages.
 *
 * Use via content projection:
 * - Default content: Chat messages displayed in the scrollable messages container or a welcome screen (empty state).
 * - `si-inline-notification` selector: Notification component displayed above the input area
 * - `si-chat-input` or `[siChatContainerInput]` selector: Input controls for composing messages
 *
 * @see {@link SiChatInputComponent} for the chat input wrapper component
 * @see {@link SiChatContainerInputDirective} for other input controls to slot in
 * @see {@link SiAiMessageComponent} for AI messages to slot in
 * @see {@link SiUserMessageComponent} for user messages (in AI chats) to slot in
 * @see {@link SiChatMessageComponent} for the chat message wrapper component to slot in other messages
 *
 * @experimental
 */
@Component({
  selector: 'si-chat-container',
  templateUrl: './si-chat-container.component.html',
  styleUrl: './si-chat-container.component.scss',
  host: {
    class: 'd-flex si-layout-inner flex-grow-1 flex-column h-100 w-100',
    '[class]': 'colorVariant()'
  }
})
export class SiChatContainerComponent implements AfterContentInit, OnDestroy {
  private readonly messagesContainer = viewChild<ElementRef<HTMLDivElement>>('messagesContainer');
  private readonly platformId = inject(PLATFORM_ID);
 
  private isUserAtBottom = true;
  private scrollTimeout: ReturnType<typeof setTimeout> | undefined;
  private lastScrollTime = 0;
  private pendingScroll = false;
  private scrollDebounceMs = 7; // ~144fps
  private resizeObserver: ResizeObserver | undefined;
  private contentObserver: MutationObserver | undefined;
 
  /**
   * The color variant to apply to the container.
   * @defaultValue 'base-0'
   */
  readonly colorVariant = input<string>('base-0');
 
  /**
   * Disables automatic scrolling to the bottom when new content is added.
   * @defaultValue false
   */
  readonly noAutoScroll = input(false, {
    transform: (value: boolean | string) => value === '' || value === true
  });
 
  constructor() {
    effect(() => {
      if (this.messagesContainer()) {
        this.setupResizeObserver();
        this.setupContentObserver();
      }
    });
  }
 
  ngAfterContentInit(): void {
    this.scrollToBottomDuringStreaming();
  }
 
  ngOnDestroy(): void {
    Iif (this.scrollTimeout) {
      clearTimeout(this.scrollTimeout);
    }
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    if (this.contentObserver) {
      this.contentObserver.disconnect();
    }
  }
 
  private scrollToBottomDuringStreaming(): void {
    Iif (this.noAutoScroll() || !this.isUserAtBottom) {
      return;
    }
 
    const container = this.messagesContainer();
    Iif (!container) {
      return;
    }
 
    const element = container.nativeElement;
    element.scrollTop = element.scrollHeight;
  }
 
  private debouncedScrollToBottom(): void {
    const now = Date.now();
    const timeSinceLastScroll = now - this.lastScrollTime;
 
    if (timeSinceLastScroll >= this.scrollDebounceMs) {
      this.lastScrollTime = now;
      this.scrollToBottomDuringStreaming();
      this.pendingScroll = false;
    } else {
      this.pendingScroll = true;
    }
 
    Iif (this.scrollTimeout) {
      clearTimeout(this.scrollTimeout);
    }
 
    this.scrollTimeout = setTimeout(() => {
      Iif (this.pendingScroll) {
        this.lastScrollTime = Date.now();
        this.scrollToBottomDuringStreaming();
        this.pendingScroll = false;
      }
    }, this.scrollDebounceMs);
  }
 
  private setupResizeObserver(): void {
    Iif (!isPlatformBrowser(this.platformId)) {
      return;
    }
 
    const container = this.messagesContainer();
    Iif (!container || this.resizeObserver) {
      return;
    }
 
    this.resizeObserver = new ResizeObserver(() => {
      this.debouncedScrollToBottom();
    });
 
    this.resizeObserver.observe(container.nativeElement);
  }
 
  private setupContentObserver(): void {
    Iif (!isPlatformBrowser(this.platformId)) {
      return;
    }
 
    const container = this.messagesContainer();
    Iif (!container || this.contentObserver) {
      return;
    }
 
    this.contentObserver = new MutationObserver(() => {
      this.debouncedScrollToBottom();
    });
 
    this.contentObserver.observe(container.nativeElement, {
      childList: true,
      subtree: true,
      characterData: true
    });
  }
 
  private checkIfUserAtBottom(): void {
    const container = this.messagesContainer();
    Iif (!container) {
      return;
    }
 
    const element = container.nativeElement;
    const threshold = 100;
    this.isUserAtBottom =
      element.scrollHeight - element.scrollTop - element.clientHeight < threshold;
  }
 
  protected onScroll(): void {
    this.checkIfUserAtBottom();
  }
 
  /**
   * Scrolls to the bottom of the messages container immediately.
   * This method forces a scroll even if the user has scrolled up.
   */
  public scrollToBottom(): void {
    this.isUserAtBottom = true;
    this.scrollToBottomDuringStreaming();
  }
 
  /**
   * Scrolls to the top of the messages container immediately.
   */
  public scrollToTop(): void {
    const container = this.messagesContainer();
    Iif (!container) {
      return;
    }
 
    const element = container.nativeElement;
    element.scrollTop = 0;
    this.isUserAtBottom = false;
  }
 
  /**
   * Focuses the messages container element.
   */
  public focus(): void {
    const container = this.messagesContainer();
    container?.nativeElement.focus();
  }
}