All files / lib/internal listbox.directive.ts

80.68% Statements 259/321
90% Branches 54/60
84% Functions 21/25
80.68% Lines 259/321

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 3221x 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 301x 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 301x 301x 301x 1x 1x 12585x 12585x 1x 1x 36x 36x 36x 36x 36x 14x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 14x 14x 14x 14x 36x 9x 9x 9x 18x 3x 3x 3x 19x                                 36x 36x 36x 36x 36x 36x 36x 36x 1x 1x 12535x 1599x 10936x 10936x 12535x 12535x 1x 1x 301x 301x 301x 1x 1x     1x 1x     1x 1x 24x 24x 1x 1x 43x 43x 1x 1x 112x 112x 33x 79x 79x 112x 112x 1x 1x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 25x 25x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 55x 1x 1x 43x 43x 43x 43x 43x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 30x 30x 1x 1x 1x 1x 1x 1x 61x 61x 61x 61x 4x 57x 57x 61x 61x 61x 61x 1x 1x 14x 14x 14x 14x 1x 1x           1x 1x                                                                       1x 1x 75x     75x 75x 1x 1x 335x 335x 532x 335x 335x 335x 1x 1x 22x 22x 1x  
import {
  AfterContentInit,
  ChangeDetectorRef,
  ContentChildren,
  Directive,
  ElementRef,
  EventEmitter,
  HostBinding,
  Input,
  Output,
  QueryList,
} from '@angular/core';
 
import { isPrintableCharacter } from '../utils/internal-utils';
import { Item, Key } from '../utils/util.types';
 
import { ListBoxItemDirective } from './listbox-item.directive';
 
export const FocusTargetFirst: unique symbol = Symbol('first');
export const FocusTargetLast: unique symbol = Symbol('last');
export const FocusTargetPrev: unique symbol = Symbol('prev');
export const FocusTargetNext: unique symbol = Symbol('next');
 
export interface SelectionEvent {
  key: Key | symbol;
  source: 'space' | 'enter' | 'programmatic';
}
 
@Directive({
  selector: '[data-gc-listbox]',
  standalone: false,
})
export class ListBoxDirective implements AfterContentInit {
  @ContentChildren(ListBoxItemDirective)
  public children!: QueryList<ListBoxItemDirective>;
 
  @Output('listbox-onSelect')
  public readonly onSelect: EventEmitter<SelectionEvent> =
    new EventEmitter<SelectionEvent>();
 
  @Output('listbox-onCancel')
  public readonly onCancel: EventEmitter<void> = new EventEmitter<void>();
 
  @Input('listbox-value')
  public value?: Key | symbol;
 
  @Input('listbox-values')
  public values?: ReadonlySet<Key>;
 
  @Input('listbox-id')
  @HostBinding('attr.id')
  public listboxId?: string;
 
  @Input('listbox-focus-mode')
  public focusMode: 'native' | 'virtual' = 'native';
 
  @Output('listbox-onItemFocus')
  public readonly onItemFocus: EventEmitter<ListBoxItemDirective> =
    new EventEmitter<ListBoxItemDirective>();
 
  @HostBinding('attr.role')
  readonly role = 'listbox';
 
  @Input({ required: true, alias: 'listbox-disabledItems' })
  public disabledItems: ReadonlySet<string> = new Set();
 
  private itemTextStart = '';
 
  private _focused?: ListBoxItemDirective;
 
  private clearTimer?: ReturnType<typeof setTimeout>;
 
  constructor(
    private el: ElementRef,
    private change: ChangeDetectorRef,
  ) {}
 
  public isFocused(item: ListBoxItemDirective): boolean {
    return this._focused == item;
  }
 
  public handleKeyDown(event: KeyboardEvent) {
    const key = event.key;
    let flag = false;
 
    switch (key) {
      case 'Enter':
      case ' ':
        {
          const focused = this.findFocusedChild();
          if (focused) {
            this.selectItem(
              focused.item.key,
              key === 'Enter' ? 'enter' : 'space',
            );
          }
        }
        flag = true;
        break;
      case 'Escape':
        this.cancel();
        flag = true;
        break;
      case 'ArrowDown':
        flag = true;
        this.moveFocusToNextItem();
        break;
      case 'ArrowUp':
        this.moveFocusToPrevItem();
        flag = true;
        break;
      case 'Home':
      case 'PageUp':
        this.moveFocusToFirstItem();
        flag = true;
        break;
      case 'End':
      case 'PageDown':
        this.moveFocusToLastItem();
        flag = true;
        break;
      case 'Tab':
        this.onCancel.emit();
        break;
      default:
        if (isPrintableCharacter(key)) {
          this.moveByKey(key);
          flag = true;
        }
    }
 
    if (flag) {
      event.stopPropagation();
      event.preventDefault();
    }
  }
 
  isKeySelected(key: Key | symbol): boolean {
    if (typeof key === 'string' && this.values) {
      return this.values.has(key);
    } else {
      return this.value === key;
    }
  }
 
