All files / lib/picker picker.component.ts

97.59% Statements 365/374
89.7% Branches 61/68
96% Functions 24/25
97.59% Lines 365/374

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 3751x 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 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16334x 16334x 16334x 1x 1x 65x 65x 65x 1x 1x 1x 1x 1x 105x 105x 105x 1x 1x 543x 543x 1x 1x 1x 47x 47x     47x 47x 1x 1x 42425x 42425x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 458x 458x 458x 458x 458x 458x 1x 1x 1x 568x 568x 503x 105x 463x 463x 568x 568x 1x 1x 1x 523x 523x 523x 241x 519x 519x 523x 1x 1x 1x 523x 523x 1x 1x 1x 1x 1x 31467x 31467x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 36x 36x 36x 36x 35x 35x 35x 36x 1x 1x 1x 36x 31x 31x 36x 36x 36x 7x 7x 7x 7x 5x 5x 2x 2x 2x 2x 1x 1x 7x 7x 7x 6x 7x 7x 28x 36x 36x 36x 1x 1x 1x 55x 55x 14x 14x 14x 14x 14x 55x 55x 1x 1x 1x 16146x 16146x 1x 1x 1x 16334x 16334x 1x 1x 1x 1240x 1240x 1x 1x 1x 1860x 1860x 1x 1x 1x 642x 642x 1x 1x 1x 620x 620x 620x 32x 588x 545x 545x 503x 503x 503x 620x 620x 1x 1x 1x               1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  Component,
  ElementRef,
  EventEmitter,
  Input,
  IterableDiffers,
  OnChanges,
  Optional,
  Output,
  SimpleChanges,
  TemplateRef,
  ViewChild,
} from '@angular/core';
 
import { BaseIndexedItem, textToLine } from '../utils/internal-utils';
import { FormControlStatus, Item, WidgetKeySet } from '../utils/util.types';
import { SoundType, createWidgetKeySet, playSound } from '../utils/utilities';
 
import { ElementInsertionContextService } from '../internal/element-insertion-context.service';
import {
  AutoIdDirective,
  LabelContainerComponent,
} from '../internal/label-container/label-container.component';
import { SelectionEvent } from '../internal/listbox.directive';
 
import { BasePickerComponent, KeyFocusTarget } from './base-picker.component';
 
/**
 * Alignment to use by the popup
 * <ul>
 * <li>Start: aligned to the left edge of the picker</li>
 * <li>Fill: fills the complete width of the picker</li>
 * <li>End: aligned to the right edge of the picker</li>
 * </ul>
 */
export type PopupAlignment = 'start' | 'end' | 'fill';
 
const NO_VALUE_ITEM_SYMBOL: unique symbol = Symbol('no-value');
 
/**
 * A Picker allowing the user to choose an item from a collapsible list of options.
 */
