All files / element-ng/chat-messages si-chat-input.component.ts

88.78% Statements 190/214
78.37% Branches 116/148
85.45% Functions 47/55
89.34% Lines 176/197

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 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710                                                                                                                                                                                                          294x 1x 86x 86x 86x 86x 86x 86x                           86x           86x             86x             86x                 86x 86x                   86x 86x                   86x 86x                   86x 86x       86x     86x     86x                   86x 86x             86x           86x               86x         86x               86x           86x           86x           86x           86x           86x           86x                 86x     86x                   86x 86x               86x                   86x 86x             86x                   86x 86x                       86x 86x                     86x 86x                 86x           86x         86x               86x         86x   86x 86x 86x 86x 86x 100x   86x 99x   86x 42x   86x 86x                             86x         86x 64x             86x 71x   86x 103x 32x   71x 8x   63x   86x 97x           86x 97x             86x     86x 90x 90x 90x 90x       86x 86x 100x 100x 62x   38x 38x 4x   34x 100x 100x 100x 100x         27x   7x 2x 2x   5x 5x           3x 3x       7x 7x         7x 7x         9x     9x 5x 4x   5x   4x 2x   2x         16x 8x   8x 7x 7x 1x   6x 3x 3x   3x     3x 1x   3x         3x     3x 2x   1x         15x               1x 1x   14x 1x 1x 1x         1x       3x   2x 2x 2x             2x         1x       1x 2x         9x     9x               9x             82x 82x 82x                         3x 3x 3x                                                           91x   91x   91x 91x 91x 91x   91x 91x 91x 91x   91x 91x 91x      
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkMenuTrigger } from '@angular/cdk/menu';
import {
  afterRenderEffect,
  AfterViewInit,
  booleanAttribute,
  Component,
  computed,
  ElementRef,
  input,
  model,
  output,
  signal,
  viewChild
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  elementAttachment,
  elementCheckedFilled,
  elementPlus,
  elementSendFilled,
  elementStateClose,
  elementStopFilled,
  elementVoice
} from '@siemens/element-icons';
import {
  SiFileUploadDirective,
  UploadFile,
  FileUploadError
} from '@siemens/element-ng/file-uploader';
import { addIcons, SiIconComponent } from '@siemens/element-ng/icon';
import { MenuItem, SiMenuFactoryComponent } from '@siemens/element-ng/menu';
import { SiTooltipDirective } from '@siemens/element-ng/tooltip';
import { SiTranslatePipe, TranslatableString, t } from '@siemens/element-translate-ng/translate';
 
import { MessageAction } from './message-action.model';
import { Attachment, SiAttachmentListComponent } from './si-attachment-list.component';
import { SiVoiceWaveformComponent } from './si-voice-waveform.component';
 
/**
 * Attachment item interface for file attachments in chat messages, extension of {@link Attachment} for {@link SiAttachmentListComponent} to use within {@link SiChatInputComponent}.
 * Adds the action file information.
 * Can be used within {@link SiChatContainerComponent}.
 *
 * @see {@link Attachment} for base attachment interface
 * @see {@link SiAttachmentListComponent} for the attachment list component
 * @see {@link SiChatInputComponent} for the chat input component
 * @see {@link SiChatContainerComponent} for the chat container component
 *
 * @experimental
 */
export interface ChatInputAttachment extends Attachment {
  /** File object */
  file: File;
  /** File size in bytes */
  size: number;
  /** MIME type */
  type: string;
}
 
/**
 * Chat input component for composing and sending messages in conversational interfaces.
 *
 * The chat input component provides a text area for users to compose messages,
 * supporting text, attachments, and contextual actions. It appears as a textarea
 * with buttons for adding attachments and sending messages, as well as an optional disclaimer.
 *
 * The component automatically handles:
 * - Styling for chat input and actions.
 * - Dynamic resizing of the textarea based on content.
 * - Uploading of and displaying of attachments above the input area.
 * - Displaying primary and secondary actions.
 *
 * Additionally to the inputs and outputs documented here, the component supports content projection via the following slots:
 * - Default content: Custom action buttons to display inline, prefer using the `actions` input for buttons, can be used in addition.
 * - `siChatInputDisclaimer` selector: Custom disclaimer content to display below the input area, prefer using the `disclaimer` input for simple text disclaimers.
 *
 * @see {@link SiAttachmentListComponent} for the base attachment component
 * @see {@link SiChatInputDisclaimerDirective} to slot in custom disclaimer content
 *
 * @experimental
 */
