All files / src/lib/wvr-dropdown wvr-dropdown.component.ts

35.29% Statements 42/119
19.61% Branches 20/102
73.91% Functions 17/23
35.04% Lines 41/117

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                              1x                         26x           1x                                                                                                                                     26x     26x     26x                                                                                           26x           13x       61x                 13x       60x                 13x       61x               13x       60x         26x           26x           26x             26x   26x     26x 26x         26x 26x         1x                                                                             1x 1x                   1x 1x                                                                                                                                                                                                                                                                                                                   1x 1x 1x   1x 1x 1x 1x 1x     1x     1x                     1x   1x                    
import { AfterViewInit, ChangeDetectionStrategy, Component, HostBinding, HostListener, Injector, Input, ViewChild } from '@angular/core';
import { NgbDropdown, NgbDropdownConfig } from '@ng-bootstrap/ng-bootstrap';
import { ThemeVariantName } from '../shared/theme';
import { projectContent } from '../shared/utility/projection.utility';
import { WvrBaseComponent } from '../shared/wvr-base.component';
 
/**
 * A dropdown with button and contextualized styling.
 */
@Component({
  selector: 'wvr-dropdown-component',
  templateUrl: './wvr-dropdown.component.html',
  styleUrls: ['./wvr-dropdown.component.scss'],
  changeDetection: ChangeDetectionStrategy.Default
})
export class WvrDropdownComponent extends WvrBaseComponent implements AfterViewInit {
 
  /** Sets asside a reference to the NgbDropdown element. */
  @ViewChild(NgbDropdown) dropdown: NgbDropdown;
 
  /** Binds the value of the animationspeed in seconds to the css variable `--wvr-dropdown-menu-animation-speed` */
  @HostBinding('style.--wvr-dropdown-menu-animation-speed') animationSpeedSeconds;
 
  /**
   * This establishes a delay in milliseconds before the dropdown is displayed.
   *
   * Do not set this too low as there may be problems with the focusIn and click events (click event may trigger or be triggered by a focusIn).
   */
  @Input() openDelay = 150;
 
  private _openDelayTimer: NodeJS.Timeout;
 
  /** A setter which sets the speed to `_animationSpeedSeconds` in seconds. */
  @Input() set menuAnimationSpeed(speed: number) {
    this.animationSpeedSeconds = `${speed / 1000}s`;
  }
 
  /** Allows for override of button background value. */
  @Input() btnBackground: string;
 
  /** Allows for override of button background value in active state. */
  @Input() btnBackgroundActive: string;
 
  /** Allows for override of button background value in hover state. */
  @Input() btnBackgroundHover: string;
 
  /** Allows for override of button border value in active state. */
  @Input() btnBorderActive: string;
 
  /** Allows for override of button border color. */
  @Input() btnBorderColor: string;
 
  /** Allows for override of button border value in focus state. */
  @Input() btnBorderFocus: string;
 
  /** Allows for override of button border value in hover state. */
  @Input() btnBorderHover: string;
 
  /** Allows for override the button color. */
  @Input() btnColor: string;
 
  /** Allows for override the button color in active state. */
  @Input() btnColorActive: string;
 
  /** Allows for override the button color in hover state. */
  @Input() btnColorHover: string;
 
  /** Allows for override the button radius. */
  @Input() btnBorderRadius: string;
 
  /** Allows for override the button box shadow in focus state. */
  @Input() btnBoxShadowFocus: string;
 
  /** Allows for override the button cursor. */
  @Input() btnCursor: string;
 
  /** Allows for override the button font family. */
  @Input() btnFontFamily: string;
 
  /** Allows for override the button font size. */
  @Input() btnFontSize: string;
 
  /** Allows for override the button font weight. */
  @Input() btnFontWeight: string;
 
  /** Allows for override the button line height. */
  @Input() btnLineHeight: string;
 
  /** Allows for override the button line height. */
  @Input() btnPadding: string;
 
  /** Allows for override the button line height. */
  @Input() btnTextAlign: string;
 
  /** Allows for override the button type. */
  @Input() btnType: string;
 
  /** Allows for override the button line height. */
  @Input() btnVerticalAlign: string;
 