@Component({
  selector: 'gc-picker',
  templateUrl: './picker.component.html',
  styleUrls: [
    '../base-range-input-field/base-slot-mode.css',
    './picker.component.css',
  ],
})
export class PickerComponent<T, I extends Item = Item>
  extends BasePickerComponent<T, I>
  implements OnChanges
{
  /** Inform about the change of the selection state */
  @Output()
  public readonly valueChange: EventEmitter<T | null> =
    new EventEmitter<T | null>();
 
  /** The label that shows on the input. */
  @Input()
  public label = '';
 
  /** Marks the input field as required. true == required */
  @Input()
  public required = false;
 
  /** A hint message that will appear below the picker if set. */
  @Input()
  public hint = '';
 
  /** Optional icon provider to use for the selected entry */
  @Input()
  public iconProvider?: TemplateRef<unknown>;
 
  /** Optional icon provider to use for the entries in the popup list */
  @Input()
  public listIconProvider?: TemplateRef<unknown>;
 
  /** variant of the picker */
  @Input()
  public variant: 'default' | 'condensed' | 'toggle-list' = 'default';
 
  /**
   * Defines how the content is displayed for the toggle-list variant:
   * - icon-only: only the icon is shown
   * - icon-left: icon is shown on the left of the text
   * - text-only: only text is displayed
   */
  @Input()
  public contentDisplay: 'icon-left' | 'icon-only' | 'text-only' = 'text-only';
  /**
   * Alignment of the picker popup.
   */
  @Input()
  public popupAlignment: PopupAlignment = 'fill';
 
  /**
   * If true, the component will be rendered in a slot-element mode.
   * This enables the component to be used in two-slot components (e.g. `gc-two-slot-label-container`).
   * @ignore
   */
  @Input()
  public _slotElementMode?:
    | 'two-slot-label-container'
    | 'ext-search-single-field';
 
  /**
   * Error message id used when `_slotElementMode` is enabled.
   * @ignore
   */
  @Input()
  public _errorMessageId?: string;
 
  /**
   * Info (hint) message id used when `_slotElementMode` is enabled.
   * @ignore
   */
  @Input()
  public _infoMessageId?: string;
 
  /** Decides whether large or small icons appearing. */
  @Input()
  public smallIcons = false;
 
  /**
   * Overrides the default text which is shown when the control is readonly and empty.
   */
  @Input()
  public readonlyEmptyValue = '';
 
  /**
   * Enables setting of the value only when the Promise resolves with value "true".
   */
  @Input()
  public permitValueChange?: (v: T | null) => Promise<boolean> | boolean;
 
  /**
   * Signals changes of the current (combined) status of the component, e.g. also reports errors triggered by internal
   * validation or input handling.
   */
  @Output()
  public readonly onStatusChange: EventEmitter<FormControlStatus> =
    new EventEmitter<FormControlStatus>(true);
 
  /** @ignore */
  @ViewChild(LabelContainerComponent)
  public labelContainer?: LabelContainerComponent;
 
  /** @ignore */
  @ViewChild('drawerSlot')
  public drawerSlot?: ElementRef;
  /**
   * Enables resetting the value i.e. the selection of a no-value (undefined) item.
   */
  @Input()
  public get resetEnabled() {
    return this._resetEnabled;
  }
 
  public set resetEnabled(value) {
    this.storage.startingIndex = value ? this.noValueListboxItem.index + 1 : 0;
    this._resetEnabled = value;
  }
 
  /**
   * The value represents the selected value
   */
  @Input()
  public get value(): T | null {
    return this.storage.selected ?? null;
  }
 
  public set value(value: T | null) {
    this.storage.selected = value ?? undefined;
  }
 
  /** An error message that will appear below the picker if set. */
  @Input()
  public set errorMessage(message: string) {
    if (this._errorMessage !== message) {
      this._errorMessage = message;
      this.emitStatusChange();
    }
  }
 
  public get errorMessage(): string {
    return this._errorMessage;
  }
 
  /** @ignore */
  protected readonly noValueListboxItem: BaseIndexedItem = {
    index: 0,
    key: NO_VALUE_ITEM_SYMBOL,
    label: '\u2013',
  };
 
  /** @ignore */
  protected readonly _widgetKeys: WidgetKeySet =
    createWidgetKeySet('gc-picker-input');
 
  /** @ignore */
  protected _focused?: boolean;
 
  /** @ignore */
  protected readonly inDialog: boolean; // Workaround for https://gitlab.bestsolution.at/gefa/gefa-web-controls/-/issues/2670
 
  private _errorMessage = '';
 
  /** @ignore */
  private _resetEnabled = false;
 
  constructor(
    itDiff: IterableDiffers,
    @Optional() eic: ElementInsertionContextService | null,
  ) {
    super(itDiff);
    this.inDialog = eic?.parent.localName === 'dialog';
  }
 
  /** @ignore */
  ngOnChanges(changes: SimpleChanges): void {
    if (
      'resetEnabled' in changes ||
      'items' in changes ||
      'itemAdapter' in changes
    ) {
      this.storage.update();
    }
  }
 
  /** @ignore */
  public override getAnker(): ElementRef {
    if (this.labelContainer) {
      return this.labelContainer.drawerSlot;
    } else if (this.drawerSlot) {
      return this.drawerSlot;
    }
    throw new Error('Unable to find a drawer slot');
  }
 
  /** @ignore */
  public override getScrollTarget(): ElementRef<HTMLElement> | undefined {
    return this.labelContainer?.boxEl;
  }
 
  /**
   * @ignore
   */
  public _processItemText(text: string) {
    return textToLine(text, 32, '<br>');
  }
 
  /** @ignore */
  public override _impl_onFocusLeft(relatedTarget?: EventTarget | null): void {
    super._impl_onFocusLeft(relatedTarget);
    // We need to wait a tick so that the control is back
    // in a sync state
    setTimeout(() => {
      if (this.errorMessage.length > 0 || this._errorMessageId !== undefined) {
        void playSound(SoundType.ERROR);
      }
    });
  }
 
  /** @ignore */
  public async _impl_onSelect(event: SelectionEvent): Promise<void> {
    if (typeof event.key === 'string' && !this._isDisabled(event.key)) {
      const value = this.storage.getValueByKey(event.key) ?? null;
      await this._impl_handleChange(value);
    } else if (event.key === NO_VALUE_ITEM_SYMBOL) {
      await this._impl_handleChange(null);
    }
    this._impl_close(true);
  }
 
  /** @ignore */
  public async _impl_handleChange(value: T | null): Promise<void> {
    const doChange = () => {
      this.value = value;
      this.valueChange.emit(value);
    };
    if (value !== this.value) {
      if (this.permitValueChange !== undefined) {
        // Close the dialog we'll anyways loose focus to the dialog
        this._impl_close(false);
        const permit = this.permitValueChange(value);
        if (typeof permit !== 'boolean') {
          // permit is of type Promise<boolean>
          const proceed = await permit;
          if (proceed) {
            doChange();
          }
        } else if (permit) {
          // permit is of type boolean
          doChange();
        }
        // Move focus back to ourselves
        setTimeout(() => {
          this.focusChild();
        });
      } else {
        doChange();
      }
    }
  }
 
  /** @ignore */
  protected _impl_onOpen(focusItem: KeyFocusTarget): KeyFocusTarget {
    // always open selected value if set
    if (this.value != undefined) {
      const key = this.storage.getItemByValue(this.value)?.key;
      if (key != undefined) {
        focusItem = key;
      }
    }
    return focusItem;
  }
 
  /** @ignore */
  protected _listboxId(autoId: AutoIdDirective): string {
    return autoId.autoId + '_listbox';
  }
 
  /** @ignore */
  protected determineListBoxValue(): string | symbol {
    return this.storage._selectedKey ?? this.noValueListboxItem.key;
  }
 
  /** @ignore */
  protected getLabelId(): string {
    return this._widgetKeys.labelKey;
  }
 
  /** @ignore */
  protected getButtonId(): string {
    return this._widgetKeys.baseKey + '-button';
  }
 
  /** @ignore */
  protected getListboxId(): string {
    return this._widgetKeys.labelKey + '-listbox';
  }
 
  /** @ignore */
  protected computeAriaDescribedBy(): string | null {
    const errId = this._errorMessageId;
    const hintId = this._infoMessageId;
    if (errId && hintId) {
      return errId + ' ' + hintId;
    } else if (errId) {
      return errId;
    } else if (hintId) {
      return hintId;
    } else {
      return null;
    }
  }
 
  /** @ignore */
  private emitStatusChange() {
    const status: FormControlStatus = {};
    if (this.errorMessage) {
      status.error = [this.errorMessage];
    }

    this.onStatusChange.emit(status);
  }
}