  ngAfterContentInit(): void {
    this.connectMenuItems();
    this.children.changes.subscribe(() => this.connectMenuItems());
  }
 
  containsFocus(): boolean {
    return this.children.toArray().some(child => child.isFocused());
  }
 
  getChildByItem(item: Item): ListBoxItemDirective | undefined {
    return this.children.toArray().find(it => it.key == item.key);
  }
 
  getChildByKey(key: string): ListBoxItemDirective | undefined {
    return this.children.toArray().find(it => it.key == key);
  }
 
  getChildByIndex(index: number): ListBoxItemDirective | undefined {
    return this.children.toArray()[index];
  }
 
  focusItem(item: ListBoxItemDirective | undefined) {
    this._focused = item;
    if (this.focusMode === 'native') {
      item?.focusNative();
    } else {
      this.onItemFocus.emit(item);
    }
  }
 
  focusItemByKey(
    key:
      | Key
      | undefined
      | typeof FocusTargetFirst
      | typeof FocusTargetLast
      | typeof FocusTargetPrev
      | typeof FocusTargetNext,
  ): void {
    if (key === FocusTargetFirst || key === undefined) {
      this.moveFocusToFirstItem();
    } else if (key === FocusTargetLast) {
      this.moveFocusToLastItem();
    } else if (key === FocusTargetNext) {
      this.moveFocusToNextItem();
    } else if (key === FocusTargetPrev) {
      this.moveFocusToPrevItem();
    } else {
      const child = this.getChildByKey(key);
 
      child?.focus();
      child?.scrollIntoView();
    }
  }
 
  focusItemByIndex(index: number): void {
    const child = this.getChildByIndex(index);
 
    child?.focus();
    child?.scrollIntoView();
  }
 
  moveFocusToNextItem(): void {
    const cur = this.findFocusedChild();
    if (cur == undefined) {
      this.moveFocusToFirstItem();
    } else {
      const idx = this.children.toArray().indexOf(cur);
      if (idx + 1 < this.children.toArray().length) {
        this.focusItemByIndex(idx + 1);
      }
    }
  }
 
  moveFocusToPrevItem(): void {
    const cur = this.findFocusedChild();
    if (cur == undefined) {
      this.moveFocusToFirstItem();
    } else {
      const idx = this.children.toArray().indexOf(cur);
      if (idx - 1 < this.children.toArray().length && idx - 1 >= 0) {
        this.focusItemByIndex(idx - 1);
      }
    }
  }
 
  moveFocusToFirstItem(): void {
    this.focusItemByIndex(0);
  }
 
  moveFocusToLastItem(): void {
    this.focusItemByIndex(this.children.toArray().length - 1);
  }
 
  selectItem(
    key: Key | symbol,
    source: 'space' | 'enter' | 'programmatic',
  ): void {
    if (typeof key === 'string' && this.disabledItems.has(key)) {
      this.focusItemByKey(key);
    } else {
      this.onSelect.emit({ key, source });
    }
    this.itemTextStart = '';
    this.clearSearchTimer();
  }
 
  cancel(): void {
    this.onCancel.emit();
    this.itemTextStart = '';
    this.clearSearchTimer();
  }
 
  selectItemByKey(key: Key): void {
    const it = this.getChildByKey(key)?.item.key;
    if (it != undefined) {
      this.selectItem(it, 'programmatic');
    }
  }
 
  moveByKey(char: string): void {
    const cur = this.findFocusedChild();
    const curIdx = cur == undefined ? 0 : this.children.toArray().indexOf(cur);

    this.itemTextStart += char;

    this.clearSearchTimer();

    this.clearTimer = setTimeout(() => {
      this.itemTextStart = '';
    }, 1000);

    let indx = this.children.toArray().findIndex((itemDirective, idx) => {
      return (
        idx >= curIdx &&
        itemDirective.label
          .toLocaleLowerCase()
          .startsWith(this.itemTextStart.toLocaleLowerCase())
      );
    });

    if (indx === -1) {
      indx = this.children.toArray().findIndex((itemDirective, idx) => {
        return (
          idx <= curIdx &&
          itemDirective.label
            .toLocaleLowerCase()
            .startsWith(this.itemTextStart.toLocaleLowerCase())
        );
      });
    }

    if (indx !== -1 && indx !== curIdx) {
      this.focusItemByIndex(indx);
    }
  }
 
  private clearSearchTimer() {
    if (this.clearTimer !== undefined) {
      clearTimeout(this.clearTimer);
      this.clearTimer = undefined;
    }
  }
 
  private connectMenuItems(): void {
    const size = this.children.length;
    this.children.forEach((e, index) => {
      e.updateItem(this, index, size);
    });
    this.change.detectChanges();
  }
 
  private findFocusedChild(): ListBoxItemDirective | undefined {
    return this.children.toArray().find(child => child.isFocused());
  }
}