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

90.9% Statements 80/88
66.66% Branches 30/45
86.36% Functions 19/22
90.8% Lines 79/87

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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346                                                                                                                1x 37x 37x   37x     37x 37x 37x           37x                     37x             37x             37x           37x             37x           37x           37x           37x                 37x 37x                   37x   37x                       37x 37x           37x             37x         37x         37x         37x         54x   37x 5x     37x 4x     37x 58x 58x 46x 4x         4x   42x     12x 1x     1x             1x 1x 1x         1x 1x       11x             80x       80x 80x 80x   80x 80x 61x     19x 19x   19x 19x   2x             19x 19x 19x       119x       39x       39x                     64x 16x   48x               26x 26x       26x     26x                         26x 26x   26x       26x 26x     37x    
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { NgTemplateOutlet } from '@angular/common';
import {
  Component,
  computed,
  input,
  output,
  booleanAttribute,
  inject,
  contentChild,
  Signal,
  isSignal,
  effect
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { BackgroundColorVariant } from '@siemens/element-ng/common';
import { SiEmptyStateComponent } from '@siemens/element-ng/empty-state';
import { SiInlineNotificationComponent } from '@siemens/element-ng/inline-notification';
import { getMarkdownRenderer } from '@siemens/element-ng/markdown-renderer';
import { MenuItem } from '@siemens/element-ng/menu';
import { SiResponsiveContainerDirective } from '@siemens/element-ng/resize-observer';
import { TranslatableString, t } from '@siemens/element-translate-ng/translate';
 
import {
  AiChatMessage,
  ChatMessage,
  MessageAction,
  TemplateChatMessage
} from './chat-message.model';
import { SiAiMessageComponent } from './si-ai-message.component';
import { SiChatContainerInputDirective } from './si-chat-container-input.directive';
import { SiChatContainerComponent } from './si-chat-container.component';
import { ChatInputAttachment, SiChatInputComponent } from './si-chat-input.component';
import { SiUserMessageComponent } from './si-user-message.component';
 
/** @experimental */
@Component({
  selector: 'si-ai-chat-container',
  imports: [
    NgTemplateOutlet,
    SiEmptyStateComponent,
    SiInlineNotificationComponent,
    SiAiMessageComponent,
    SiUserMessageComponent,
    SiChatContainerComponent,
    SiChatContainerInputDirective
  ],
  templateUrl: './si-ai-chat-container.component.html',
  host: {
    class: 'd-flex si-layout-inner flex-grow-1 flex-column h-100 w-100'
  },
  hostDirectives: [SiResponsiveContainerDirective]
})
export class SiAiChatContainerComponent {
  private readonly chatInput = contentChild<SiChatInputComponent>(SiChatInputComponent);
  private sanitizer = inject(DomSanitizer);
 
  protected markdownRenderer = getMarkdownRenderer(this.sanitizer);
 
  constructor() {
    effect(() => {
      const inputComponent = this.chatInput();
      Iif (inputComponent) {
        inputComponent.registerStates(this.inputSending, this.inputInterruptible);
      }
    });
  }
 
  private messageActionsCache = new WeakMap<
    ChatMessage,
    { primary: MessageAction[]; secondary: MenuItem[] }
  >();
 
  /**
   * List of chat messages to display. Messages can contain either content (string)
   * or a template (TemplateRef) for custom rendering. When both content and template
   * are provided, the template takes precedence.
   * Leave undefined to manage messages via ng-content instead.
   */
  readonly messages = input<ChatMessage[] | undefined>();
 
  /**
   * Whether a message is currently being sent, disables input and shows a loading state in the input area.
   * If you want to show a loading state for the latest AI message, set {@link loading} to true instead.
   * @defaultValue false
   */
  readonly sending = input(false, { transform: booleanAttribute });
 
  /**
   * Whether a pending loading AI message should be shown (e.g. while waiting for response).
   * If you also want to prevent the user from sending new messages, set {@link sending} to true as well.
   * @defaultValue false
   */
  readonly loading = input(false, { transform: booleanAttribute });
 
  /**
   * Whether to disable the interrupt functionality
   * @defaultValue false
   */
  readonly disableInterrupt = input(false, { transform: booleanAttribute });
 
  /**
   * Whether the system is currently interrupting an operation. When true,
   * forces interruptible mode and shows sending state on the input.
   * @defaultValue false
   */
  readonly interrupting = input(false, { transform: booleanAttribute });
 
  /**
   * Disable auto-scroll to bottom when new messages are added
   * @defaultValue false
   */
  readonly noAutoScroll = input(false, { transform: booleanAttribute });
 
  /**
   * Custom AI icon name, used for empty state
   * @defaultValue 'element-ai'
   */
  readonly aiIcon = input('element-ai');
 
  /**
   * Color to use for component background.
   * @defaultValue 'base-0'
   */
  readonly colorVariant = input<BackgroundColorVariant>('base-0');
 
  /**
   * Title for empty state
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_CONTAINER.EMPTY_STATE_TITLE:Start a conversation`)
   * ```
   */
  readonly emptyStateTitle = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_CONTAINER.EMPTY_STATE_TITLE:Start a conversation`)
  );
 
  /**
   * Description for empty state
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_CONTAINER.EMPTY_STATE_DESCRIPTION:Send a message to begin chatting`)
   * ```
   */
  readonly emptyStateDescription = input<TranslatableString>(
    t(
      () => $localize`:@@SI_CHAT_CONTAINER.EMPTY_STATE_DESCRIPTION:Send a message to begin chatting`
    )
  );
 
  /**
   * More actions button aria label
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_CONTAINER.SECONDARY_ACTIONS:More actions`)
   * ```
   */
  readonly secondaryActionsLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_CONTAINER.SECONDARY_ACTIONS:More actions`)
  );
 
  /**
   * Status notification severity
   */
  readonly statusSeverity = input<
    'info' | 'success' | 'caution' | 'warning' | 'danger' | 'critical'
  >();
 
  /**
   * Status notification heading
   */
  readonly statusHeading = input<string>();
 
  /**
   * Status notification message
   */
  readonly statusMessage = input<string>();
 
  /**
   * Status notification action link
   */
  readonly statusAction = input<{ title: string; href: string; target?: string }>();
 
  /**
   * Emitted when a new message is sent
   */
  readonly messageSent = output<{
    content: string;
    attachments: ChatInputAttachment[];
  }>();
 
  protected readonly isEmpty = computed(() => this.messages()?.length === 0 && !this.loading());
 
  protected readonly inputInterruptible = computed(() => {
    return this.interrupting() || (this.loading() && !this.disableInterrupt() && !this.sending());
  });
 
  protected readonly inputSending = computed(() => {
    return this.sending() || this.interrupting();
  });
 
  protected readonly displayMessages = computed(() => {
    const messages = this.messages();
    if (!messages?.length) {
      if (this.loading()) {
        const loadingMessage: AiChatMessage = {
          type: 'ai',
          content: '',
          loading: true
        };
        return [loadingMessage];
      }
      return [];
    }
 
    if (this.loading() && messages.length > 0) {
      const latestMessage = messages[messages.length - 1];
 
      const shouldAddAiMessage =
        this.isTemplateMessage(latestMessage) ||
        (latestMessage.type === 'ai' &&
          this.getContentValue(latestMessage.content) &&
          !this.getLoadingState(latestMessage.loading, latestMessage.content, false) &&
          !this.isStreamingContent(latestMessage.content)) ||
        latestMessage.type === 'user';
 
      if (shouldAddAiMessage) {
        const newMessages = [...messages];
        const loadingMessage: AiChatMessage = {
          type: 'ai',
          content: '',
          loading: true
        };
        newMessages.push(loadingMessage);
        return newMessages;
      }
    }
 
    return messages;
  });
 
  private getMessageActions(message: ChatMessage): {
    primary: MessageAction[];
    secondary: MenuItem[];
  } {
    Iif (this.isTemplateMessage(message)) {
      return { primary: [], secondary: [] };
    }
 
    const actions = message.actions ?? [];
    let primary: MessageAction[] = [];
    let secondary: MenuItem[] = [];
 
    const cached = this.messageActionsCache.get(message);
    if (cached) {
      return cached;
    }
 
    const primaryActions = actions.slice(0, 3);
    const secondaryActions = actions.slice(3);
 
    primary = primaryActions;
    secondary = secondaryActions.map(
      action =>
        ({
          ...action,
          action: action.action as unknown as (actionParam: any, source: MenuItem) => void,
          type: 'action'
        }) as MenuItem
    );
 
    const result = { primary, secondary };
    this.messageActionsCache.set(message, result);
    return result;
  }
 
  protected isTemplateMessage(message: ChatMessage): message is TemplateChatMessage {
    return 'template' in message && message.template !== undefined;
  }
 
  protected getMessagePrimaryActions(message: ChatMessage): MessageAction[] {
    return this.getMessageActions(message).primary;
  }
 
  protected getMessageSecondaryActions(message: ChatMessage): MenuItem[] {
    return this.getMessageActions(message).secondary;
  }
 
  public focus(): void {
    const inputComponent = this.chatInput();
    Iif (inputComponent) {
      inputComponent.focus();
    }
  }
 
  protected getContentValue(content: string | Signal<string> | undefined): string {
    if (isSignal(content)) {
      return content();
    }
    return content ?? '';
  }
 
  protected getOutputValue(content: string | Signal<string> | undefined): string | Signal<string> {
    return content ?? '';
  }
 
  private isEmptyContent(content: string | Signal<string> | undefined): boolean {
    const contentValue = this.getContentValue(content);
    return !contentValue || contentValue.trim().length === 0;
  }
 
  private getLoadingValue(loading: boolean | Signal<boolean> | undefined): boolean {
    Iif (isSignal(loading)) {
      return loading();
    }
    return loading ?? false;
  }
 
  private isStreamingContent(content: string | Signal<string> | undefined): boolean {
    return isSignal(content) && this.getContentValue(content).trim().length > 0;
  }
 
  protected getLoadingState(
    messageLoading: boolean | Signal<boolean> | undefined,
    content: string | Signal<string> | undefined,
    isLatest: boolean,
    globalLoading: boolean = false
  ): boolean {
    const messageLoadingValue = this.getLoadingValue(messageLoading);
    const isEmptyContent = this.isEmptyContent(content);
 
    return messageLoadingValue || (isLatest && globalLoading && isEmptyContent);
  }
 
  protected isLatestMessage(message: ChatMessage): boolean {
    const messages = this.displayMessages();
    return messages[messages.length - 1] === message;
  }
 
  protected readonly isSignal = isSignal;
}