@Component({
  selector: 'si-chat-input',
  imports: [
    CdkMenuTrigger,
    FormsModule,
    SiIconComponent,
    SiTranslatePipe,
    SiAttachmentListComponent,
    SiMenuFactoryComponent,
    SiFileUploadDirective,
    SiTooltipDirective,
    SiVoiceWaveformComponent
  ],
  templateUrl: './si-chat-input.component.html',
  styleUrl: './si-chat-input.component.scss'
})
export class SiChatInputComponent implements AfterViewInit {
  private static idCounter = 0;
  private readonly textInput = viewChild<ElementRef<HTMLTextAreaElement>>('textInput');
  private readonly voiceButton = viewChild<ElementRef<HTMLButtonElement>>('voiceButton');
  private readonly submitButton = viewChild<ElementRef<HTMLButtonElement>>('submitButton');
  private readonly fileUploadDirective = viewChild(SiFileUploadDirective);
  protected readonly fileInput = viewChild<ElementRef<HTMLInputElement>>('fileInput');
  protected readonly icons = addIcons({
    elementAttachment,
    elementCheckedFilled,
    elementPlus,
    elementSendFilled,
    elementStateClose,
    elementStopFilled,
    elementVoice
  });
 
  /**
   * Current input value
   * @defaultValue ''
   */
  readonly value = model<string>('');
 
  /**
   * Whether voice input controls are available. Speech recognition is managed by the consumer.
   * @defaultValue false
   */
  readonly voiceInput = input(false, { transform: booleanAttribute });
 
  /**
   * Consumer-controlled voice input state. Use listening during startup and while awaiting speech,
   * and recording when transcription starts. Stream transcript updates through {@link value}.
   * @defaultValue 'idle'
   */
  readonly voiceInputState = input<'idle' | 'listening' | 'recording'>('idle');
 
  /**
   * Latest normalized audio level, from 0 (silence) to 1 (maximum volume).
   * Omit to use simulated speech bursts while recording. Audio capture is managed by the consumer.
   * @defaultValue undefined
   */
  readonly voiceInputLevel = input<number>();
 
