All files / lib/table table-cell-simple.component.ts

96.28% Statements 545/566
91.96% Branches 103/112
94.44% Functions 34/36
96.28% Lines 545/566

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 5671x 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 300x 300x 300x 300x 300x 1x 1x 339x 337x 337x 337x 337x 337x 337x 339x 339x 1x 1x 337x 337x 337x 337x 337x 337x 337x 337x 337x 337x 1x 1x 337x 337x 337x 1339x 1339x 337x 337x 337x 337x 337x 337x 337x 337x 337x 337x 337x 337x 337x 337x 1339x 337x 337x 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 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 2383x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 300x 300x 300x 1x 1x 1x 78165x 78165x       144x 144x 78165x 6450x 6450x 6450x 6450x 6450x 6450x 78165x 45756x 6602x 6602x 6602x   6602x 45756x 39154x 78165x 78165x 1x 1x 1x 22773x 22773x 3186x 19587x 19587x 1593x 7x 7x 7x 19580x 19580x 22773x 22773x 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 2383x 4467x 2383x 2383x 1x 1x 1x 2955x 340x 2955x 2955x 1x 1x 1x 834x 834x 1x 1x 1x 45444x 45444x 1x 1x 1x 4467x 4467x 4467x 4467x 4467x 4467x 4467x 4467x 4467x 4467x 4467x 2084x 2084x 2084x 2084x 2567x 2567x 2567x 2527x 2527x 2567x 2567x 40x 40x 40x 40x 2567x 2567x 2567x 2084x 4467x 4467x 4467x 1x 1x 1x 7034x 7034x 7034x 7034x 7034x 7034x 7034x 7034x 7034x 35x 6999x 7034x 7034x 7034x 7034x 1x 1x 1x 13046x 13006x 40x 40x     13046x 13046x 1x 1x 94584x 94584x 1x 1x 1x 4x 4x 1x 1x 1x           1x 1x 1x 53x 53x 1x 1x 1x 7087x 7087x 3269x 3818x 7087x 4704x 4704x 4704x 4704x 4704x 4704x 4704x 3283x 4704x 7087x 7087x 1x 1x 1x 45784x 45784x 1x 1x 1x 6908x 6908x 6908x 6908x 1x 1x 1x 3283x 3283x     3283x 1x 1x 1x 1x 1x         1x 1x 1x 9849x 6x 9843x 9849x 1x 1x 1x 3283x 2x 3281x 3283x 1x 1x 1x 4x 2x 2x 1x 1x     1x 1x 1x 1x 1x 1x 1x     2x 2x 2x 2x 2x 2x 4x 1x 1x 1x 45756x 45756x 1x 1x 1x 340x 339x 339x 339x 339x 339x 1x 1x 340x 340x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  NgTemplateOutlet,
  formatNumber,
  registerLocaleData,
} from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';
import {
  Component,
  ElementRef,
  Input,
  NgZone,
  OnChanges,
  OnDestroy,
  QueryList,
  SimpleChanges,
  TemplateRef,
  ViewChild,
  ViewChildren,
  effect,
  input,
  viewChild,
} from '@angular/core';
 
import { LinkEvent } from '../utils/event.types';
import { observeSizeOutsideAngular } from '../utils/internal-utils';
import {
  BadgeColor,
  BadgeStatus,
  BadgeVariant,
  Consumer,
  HasHighlight,
  WidgetKeySet,
} from '../utils/util.types';
import { createWidgetKeySet } from '../utils/utilities';
 
import { SurfaceColors } from '../internal/surface.directive';
 
registerLocaleData(localeDe, 'de-DE', localeDeExtra);
 
@Component({
  selector: 'gc-aligned-number',
  template:
    '<span class="gc-num-integer">{{ integer }}</span>@if (fraction.length > 0) {,}<span class="gc-num-fraction">{{ fraction }}</span>',
  styles: [
    `
      :host {
        white-space: nowrap;
      }
      .gc-num-fraction {
        display: inline-block;
        text-align: left;
      }
    `,
  ],
  standalone: false,
})
export class AlignedNumberComponent implements OnChanges {
  @Input()
  public integer = '';
 
  @Input()
  public fraction = '';
 
  private readonly componentTag: string;
 
  constructor(
    private readonly el: ElementRef<HTMLElement>,
    private readonly zone: NgZone,
  ) {
    this.componentTag = el.nativeElement.tagName;
  }
 
