All files / lib/picker picker.component.ts

96.66% Statements 319/330
87.71% Branches 50/57
94.73% Functions 18/19
96.66% Lines 319/330

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 3311x 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 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x 456x   456x 456x 456x 456x 456x 456x 456x 456x 507x   507x 507x 507x 456x 456x 456x 469x 469x 469x 469x 469x 469x 456x 456x 456x 456x 456x 912x 912x 912x 912x 912x 912x 452x 904x 904x 912x 456x 456x 456x 912x 912x 456x 456x 456x 27723x 27723x 456x 456x 456x 14732x 14732x 456x 456x 456x 359x 359x 359x 359x 359x 456x 456x 456x 54371x 54371x 54371x 54371x 54371x 456x 456x 456x 5216x 1x 1x 1x 1x 108024x 108024x 1x 1x 1x 54012x 54012x 54012x 54012x 54012x 1x 1x 1x 912x 912x 912x 7208x 7208x 7208x 6437x     6437x 6437x 554x 6437x 6437x 6437x   7208x 912x 1x 1x 1x 33x 33x 1x 1x 1x 33x 26x 26x 26x 26x 26x 26x 26x 26x 26x             26x 26x 26x 33x 30x 30x 7x 7x 7x 7x 5x 5x 2x 2x 2x 2x 1x 1x 7x 7x 7x 5x 7x 7x 23x 30x 30x 33x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  IterableDiffers,
  TemplateRef,
  effect,
  input,
  model,
  output,
  viewChild,
} from '@angular/core';
 
import { IndexedItem, textToLine } from '../utils/internal-utils';
import { Converter, FormControlStatus, Item } from '../utils/util.types';
import { SoundType, isItem, playSound } from '../utils/utilities';
 
import {
  AutoIdDirective,
  LabelContainerComponent,
} from '../internal/label-container/label-container.component';
 
import { BasePickerComponent } 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';
 
