All files / element-ng/navbar-vertical si-navbar-vertical-group-trigger.directive.ts

96.87% Statements 62/64
90.9% Branches 30/33
100% Functions 13/13
96.36% Lines 53/55

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                                                                    2x           2x   1x                           45x 2x     10x 10x     10x         10x     10x     10x     10x     10x   10x     10x 10x 10x 10x                     10x   1x       10x 16x 16x 16x 11x       11x 11x 11x     11x             10x         3x 1x 1x 1x 1x 1x 1x         6x 1x   5x 5x         1x     1x 1x       11x 11x 11x           1x 1x 1x     1x 1x   1x      
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Overlay } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import {
  ChangeDetectionStrategy,
  Component,
  ComponentRef,
  computed,
  Directive,
  effect,
  EmbeddedViewRef,
  inject,
  Injector,
  input,
  model,
  OnInit,
  signal,
  TemplateRef,
  ViewContainerRef
} from '@angular/core';
import { Subscription } from 'rxjs';
 
import { NavbarVerticalItem, NavbarVerticalItemGroup } from './si-navbar-vertical.model';
import { SI_NAVBAR_VERTICAL } from './si-navbar-vertical.provider';
 
/**
 * Using this component, to anchor the flyout inside the navbar within the a11y tree.
 * Otherwise, without aria-owns, screen reader will announce the leaving of the navbar when moving to the flyout.
 * Aria-owns cannot be put directly on the trigger
 * as chrome will include the flyout children in the a11y label of the trigger.
 */
@Component({
  selector: 'si-navbar-flyout-anchor',
  template: '',
  changeDetection: ChangeDetectionStrategy.Eager,
  host: { '[attr.aria-owns]': 'groupId()' }
})
class SiNavbarFlyoutAnchorComponent {
  /** ID of the flyout group owned by this accessibility anchor. */
  readonly groupId = input<string>();
}
 
@Directive({
  selector: 'button[siNavbarVerticalGroupTriggerFor]',
  host: {
    class: 'dropdown-toggle',
    '[id]': 'id',
    '[class.show]': 'expanded()',
    '[attr.aria-controls]': 'groupId',
    '[attr.aria-expanded]': 'expanded()',
    '(click)': 'triggered()'
  }
})
export class SiNavbarVerticalGroupTriggerDirective implements OnInit {
  private static idCounter = 0;
 
  /** @internal */
  readonly groupId = `si-navbar-vertical-group-${SiNavbarVerticalGroupTriggerDirective.idCounter++}`;
  readonly id = `${this.groupId}-trigger`;
 
  /** Template rendered for the expandable group. */
  readonly groupTemplate = input.required<TemplateRef<unknown>>({
    alias: 'siNavbarVerticalGroupTriggerFor'
  });
 
  /** Context passed to the group template. */
  readonly groupData = input<{ item?: NavbarVerticalItem; group: NavbarVerticalItemGroup }>();
 
  /** Key used to persist the expanded state of this group. */
  readonly stateId = input<string>();
 
  /** Whether the group is expanded. Emits `expandedChange` when changed. */
  readonly expanded = model.required<boolean>();
 
  /** @internal */
  readonly flyout = signal(false);
 
  /** @internal */
  readonly active = signal(false);
 
  protected readonly navbar = inject(SI_NAVBAR_VERTICAL);
 
  private flyoutOutsideClickSubscription?: Subscription;
  private readonly viewContainer = inject(ViewContainerRef);
  private readonly overlay = inject(Overlay);
  private readonly injector = Injector.create({ parent: inject(Injector), providers: [] });
  private readonly overlayRef = this.overlay.create({
    positionStrategy: this.overlay
      .position()
      .flexibleConnectedTo(this.viewContainer.element)
      .withPositions([
        { originX: 'end', originY: 'top', overlayX: 'start', overlayY: 'top' },
        { originX: 'end', originY: 'bottom', overlayX: 'start', overlayY: 'bottom' }
      ])
  });
  private groupView!: EmbeddedViewRef<unknown>;
  private flyoutAnchorComponentRef?: ComponentRef<SiNavbarFlyoutAnchorComponent>;
  private readonly templatePortal = computed(
    () =>
      new TemplatePortal(this.groupTemplate(), this.viewContainer, this.groupData(), this.injector)
  );
 
  constructor() {
    effect(() => {
      const data = this.groupData();
      const view = this.groupView;
      if (data && view && !view.destroyed) {
        const context = view.context as {
          item?: NavbarVerticalItem;
          group: NavbarVerticalItemGroup;
        };
        Eif (context) {
          context.group = data.group;
          Iif (data.item !== undefined) {
            context.item = data.item;
          }
          view.detectChanges();
        }
      }
    });
  }
 
  ngOnInit(): void {
    this.attachInline();
  }
 
  /** @internal */
  hideFlyout(): void {
    if (this.flyout()) {
      this.flyout.set(false);
      this.active.set(false);
      this.flyoutAnchorComponentRef?.destroy();
      this.flyoutAnchorComponentRef = undefined;
      this.attachInline();
      this.flyoutOutsideClickSubscription?.unsubscribe();
    }
  }
 
  protected triggered(): void {
    if (this.navbar.collapsed()) {
      this.toggleFlyout();
    } else {
      this.expanded.set(!this.expanded());
      this.navbar.groupTriggered();
    }
  }
 
  private toggleFlyout(): void {
    Iif (this.flyout()) {
      this.hideFlyout();
    } else {
      this.flyout.set(true);
      this.attachFlyout();
    }
  }
  private attachInline(): void {
    this.overlayRef.detach();
    this.groupView?.destroy(); // we need ?. for first attachment
    this.groupView = this.viewContainer.createEmbeddedView(this.groupTemplate(), this.groupData(), {
      injector: this.injector
    });
  }
 
  private attachFlyout(): void {
    this.groupView.destroy();
    this.groupView = this.overlayRef.attach(this.templatePortal());
    this.flyoutAnchorComponentRef = this.viewContainer.createComponent(
      SiNavbarFlyoutAnchorComponent
    );
    this.flyoutAnchorComponentRef.setInput('groupId', this.groupId);
    this.flyoutOutsideClickSubscription = this.overlayRef
      .outsidePointerEvents()
      .subscribe(() => this.hideFlyout());
  }
}