  /**
   * Start dictation button label.
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.START_DICTATION:Start dictation`)
   * ```
   */
  readonly startDictationLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.START_DICTATION:Start dictation`)
  );
 
  /**
   * Cancel dictation button label.
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.CANCEL_DICTATION:Cancel dictation`)
   * ```
   */
  readonly cancelDictationLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.CANCEL_DICTATION:Cancel dictation`)
  );
 
  /**
   * Confirm dictation button label.
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.CONFIRM_DICTATION:Confirm dictation`)
   * ```
   */
  readonly confirmDictationLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.CONFIRM_DICTATION:Confirm dictation`)
  );
 
  /**
   * Placeholder while waiting for speech.
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.LISTENING:Listening…`)
   * ```
   */
  readonly listeningLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.LISTENING:Listening…`)
  );
 
  /** Requests that the consumer start speech recognition. Does not change the state or value. */
  readonly voiceInputStart = output<void>();
 
  /** Requests that the consumer stop recognition and keep the transcript for review, without sending. */
  readonly voiceInputConfirm = output<void>();
 
  /** Requests that the consumer stop recognition and restore the draft from before dictation. */
  readonly voiceInputCancel = output<void>();
 
  /**
   * Placeholder text for the input
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.PLACEHOLDER:Enter a message…`)
   * ```
   */
  readonly placeholder = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.PLACEHOLDER:Enter a message…`)
  );
 
  /**
   * Whether the input is disabled
   * @defaultValue false
   */
  readonly disabled = input(false, { transform: booleanAttribute });
 
  /**
   * Whether a message is currently being sent, also prevent the sending of new ones while still allowing the user to type
   * @defaultValue false
   */
  readonly sending = input(false, { transform: booleanAttribute });
 
  /**
   * Whether the input supports interrupting ongoing operations. When active,
   * the send button transforms into an interrupt button (with element-stop-filled icon).
   * If sending is true, the interrupt button will be disabled.
   * @defaultValue false
   */
  readonly interruptible = input(false, { transform: booleanAttribute });
 
  /**
   * Maximum number of characters allowed
   */
  readonly maxLength = input<number>();
 
  /**
   * A disclaimer to display.
   *
   * If not provided, the component will look for projected content with the `siChatInputDisclaimer` directive.
   * If both are empty, no disclaimer section will be shown (handled via CSS :empty).
   */
  readonly disclaimer = input<TranslatableString>();
 
  /**
   * Primary actions available in the input. Provide at most one action.
   * @defaultValue []
   */
  readonly actions = input<MessageAction[]>([]);
 
  /**
   * Secondary actions available in dropdown menu
   * @defaultValue []
   */
  readonly secondaryActions = input<MenuItem[]>([]);
 
  /**
   * Whether file attachments are supported
   * @defaultValue false
   */
  readonly allowAttachments = input(false);
 
  /**
   * Accepted file types for attachments (as accept string)
   * @defaultValue undefined
   */
  readonly accept = input<string>();
 
  /**
   * Maximum file size in bytes
   * @defaultValue 10485760 (10MB)
   */
  readonly maxFileSize = input(10485760);
 
  /**
   * Current attachments
   * @defaultValue []
   */
  readonly attachments = model<ChatInputAttachment[]>([]);
 
  /**
   * The label for the input, used for accessibility
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.LABEL:Chat input`)
   * ```
   */
  readonly label = input<string>(t(() => $localize`:@@SI_CHAT_INPUT.LABEL:Chat input`));
 
  /** Parameter to pass to action handlers */
  readonly actionParam = input<any>();
 
  /**
   * Send button label
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.SEND:Send`)
   * ```
   */
  readonly sendButtonLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.SEND:Send`)
  );
 
  /**
   * Send button icon
   *
   * @defaultValue this.icons.elementSendFilled
   */
  readonly sendButtonIcon = input(this.icons.elementSendFilled);
 
  /**
   * Interrupt button label
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.INTERRUPT:Stop processing`)
   * ```
   */
  readonly interruptButtonLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.INTERRUPT:Stop processing`)
  );
 
  /**
   * Auto-focus the input on component initialization
   * @defaultValue false
   */
  readonly autoFocus = input(false, { transform: booleanAttribute });
 
  /**
   * Attach file button aria label
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.ATTACH_FILE:Attach file`)
   * ```
   */
  readonly attachFileLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.ATTACH_FILE:Attach file`)
  );
 
  /**
   * Remove attachment aria label.
   * The attachment name is available with `{{attachment}}`.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_ATTACHMENT_LIST.REMOVE_ATTACHMENT:Remove {{attachment}}`)
   * ```
   */
  readonly removeAttachmentLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_ATTACHMENT_LIST.REMOVE_ATTACHMENT:Remove {{attachment}}`)
  );
 
  /**
   * More actions button aria label
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_CHAT_INPUT.SECONDARY_ACTIONS:Additional actions`)
   * ```
   */
  readonly secondaryActionsLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_CHAT_INPUT.SECONDARY_ACTIONS:Additional actions`)
  );
 
  /**
   * Suggested follow-up prompts to display as pill buttons above the chat input.
   * Use `followUpPromptSelected` to handle selection and update the input value.
   * Typically populated from AI response data and cleared after selection or on send.
   * @defaultValue []
   */
  readonly followUpPrompts = input<string[]>([]);
 
  /**
   * Emitted when the user selects a follow-up prompt.
   * The emitted value is the text of the selected prompt.
   */
  readonly followUpPromptSelected = output<string>();
 
  /**
   * Emitted when the user wants to send a message
   */
  readonly send = output<{
    content: string;
    attachments: ChatInputAttachment[];
  }>();
 
  /**
   * Emitted when the user wants to interrupt the current operation
   */
  readonly interrupt = output<void>();
 
  /**
   * Emitted when file upload errors occur
   */
  readonly fileError = output<FileUploadError>();
 
  protected readonly id = `__si-chat-input-${SiChatInputComponent.idCounter++}`;
  protected readonly hasContent = computed(() => this.value().trim().length > 0);
  protected readonly hasAttachments = computed(() => this.attachments().length > 0);
  protected readonly hasActions = computed(() => this.actions().length > 0);
  protected readonly voiceActive = computed(
    () => this.voiceInput() && this.voiceInputState() !== 'idle'
  );
  protected readonly voiceRecording = computed(
    () => this.voiceActive() && this.voiceInputState() === 'recording'
  );
  protected readonly voiceButtonLabel = computed(() =>
    this.voiceActive() ? this.cancelDictationLabel() : this.startDictationLabel()
  );
  protected readonly hasSecondaryActions = computed(() => this.secondaryActions().length > 0);
  protected readonly combinedMenuActions = computed<MenuItem[]>(() => [
    ...(this.allowAttachments()
      ? [
          {
            type: 'action' as const,
            label: this.attachFileLabel(),
            icon: this.icons.elementAttachment,
            disabled: this.disabled(),
            action: () => this.triggerFileInput()
          } satisfies MenuItem
        ]
      : []),
    ...this.secondaryActions()
  ]);
 
  protected readonly hasMenuActions = computed(() => this.hasSecondaryActions());
 
  protected triggerFileInput(): void {
    this.fileInput()?.nativeElement.click();
  }
  protected readonly canSend = computed(
    () =>
      (this.hasContent() || this.hasAttachments()) &&
      !this.disabled() &&
      !this.sending() &&
      !this.voiceActive()
  );
 
  protected readonly showInterruptButton = computed(
    () => this.interruptible() && !this.voiceActive()
  );
  protected readonly buttonDisabled = computed(() => {
    if (this.voiceActive()) {
      return this.disabled() || !this.voiceRecording();
    }
    if (this.showInterruptButton()) {
      return this.disabled() || this.sending();
    }
    return !this.canSend();
  });
  protected readonly buttonIcon = computed(() =>
    this.voiceRecording()
      ? this.icons.elementCheckedFilled
      : this.showInterruptButton()
        ? this.icons.elementStopFilled
        : this.sendButtonIcon()
  );
  protected readonly buttonLabel = computed(() =>
    this.voiceRecording()
      ? this.confirmDictationLabel()
      : this.showInterruptButton()
        ? this.interruptButtonLabel()
        : this.sendButtonLabel()
  );
 
  protected readonly dragOver = signal(false);
 
  constructor() {
    afterRenderEffect(() => {
      this.value();
      const textarea = this.textInput()?.nativeElement;
      Eif (textarea) {
        this.setTextareaHeight(textarea);
      }
    });
 
    let previousState = 'idle';
    afterRenderEffect(() => {
      const state = this.voiceActive() ? this.voiceInputState() : 'idle';
      if (state === previousState) {
        return;
      }
      previousState = state;
      if (this.disabled()) {
        return;
      }
      const textarea = this.textInput()?.nativeElement;
      const voiceButton = this.voiceButton()?.nativeElement;
      const submitButton = this.submitButton()?.nativeElement;
      const activeElement = textarea?.ownerDocument.activeElement;
      if (
        activeElement !== textarea &&
        activeElement !== voiceButton &&
        activeElement !== submitButton
      ) {
        return;
      }
      if (state === 'idle') {
        textarea?.focus();
        textarea?.setSelectionRange(textarea.value.length, textarea.value.length);
      } else {
        const button = state === 'listening' ? voiceButton : submitButton;
        button?.focus();
      }
    });
  }
 
  protected selectFollowUpPrompt(prompt: string): void {
    this.followUpPromptSelected.emit(prompt);
    this.focus();
  }
 
  protected onSend(): void {
    Eif (this.canSend()) {
      this.send.emit({
        content: this.value(),
        attachments: this.attachments()
      });
 
      this.value.set('');
      this.attachments.set([]);
    }
  }
 
  protected onButtonClick(): void {
    Iif (this.disabled()) {
      return;
    }
    if (this.voiceActive()) {
      if (this.voiceRecording()) {
        this.voiceInputConfirm.emit();
      }
      return;
    }
    if (this.showInterruptButton()) {
      this.interrupt.emit();
    } else {
      this.onSend();
    }
  }
 
  protected onKeyDown(event: KeyboardEvent): void {
    if (event.isComposing || this.disabled()) {
      return;
    }
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault();
      if (event.repeat) {
        return;
      }
      if (this.voiceActive()) {
        this.onButtonClick();
        return;
      }
      Iif (!this.canSend()) {
        return;
      }
      if (this.showInterruptButton()) {
        this.interrupt.emit();
      }
      this.onSend();
    }
  }
 
  protected onVoiceButtonClick(): void {
    Iif (this.disabled() || (!this.voiceActive() && (this.sending() || this.interruptible()))) {
      return;
    }
    if (this.voiceActive()) {
      this.voiceInputCancel.emit();
    } else {
      this.voiceInputStart.emit();
    }
  }
 
  protected onVoiceKeyDown(event: KeyboardEvent): void {
    if (
      event.key === 'Enter' &&
      !event.shiftKey &&
      event.repeat &&
      !event.isComposing &&
      (event.target === this.voiceButton()?.nativeElement ||
        event.target === this.submitButton()?.nativeElement)
    ) {
      event.preventDefault();
      return;
    }
    if (event.key === 'Escape' && this.voiceActive() && !this.disabled() && !event.isComposing) {
      event.preventDefault();
      event.stopPropagation();
      this.voiceInputCancel.emit();
    }
  }
 
  protected onInput(event: Event): void {
    this.setTextareaHeight(event.target as HTMLTextAreaElement);
  }
 
  protected onFilesAdded(uploadFiles: UploadFile[]): void {
    const validFiles = uploadFiles.filter(uploadFile => uploadFile.status === 'added');
 
    validFiles.forEach(uploadFile => {
      const size = parseInt(uploadFile.size, 10);
      const attachment: ChatInputAttachment = {
        name: uploadFile.fileName,
        size: isNaN(size) ? uploadFile.file.size : size,
        type: uploadFile.file.type,
        file: uploadFile.file
      };
 
      this.attachments.update(current => [...current, attachment]);
    });
  }
 
  protected onFileError(error: FileUploadError): void {
    this.fileError.emit(error);
  }
 
  protected removeAttachment(attachment: Attachment): void {
    this.attachments.update(current => {
      return current.filter(a => a !== attachment);
    });
  }
 
  protected onContainerClick(event: Event): void {
    const target = event.target as HTMLElement;
 
    // Don't focus if clicking on interactive elements
    Eif (
      target.tagName === 'BUTTON' ||
      target.tagName === 'INPUT' ||
      target.tagName === 'TEXTAREA' ||
      target.closest('button') ||
      target.closest('[siChatMessageAction]') ||
      (target.closest('si-attachment-list') && target.closest('.attachment-item'))
    ) {
      return;
    }
 
    this.focus();
  }
 
  ngAfterViewInit(): void {
    const textarea = this.textInput();
    Eif (textarea?.nativeElement) {
      Iif (this.autoFocus() && !this.voiceActive()) {
        // Use setTimeout to ensure the element is fully rendered
        setTimeout(() => {
          textarea.nativeElement.focus();
        }, 0);
      }
    }
  }
 
  /**
   * Focus the textarea input
   */
  focus(): void {
    const textarea = this.textInput();
    Eif (textarea?.nativeElement) {
      textarea.nativeElement.focus();
    }
  }
 
  protected dropHandler(event: DragEvent): void {
    event.preventDefault();
    event.stopPropagation();
    this.dragOver.set(false);
 
    if (!this.allowAttachments() || this.disabled()) {
      return;
    }
 
    const directive = this.fileUploadDirective();
    if (directive && event.dataTransfer?.files) {
      directive.handleFiles(event.dataTransfer.files);
    }
  }
 
  protected dragOverHandler(event: DragEvent): void {
    if (!this.allowAttachments() || this.disabled()) {
      return;
    }
 
    event.preventDefault();
    event.stopPropagation();
    this.dragOver.set(true);
  }
 
  private setTextareaHeight(textarea: HTMLTextAreaElement): void {
    textarea.style.blockSize = 'auto';
 
    const computedStyle = window.getComputedStyle(textarea);
    const lineHeight =
      parseInt(computedStyle.lineHeight, 10) || parseInt(computedStyle.fontSize, 10) * 1.2;
    const paddingTop = parseInt(computedStyle.paddingBlockStart, 10) || 0;
    const paddingBottom = parseInt(computedStyle.paddingBlockEnd, 10) || 0;
    const minHeight = lineHeight + paddingTop + paddingBottom;
 
    const viewportHeight = window.innerHeight;
    const maxViewportHeight = viewportHeight * 0.3;
    const maxLinesHeight = lineHeight * 8;
    const maxHeight = Math.min(maxViewportHeight, maxLinesHeight) + paddingTop + paddingBottom;
 
    const scrollHeight = textarea.scrollHeight;
    const finalHeight = Math.max(Math.min(scrollHeight, maxHeight), minHeight);
    textarea.style.height = finalHeight + 'px';
  }
}