  /** Allows for override of button href value. */
  @Input() btnHref = '';
 
  /** Allows for override of button size.  */
  @Input() btnSize = '';
 
  /** Allows for the visual customization of the dropdown menu activation button.  */
  @Input() themeVariant: ThemeVariantName = 'secondary';
 
  /** Binds the input from `menuBackground` to the css variable `--wvr-dropdown-menu-background` */
  @Input() menuThemeVariant: ThemeVariantName;
 
  /** Allows for override of role value (such as setting role="menu"). */
  @Input() role: string;
 
  /** Binds the input from `menu-border` to the css variable `--wvr-dropdown-menu-border` */
  @HostBinding('style.--wvr-dropdown-menu-border') @Input() menuBorder;
 
  /** Binds the input from `menu-border-radius` to the css variable `--wvr-dropdown-menu-border-radius` */
  @HostBinding('style.--wvr-dropdown-menu-border-radius') @Input() menuBorderRadius;
 
  /** Binds the input from `menu-border-display` to the css variable `--wvr-dropdown-menu-display` */
  @HostBinding('style.--wvr-dropdown-menu-display') @Input() menuBorderDisplay;
 
  /** Binds the input from `menu-border-flexDirection` to the css variable `--wvr-dropdown-menu-flex-direction` */
  @HostBinding('style.--wvr-dropdown-menu-flex-direction') @Input() menuFlexDirection;
 
  /** Binds the input from `menu-padding` to the css variable `--wvr-dropdown-menu-padding` */
  @HostBinding('style.--wvr-dropdown-menu-padding') @Input() menuPadding;
 
  /** Binds the input from `menu-width` to the css variable `--wvr-dropdown-menu-width` */
  @HostBinding('style.--wvr-dropdown-menu-width') @Input() menuWidth;
 
  /**
   * Binds the input from `menu-x-offset` to the css variable `--wvr-dropdown-x-offset`.
   * This css variable is applied by `left` css rule to the menu.
   */
  @HostBinding('style.--wvr-dropdown-menu-x-offset') @Input() menuXOffset;
 
  /**
   * Binds the input from `menu-y-offset` to the css variable `--wvr-dropdown-y-offset`.
   * This css variable is applied by `margin-top` css rule to the menu.
   */
  @HostBinding('style.--wvr-dropdown-menu-y-offset') @Input() menuYOffset;
 
  /**
   * Binds the input from `item-margin` to the css variable `--wvr-dropdown-item-margin`.
   * This css variable is applied by both the `[wvre-dropdown-menu-item]` and the `wvre-dropdown-menu-item`
   * css rules to each item passed to the the dropdown menu.
   */
  @HostBinding('style.--wvr-dropdown-menu-item-margin') @Input() menuItemMargin;
 
  /** Configures the event type which will activate the dropdown menu. */
  @Input() toggleOn: 'click' | 'mouseover' = 'click';
 
  /** Allows for override the button text decoration. */
  private _btnTextDecoration: string;
 
  @Input() set btnTextDecoration(value: string) {
    this._btnTextDecoration = value;
  }
 
  get btnTextDecoration(): string {
    return this._btnTextDecoration ?
      this._btnTextDecoration :
      `var(--wvr-btn-${this.themeVariant}-text-decoration-default)`;
  }
 
  /** Allows for override the button text decoration. */
  private _btnTextDecorationActive: string;
 
  @Input() set btnTextDecorationActive(value: string) {
    this._btnTextDecorationActive = value;
  }
 
  get btnTextDecorationActive(): string {
    return this._btnTextDecorationActive ?
      this._btnTextDecorationActive :
      `var(--wvr-btn-${this.themeVariant}-active-text-decoration-default)`;
  }
 
  // text-decoration-focus
  private _btnTextDecorationFocus: string;
 
  @Input() set btnTextDecorationFocus(value: string) {
    this._btnTextDecorationFocus = value;
  }
 
  get btnTextDecorationFocus(): string {
    return this._btnTextDecorationFocus ?
      this._btnTextDecorationFocus :
      `var(--wvr-btn-${this.themeVariant}-focus-text-decoration-default)`;
  }
 
