All files / lib/text-input-field text-input-field.component.ts

97.87% Statements 507/518
94.44% Branches 85/90
97.22% Functions 35/36
97.87% Lines 507/518

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 5191x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 12827x 12827x 407x 407x 407x 407x 407x 113x 113x 4x 4x 113x 113x 407x 407x 12729x 12729x 407x 407x 407x 558x 558x 407x 407x 407x 302x 302x 302x 302x 407x 407x 715x 12x 12x 715x 715x 407x 407x 12868x 12868x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 407x 1x 1x 15x 15x 15x 15x 15x 15x 1x 1x 1x 739x 739x 10x 10x 10x 10x 10x       10x 672x 662x 132x 530x 662x 662x 662x 739x 739x 1x 1x 1x 1x 1x 1314x 544x 770x 770x 1314x 1314x 1x 1x 1x 1x 1x 1314x 1314x       1314x 1x 1x 1x 1x 1x 1x 1x 1x 43x 43x 20x 23x 43x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 43x 43x 43x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 432x 432x 432x 432x 1x 1x 1x 450x 10x 5x 5x 10x 10x     10x 10x 3x 3x 10x 10x     10x 10x 1x 1x 10x 10x 1x 1x 450x 450x 450x 1x 1x 1x 1x 1x 43x 43x 43x 43x 43x   43x 43x 43x 2x 43x 43x 43x 43x 43x 43x 43x 43x 1x 43x 43x 43x 43x 1x 1x 1x 1x 1x 80x 80x 1x 1x 1x 1x 1x 457x 457x 457x 457x 457x 457x 457x 457x 457x 1x 1x 1x 1117x 671x 671x 1117x 1117x 1x 1x 1x 6132x 6132x 1x 1x 1x 14504x 14504x 1x 1x 1x 8372x 8372x 1x 1x 1x 6206x 42x 30x 12x 12x 6164x 6164x 6164x 6206x 6206x 1x 1x 1x 16x 16x 14x 14x 11x 14x 14x 4x 16x 16x 16x 16x 16x 1x 1x 1x 30x 30x 30x 30x 30x 30x 30x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  QueryList,
  SimpleChanges,
  ViewChild,
  ViewChildren,
} from '@angular/core';
 
import {
  computeErrorTextPrefix,
  playSoundIfLengthExceeded,
} from '../utils/internal-utils';
import { isGecko } from '../utils/user-agent';
import {
  FocusableElementOwner,
  FormControlStatus,
  InvalidControlValue,
  WidgetKeySet,
} from '../utils/util.types';
import {
  SoundType,
  createWidgetKeySet,
  isInvalidControlValue,
  playSound,
} from '../utils/utilities';
 
import { FocusScopeDirective } from '../internal/focus-scope.directive';
import {
  AutoIdDirective,
  LabelContainerComponent,
} from '../internal/label-container/label-container.component';
import { OverlayContainerComponent } from '../internal/overlay-container/overlay-container.component';
 
import { AutoCompleteDirective } from './auto-complete/auto-complete.directive';
import {
  TextInputFormatter,
  isParseError,
} from './text-input-field.formatters';
 
/**
 * A Text Input element that allows users to enter a text value.
 */
