All files / lib/internal virtual-listbox.directive.ts

97.55% Statements 279/286
89.7% Branches 61/68
95.65% Functions 22/23
97.55% Lines 279/286

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 2871x 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 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 1x 1x 1x 1809x 1809x 1809x 1x 1x 87x 87x 1x 1x 42721x 42721x 1x 1x 128x 128x 128x 128x 29x 128x 128x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 6x 6x 6x 6x 27x 27x 27x 27x 27x 27x 27x 1x 1x 1x 14x 14x 1x 1x 1x 1x 39x 39x 39x 16x 16x 16x 32x 3x 3x 3x 34x 8x 8x 8x 37x 1x 1x 1x 1x 1x 1x 1x 39x 10x 2x 2x 8x 6x 6x 39x 39x 39x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 16x 16x 16x 16x 16x 1x 1x 1x 8x   8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 3x   3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 99x 99x 3x 3x 3x 3x 3x 3x 3x 3x 3x 99x 99x 1x 1x 20x 20x 1x 1x 34x 34x 1x 1x 87x 66x 66x 66x 66x 66x 87x 87x 87x 87x 87x 84x 84x 3x 3x 87x 87x 1x 1x 102x 102x 865x 865x 102x 102x 102x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x 6x 32x 13x 13x 13x 13x 13x     6x 6x 1x 1x 2x 2x 2x 2x 2x     6x 6x 6x 3x 6x 6x 1x 1x 6x 4x 4x 6x 6x 1x  
import {
  AfterContentInit,
  ChangeDetectorRef,
  ContentChildren,
  Directive,
  EventEmitter,
  HostBinding,
  HostListener,
  Input,
  OnDestroy,
  Output,
  QueryList,
} from '@angular/core';
import { Subscription } from 'rxjs';
 
import { isPrintableCharacter } from '../utils/internal-utils';
import { Converter, Item, Key } from '../utils/util.types';
 
import { VirtualListBoxItemDirective } from './virtual-listbox-item.directive';
 
export interface ListboxSelectEvent {
  key: Key;
  open: boolean;
}
 
/**
 * Aria Support for ListBox using a virtual focus with aria-activedescendant
 */
@Directive({
  selector: '[data-gc-virtual-listbox]',
})
export class VirtualListBoxDirective implements AfterContentInit, OnDestroy {
  @Output()
  public readonly onSelect: EventEmitter<ListboxSelectEvent> =
    new EventEmitter<ListboxSelectEvent>();
 
  @HostBinding('attr.role')
  readonly role = 'listbox';
 
  @HostBinding('tabindex')
  readonly tabindex = 0;
 
  @ContentChildren(VirtualListBoxItemDirective)
  public children?: QueryList<VirtualListBoxItemDirective>;
 
  @HostBinding('attr.aria-activedescendant')
  public get activeDescendant(): string | null {
    return this.hasFocus ? this._activeDescendant : null; // Only render active descendant if it has focus otherwise FF & NVDA thinks the list has the focus
  }
 
  public set activeDescendant(value: string | null) {
    this._activeDescendant = value;
  }
 
  public get value(): Key | undefined {
    return this._value;
  }
 
  @Input()
  @Output()
  public set value(value: Key | undefined) {
    this._value = value;
    if (this.children) {
      this.children.find(c => c.item.key === value)?.scrollIntoView();
    }
  }
 
  public _value?: Key;
 
  private focusedListIndex = -1;
 
  private childrenChangeSubscription?: Subscription;
 
  private _activeDescendant: string | null = null;
 
  private hasFocus = false;
 
  private itemSearchText = '';
 
  private clearTimer?: ReturnType<typeof setTimeout>;
 
  constructor(private change: ChangeDetectorRef) {}
 
  @Input()
  public itemIdComputer: Converter<Item, string> = i => 'item-' + i.key;
 
  @HostListener('focus', ['$event'])
  public _impl_onFocus(): void {
    this.hasFocus = true;
    if (
      this.focusedListIndex === -1 &&
      this.children &&
      this.children.length > 0
    ) {
      this.updateFocusedIndex(0);
    }
 
    // Do not sync with selection - eg windows explorer does not do it either
    if (this.focusedListIndex !== -1) {
      this.children?.get(this.focusedListIndex)?.scrollIntoView();
    }
  }
 
  @HostListener('blur', ['$event'])
  public _impl_onBlur(): void {
    this.hasFocus = false;
  }
 