  public ngOnChanges(changes: SimpleChanges): void {
    if ('fraction' in changes) {
      this.zone.runOutsideAngular(() => {
        requestAnimationFrame(() => {
          NgZone.assertNotInAngularZone();
          this.fixIt();
        });
      });
    }
  }
 
  private fixIt(): void {
    const table = this.el.nativeElement.closest('table');
    const td = this.el.nativeElement.closest('td');
    const columnId = td?.dataset.gcTableColumnKey;
    if (columnId && table) {
      const numFractionsInColumn = table.querySelectorAll<HTMLElement>(
        `td[data-gc-table-column-key='${columnId}'] ${this.componentTag} .gc-num-fraction`,
      );
      this.fixNumberAlignments(numFractionsInColumn);
    }
  }
 
  private fixNumberAlignments(columnNodes: NodeListOf<HTMLElement>): void {
    let charCount = 0;
    let max = 0;
    columnNodes.forEach(node => {
      const cur = node.textContent?.length ?? 0;
      max = Math.max(cur, max);
    });
 
    if (max > 0) {
      charCount = max + 0.05; // add some buffer to allow for font variance between width of "0" (1ch) and other characters
    }
 
    /*
     * if a letter spacing is set it is appended on each character - also the last
     * so we can simply use the char count and multiply that with the char spacing
     * set
     */
    const width = `calc( ${max.toString()} * var(--gc-setting-typography-letter-spacing, 0em) + ${charCount.toFixed(2)}ch  )`;
 
    columnNodes.forEach(node => {
      node.style.width = width;
    });
  }
}
 
/**
 * Data required to show a cell with a link
 */
export type CellLinkData =
  | string
  | {
      /** URL that the user will be sent to on click. */
      link: string;
      /** Opens the link in a new browser tab  */
      openInNewTab?: true;
      /** decides if an arrow icon will be rendered, and the link will be opened in new tab or not. */
      defaultOpenInNewTab?: boolean;
    };
 
type InlineIconType<C> =
  | TemplateRef<C>
  | { template: TemplateRef<C>; size: number; label: string };
 
/**
 * A simple table cell.
 */