@Component({
  selector: 'gc-text-input-field',
  templateUrl: './text-input-field.component.html',
  styleUrls: [
    '../base-range-input-field/base-slot-mode.css',
    './text-input-field.component.css',
    './auto-complete/auto-complete.style.css',
  ],
})
export class TextInputComponent
  extends AutoCompleteDirective
  implements FocusableElementOwner, AfterViewInit, OnChanges
{
  /**
   * Custom ID to use
   */
  @Input()
  public id?: string;
 
  /**
   * The label that shows on the input.
   */
  @Input()
  public label = '';
 
  /**
   * Decides if the control will be rendered in a readonly state.
   */
  @Input()
  public readonly = false;
 
  /**
   * Overrides the default text which is shown when the control is readonly and empty.
   */
  @Input()
  public readonlyEmptyValue = '';
 
  /**
   * If set to true the state of the input is set to disabled which means that it is no longer possible to type text inside the input.
   */
  @Input()
  public disabled = false;
 
  /**
   * Marks the input field as required.
   */
  @Input()
  public required = false;
 
  /**
   * Hint message that appears below the text input field.
   */
  @Input()
  public hint = '';
 
  /**
   * Max number of chars allowed inside that text field
   */
  @Input()
  public maxLength?: number;
 
  /**
   * Formatter to display the value in a custom format and convert user input to the internal representation
   */
  @Input()
  public formatter?: TextInputFormatter;
 
  /**
   * The value of the text input.
   */
  @Input()
  public value: string | InvalidControlValue = '';
 
  /**
   * If true, the component will be rendered in a slot-element mode.
   * This enables the component to be used in internal label containers (e.g. `gc-two-slot-label-container`).
   * @ignore
   */
  @Input()
  public _slotElementMode?:
    | 'two-slot-label-container'
    | 'ext-search-single-field'
    | 'ext-search-range-field';
 
  /**
   * Error message id used when `_slotElementMode` is enabled.
   * @ignore
   */
  @Input()
  public _errorMessageId?: string;
 
  /**
   * Info (hint) message id used when `_slotElementMode` is enabled.
   * @ignore
   */
  @Input()
  public _infoMessageId?: string;
 
  /**
   * Informs about a change of the value. Does not fire when updating the value programmatically, only on user inputs.
   *
   * Note that `InvalidControlValue` is only expected when working with a `formatter` in practice, as in regular
   * text input fields raw input is always forwarded without further checks and thus is valid.
   */
  @Output()
  public readonly valueChange: EventEmitter<string | InvalidControlValue> =
    new EventEmitter<string | InvalidControlValue>();
 
  /**
   * Event fired when the control looses focus
   */
  @Output()
  public readonly onFocusLeft: EventEmitter<void> = new EventEmitter<void>();
 
  /**
   * Event fired when the control gains focus
   */
  @Output()
  public readonly onFocusEntered: EventEmitter<void> = new EventEmitter<void>();
 
  /**
   * Signals changes of the current (combined) status of the component, e.g. also reports errors triggered by internal
   * validation or input handling.
   */
  @Output()
  public readonly onStatusChange: EventEmitter<FormControlStatus> =
    new EventEmitter<FormControlStatus>(true);
 
  /**
   * Signals that the text value has changed. In contrast to "valueChange" this event is emitted immediately
   * and provides the current (unprocessed) text visible in the control
   */
  @Output()
  public readonly onInputChange: EventEmitter<string> =
    new EventEmitter<string>(true);
 
  /** @ignore */
  @ViewChild(FocusScopeDirective)
  protected focusScope?: FocusScopeDirective;
 
  /** @ignore */
  @ViewChild(AutoIdDirective)
  protected autoId!: AutoIdDirective;
 
  /** @ignore */
  @ViewChild('popup')
  protected popup?: OverlayContainerComponent;
 
  /** @ignore */
  @ViewChildren('autocompleteItem')
  protected autocompleteItems?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChild('textInput')
  private textInputEl?: ElementRef<HTMLInputElement>;
 
  /** @ignore */
  @ViewChild(LabelContainerComponent)
  private labelContainer?: LabelContainerComponent;
 
  public get _combinedErrorMessage(): string {
    return this.internalErrorMessage || this.errorMessage;
  }
 
  /**
   * Error message that appears below the input field.
   */
  @Input()
  public set errorMessage(message: string) {
    if (this._errorMessage !== message) {
      this._errorMessage = message;
      this.emitStatusChange();
    }
  }
 
  public get errorMessage(): string {
    return this._errorMessage;
  }
 
  /** @ignore */
  protected override get popupAnker(): undefined | ElementRef<HTMLElement> {
    return this.labelContainer?.drawerSlot;
  }
 
  /** @ignore */
  protected override get popupScrollTarget():
    | undefined
    | ElementRef<HTMLElement> {
    return this.labelContainer?.boxEl;
  }
 
  private set internalErrorMessage(message: string) {
    if (message !== this._internalErrorMessage) {
      this._internalErrorMessage = message;
      this.emitStatusChange();
    }
  }
 
  private get internalErrorMessage(): string {
    return this._internalErrorMessage;
  }
 
  /**
   * @ignore
   */
  public _text = '';
 
  /**
   * @ignore
   */
  public _maxLengthAriaText?: string;
 
  /** @ignore */
  protected readonly _widgetKeys: WidgetKeySet =
    createWidgetKeySet('gc-text-input');
 
  /**
   * displayed on readonly when readonlyEmptyValue is empty
   * @ignore
   */
  protected readonly READONLY_DEFAULT_EMPTY_VALUE = '\u2013';
 
  private _errorMessage = '';
 
  private _internalErrorMessage = '';
 
  focusChild(): boolean {
    if (!this.disabled) {
      this.textInputEl?.nativeElement.focus();
      return true;
    }
    return false;
  }
 
  /** @ignore */
  public ngOnChanges(changes: SimpleChanges): void {
    if ('value' in changes || 'formatter' in changes) {
      if (isInvalidControlValue(this.value)) {
        this.updateTextValue(this.value.rawValue);
        const parseResult = this.formatter?.parse(this.value.rawValue);
        if (parseResult && isParseError(parseResult)) {
          this.internalErrorMessage = this.generateErrorMsg(
            parseResult.message,
          );
        } else {
          this.internalErrorMessage = '';
        }
      } else {
        const newValue = this.formatter
          ? this.formatter.format(this.value)
          : this.value;
        this.updateTextValue(newValue);
        this.internalErrorMessage = '';
      }
    }
  }
 
  /**
   * @ignore
   */
  public length(): number {
    if (this._text) {
      return this._text.length;
    } else {
      return 0;
    }
  }
 
  /**
   * @ignore
   */
  public maxLengthAriaText(): string | null {
    if (this.maxLength !== undefined && this.maxLength !== 0) {
      return 'maximal ' + this.maxLength.toString() + ' Zeichen';
    }

    return null;
  }
 
  /** @ignore */
  protected override focusInputField(): void {
    this.focusChild();
  }
 
  /** @ignore */
  protected override _handleChange(): void {
    const currentText = this._text || '';
    const parseResult = this.formatter
      ? this.formatter.parse(currentText)
      : currentText;
    if (!isParseError(parseResult)) {
      this.value = parseResult;
      // formatter may create situation where the formatted value is unchanged (different inputs
      // may create the same formatted value, e.g. leading zeroes on a number formatter),
      // the input's value is now desynchronized from the re-formatted value
      if (this.formatter) {
        this.updateTextValue(this.formatter.format(parseResult));
      }
      this.internalErrorMessage = '';
    } else {
      this.value = {
        kind: 'InvalidControlInput',
        rawValue: currentText,
        errorMessage: this.generateErrorMsg(parseResult.message),
      };
      this.internalErrorMessage = this.generateErrorMsg(parseResult.message);
    }
    this.valueChange.emit(this.value);
  }
 
  /** @ignore */
  protected override _handleAutoCompleteSelection(text: string) {
    this.updateTextValue(text);
  }
 
  /**
   * @ignore
   */
  protected async _handleInputChange(evt: Event): Promise<void> {
    const currentText = (evt.target as HTMLInputElement).value;
    this.updateTextValue(currentText);
    await this._autoCompleteOnInput(currentText);
  }
 
  /** @ignore */
  protected _handleInputKeyDown(evt: KeyboardEvent): void {
    if (this._impl_drawerOpen) {
      if (evt.key == 'ArrowDown') {
        this._popup_focusNext();
        evt.preventDefault();
      }
      if (evt.key == 'ArrowUp') {
        this._popup_focusPrev();
        evt.preventDefault();
      }
      if (evt.key == 'Enter') {
        this._popup_applyFocused();
        evt.preventDefault();
      }
      if (evt.key === 'Escape') {
        this._hideCompletions();
        evt.preventDefault();
      }
      if (evt.key === 'Home') {
        this._popup_focusFirst();
        evt.preventDefault();
      }
      if (evt.key === 'End') {
        this._popup_focusLast();
        evt.preventDefault();
      }
    }
  }
 
  /**
   * @ignore
   */
  protected _handleFocusLeave(): void {
    /**
     * Firefox doesn't automatically scroll to the very left, after blur on input element
     * https://bugzilla.mozilla.org/show_bug.cgi?id=860329
     */
    if (this.textInputEl && isGecko()) {
      this.textInputEl.nativeElement.scrollLeft = 0;
    }
    this.onFocusLeft.next();
    if (this._impl_drawerOpen) {
      this._hideCompletions();
    }
 
    // We need to wait a tick so that the control is back
    // in a sync state
    setTimeout(() => {
      if (
        this._combinedErrorMessage.length > 0 ||
        this._errorMessageId !== undefined
      ) {
        void playSound(SoundType.ERROR);
      }
    });
  }
 
  /**
   * @ignore
   */
  protected _handleFocusEntered(): void {
    this.onFocusEntered.next();
  }
 
  /**
   * @ignore
   */
  protected _handleBeforeInput(evt: InputEvent): void {
    if (this.textInputEl) {
      playSoundIfLengthExceeded(
        this.textInputEl.nativeElement,
        this._text,
        this.maxLength,
        evt,
      );
    }
  }
 
  /** @ignore */
  protected updateTextValue(text: string) {
    if (this._text !== text) {
      this._text = text;
      this.onInputChange.emit(text);
    }
  }
 
  /** @ignore */
  protected getLabelId(): string {
    return this._widgetKeys.labelKey;
  }
 
  /** @ignore */
  protected getInputId(): string {
    return this._widgetKeys.widgetKey;
  }
 
  /** @ignore */
  protected computeAriaDescribedBy(): string | null {
    return this._infoMessageId ?? null;
  }
 
  /** @ignore */
  protected sizeHelperText(): string {
    if (this.readonly && this._text.length === 0) {
      if (this.readonlyEmptyValue === '') {
        return this.READONLY_DEFAULT_EMPTY_VALUE;
      } else {
        return this.readonlyEmptyValue;
      }
    } else {
      return this._text;
    }
  }
 
  /** @ignore */
  private emitStatusChange() {
    const status: FormControlStatus = {};
    if (this.internalErrorMessage || this.errorMessage) {
      status.error = [];
      if (this.internalErrorMessage) {
        status.error.push(this.internalErrorMessage);
      }
      if (this.errorMessage) {
        status.error.push(this.errorMessage);
      }
    }
 
    this.onStatusChange.emit(status);
  }
 
  /** @ignore */
  private generateErrorMsg(errorMessage: string): string {
    const errorPrefix = computeErrorTextPrefix(
      this.label,
      this._slotElementMode,
      'Wert',
    );
    return errorPrefix + errorMessage;
  }
}