  private _btnTextDecorationHover: string;
 
  @Input() set btnTextDecorationHover(value: string) {
    this._btnTextDecorationHover = value;
  }
 
  get btnTextDecorationHover(): string {
    return this._btnTextDecorationHover ?
      this._btnTextDecorationHover :
      `var(--wvr-btn-${this.themeVariant}-hover-text-decoration-default)`;
  }
 
  @Input() placement = 'top-right';
 
  /**
   * A public access reference to the open/closed state of the dropdown menu. Used for
   * animations;
   */
  open = false;
 
  /**
   * A state used to represent that focus is on or within the element.
   * Used for button navigation decisions.
   */
  focus = false;
 
  /**
   * Designate that a close has been requested.
   *
   * Used to inform that the popup should be closed while the popup is still in the process of opening up.
   */
  private requestClose = false;
 
  @Input() dropdownMenuDisplay = 'dynamic';
 
  constructor(injector: Injector, config: NgbDropdownConfig) {
    super(injector);
    config.autoClose = false;
  }
 
  /** Called after the view has been intialized. Handles the rendering of the projected content. */
  ngAfterViewInit(): void {
    projectContent(this.eRef, 'template[dropdown-button]', 'span[button-content]');
    projectContent(this.eRef, 'template[dropdown-menu]', 'div[dropdown-menu]');
  }
 
  /** An access method to expose the `isOpen` utility method from `NgbDropdown` */
  isOpen(): boolean {
    return this.dropdown ? this.dropdown.isOpen() : false;
  }
 
  /**
   * A handler method for the `focus` event.
   */
  @HostListener('focusin', ['$event']) focusIn($event: Event): void {
    if (this.eRef.nativeElement.contains($event.target)) {
      if (!this.focus) {
        $event.stopPropagation();
        $event.preventDefault();
 
        this.giveFocus();
      }
    } else {
      this.takeFocus();
    }
  }
 
  /**
   * A handler method for the `focus` event.
   *
   * The 'relatedTarget' may be null if the focus lost is due to the focus leaving the web browser itself rather than the element within the page.
   * In this case, do not remove focus because the what goes on outside of the page should not affect what goes inside the page.
   */
  @HostListener('focusout', ['$event']) focusOut($event: Event): void {
    if ($event['relatedTarget'] !== null) {
      if (!this.eRef.nativeElement.contains($event['relatedTarget'])) {
        this.takeFocus();
      }
    }
  }
 
  /**
   * A handler method for the `mouseenter` event.
   *
   * Opens the dropdown if `toggleOn` is set to `mouseover`.
   */
  @HostListener('mouseenter', ['$event']) hoverOpen($event: Event): void {
    Eif (this.toggleOn === 'mouseover') {
      this.giveFocus();
    }
  }
 
  /**
   * A handler method for the `mouseleave` event.
   *
   * Closes the dropdown if `toggleOn` is set to `mouseover`.
   */
  @HostListener('mouseleave', ['$event']) hoverClose($event: Event): void {
    Eif (this.toggleOn === 'mouseover') {
      this.takeFocus();
    }
  }
 
  /**
   * A handler method for the `document:mousedown` event.
   *
   * Closes the dropdown if `toggleOn` is set to `click`
   * And the click occured off of the wvre-dropdown component.
   *
   * The event.button == 0 is the left click or the un-initialized state.
   *
   * The 'mousedown' is used instead of 'click' to avoid bubbling problems.
   * The 'click' does not happen before 'focusin' and there is a race condition between the two.
   * When 'mousedown' is used, it happens before 'focusin' and the bubbling can be blocked to avoid a race condition.
   */
  @HostListener('document:mousedown', ['$event']) documentClick($event: MouseEvent): void {
    if ($event.button == 0) {
      const dropDownButton = this.eRef.nativeElement.querySelector(".wvr-dropdown > div > wvr-button-component");
      if (!!dropDownButton && !!dropDownButton.nativeElement && !!$event.target) {
        if (dropDownButton.nativeElement.contains($event.target)) {
          if (this.toggleOn === 'click') {
            $event.stopPropagation();
            $event.preventDefault();
 
            if (this.isOpen()) {
              this.takeFocus();
            } else {
              this.giveFocus();
            }
          }
        } else {
          this.takeFocus();
        }
      }
    }
  }
 
