All files / lib/text-input-field/auto-complete auto-complete.directive.ts

90.34% Statements 365/404
86.48% Branches 64/74
88.46% Functions 23/26
90.34% Lines 365/404

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 4051x 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 70x 70x 70x 70x 70x 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 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 558x 558x 558x 1x 1x 1x 558x 558x   558x 558x 558x 558x 558x 558x 558x 296x 296x 197x 558x 558x 558x 558x 1x 1x 1x 607x 39x 37x 37x 35x 35x 26x 26x 26x 9x 9x       607x 607x 607x 1x 1x 1x 37x 37x 37x 37x 37x 37x 35x 3x 32x 37x 3x 32x 37x 37x 21x 21x 1x 1x 20x 20x 2x 2x 2x 2x 2x 18x 18x 18x 18x 37x 37x 37x 37x 1x 1x 1x 1x 1x 4731x 4534x 197x 197x 4731x 1x 1x 1x 26x 26x 26x 1x 1x 1x 16x 16x 16x 16x 16x 13x 13x 13x 13x 1x 1x 13x 13x 16x 16x 1x 1x 1x 39x 39x 22x 39x 39x 37x 39x 39x 39x 1x 1x 1x 1696x   1696x 1696x 1696x 1696x 1x 1x 1x 15x 15x 15x 1x 1x 1x 20x 1x 1x 1x 1x   1x 1x 1x 1x 41x 41x 1x 1x 1x 3x 3x 1x 1x 1x 3x   3x 3x 3x 3x 3x 3x 1x 1x 1x 10x 10x                       10x 10x 1x 1x 1x                                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 1x 1x 1x 23x 23x 23x 23x 1x 1x 1x 37x 37x 37x 2x 2x 2x 37x 37x 37x 37x   37x 37x 37x 37x 37x 1x 1x 1x 1x 1x 12x 12x   12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  AfterViewInit,
  ChangeDetectorRef,
  Directive,
  ElementRef,
  Input,
  QueryList,
  ViewChild,
} from '@angular/core';
 
import { AriaLiveReaderComponent } from '../../internal/aria-live-reader/aria-live-reader.component';
import { FocusScopeDirective } from '../../internal/focus-scope.directive';
import { AutoIdDirective } from '../../internal/label-container/label-container.component';
import {
  OverlayContainerComponent,
  OverlayLocation,
} from '../../internal/overlay-container/overlay-container.component';
 
interface AutoCompleteResultComplex {
  readonly entries: readonly string[];
  readonly additionalEntriesCount: number;
}
 
export type AutoCompleteResult = readonly string[] | AutoCompleteResultComplex;
 
function isComplexResult(
  value: AutoCompleteResult,
): value is AutoCompleteResultComplex {
  return !Array.isArray(value);
}
 
/**
 * Internal base directive to implement AutoComplete for text input components
 */
@Directive()
export abstract class AutoCompleteDirective implements AfterViewInit {
  /**
   * Optional function to compute a list of auto-complete entries
   */
  @Input()
  public autoComplete?: (text: string) => Promise<AutoCompleteResult>;
 
  /**
   * Timeout (in milliseconds) to wait until auto-complete is triggered.
   *
   * Default 400ms
   */
  @Input()
  public autoCompleteTriggerTimeout = 400;
 
  @ViewChild('ariaLiveRegion')
  private ariaLiveRegion?: AriaLiveReaderComponent;
 
  /** @ignore */
  protected _popup_overlayLocation: OverlayLocation = 'end-bottom';
 
  /** @ignore */
  protected _impl_loading = false;
 
  /** @ignore */
  protected _impl_drawerOpen = false;
 
  /** @ignore */
  protected _impl_id?: string;
 
  /** @ignore */
  protected _impl_input_id?: string;
 
  /** @ignore */
  protected _impl_listbox_id?: string;
 
  /** @ignore */
  protected _popup_items: readonly string[] = [];
 
  /** @ignore */
  protected _popup_extra_item?: string;
 
  /** @ignore */
  protected _popup_focused?: string;
 
  /** @ignore */
  private _lastLoadId = 0;
 
  /** @ignore */
  private _debounceTimeout?: ReturnType<typeof setTimeout>;
 
  /** @ignore */
  protected abstract focusScope?: FocusScopeDirective;
 
  /** @ignore */
  protected abstract autoId?: AutoIdDirective;
 
  /** @ignore */
  protected abstract popup?: OverlayContainerComponent;
 