@Component({
  selector: 'gc-table-cell-simple',
  templateUrl: './table-cell-simple.component.html',
  styleUrls: [
    './table-cell-simple.component.css',
    '../utils/styles/patterns.css',
  ],
  standalone: false,
})
export class TableCellSimpleComponent<
    C extends NonNullable<NgTemplateOutlet['ngTemplateOutletContext']>,
  >
  implements OnChanges, OnDestroy
{
  /** Context passed when instantiating templates for the cell, e.g. icons. */
  @Input()
  public templateContext: C | null = null;
 
  /** The text to be shown. */
  @Input()
  public text?: string | [string, string] | null;
 
  /** The text to be shown in the tooltip. */
  @Input()
  public tooltipText?: string | null;
 
  /** The url to be linked to. If specified the cell will be a hyperlink. */
  @Input()
  public link?: CellLinkData;
 
  /** Optional handler to customize handling of navigation requests */
  @Input()
  public linkHandler?: Consumer<LinkEvent>;
 
  /** The badge label to be shown. */
  @Input()
  public badge?: string;
 
  /** The badge variant. */
  @Input()
  public badgeVariant: BadgeVariant = 'primary';
 
  /** The badge color. */
  @Input()
  public badgeColor: BadgeStatus | BadgeColor = 'basic';
 
  /**
   * Icon provider for badge
   */
  @Input()
  public badgeIconProvider?: TemplateRef<unknown>;
 
  /** Decides the color of the label. */
  @Input()
  public textColor: 'light' | 'dark' = 'dark';
 
  /** The template to the icon to be used. */
  @Input()
  public icon?: TemplateRef<C> | { template: TemplateRef<C>; size: number };
 
  /** The number to be shown. */
  @Input()
  public number?: number;
 
  /**
   * Format that should be used to display the number.
   *
   * Specified as a string in the following format: `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}.
   */
  @Input()
  public numberFormat = '1.2-4';
 
  /** Optional visual highlight for the cell. */
  @Input()
  public highlight?: HasHighlight;
 
  /** Turn on / off text highlighting */
  @Input()
  public showTextHighlight = true;
 
  /**
   * Mark the content as new entry.
   */
  @Input()
  public newItem = false;
 
  /**
   * (Optional) Sublabel to display
   */
  @Input()
  public sublabel = '';
 
  /** (Optional) Surface setting for the cell. */
  @Input()
  public surface?: SurfaceColors;
 
  /** @ignore */
  @ViewChild('cellEl')
  protected cellElement!: ElementRef<HTMLElement>;
 
  /** @ignore */
  @ViewChildren('textHighlight', { read: ElementRef })
  protected textHighlights?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChildren('textNode')
  protected textNodes?: QueryList<ElementRef<HTMLElement>>;
 
  /** The badge status.
   * @deprecated use `badgeColor` instead
   */
  @Input()
  public set badgeStatus(status: BadgeStatus) {
    this.badgeColor = status;
  }
 
  /** @ignore */
  protected get titleText(): string {
    if (this.text && this.sublabel) {
      if (this.badge) {
        return `${this.badge} ${this.straightenText(this.text)} ${
          this.sublabel
        }`;
      }
      return `${this.text.toString()} ${this.sublabel}`;
    } else if (this.number) {
      const formattedNumber = formatNumber(
        this.number,
        'de-DE',
        this.numberFormat,
      );
      return this.badge ? `${formattedNumber} ${this.badge}` : formattedNumber;
    } else if (this.text) {
      if (this.badge) {
        const straightText = this.straightenText(this.text);
        return this.badgeColor === 'critical'
          ? `${this.badge} ${straightText}`
          : `${straightText} ${this.badge}`;
      }
      return this.straightenText(this.text);
    }
    return this.badge ? this.badge : '';
  }
 
  /** @ignore */
  protected get effectiveTooltipText(): string {
    const inlineIcon = this.$inlineIcon();
    if (this.tooltipText) {
      return this.tooltipText;
    } else if (
      !this.titleText &&
      inlineIcon &&
      this.isIconWithDetails(inlineIcon)
    ) {
      return inlineIcon.label;
    } else {
      return this.titleText;
    }
  }
 
  /**
   * @ignore
   */
  public readonly $inlineIcon = input<InlineIconType<C>>(undefined, {
    alias: 'inlineIcon',
  });
 
  /** @ignore */
  protected numberInt = '';
 
  /** @ignore */
  protected numberFraction = '';
 
  /** @ignore */
  protected inlineIconHasTwoRows = false;
 
  /** @ignore */
  protected inlineIconTextIsTruncated = false;
 
  /** @ignore */
  protected inlineIconPaddingBottom = 0;
 
  /** @ignore */
  private readonly widgetKeySet: WidgetKeySet = createWidgetKeySet(
    'gc-table-cell-simple',
  );
 
  /**
   * @ignore
   */
  private linkExternalDescriptionId?: string;
 
  /**
   * @ignore
   */
  private sizeObserver?: () => void;
 
  /**
   * @ignore
   */
  private readonly _textContainer =
    viewChild<ElementRef<HTMLElement>>('textContainer');
 
  constructor(private readonly zone: NgZone) {
    effect(() => {
      this.setupInlineIconSupport(this._textContainer(), this.$inlineIcon());
    });
  }
 
  /** @ignore */
  ngOnChanges(changes: SimpleChanges): void {
    if ('number' in changes || 'numberFormat' in changes) {
      this.updateNumberStrings();
    }
  }
 
  /** @ignore */
  ngOnDestroy(): void {
    this.sizeObserver?.();
  }
 
  /** @ignore */
  public _hasHighlight(): boolean {
    return this.highlight !== undefined;
  }
 
  /** @ignore */
  protected setupInlineIconSupport(
    textContainer: ElementRef<HTMLElement> | undefined,
    inlineIcon: InlineIconType<C> | undefined,
  ) {
    const d = this._recomputeForInlineIcon(textContainer, inlineIcon);
    this.inlineIconHasTwoRows = d[0];
    this.inlineIconTextIsTruncated = d[1];
    this.inlineIconPaddingBottom = d[2];
 
    this.sizeObserver?.();
 
    if (textContainer) {
      this.sizeObserver = observeSizeOutsideAngular(
        this.zone,
        [textContainer.nativeElement],
        () => {
          const d = this._recomputeForInlineIcon(textContainer, inlineIcon);
          if (
            this.inlineIconHasTwoRows !== d[0] ||
            this.inlineIconTextIsTruncated !== d[1] ||
            this.inlineIconPaddingBottom !== d[2]
          ) {
            return () => {
              this.inlineIconHasTwoRows = d[0];
              this.inlineIconTextIsTruncated = d[1];
              this.inlineIconPaddingBottom = d[2];
            };
          } else {
            return undefined;
          }
        },
      );
    }
  }
 
  /** @ignore */
  protected _recomputeForInlineIcon(
    textContainer: ElementRef<HTMLElement> | undefined,
    inlineIcon: InlineIconType<C> | undefined,
  ) {
    return [
      textContainer ? textContainer.nativeElement.clientHeight > 22 : false,
      this.isTextTruncated(),
      Math.abs(
        (22 -
          (inlineIcon && this.isIconWithDetails(inlineIcon)
            ? inlineIcon.size
            : 40)) /
          2,
      ),
    ] as const;
  }
 
  /** @ignore */
  protected singleValueText(): string | undefined {
    if (this.isSingleValue(this.text)) {
      return this.text;
    } else if (Array.isArray(this.text)) {
      return this.text[0];
    } else {
      return undefined;
    }
  }
 
  protected isSingleValue(v: unknown): v is string {
    return typeof this.text === 'string';
  }
 
  /** @ignore */
  protected _handleClick(): boolean {
    return this._internalHandleClick(true);
  }
 
  /** @ignore */
  protected _handleAuxClick(event: MouseEvent): boolean {
    if (event.button === 1) {
      return this._internalHandleClick(false);
    }
    return true;
  }
 
  /** @ignore */
  protected permitTooltip(): boolean {
    return this.isTextTruncated() || this.effectiveTooltipText !== this.text;
  }
 
  /** @ignore */
  protected isTextTruncated(): boolean {
    const elements =
      this.textHighlights && this.textHighlights.length > 0
        ? this.textHighlights
        : this.textNodes;
    if (!elements) {
      return false;
    }
 
    return elements
      .toArray()
      .some(
        el =>
          el.nativeElement.scrollWidth > el.nativeElement.offsetWidth ||
          el.nativeElement.scrollHeight > el.nativeElement.offsetHeight,
      );
  }
 
  /** @ignore */
  protected isValidNumber(val: number | undefined): val is number {
    return typeof val === 'number' && !Number.isNaN(val);
  }
 
  /** @ignore */
  protected isIconWithDetails(
    icon: TemplateRef<C> | { template: TemplateRef<C>; size: number },
  ): icon is { template: TemplateRef<C>; size: number } {
    return 'size' in icon;
  }
 
  /** @ignore */
  protected linkUrl() {
    if (this.link) {
      return typeof this.link === 'string' ? this.link : this.link.link;
    }
    return '';
  }
 
  /**
   * @ignore
   */
  protected getLinkExternalDescriptionId() {
    this.linkExternalDescriptionId ??=
      this.widgetKeySet.baseKey + '-description';
    return this.linkExternalDescriptionId;
  }
 
  /** @ignore */
  protected linkDefaultOpenInNewTab() {
    return this.link && typeof this.link === 'object'
      ? this.link.defaultOpenInNewTab
      : false;
  }
 
  /** @ignore */
  protected linkOpenInNewTab() {
    return this.link && typeof this.link === 'object'
      ? this.link.openInNewTab
      : false;
  }
 
  /** @ignore */
  private _internalHandleClick(replace: boolean): boolean {
    if (this.linkHandler && this.link) {
      if (typeof this.link === 'string') {
        try {
          this.linkHandler({ linkInfo: this.link, replace });
        } catch (e) {
          console.error('Failed to execute link handler', e);
        }
      } else {
        try {
          this.linkHandler({
            linkInfo: this.link.link,
            replace: this.link.openInNewTab ? false : replace,
          });
        } catch (e) {
          console.error('Failed to execute link handler', e);
        }
      }
 
      return false;
    }
 
    return true;
  }
 
  /** @ignore */
  private straightenText(value: string | [string, string]): string {
    return this.isSingleValue(value) ? value : `${value[0]} ${value[1]}`;
  }
 
  /** @ignore */
  private updateNumberStrings(): void {
    if (this.isValidNumber(this.number)) {
      const formatted = formatNumber(this.number, 'de-DE', this.numberFormat);
      const split = formatted.split(',');
      this.numberInt = split[0];
      this.numberFraction = split[1];
    } else {
      this.numberInt = '';
      this.numberFraction = '';
    }
  }
}