  /**
   * A single handler method for when the any key is down while associated with the host element.
   */
  @HostListener('keydown', ['$event']) keyDown($event): void {
    const lowerKey = $event.key.toLowerCase();
 
    if (lowerKey == "escape") {
      if (this.isOpen()) {
        const list = this.eRef.nativeElement.querySelector('.dropdown-menu > *');
 
        $event.stopPropagation();
        $event.preventDefault();
 
        if (!!list && list.contains($event.target)) {
          this.focusToToggle();
        } else {
          this.takeFocus();
        }
      }
    }
    else if (lowerKey == "space") {
      const list = this.eRef.nativeElement.querySelector('.dropdown-menu > *');
 
      if (!!list && list.contains($event.target)) {
        // @todo
      } else {
        $event.stopPropagation();
        $event.preventDefault();
 
        if (this.isOpen()) {
          this.takeFocus();
        } else {
          this.giveFocus();
        }
      }
    }
    else if (lowerKey == "arrowup" || lowerKey == "arrowdown") {
      const list = this.eRef.nativeElement.querySelector('.dropdown-menu > *');
 
      if (!!list) {
        const up = lowerKey == "arrowup";
 
        $event.stopPropagation();
        $event.preventDefault();
 
        if (list.contains($event.target)) {
          let focused = list.children.length;
 
          for (let i = 0; i < list.children.length; i++) {
            if ($event.target == list.children[i]) {
              focused = i;
            }
          }
 
          this.focusToChild(focused, up, list);
        }
        else if (list.children.length > 0) {
          const focused = up ? list.children.length - 1 : -1;
 
          this.focusToChild(focused, up, list);
        }
      }
    }
  }
 
  /** Change focus to the drop down toggle that exists outside of the drop down list. */
  private focusToToggle() {
    const dropdown = this.eRef.nativeElement.querySelector('.dropdown .dropdown-toggle .wvr-button');
 
    if (!!dropdown) {
      dropdown.focus();
    }
  }
 
  /** Change focus to a non-disabled child based on the current focused position within the list. */
  private focusToChild(focused: number, up: boolean, list: any): void {
    if (focused == list.children.length || up && focused == 0 || !up && focused == list.children.length) {
      this.focusToToggle();
    } else {
      let i = up ? focused - 1 : focused + 1;
 
      // Select the first non-disabled child.
      if (up) {
        for (; i >= 0; i--) {
          if (!list.children[i].hasAttribute('disabled')) {
            break;
          }
 
          // There is no available child to move to, so set out of range.
          if (i == 0) {
            i = list.children.length;
            break;
          }
        }
      } else {
        for (; i < list.children.length; i++) {
          if (!list.children[i].hasAttribute('disabled')) {
            break;
          }
        }
      }
 
      if (i == list.children.length) {
        this.focusToToggle();
      } else {
        list.children[i].focus();
      }
    }
  }
 
  /**
   * If focus is not set, then set focus.
   *
   * Does open dropdown, if it is closed and not already in the process of opening.
   */
  private giveFocus(): void {
    Eif (!this._openDelayTimer && !this.focus) {
      this.focus = true;
      this.requestClose = false;
 
      this._openDelayTimer = setTimeout(() => {
        Eif (this.focus) {
          Eif (!this.requestClose && !this.isMobileLayout) {
            this.open = true;
            this.dropdown.open();
          }
 
          this._openDelayTimer = undefined;
        }
 
        this.requestClose = false;
      }, this.openDelay);
    }
  };
 
  /**
   * If focus is set, then unset focus.
   *
   * Does close dropdown, if it is open.
   */
  private takeFocus(): void {
    Iif (!!this._openDelayTimer) {
      this.requestClose = true;
    } else Iif (this.focus) {
      this.focus = false;
 
      if (this.isOpen()) {
        this.open = false;
        this.dropdown.close();
      }
    }
  };
}