  /** @ignore */
  protected abstract autocompleteItems?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  protected abstract get popupAnker(): undefined | ElementRef<HTMLElement>;
 
  /** @ignore */
  protected abstract get popupScrollTarget():
    | undefined
    | ElementRef<HTMLElement>;
 
  constructor(
    private readonly change: ChangeDetectorRef,
    private readonly showEmptyResult = false,
  ) {}
 
  /** @ignore */
  public ngAfterViewInit(): void {
    if (this.autoId === undefined) {
      throw new Error(
        'missing autoId directive, must be set by the extending class',
      );
    }
    this._impl_id = this.autoId.autoId;
    this._impl_listbox_id = this._impl_id + '_listbox';
    this._impl_input_id = this.autoId.inputId;
 
    if (this.popup && this.popupAnker) {
      this.popup.anker = this.popupAnker;
      if (this.popupScrollTarget) {
        this.popup.scrollTargetElement = this.popupScrollTarget;
      }
    }
    this.change.detectChanges();
  }
 
  /** @ignore */
  protected async _autoCompleteOnInput(inputText: string) {
    if (this.autoComplete) {
      await this.debounce(this.autoCompleteTriggerTimeout);
      if (this.isFocusWithin()) {
        await this._loadAutoCompleteItems(inputText);
        if (
          (this._popup_items.length > 0 || this._popup_extra_item) &&
          this.isFocusWithin()
        ) {
          this._showCompletions();
        } else {
          this._impl_drawerOpen = false;
        }
      } else {
        this._impl_drawerOpen = false;
      }
    }
  }
 
  /** @ignore */
  protected async _loadAutoCompleteItems(text: string) {
    if (this.autoComplete === undefined) {
      this._popup_items = [];
    } else {
      const loadId = ++this._lastLoadId;
      const autoCompleteResults =
        await this.loadItemsWithLoadingIndicator(text);
      const items = isComplexResult(autoCompleteResults)
        ? autoCompleteResults.entries
        : autoCompleteResults;
      const additionalEntryCount = isComplexResult(autoCompleteResults)
        ? autoCompleteResults.additionalEntriesCount
        : undefined;
 
      if (loadId === this._lastLoadId) {
        this._popup_items = items;
        if (items.length === 0 && this.showEmptyResult) {
          this._popup_extra_item = `Keine Treffer für „${text}” gefunden`;
          this.readAriaLive(`Keine Treffer für „${text}” gefunden`);
        } else if (
          additionalEntryCount !== undefined &&
          additionalEntryCount > 0
        ) {
          this._popup_extra_item = `und ${additionalEntryCount.toFixed(0)} weitere Treffer – bitte geben Sie mehr Zeichen ein`;
          this.readAriaLive(
            `Mehr als ${items.length.toFixed(0)} Treffer gefunden`,
          );
        } else {
          this._popup_extra_item = undefined;
          this.readAriaLive(`${items.length.toFixed(0)} Vorschläge vorhanden`);
        }
      }
    }
  }
 
  /**
   * @ignore
   */
  protected isFocusWithin(): boolean {
    if (this.focusScope !== undefined) {
      return this.focusScope.focusWithin;
    }
    return false;
  }
 
  /** @ignore */
  protected _showCompletions() {
    this._popup_focused = undefined;
    this._impl_drawerOpen = true;
  }
 
  /** @ignore */
  protected _hideCompletions(skipFocus?: boolean) {
    this._impl_drawerOpen = false;
    this._popup_focused = undefined;
    // if the popup is closed due to a click in a random area outside (e.g. not moving to another element via 'Tab'),
    // then move the focus back to the component; detectable as no specific (other) element is focused
    if (!skipFocus) {
      setTimeout(() => {
        if (
          document.activeElement === null ||
          document.activeElement === document.body
        ) {
          this.focusInputField();
        }
      });
    }
  }
 
  /** @ignore */
  protected debounce(ms: number) {
    return new Promise<void>(resolve => {
      if (this._debounceTimeout) {
        clearTimeout(this._debounceTimeout);
      }
      this._debounceTimeout = setTimeout(() => {
        resolve();
      }, ms);
    });
  }
 
  /** @ignore */
  protected _popup_getItemId(item: string) {
    if (item === this._popup_extra_item) {
      return this._popup_getExtraItemId();
    }
    const id = this._impl_id?.toString();
    return (id ?? '') + '_ac-' + this._popup_items.indexOf(item).toString();
  }
 
