All files / lib/responsive-container responsive-container.component.ts

95.23% Statements 200/210
88.57% Branches 31/35
80% Functions 8/10
95.23% Lines 200/210

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 2111x 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 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 1x 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 8x 8x 1x 1x 1x 11x   11x 11x 1x 1x 1x 8x 8x 8x 8x 8x 1x 1x 1x             1x 1x 1x 28x 28x 28x 28x 28x 52x 52x 52x 52x 52x 52x 52x 52x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 52x 28x 1x 1x 28x 28x 1x 1x 1x 1x 1x 1x 27x 27x 27x 28x 28x 1x 1x 1x 8x 8x 8x 24x 8x 8x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  AfterViewInit,
  Component,
  ContentChild,
  ElementRef,
  HostBinding,
  Input,
  NgZone,
  OnChanges,
  OnDestroy,
  QueryList,
  SimpleChanges,
  ViewChildren,
} from '@angular/core';
import { Subscription, startWith } from 'rxjs';
 
import { createResizeObserver } from '../utils/internal-utils';
import { Callback } from '../utils/util.types';
 
import { ResponsiveItemHelperDirective } from './responsive-item-helper.directive';
import { ResponsiveItemTemplateDirective } from './responsive-item-template.directive';
 
interface Breakpoint<K extends ResponsiveBreakpointKey> {
  key: K;
  size: number;
}
 
/**
 * Type of keys in the `Breakpoints` structure.
 */
export type ResponsiveBreakpointKey = string | symbol;
 
/**
 * Collection of breakpoints, associating keys with minimum widths. A value of `null`
 * represents a default breakpoint to use if no other value applies and should be present
 * only once in the structure.
 */
export type Breakpoints<K extends ResponsiveBreakpointKey> = Record<
  K,
  number | null
>;
 
/**
 * Layout utility to switch between responsive items based on remaining space for some other component.
 *
 * The component renders its content besides an instance of the provided `ResponsiveItemTemplateDirective`. The actual breakpoint for rendering
 * the item template is chosen based on the passed set of available breakpoints. The largest breakpoint, for which the corresponding rendered item
 * leaves at least the specified remaining width *available for the primary content*, is chosen.
 */
@Component({
  selector: 'gc-responsive-container',
  templateUrl: './responsive-container.component.html',
  styleUrls: ['./responsive-container.component.css'],
})
export class ResponsiveContainerComponent<K extends ResponsiveBreakpointKey>
  implements OnDestroy, AfterViewInit, OnChanges
{
  /**
   * Reverse the tab-order of the two elements inside `gc-responsive-container`
   */
  @HostBinding('class.gc-row-reverse')
  @Input()
  public tabReverse = false;
 
  /** @ignore */
  @ContentChild(ResponsiveItemTemplateDirective)
  protected responsiveTemplate?: ResponsiveItemTemplateDirective<K>;
 
  /** @ignore */
  @ViewChildren(ResponsiveItemHelperDirective)
  protected responsiveItems!: QueryList<ResponsiveItemHelperDirective<K>>;
 
  /**
   * Breakpoints to use for switching between the responsive items.
   */
  @Input()
  public set breakpoints(value: Breakpoints<K>) {
    this._breakpoints = value;
    const ar: Breakpoint<K>[] = [];
 
    for (const key in value) {
      ar.push({ key, size: value[key] ?? Number.MAX_VALUE });
    }
 
    ar.sort((a, b) => a.size - b.size);
    this.arBreakpoints = ar;
 
    // set current breakpoint if none is set (e.g. initial render) or if it became invalid,
    // optimistic assumption is that the largest one will usually be correct (recalculated after content becomes visible)
    if (
      this.currentBreakpoint === undefined ||
      !(this.currentBreakpoint in value)
    ) {
      this.currentBreakpoint =
        this.arBreakpoints[this.arBreakpoints.length - 1]?.key;
    }
  }
 
  public get breakpoints() {
    return this._breakpoints;
  }
 
  /** @ignore */
  protected arBreakpoints: readonly Breakpoint<K>[] = [];
  /** @ignore */
  protected currentBreakpoint?: K;
  /** @ignore */
  private _breakpoints: Breakpoints<K> = {} as Breakpoints<K>;
 
  /** @ignore */
  private resizeObserver: ResizeObserver;
  /** @ignore */
  private sizeObserverCleanup: Callback;
  /** @ignore */
  private responsiveItemsObserver?: Subscription;
  /** @ignore */
  private breakpointUpdateTimeout?: ReturnType<typeof setTimeout>;
 
  constructor(
    private el: ElementRef<HTMLElement>,
    zone: NgZone,
  ) {
    [this.resizeObserver, this.sizeObserverCleanup] = createResizeObserver(
      zone,
      () => this.recomputeBreakpoint(false),
    );
  }
 
  /** @ignore */
  public ngOnChanges(changes: SimpleChanges): void {
    if ('breakpoints' in changes && !changes.breakpoints.firstChange) {
      this.recomputeBreakpoint(true);
    }
  }
 
  /** @ignore */
  public ngAfterViewInit(): void {
    this.responsiveItemsObserver = this.responsiveItems.changes
      .pipe(startWith([])) // trigger initial setup, as there are initially no changes when the subscription is created
      .subscribe(() => this.setupResizeObservations());
    this.recomputeBreakpoint(true);
  }
 
  /** @ignore */
  public ngOnDestroy(): void {
    this.responsiveItemsObserver?.unsubscribe();
    this.sizeObserverCleanup();
    if (this.breakpointUpdateTimeout !== undefined) {
      clearTimeout(this.breakpointUpdateTimeout);
    }
  }
 
  /** @ignore */
  private recomputeBreakpoint(triggeredByInputChange: boolean) {
    const totalWidth = this.el.nativeElement.clientWidth;
    let newBreakpoint =
      this.arBreakpoints.length > 0 ? this.arBreakpoints[0].key : undefined;
 
    for (let i = 1; i < this.arBreakpoints.length; i++) {
      const item = this.responsiveItems.find(
        respItem => respItem.breakpoint === this.arBreakpoints[i].key,
      );
      if (item) {
        const availableWidth =
          totalWidth - item._element.nativeElement.clientWidth;
        if (availableWidth > this.arBreakpoints[i - 1].size) {
          newBreakpoint = this.arBreakpoints[i].key;
        } else {
          break;
        }
      } else {
        console.error(
          'failed to find rendered compute helper item for breakpoint',
          this.arBreakpoints[i].key,
        );
        break;
      }
    }
 
    if (this.breakpointUpdateTimeout !== undefined) {
      clearTimeout(this.breakpointUpdateTimeout);
      this.breakpointUpdateTimeout = undefined;
    }
    if (triggeredByInputChange && this.currentBreakpoint !== newBreakpoint) {
      // if the breakpoint calculation was triggered by an Angular change detection cycle, immediately
      // updating the current breakpoint would result in an NG0100 error (expression changed after checked),
      // in this case delay the update to workaround the error.
      // ideally the initially set breakpoint is guessed correctly, in which case no initial update is needed
      this.breakpointUpdateTimeout = setTimeout(
        () => (this.currentBreakpoint = newBreakpoint),
      );
    } else {
      this.currentBreakpoint = newBreakpoint;
    }
  }
 
  /** @ignore */
  private setupResizeObservations(): void {
    this.resizeObserver.disconnect();
    this.resizeObserver.observe(this.el.nativeElement);
    this.responsiveItems.forEach(i =>
      this.resizeObserver.observe(i._element.nativeElement),
    );
  }
}