All files / lib/filter filter.component.ts

96.84% Statements 522/539
92.59% Branches 75/81
93.1% Functions 27/29
96.84% Lines 522/539

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 5401x 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 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 5524x 5524x 5524x 1x 1x 57x 12x 12x 12x 12x 12x 12x 12x 12x 12x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 57x 57x 57x 57x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 4095x 4095x 1x 1x 1x 1x 1x 97x 97x 97x 97x     97x 97x 97x 97x 31x 31x 29x 29x 31x 31x 2x 2x 31x 31x 31x 31x     31x 31x 97x 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 32x 32x 32x 32x 32x 32x 32x 32x 32x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 63x 63x 1x 1x 1x 1x 1x 2508x 2508x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 13x 13x 13x 13x   13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 3x 3x 3x 3x 2x 3x 3x 3x 1x 1x 1x 1x 1x 2508x 2508x 2508x 2508x 2508x 1x 1x 1x 1x 1x 13x 13x 1x 1x 1x 1x 1x 788x 8668x 788x 788x 788x 4728x 4728x 4728x 4728x 4728x 1734x 1734x 1734x 2994x 2994x 4728x 4728x 4728x 4728x 1734x 1734x 4728x 788x 788x 788x 788x 788x 788x 788x 788x 1x 1x 1x 1x 1x 4242x 3468x 3468x 3346x 122x 100x 22x 22x 3468x 3468x 4242x 4242x 4242x 1x 1x 1x 1x 1x 12x     12x 12x 12x 12x 12x 12x 12x 2x 12x 12x 1x 1x 1x 1x 1x 7x 7x 7x 6x 7x 5x 5x 5x 5x 5x 5x 5x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2508x 2508x 1x 1x 788x 788x 788x 788x 788x 1x 1x 3857x 3857x 1x 1x 1337x 1337x 1x 1x 1x 4x 4x 4x 4x 4x 4x     4x 4x 1x 1x 1x 17x 17x 17x 17x 1x 1x 1x 1x 1x 97x 97x 97x 97x 97x 97x 94x 94x 295x 94x 94x 97x 3x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  Component,
  ElementRef,
  EventEmitter,
  Input,
  NgZone,
  OnChanges,
  OnDestroy,
  Output,
  QueryList,
  TemplateRef,
  ViewChild,
  ViewChildren,
} from '@angular/core';
 
import { observeElementSize } from '../utils/internal-utils';
import {
  Callback,
  FilterAction,
  FilterItem,
  FilterSlots,
  FocusableElementOwner,
  HasSublabel,
  Item,
  ItemGroup,
  SlotItem,
} from '../utils/util.types';
import { itemTrack } from '../utils/utilities';
 
import { ButtonComponent } from '../button/button.component';
import { FilterButtonComponent } from './filter-button/filter-button.component';
import { FilterContainerComponent } from './filter-container/filter-container.component';
 
/**
 * Filter component that can be used to reduce the content of the page by applying various filters.
 */