  /** @ignore */
  protected _popup_getExtraItemId() {
    const id = this._impl_id?.toString();
    return (id ?? '') + '_ac-extra_item';
  }
 
  /** @ignore */
  protected _popup_handleVisible() {
    // empty
  }
 
  /** @ignore */
  protected _popup_handleHide() {
    // empty
  }
 
  /** @ignore */
  protected _popup_handleLocationChange(location: OverlayLocation) {
    this._popup_overlayLocation = location;
  }
 
  /** @ignore */
  protected _popup_onMouseDown(event: MouseEvent) {
    event.preventDefault();
  }
 
  /** @ignore */
  protected async _popup_onClick(item: string) {
    if (this._popup_extra_item === item) {
      this._popup_focused = this._popup_extra_item;
    } else {
      this._handleAutoCompleteSelection(item);
      this._hideCompletions(false);
      await this._handleChange();
    }
  }
 
  /** @ignore */
  protected _popup_focusNext() {
    if (this._popup_focused === undefined) {
      this._popup_focused = this._popup_items[0];
    } else {
      const idx = this._popup_items.indexOf(this._popup_focused);
      if (idx >= 0 && this._popup_items.length > idx + 1) {
        this._popup_focused = this._popup_items[idx + 1];
      } else if (
        this._popup_extra_item &&
        idx + 1 === this._popup_items.length
      ) {
        this._popup_focused = this._popup_extra_item;
      }
    }
    this.scrollToFocusedItem();
  }
 
  /** @ignore */
  protected _popup_focusPrev() {
    if (this._popup_focused === undefined) {
      if (this._popup_extra_item) {
        this._popup_focused = this._popup_extra_item;
      } else {
        this._popup_focused = this._popup_items[this._popup_items.length - 1];
      }
    } else {
      const idx = this._popup_items.indexOf(this._popup_focused);
      if (0 <= idx - 1) {
        this._popup_focused = this._popup_items[idx - 1];
      } else if (
        this._popup_extra_item &&
        this._popup_focused === this._popup_extra_item
      ) {
        this._popup_focused = this._popup_items[this._popup_items.length - 1];
      }
    }
    this.scrollToFocusedItem();
  }
 
  /** @ignore */
  protected _popup_focusFirst() {
    this._popup_focused = this._popup_items[0];
    this.scrollToFocusedItem();
  }
 
  /** @ignore */
  protected _popup_focusLast() {
    this._popup_focused =
      this._popup_extra_item ?? this._popup_items[this._popup_items.length - 1];
    this.scrollToFocusedItem();
  }
 
  /** @ignore */
  protected async _popup_applyFocused() {
    if (this._popup_focused && this._popup_focused !== this._popup_extra_item) {
      this._handleAutoCompleteSelection(this._popup_focused);
      this._hideCompletions(false);
      await this._handleChange();
    }
  }
 
  /** @ignore */
  private readAriaLive(text: string) {
    if (this.ariaLiveRegion) {
      this.ariaLiveRegion.readText(text);
    }
  }
 
  /** @ignore */
  private async loadItemsWithLoadingIndicator(
    value: string,
  ): Promise<AutoCompleteResult> {
    const loadingTimeout = window.setTimeout(() => {
      this._impl_loading = true;
      this._impl_drawerOpen = true;
      this.readAriaLive('Ergebnisse werden geladen');
    }, 200);
 
    const result: AutoCompleteResult = this.autoComplete
      ? await this.autoComplete(value)
      : [];
    window.clearTimeout(loadingTimeout);
    this._impl_loading = false;
    this._impl_drawerOpen = false;
    return result;
  }
 
  /**
   * @ignore
   */
  private scrollToFocusedItem(): void {
    if (this.autocompleteItems) {
      const searchItems = this._popup_extra_item
        ? [...this._popup_items, this._popup_extra_item]
        : this._popup_items;
      const focusedItemIdx = searchItems.findIndex(
        i => i === this._popup_focused,
      );
      this.autocompleteItems
        .get(focusedItemIdx)
        ?.nativeElement.scrollIntoView({ block: 'nearest', inline: 'nearest' });
    }
  }
 
  /** @ignore */
  protected abstract focusInputField(): void;
 
  /**
   * @ignore
   * Is used to update only the input value
   */
  protected abstract _handleAutoCompleteSelection(text: string): void;
 
  /**
   * @ignore
   * Is used to manually trigger the `change` event handling of the input element
   */
  protected abstract _handleChange(): Promise<void>;
}