/**
 * 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',
  ],
  changeDetection: ChangeDetectionStrategy.Default,
  standalone: false,
})
export class PickerComponent<T> extends BasePickerComponent<T, Item> {
  /** @ignore */
  protected get noValueItemAriaLabel(): string {
    return (
      'Keine Auswahl' +
      (this.storage.selectedItem?.key === this.noValueListboxItem.key
        ? ' Selektiert'
        : '')
    );
  }
 
  /** The label that shows on the input. */
  public label = input('');
 
  /** Marks the input field as required. true == required */
  public required = input(false);
 
  /** A hint message that will appear below the picker if set. */
  public hint = input('');
 
  /** Optional icon provider to use for the selected entry */
  public iconProvider = input<TemplateRef<unknown>>();
 
  /** Optional icon provider to use for the entries in the popup list */
  public listIconProvider = input<TemplateRef<unknown>>();
 
  /** variant of the picker */
  public variant = input<'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
   */
  public contentDisplay = input<'icon-left' | 'icon-only' | 'text-only'>(
    'text-only',
  );
  /**
   * Alignment of the picker popup.
   */
  public popupAlignment = input<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
   */
  public _slotElementMode = input<
    'two-slot-label-container' | 'ext-search-single-field'
  >();
 
  /**
   * Error message id used when `_slotElementMode` is enabled.
   * @ignore
   */
  public _errorMessageId = input<string>();
 
  /**
   * Info (hint) message id used when `_slotElementMode` is enabled.
   * @ignore
   */
  public _infoMessageId = input<string>();
 
  /** Decides whether large or small icons appearing. */
  public smallIcons = input(false);
 
  /**
   * Overrides the default text which is shown when the control is readonly and empty.
   */
  public readonlyEmptyValue = input('');
 
  /**
   * Enables setting of the value only when the Promise resolves with value "true".
   */
  public permitValueChange =
    input<(v: T | null) => Promise<boolean> | boolean>();
 
  /**
   * Enables resetting the value i.e. the selection of a no-value (undefined) item.
   */
 
  public resetEnabled = input(false);
 
  /**
   * Signals changes of the current (combined) status of the component, e.g. also reports errors triggered by internal
   * validation or input handling.
   */
  public readonly onStatusChange = output<FormControlStatus>();
 
  /**
   * The value represents the selected value
   */
  public value = model<T | null>(null);
 
  /** An error message that will appear below the picker if set. */
  public errorMessage = input('');
 
  /** @ignore */
  protected readonly noValueListboxItem: Item = {
    key: '__no-value', // TODO: switch to symbol and add support for it in ItemStorage
    label: '\u2013',
  };
 
  /** @ignore */
  private labelContainer = viewChild(LabelContainerComponent);
 
  /** @ignore */
  private drawerSlot = viewChild<ElementRef>('drawerSlot');
 
  constructor(itDiff: IterableDiffers) {
    super(itDiff);
 
    effect(() => {
      const errorMessage = this.errorMessage();
      const status: FormControlStatus = {};
      if (errorMessage) {
        status.error = [errorMessage];
      }
 
      queueMicrotask(() => {
        this.onStatusChange.emit(status);
      });
    });
 
    effect(() => {
      if (this.resetEnabled()) {
        this.storage.selected = this.value();
      } else {
        this.storage.selected = this.value() ?? undefined;
      }
    });
 
    effect(() => {
      const resetEnabled = this.resetEnabled();
      const items = this.items();
      this.itemAdapter();
 
      this.storage.values = resetEnabled ? [null, ...items] : items;
      this.storage.update();
    });
  }
 
  /** @ignore */
  protected override getAnker(): ElementRef {
    const labelContainer = this.labelContainer();
    const drawerSlot = this.drawerSlot();
 
    if (labelContainer) {
      return labelContainer.drawerSlot();
    } else if (drawerSlot) {
      return drawerSlot;
    }
    throw new Error('Unable to find a drawer slot');
  }
 
  /** @ignore */
  protected override getScrollTarget(): ElementRef<HTMLElement> | undefined {
    return this.labelContainer()?.boxEl();
  }
 
  /** @ignore */
  protected _processItemText(text: string) {
    return textToLine(text, 32, '<br>');
  }
 
  /** @ignore */
  protected _listboxId(autoId: AutoIdDirective): string {
    return autoId.autoId + '-listbox';
  }
 
  /** @ignore */
  protected getFocusedItemId(autoId: AutoIdDirective): string | undefined {
    if (this.focusItem === undefined) {
      return undefined;
    }
    return this.getItemId(autoId, this.focusItem);
  }
 
  /** @ignore */
  protected getItemId(
    autoId: AutoIdDirective,
    item: IndexedItem<T | null>,
  ): string {
    return autoId.autoId + '_k_' + item.key;
  }
 
  /** @ignore */
  protected _itemTrackBy = (item: IndexedItem<T | null>) => {
    return item.item.key;
  };
 
  /** @ignore */
  protected isItemSelected(item?: IndexedItem<T | null>): boolean {
    return this.storage.selectedItem?.key === item?.key;
  }
 
  /** @ignore */
  protected isItemFocused(item?: IndexedItem<T | null>): boolean {
    return (
      (this.focusItem === undefined && item === undefined) ||
      this.focusItem?.key === item?.key
    );
  }
 
  /** @ignore */
  protected override createInternalItemAdapter(
    itemAdapter?: Converter<T, Item>,
  ): Converter<T | null, Item> {
    return (value: T | null): Item => {
      if (isItem(value)) {
        return value;
      } else if (value === null) {
        return {
          label: this.noValueListboxItem.label,
          key: this.noValueListboxItem.key,
        };
      } else if (itemAdapter) {
        return itemAdapter(value);
      }
 
      console.error('Missing converter for ', value);
      throw new Error('missing converter');
    };
  }
 
  /** @ignore */
  protected override selectAndCloseCallback(item: IndexedItem<T | null>): void {
    void this._impl_handleChange(item.value);
  }
 
  /** @ignore */
  private async _impl_handleChange(value: T | null): Promise<void> {
    const doChange = () => {
      this.value.set(value);
      this.storage.selected = value;
 
      // 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, [
            'FIELD',
            'ERROR',
            'VALIDATION_ERROR',
          ]);
        }
      });
    };
    if (value !== this.value()) {
      const permitValueChange = this.permitValueChange();
      if (permitValueChange !== undefined) {
        // Close the dialog we'll anyways loose focus to the dialog
        this._impl_close(false);
        const permit = 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();
      }
    }
  }
}