@Component({
  selector: 'gc-filter',
  templateUrl: './filter.component.html',
  styleUrls: [
    '../utils/styles/reset-form.css',
    '../utils/styles/reset-list.css',
    './filter.component.css',
  ],
})
export class FilterComponent
  implements OnDestroy, FocusableElementOwner, OnChanges
{
  /**
   * Items that will show as filters.
   */
  @Input()
  public items: readonly FilterItem[] = [];
 
  /**
   * Content of the filter.
   */
  @Input()
  public filterContent?: TemplateRef<unknown>;
 
  /**
   * Key of the primary action shown in the filter container.
   */
  @Input()
  public primaryFooterActionKey = '';
 
  /**
   * Decides if the passed error items will be shown. true === shown
   */
  @Input()
  public showErrors = false;
 
  /**
   * Fires upon a filter action press and emits an action.
   */
  @Output()
  public readonly onAction: EventEmitter<FilterAction> =
    new EventEmitter<FilterAction>();
 
  /**
   * Fires upon an error item press and emits the error item.
   */
  @Output()
  public readonly onErrorItemAction: EventEmitter<Item> =
    new EventEmitter<Item>();
 
  /**
   * Fires upon a change of the overlay visibility.
   * @deprecated visibility is implied by the selectedFilterItem, event will never be fired
   */
  @Output()
  public readonly overlayVisibleChange: EventEmitter<boolean> =
    new EventEmitter<boolean>();
 
  /**
   * Fires upon adding a filter to the added filter items that are shown in non-responsive-mode
   */
  @Output()
  public readonly onAdd: EventEmitter<FilterItem> =
    new EventEmitter<FilterItem>();
 
  /**
   * Fires upon removing an item from the added filter items.
   */
  @Output()
  public readonly onRemove: EventEmitter<FilterItem> =
    new EventEmitter<FilterItem>();
 
  /**
   * Fires upon the change of the currently selected filter item.
   */
  @Output()
  public readonly selectedFilterItemChange: EventEmitter<
    FilterItem | undefined
  > = new EventEmitter<FilterItem | undefined>();
 
  /**
   * @ignore
   */
  @ViewChild('addButton', { read: ButtonComponent })
  private addButtonComponent!: ButtonComponent;
 
  /**
   * @ignore
   */
  @ViewChild('condensedFiltersButton', { read: FilterButtonComponent })
  private condensedFiltersButton!: FilterButtonComponent;
 
  /**
   * @ignore
   */
  @ViewChildren('filterButton')
  private filterButtons?: QueryList<FilterButtonComponent>;
 
  /** @ignore */
  @ViewChildren('filterButtonListItem')
  private filterButtonElements?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChild('filterContainerComponent')
  private filterContainerComponent?: FilterContainerComponent;
 
  /**
   * Currently selected item.
   */
  @Input()
  public get selectedFilterItem(): FilterItem | undefined {
    return this._selectedFilterItem;
  }
 
  public set selectedFilterItem(item: FilterItem | undefined) {
    if (this._selectedFilterItem === item) {
      return;
    }
 
    // close an already open container, also includes closure when the selection is cleared
    this._closeContainer(false);
 
    this._selectedFilterItem = item;
 
    if (item) {
      // determine the anchor for the item and open the container
      // if the list of filters is updated in the same tick as the selected filter, the anchor/button may not yet be available in the DOM, need to wait a tick
      setTimeout(() => {
        const anchor = this.getFilterContainerAnchor(item);
        if (anchor === undefined) {
          throw new Error(
            `failed to find filter button for item with key '${item.key}', check that the filter is added`,
          );
        } else {
          anchor.nativeElement.focus(); //Focus the filter-pill to make sure the pill gets the focus back after closing the container
          this.openFilterContainer(anchor);
        }
      });
    }
  }
 
  /**
   * input has no effect, previously toggled the filter container overlay
   * @deprecated input has no effect, control filter container visibility via `selectedFilterItem`
   */
  @Input()
  public set overlayVisible(_value: boolean) {
    console.warn(
      'usage of overlayVisible is deprectated and has no effect, use selectedFilterItem instead',
    );
  }
 
  /**
   * @ignore
   */
  get filterButtonsCanFit(): boolean {
    return this._filterButtonsCanFit;
  }
 
  /**
   * @ignore
   */
  set filterButtonsCanFit(value: boolean) {
    const previousValue = this._filterButtonsCanFit;
    this._filterButtonsCanFit = value;
 
    if (value !== previousValue && this.selectedFilterItem !== undefined) {
      this.overlayContainerAnker = this.getFilterContainerAnchor(
        this.selectedFilterItem,
      );
    }
 
    if (value !== previousValue) {
      const wasCollapsedAndCondensedButtonFocused =
        !previousValue &&
        document.activeElement ===
          this.condensedFiltersButton.button.nativeElement;
      const wasExpandedAndFilterButtonFocused =
        previousValue &&
        this.filterButtons?.find(
          fb => document.activeElement === fb.button.nativeElement,
        ) !== undefined;
      if (
        wasCollapsedAndCondensedButtonFocused ||
        wasExpandedAndFilterButtonFocused
      ) {
        setTimeout(() => this.focusChild());
      }
    }
  }
 
  /**
   * @ignore
   */
  public menuFilterButtonVisible = false;
 
  /**
   * @ignore
   */
  public _filterContainerIsFullScreen = false;
 
  /** @ignore */
  public _filterContainerVisible = false;
 
  /** @ignore */
  protected overlayContainerAnker?: ElementRef<HTMLElement>;
 
  /**
   * @ignore
   */
  private _filterButtonsCanFit = false;
 
  /** @ignore */
  private _selectedFilterItem?: FilterItem;
 
  /**
   * @ignore
   */
  private resizeObserver: Callback;
 
  constructor(
    zone: NgZone,
    private el: ElementRef<HTMLElement>,
  ) {
    this.resizeObserver = observeElementSize(
      el.nativeElement,
      zone,
      this.toggleFilterButtonsVisibility.bind(this),
    );
  }
 
  /**
   * Try to move the focus to the error section of the currently open filter-popup
   *
   * @returns `true` if focus got transfered successfully
   */
  public moveFocusToError(): boolean {
    if (this.filterContainerComponent) {
      return this.filterContainerComponent.moveFocusToError();
    }
    return false;
  }
 
  /**
   * @ignore
   */
  ngOnDestroy(): void {
    this.resizeObserver();
  }
 
  /**
   * @ignore
   */
  ngOnChanges(): void {
    this.toggleFilterButtonsVisibility();
  }
 
  /**
   * @ignore
   */
  public _itemTrackBy(_index: number, item: Item): string {
    return itemTrack(item);
  }
 
  /**
   * @ignore
   */
  public _onAddButtonMenuAction(item: FilterItem): void {
    this.onAdd.emit(item);
  }
 
  /**
   * @ignore
   */
  public _onRemoveFilterButton(item: FilterItem): void {
    this.onRemove.emit(item);
  }
 
  /**
   * @ignore
   */
  public _onButtonAction(
    item: FilterItem,
    button: ElementRef<HTMLElement>,
  ): void {
    if (item.key === this.selectedFilterItem?.key) {
      this._closeContainer(true);
    } else {
      this._selectedFilterItem = item;
      this.selectedFilterItemChange.emit(item);
      this.openFilterContainer(button);
    }
  }
 
  /**
   * @ignore
   */
  public _onResponsiveButtonAction(
    item: FilterItem,
    button: ElementRef<HTMLElement>,
  ): void {
    if (!item.added) {
      this.onAdd.emit(item);
    }
    this._onButtonAction(item, button);
  }
 
  /**
   * @ignore
   */
  public _filterSlot(
    items: readonly SlotItem<FilterSlots>[],
    slot: FilterSlots,
  ): readonly SlotItem<FilterSlots>[] {
    return items.filter(item => item.slot === slot);
  }
 
  /**
   * @ignore
   */
  public _onAction(action: SlotItem<FilterSlots>, item: FilterItem): void {
    this.onAction.emit({ item, action });
  }
 
  /**
   * @ignore
   */
  public responsiveFilterItems(): ItemGroup<FilterItem & HasSublabel>[] {
    const sortedItems = [...this.items].sort((a, b) =>
      a.label.localeCompare(b.label),
    );
    return sortedItems.reduce<ItemGroup<FilterItem & HasSublabel>[]>(
      (group, entry) => {
        const active = entry.added === true && entry.value.length > 0;
        return [
          {
            ...group[0],
            items: active
              ? group[0].items.concat({
                  ...entry,
                  sublabel: this._convertItemValuesToText(entry.value, 42),
                })
              : group[0].items,
          },
          {
            ...group[1],
            items: !active
              ? group[1].items.concat({ ...entry, sublabel: '\u2013' })
              : group[1].items,
          },
        ];
      },
      [
        { key: 'active-filter', label: 'Aktive Filter', items: [] },
        { key: 'inactive-filter', label: 'Weitere Filter', items: [] },
      ],
    );
  }
 
  /**
   * @ignore
   */
  public _convertItemValuesToText(value: string[], maxLength?: number): string {
    if (value.length > 0) {
      const joinedValue = value.join('; ');
      if (maxLength === undefined || joinedValue.length < maxLength) {
        return joinedValue;
      } else if (value.length > 1) {
        return value.length.toString() + ' ausgewählt';
      } else {
        return joinedValue;
      }
    } else {
      return '\u2013';
    }
  }
 
  /**
   * @ignore
   */
  public _closeContainer(clearSelectedItem: boolean): void {
    if (clearSelectedItem) {
      this.selectedFilterItem = undefined;
      this.selectedFilterItemChange.emit(undefined);
    }
    this._filterContainerVisible = false;
 
    // closing the container closes the modalOverlayRef that tries to return the focus to the last element,
    // when the responsive/condensed filter pill is shown however this won't work as the
    // focus was within the associated menu -> set focus on the indended element here
    if (!this.filterButtonsCanFit) {
      this.condensedFiltersButton.focusChild();
    }
  }
 
  /**
   * @ignore
   */
  public focusChild(): boolean {
    if (this.getAddedItems().length === 0) {
      return this.addButtonComponent.focusChild();
    } else if (!this.filterButtonsCanFit) {
      return this.condensedFiltersButton.focusChild();
    } else {
      const firstFilterButton = this.filterButtons?.get(0);
      if (firstFilterButton) {
        return firstFilterButton.focusChild();
      } else {
        return false;
      }
    }
  }
 
  /**
   * Move the focus to the item
   * @returns `true` if the focus could be moved, otherwise false
   */
  public focusItem(item: FilterItem): boolean {
    const button = this.filterButtons?.find(b => b.itemKey === item.key);
    if (button) {
      return button.focusChild();
    }
    return false;
  }
 
  /** @ignore */
  protected abbreviate(item: FilterItem): boolean {
    return item.allowAbbreviation === true && item.value.length === 1;
  }
 
  protected responsiveFilterButtonLabel(): string {
    const number = this.getAddedItems().filter(
      item => item.value.length > 0 && item.added === true,
    ).length;
    return (number > 0 ? number.toString() + ' aktive ' : '') + 'Filter';
  }
 
  protected getAddedItems(): FilterItem[] {
    return this.items.filter(item => item.added === true);
  }
 
  protected getHiddenItems(): FilterItem[] {
    return this.items.filter(item => !item.added);
  }
 
  /** @ignore */
  private getFilterContainerAnchor(
    item: FilterItem,
  ): ElementRef<HTMLElement> | undefined {
    if (this.filterButtonsCanFit) {
      return this.filterButtons?.find(
        filterButton => filterButton.itemKey === item.key,
      )?.button;
    } else {
      return this.condensedFiltersButton.button;
    }
  }
 
  /** @ignore */
  private openFilterContainer(anchor: ElementRef<HTMLElement>) {
    this.overlayContainerAnker = anchor;
 
    this._filterContainerVisible = true;
  }
 
  /**
   * @ignore
   */
  private toggleFilterButtonsVisibility(): void {
    setTimeout(() => {
      const gap = 12;
 
      const filterButtonsWidth =
        this.filterButtonElements !== undefined &&
        this.filterButtonElements.length > 0
          ? this.filterButtonElements.reduce(
              (width, el) =>
                width + el.nativeElement.getBoundingClientRect().width,
              0,
            ) +
            (this.filterButtonElements.length - 1) * gap
          : 0;
 
      // 32 === width of filter icon (incl. padding); 40 === add button width (40)
      const filterButtonsContainerWidth =
        32 +
        gap +
        filterButtonsWidth +
        (this.getHiddenItems().length > 0 ? gap + 40 : 0);
 
      if (filterButtonsContainerWidth > this.el.nativeElement.clientWidth) {
        this.filterButtonsCanFit = false;
      } else {
        this.filterButtonsCanFit = true;
      }
    });
  }
}