  /** @ignore */
  @HostListener('keydown', ['$event'])
  public _impl_onKeyDown(event: KeyboardEvent): void {
    const key = event.key;
    switch (key) {
      case 'Enter':
        this._impl_onEnter();
        event.preventDefault();
        break;
      case 'ArrowUp':
        this._impl_onUp();
        event.preventDefault();
        break;
      case 'ArrowDown':
        this._impl_onDown();
        event.preventDefault();
        break;
      case 'End':
        this._impl_onEnd();
        event.preventDefault();
        break;
      case 'Home':
        this.updateFocusedIndex(0);
        event.preventDefault();
        break;
      default:
        if (key === ' ' && this.itemSearchText === '') {
          this._impl_onSpace();
          event.preventDefault();
        } else if (key === ' ' || isPrintableCharacter(key)) {
          this.moveByKey(key);
          event.preventDefault();
        }
    }
  }
 
  /** @ignore */
  public _impl_onSpace(): void {
    const el = this.children?.get(this.focusedListIndex);
    if (el) {
      this.selectItem(el.item.item, false);
    }
  }
 
  /** @ignore */
  public _impl_onEnter(): void {
    const el = this.children?.get(this.focusedListIndex);
    if (el) {
      this.selectItem(el.item.item, true);
    }
  }
 
  /** @ignore */
  public _impl_onDown(): void {
    if (this.focusedListIndex == -1) {
      this.updateFocusedIndex(0);
    } else if (
      this.children &&
      this.focusedListIndex + 1 < this.children.length
    ) {
      this.updateFocusedIndex(this.focusedListIndex + 1);
    }
  }
 
  /** @ignore */
  public _impl_onUp(): void {
    if (this.focusedListIndex == -1 && this.children) {
      this.updateFocusedIndex(this.children.length - 1);
    } else if (this.focusedListIndex - 1 >= 0) {
      this.updateFocusedIndex(this.focusedListIndex - 1);
    }
  }
 
  public _impl_onEnd(): void {
    if (this.children) {
      this.updateFocusedIndex(this.children.length - 1);
    }
  }
 
  ngAfterContentInit(): void {
    this.connectMenuItems();
    this.childrenChangeSubscription = this.children?.changes.subscribe(() => {
      this.connectMenuItems();
      // Fix dev exception value change while ...
      setTimeout(() => {
        this.updateFocusedIndex(
          this.children
            ? this.children.toArray().findIndex(c => c.item.key === this.value)
            : -1,
        );
      });
    });
  }
 
  ngOnDestroy(): void {
    this.childrenChangeSubscription?.unsubscribe();
  }
 
  selectItem(item: Item, open: boolean): void {
    this.onSelect.emit({ key: item.key, open });
  }
 
  updateFocusedIndex(idx: number) {
    if (this.focusedListIndex != -1) {
      const prevItem = this.children?.get(this.focusedListIndex);
      if (prevItem) {
        prevItem.focused = false;
      }
    }
 
    this.focusedListIndex = idx;
 
    const item = this.children?.get(idx);
    if (item) {
      item.focused = true;
      this.activeDescendant = this.itemIdComputer(item.item);
    } else {
      this.activeDescendant = null;
    }
  }
 
  private connectMenuItems(): void {
    const size = this.children?.length ?? 0;
    this.children?.forEach((e, index) => {
      e.updateItem(this, index, size);
      e.focused = false;
    });
    this.change.detectChanges();
  }
 
  private moveByKey(char: string): void {
    const curIdx = this.focusedListIndex === -1 ? 0 : this.focusedListIndex;
 
    const firstSearch = this.itemSearchText === '';
 
    this.itemSearchText += char;
 
    this.clearSearchTimer();
 
    this.clearTimer = setTimeout(() => {
      this.itemSearchText = '';
    }, 1000);
 
    let indx =
      this.children?.toArray().findIndex((itemDirective, idx) => {
        const indexCheck = firstSearch ? idx > curIdx : idx >= curIdx;
        return (
          indexCheck &&
          itemDirective.item.label
            .toLocaleLowerCase()
            .includes(this.itemSearchText.toLocaleLowerCase())
        );
      }) ?? -1;
 
    if (indx === -1) {
      indx =
        this.children?.toArray().findIndex((itemDirective, idx) => {
          return (
            idx <= curIdx &&
            itemDirective.item.label
              .toLocaleLowerCase()
              .includes(this.itemSearchText.toLocaleLowerCase())
          );
        }) ?? -1;
    }
 
    if (indx !== -1 && indx !== curIdx) {
      this.updateFocusedIndex(indx);
    }
  }
 
  private clearSearchTimer() {
    if (this.clearTimer !== undefined) {
      clearTimeout(this.clearTimer);
      this.clearTimer = undefined;
    }
  }
}