primeng
Version:
PrimeNG is an open source UI library for Angular featuring a rich set of 80+ components, a theme designer, various theme alternatives such as Material, Bootstrap, Tailwind, premium templates and professional support. In addition, it integrates with PrimeB
1,404 lines (1,397 loc) • 110 kB
JavaScript
export * from 'primeng/types/autocomplete';
import * as i3 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { Injectable, InjectionToken, forwardRef, inject, input, EventEmitter, signal, computed, booleanAttribute, numberAttribute, ContentChildren, HostListener, ContentChild, ViewChild, Output, Input, ViewEncapsulation, ChangeDetectionStrategy, Component, NgModule } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { equals, isNotEmpty, uuid, findLastIndex, resolveFieldData, focus, isEmpty, findSingle } from '@primeuix/utils';
import * as i1 from 'primeng/api';
import { TranslationKeys, SharedModule, PrimeTemplate } from 'primeng/api';
import { AutoFocus } from 'primeng/autofocus';
import { PARENT_INSTANCE } from 'primeng/basecomponent';
import { BaseInput } from 'primeng/baseinput';
import * as i2 from 'primeng/bind';
import { Bind, BindModule } from 'primeng/bind';
import { Chip } from 'primeng/chip';
import { TimesCircleIcon, SpinnerIcon, ChevronDownIcon, TimesIcon } from 'primeng/icons';
import { InputText } from 'primeng/inputtext';
import { Overlay } from 'primeng/overlay';
import { Ripple } from 'primeng/ripple';
import { Scroller } from 'primeng/scroller';
import { style as style$1 } from '@primeuix/styles/autocomplete';
import { BaseStyle } from 'primeng/base';
const style = /*css*/ `
${style$1}
/* For PrimeNG */
p-autoComplete.ng-invalid.ng-dirty .p-autocomplete-input,
p-autoComplete.ng-invalid.ng-dirty .p-autocomplete-input-multiple,
p-auto-complete.ng-invalid.ng-dirty .p-autocomplete-input,
p-auto-complete.ng-invalid.ng-dirty .p-autocomplete-input-multiple p-autocomplete.ng-invalid.ng-dirty .p-autocomplete-input,
p-autocomplete.ng-invalid.ng-dirty .p-autocomplete-input-multiple {
border-color: dt('autocomplete.invalid.border.color');
}
p-autoComplete.ng-invalid.ng-dirty .p-autocomplete-input:enabled:focus,
p-autoComplete.ng-invalid.ng-dirty:not(.p-disabled).p-focus .p-autocomplete-input-multiple,
p-auto-complete.ng-invalid.ng-dirty .p-autocomplete-input:enabled:focus,
p-auto-complete.ng-invalid.ng-dirty:not(.p-disabled).p-focus .p-autocomplete-input-multiple,
p-autocomplete.ng-invalid.ng-dirty .p-autocomplete-input:enabled:focus,
p-autocomplete.ng-invalid.ng-dirty:not(.p-disabled).p-focus .p-autocomplete-input-multiple {
border-color: dt('autocomplete.focus.border.color');
}
p-autoComplete.ng-invalid.ng-dirty .p-autocomplete-input-chip input::placeholder,
p-auto-complete.ng-invalid.ng-dirty .p-autocomplete-input-chip input::placeholder,
p-autocomplete.ng-invalid.ng-dirty .p-autocomplete-input-chip input::placeholder {
color: dt('autocomplete.invalid.placeholder.color');
}
p-autoComplete.ng-invalid.ng-dirty .p-autocomplete-input::placeholder,
p-auto-complete.ng-invalid.ng-dirty .p-autocomplete-input::placeholder,
p-autocomplete.ng-invalid.ng-dirty .p-autocomplete-input::placeholder {
color: dt('autocomplete.invalid.placeholder.color');
}
`;
const inlineStyles = {
root: { position: 'relative' }
};
const classes = {
root: ({ instance }) => [
'p-autocomplete p-component p-inputwrapper',
{
'p-invalid': instance.invalid(),
'p-focus': instance.focused,
'p-inputwrapper-filled': instance.$filled(),
'p-inputwrapper-focus': (instance.focused && !instance.$disabled()) || instance.autofocus || instance.overlayVisible,
'p-autocomplete-open': instance.overlayVisible,
'p-autocomplete-clearable': instance.showClear && !instance.$disabled(),
'p-autocomplete-fluid': instance.hasFluid
}
],
pcInputText: 'p-autocomplete-input',
inputMultiple: ({ instance }) => [
'p-autocomplete-input-multiple',
{
'p-disabled': instance.$disabled(),
'p-variant-filled': instance.$variant() === 'filled'
}
],
chipItem: ({ instance, i }) => [
'p-autocomplete-chip-item',
{
'p-focus': instance.focusedMultipleOptionIndex() === i
}
],
pcChip: 'p-autocomplete-chip',
chipIcon: 'p-autocomplete-chip-icon',
inputChip: 'p-autocomplete-input-chip',
loader: 'p-autocomplete-loader',
dropdown: 'p-autocomplete-dropdown',
overlay: ({ instance }) => ['p-autocomplete-overlay p-component-overlay p-component', { 'p-input-filled': instance.$variant() === 'filled', 'p-ripple-disabled': instance.config.ripple() === false }],
listContainer: 'p-autocomplete-list-container',
list: 'p-autocomplete-list',
optionGroup: 'p-autocomplete-option-group',
option: ({ instance, option, i, scrollerOptions }) => ({
'p-autocomplete-option': true,
'p-autocomplete-option-selected': instance.isSelected(option),
'p-focus': instance.focusedOptionIndex() === instance.getOptionIndex(i, scrollerOptions),
'p-disabled': instance.isOptionDisabled(option)
}),
emptyMessage: 'p-autocomplete-empty-message',
clearIcon: 'p-autocomplete-clear-icon'
};
class AutoCompleteStyle extends BaseStyle {
name = 'autocomplete';
style = style;
classes = classes;
inlineStyles = inlineStyles;
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.5", ngImport: i0, type: AutoCompleteStyle, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.0.5", ngImport: i0, type: AutoCompleteStyle });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.5", ngImport: i0, type: AutoCompleteStyle, decorators: [{
type: Injectable
}] });
/**
*
* AutoComplete is an input component that provides real-time suggestions while being typed.
*
* [Live Demo](https://www.primeng.org/autocomplete/)
*
* @module autocompletestyle
*
*/
var AutoCompleteClasses;
(function (AutoCompleteClasses) {
/**
* Class name of the root element
*/
AutoCompleteClasses["root"] = "p-autocomplete";
/**
* Class name of the input element
*/
AutoCompleteClasses["pcInputText"] = "p-autocomplete-input";
/**
* Class name of the input multiple element
*/
AutoCompleteClasses["inputMultiple"] = "p-autocomplete-input-multiple";
/**
* Class name of the chip item element
*/
AutoCompleteClasses["chipItem"] = "p-autocomplete-chip-item";
/**
* Class name of the chip element
*/
AutoCompleteClasses["pcChip"] = "p-autocomplete-chip";
/**
* Class name of the chip icon element
*/
AutoCompleteClasses["chipIcon"] = "p-autocomplete-chip-icon";
/**
* Class name of the input chip element
*/
AutoCompleteClasses["inputChip"] = "p-autocomplete-input-chip";
/**
* Class name of the loader element
*/
AutoCompleteClasses["loader"] = "p-autocomplete-loader";
/**
* Class name of the dropdown element
*/
AutoCompleteClasses["dropdown"] = "p-autocomplete-dropdown";
/**
* Class name of the panel element
*/
AutoCompleteClasses["panel"] = "p-autocomplete-overlay";
/**
* Class name of the list element
*/
AutoCompleteClasses["list"] = "p-autocomplete-list";
/**
* Class name of the option group element
*/
AutoCompleteClasses["optionGroup"] = "p-autocomplete-option-group";
/**
* Class name of the option element
*/
AutoCompleteClasses["option"] = "p-autocomplete-option";
/**
* Class name of the empty message element
*/
AutoCompleteClasses["emptyMessage"] = "p-autocomplete-empty-message";
/**
* Class name of the clear icon
*/
AutoCompleteClasses["clearIcon"] = "p-autocomplete-clear-icon";
})(AutoCompleteClasses || (AutoCompleteClasses = {}));
const AUTOCOMPLETE_INSTANCE = new InjectionToken('AUTOCOMPLETE_INSTANCE');
const AUTOCOMPLETE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => AutoComplete),
multi: true
};
/**
* AutoComplete is an input component that provides real-time suggestions when being typed.
* @group Components
*/
class AutoComplete extends BaseInput {
overlayService;
zone;
$pcAutoComplete = inject(AUTOCOMPLETE_INSTANCE, { optional: true, skipSelf: true }) ?? undefined;
bindDirectiveInstance = inject(Bind, { self: true });
/**
* Minimum number of characters to initiate a search.
* @deprecated since v20.0.0, use `minQueryLength` instead.
* @group Props
*/
minLength = 1;
/**
* Minimum number of characters to initiate a search.
* @group Props
*/
minQueryLength;
/**
* Delay between keystrokes to wait before sending a query.
* @group Props
*/
delay = 300;
/**
* Inline style of the overlay panel element.
* @group Props
*/
panelStyle;
/**
* Style class of the component.
* @deprecated since v20.0.0, use `class` instead.
* @group Props
*/
styleClass;
/**
* Style class of the overlay panel element.
* @group Props
*/
panelStyleClass;
/**
* Inline style of the input field.
* @group Props
*/
inputStyle;
/**
* Identifier of the focus input to match a label defined for the component.
* @group Props
*/
inputId;
/**
* Inline style of the input field.
* @group Props
*/
inputStyleClass;
/**
* Hint text for the input field.
* @group Props
*/
placeholder;
/**
* When present, it specifies that the input cannot be typed.
* @group Props
*/
readonly;
/**
* Maximum height of the suggestions panel.
* @group Props
*/
scrollHeight = '200px';
/**
* Defines if data is loaded and interacted with in lazy manner.
* @group Props
*/
lazy = false;
/**
* Whether the data should be loaded on demand during scroll.
* @group Props
*/
virtualScroll;
/**
* Height of an item in the list for VirtualScrolling.
* @group Props
*/
virtualScrollItemSize;
/**
* Whether to use the scroller feature. The properties of scroller component can be used like an object in it.
* @group Props
*/
virtualScrollOptions;
/**
* When enabled, highlights the first item in the list by default.
* @group Props
*/
autoHighlight;
/**
* When present, autocomplete clears the manual input if it does not match of the suggestions to force only accepting values from the suggestions.
* @group Props
*/
forceSelection;
/**
* Type of the input, defaults to "text".
* @group Props
*/
type = 'text';
/**
* Whether to automatically manage layering.
* @group Props
*/
autoZIndex = true;
/**
* Base zIndex value to use in layering.
* @group Props
*/
baseZIndex = 0;
/**
* Defines a string that labels the input for accessibility.
* @group Props
*/
ariaLabel;
/**
* Defines a string that labels the dropdown button for accessibility.
* @group Props
*/
dropdownAriaLabel;
/**
* Specifies one or more IDs in the DOM that labels the input field.
* @group Props
*/
ariaLabelledBy;
/**
* Icon class of the dropdown icon.
* @group Props
*/
dropdownIcon;
/**
* Ensures uniqueness of selected items on multiple mode.
* @group Props
*/
unique = true;
/**
* Whether to display options as grouped when nested options are provided.
* @group Props
*/
group;
/**
* Whether to run a query when input receives focus.
* @group Props
*/
completeOnFocus = false;
/**
* When enabled, a clear icon is displayed to clear the value.
* @group Props
*/
showClear = false;
/**
* Displays a button next to the input field when enabled.
* @group Props
*/
dropdown;
/**
* Whether to show the empty message or not.
* @group Props
*/
showEmptyMessage = true;
/**
* Specifies the behavior dropdown button. Default "blank" mode sends an empty string and "current" mode sends the input value.
* @group Props
*/
dropdownMode = 'blank';
/**
* Specifies if multiple values can be selected.
* @group Props
*/
multiple;
/**
* When enabled, the input value is added to the selected items on tab key press when multiple is true and typeahead is false.
* @group Props
*/
addOnTab = false;
/**
* Index of the element in tabbing order.
* @group Props
*/
tabindex;
/**
* A property to uniquely identify a value in options.
* @group Props
*/
dataKey;
/**
* Text to display when there is no data. Defaults to global value in i18n translation configuration.
* @group Props
*/
emptyMessage;
/**
* Transition options of the show animation.
* @group Props
* @deprecated since v21.0.0, use `motionOptions` instead.
*/
showTransitionOptions = '.12s cubic-bezier(0, 0, 0.2, 1)';
/**
* Transition options of the hide animation.
* @group Props
* @deprecated since v21.0.0, use `motionOptions` instead.
*/
hideTransitionOptions = '.1s linear';
/**
* When present, it specifies that the component should automatically get focus on load.
* @group Props
*/
autofocus;
/**
* Used to define a string that autocomplete attribute the current element.
* @group Props
*/
autocomplete = 'off';
/**
* Name of the options field of an option group.
* @group Props
*/
optionGroupChildren = 'items';
/**
* Name of the label field of an option group.
* @group Props
*/
optionGroupLabel = 'label';
/**
* Options for the overlay element.
* @group Props
*/
overlayOptions;
/**
* An array of suggestions to display.
* @group Props
*/
get suggestions() {
return this._suggestions();
}
set suggestions(value) {
this._suggestions.set(value);
this.handleSuggestionsChange();
}
/**
* Property name or getter function to use as the label of an option.
* @group Props
*/
optionLabel;
/**
* Property name or getter function to use as the value of an option.
* @group Props
*/
optionValue;
/**
* Unique identifier of the component.
* @group Props
*/
id;
/**
* Text to display when the search is active. Defaults to global value in i18n translation configuration.
* @group Props
* @defaultValue '{0} results are available'
*/
searchMessage;
/**
* Text to display when filtering does not return any results. Defaults to global value in i18n translation configuration.
* @group Props
* @defaultValue 'No selected item'
*/
emptySelectionMessage;
/**
* Text to be displayed in hidden accessible field when options are selected. Defaults to global value in i18n translation configuration.
* @group Props
* @defaultValue '{0} items selected'
*/
selectionMessage;
/**
* Whether to focus on the first visible or selected element when the overlay panel is shown.
* @group Props
*/
autoOptionFocus = false;
/**
* When enabled, the focused option is selected.
* @group Props
*/
selectOnFocus;
/**
* Locale to use in searching. The default locale is the host environment's current locale.
* @group Props
*/
searchLocale;
/**
* Property name or getter function to use as the disabled flag of an option, defaults to false when not defined.
* @group Props
*/
optionDisabled;
/**
* When enabled, the hovered option will be focused.
* @group Props
*/
focusOnHover = true;
/**
* Whether typeahead is active or not.
* @defaultValue true
* @group Props
*/
typeahead = true;
/**
* Whether to add an item on blur event if the input has value and typeahead is false with multiple mode.
* @defaultValue false
* @group Props
*/
addOnBlur = false;
/**
* Separator char to add item when typeahead is false and multiple mode is enabled.
* @group Props
*/
separator;
/**
* Target element to attach the overlay, valid values are "body" or a local ng-template variable of another element (note: use binding with brackets for template variables, e.g. [appendTo]="mydiv" for a div element having #mydiv as variable name).
* @defaultValue 'self'
* @group Props
*/
appendTo = input(undefined, ...(ngDevMode ? [{ debugName: "appendTo" }] : []));
/**
* The motion options.
* @group Props
*/
motionOptions = input(undefined, ...(ngDevMode ? [{ debugName: "motionOptions" }] : []));
/**
* Callback to invoke to search for suggestions.
* @param {AutoCompleteCompleteEvent} event - Custom complete event.
* @group Emits
*/
completeMethod = new EventEmitter();
/**
* Callback to invoke when a suggestion is selected.
* @param {AutoCompleteSelectEvent} event - custom select event.
* @group Emits
*/
onSelect = new EventEmitter();
/**
* Callback to invoke when a selected value is removed.
* @param {AutoCompleteUnselectEvent} event - custom unselect event.
* @group Emits
*/
onUnselect = new EventEmitter();
/**
* Callback to invoke when an item is added via addOnBlur or separator features.
* @param {AutoCompleteAddEvent} event - Custom add event.
* @group Emits
*/
onAdd = new EventEmitter();
/**
* Callback to invoke when the component receives focus.
* @param {Event} event - Browser event.
* @group Emits
*/
onFocus = new EventEmitter();
/**
* Callback to invoke when the component loses focus.
* @param {Event} event - Browser event.
* @group Emits
*/
onBlur = new EventEmitter();
/**
* Callback to invoke to when dropdown button is clicked.
* @param {AutoCompleteDropdownClickEvent} event - custom dropdown click event.
* @group Emits
*/
onDropdownClick = new EventEmitter();
/**
* Callback to invoke when clear button is clicked.
* @param {Event} event - Browser event.
* @group Emits
*/
onClear = new EventEmitter();
/**
* Callback to invoke on input key down.
* @param {KeyboardEvent} event - Keyboard event.
* @group Emits
*/
onInputKeydown = new EventEmitter();
/**
* Callback to invoke on input key up.
* @param {KeyboardEvent} event - Keyboard event.
* @group Emits
*/
onKeyUp = new EventEmitter();
/**
* Callback to invoke on overlay is shown.
* @param {Event} event - Browser event.
* @group Emits
*/
onShow = new EventEmitter();
/**
* Callback to invoke on overlay is hidden.
* @param {Event} event - Browser event.
* @group Emits
*/
onHide = new EventEmitter();
/**
* Callback to invoke on lazy load data.
* @param {AutoCompleteLazyLoadEvent} event - Lazy load event.
* @group Emits
*/
onLazyLoad = new EventEmitter();
inputEL;
multiInputEl;
multiContainerEL;
dropdownButton;
itemsViewChild;
scroller;
overlayViewChild;
itemsWrapper;
/**
* Custom item template.
* @group Templates
*/
itemTemplate;
/**
* Custom empty message template.
* @group Templates
*/
emptyTemplate;
/**
* Custom header template.
* @group Templates
*/
headerTemplate;
/**
* Custom footer template.
* @group Templates
*/
footerTemplate;
/**
* Custom selected item template.
* @group Templates
*/
selectedItemTemplate;
/**
* Custom group template.
* @group Templates
*/
groupTemplate;
/**
* Custom loader template.
* @group Templates
*/
loaderTemplate;
/**
* Custom remove icon template.
* @group Templates
*/
removeIconTemplate;
/**
* Custom loading icon template.
* @group Templates
*/
loadingIconTemplate;
/**
* Custom clear icon template.
* @group Templates
*/
clearIconTemplate;
/**
* Custom dropdown icon template.
* @group Templates
*/
dropdownIconTemplate;
onHostClick(event) {
this.onContainerClick(event);
}
value;
_suggestions = signal(null, ...(ngDevMode ? [{ debugName: "_suggestions" }] : []));
timeout;
overlayVisible;
suggestionsUpdated;
highlightOption;
highlightOptionChanged;
focused = false;
loading;
scrollHandler;
listId;
searchTimeout;
dirty = false;
_itemTemplate;
_groupTemplate;
_selectedItemTemplate;
_headerTemplate;
_emptyTemplate;
_footerTemplate;
_loaderTemplate;
_removeIconTemplate;
_loadingIconTemplate;
_clearIconTemplate;
_dropdownIconTemplate;
focusedMultipleOptionIndex = signal(-1, ...(ngDevMode ? [{ debugName: "focusedMultipleOptionIndex" }] : []));
focusedOptionIndex = signal(-1, ...(ngDevMode ? [{ debugName: "focusedOptionIndex" }] : []));
_componentStyle = inject(AutoCompleteStyle);
$appendTo = computed(() => this.appendTo() || this.config.overlayAppendTo(), ...(ngDevMode ? [{ debugName: "$appendTo" }] : []));
visibleOptions = computed(() => {
return this.group ? this.flatOptions(this._suggestions()) : this._suggestions() || [];
}, ...(ngDevMode ? [{ debugName: "visibleOptions" }] : []));
inputValue = computed(() => {
const modelValue = this.modelValue();
const selectedOption = this.optionValueSelected ? (this.suggestions || []).find((option) => equals(option, modelValue, this.equalityKey())) : modelValue;
if (isNotEmpty(modelValue)) {
if (typeof modelValue === 'object' || this.optionValueSelected) {
const label = this.getOptionLabel(selectedOption);
return label != null ? label : modelValue;
}
else {
return modelValue;
}
}
else {
return '';
}
}, ...(ngDevMode ? [{ debugName: "inputValue" }] : []));
get focusedMultipleOptionId() {
return this.focusedMultipleOptionIndex() !== -1 ? `${this.id}_multiple_option_${this.focusedMultipleOptionIndex()}` : null;
}
get focusedOptionId() {
return this.focusedOptionIndex() !== -1 ? `${this.id}_${this.focusedOptionIndex()}` : null;
}
get searchResultMessageText() {
return isNotEmpty(this.visibleOptions()) && this.overlayVisible ? this.searchMessageText.replaceAll('{0}', this.visibleOptions().length) : this.emptySearchMessageText;
}
get searchMessageText() {
return this.searchMessage || this.config.translation.searchMessage || '';
}
get emptySearchMessageText() {
return this.emptyMessage || this.config.translation.emptySearchMessage || '';
}
get selectionMessageText() {
return this.selectionMessage || this.config.translation.selectionMessage || '';
}
get emptySelectionMessageText() {
return this.emptySelectionMessage || this.config.translation.emptySelectionMessage || '';
}
get selectedMessageText() {
return this.hasSelectedOption() ? this.selectionMessageText.replaceAll('{0}', this.multiple ? this.modelValue()?.length : '1') : this.emptySelectionMessageText;
}
get ariaSetSize() {
return this.visibleOptions().filter((option) => !this.isOptionGroup(option)).length;
}
get listLabel() {
return this.config.getTranslation(TranslationKeys.ARIA)['listLabel'];
}
get virtualScrollerDisabled() {
return !this.virtualScroll;
}
get optionValueSelected() {
return typeof this.modelValue() === 'string' && this.optionValue;
}
chipItemClass(index) {
return this._componentStyle.classes.chipItem({ instance: this, i: index });
}
constructor(overlayService, zone) {
super();
this.overlayService = overlayService;
this.zone = zone;
}
onInit() {
this.id = this.id || uuid('pn_id_');
this.cd.detectChanges();
}
templates;
onAfterContentInit() {
this.templates.forEach((item) => {
switch (item.getType()) {
case 'item':
this._itemTemplate = item.template;
break;
case 'group':
this._groupTemplate = item.template;
break;
case 'selecteditem':
this._selectedItemTemplate = item.template;
break;
case 'selectedItem':
this._selectedItemTemplate = item.template;
break;
case 'header':
this._headerTemplate = item.template;
break;
case 'empty':
this._emptyTemplate = item.template;
break;
case 'footer':
this._footerTemplate = item.template;
break;
case 'loader':
this._loaderTemplate = item.template;
break;
case 'removetokenicon':
this._removeIconTemplate = item.template;
break;
case 'loadingicon':
this._loadingIconTemplate = item.template;
break;
case 'clearicon':
this._clearIconTemplate = item.template;
break;
case 'dropdownicon':
this._dropdownIconTemplate = item.template;
break;
default:
this._itemTemplate = item.template;
break;
}
});
}
onAfterViewChecked() {
this.bindDirectiveInstance.setAttrs(this.ptms(['host', 'root']));
//Use timeouts as since Angular 4.2, AfterViewChecked is broken and not called after panel is updated
if (this.suggestionsUpdated && this.overlayViewChild) {
this.zone.runOutsideAngular(() => {
setTimeout(() => {
if (this.overlayViewChild) {
this.overlayViewChild.alignOverlay();
}
}, 1);
this.suggestionsUpdated = false;
});
}
}
handleSuggestionsChange() {
if (this.loading) {
this._suggestions()?.length > 0 || this.showEmptyMessage || !!this.emptyTemplate ? this.show() : this.hide();
const focusedOptionIndex = this.overlayVisible && this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;
this.focusedOptionIndex.set(focusedOptionIndex);
this.suggestionsUpdated = true;
this.loading = false;
this.cd.markForCheck();
}
}
flatOptions(options) {
return (options || []).reduce((result, option, index) => {
result.push({ optionGroup: option, group: true, index });
const optionGroupChildren = this.getOptionGroupChildren(option);
optionGroupChildren && optionGroupChildren.forEach((o) => result.push(o));
return result;
}, []);
}
isOptionGroup(option) {
return this.optionGroupLabel && option.optionGroup && option.group;
}
findFirstOptionIndex() {
return this.visibleOptions().findIndex((option) => this.isValidOption(option));
}
findLastOptionIndex() {
return findLastIndex(this.visibleOptions(), (option) => this.isValidOption(option));
}
findFirstFocusedOptionIndex() {
const selectedIndex = this.findSelectedOptionIndex();
return selectedIndex < 0 ? this.findFirstOptionIndex() : selectedIndex;
}
findLastFocusedOptionIndex() {
const selectedIndex = this.findSelectedOptionIndex();
return selectedIndex < 0 ? this.findLastOptionIndex() : selectedIndex;
}
findSelectedOptionIndex() {
return this.hasSelectedOption() ? this.visibleOptions().findIndex((option) => this.isValidSelectedOption(option)) : -1;
}
findNextOptionIndex(index) {
const matchedOptionIndex = index < this.visibleOptions().length - 1
? this.visibleOptions()
.slice(index + 1)
.findIndex((option) => this.isValidOption(option))
: -1;
return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : index;
}
findPrevOptionIndex(index) {
const matchedOptionIndex = index > 0 ? findLastIndex(this.visibleOptions().slice(0, index), (option) => this.isValidOption(option)) : -1;
return matchedOptionIndex > -1 ? matchedOptionIndex : index;
}
isValidSelectedOption(option) {
return this.isValidOption(option) && this.isSelected(option);
}
isValidOption(option) {
return option && !(this.isOptionDisabled(option) || this.isOptionGroup(option));
}
isOptionDisabled(option) {
return this.optionDisabled ? resolveFieldData(option, this.optionDisabled) : false;
}
isSelected(option) {
if (this.multiple) {
return this.unique ? this.modelValue()?.some((model) => equals(model, option, this.equalityKey())) : false;
}
return equals(this.modelValue(), option, this.equalityKey());
}
isOptionMatched(option, value) {
return this.isValidOption(option) && this.getOptionLabel(option).toLocaleLowerCase(this.searchLocale) === value.toLocaleLowerCase(this.searchLocale);
}
isInputClicked(event) {
return event.target === this.inputEL?.nativeElement;
}
isDropdownClicked(event) {
return this.dropdownButton?.nativeElement ? event.target === this.dropdownButton.nativeElement || this.dropdownButton.nativeElement.contains(event.target) : false;
}
equalityKey() {
return this.optionValue ? undefined : this.dataKey;
}
onContainerClick(event) {
if (this.$disabled() || this.loading || this.isInputClicked(event) || this.isDropdownClicked(event)) {
return;
}
if (!this.overlayViewChild || !this.overlayViewChild.overlayViewChild?.nativeElement.contains(event.target)) {
focus(this.inputEL?.nativeElement);
}
}
handleDropdownClick(event) {
let query = undefined;
if (this.overlayVisible) {
this.hide(true);
}
else {
focus(this.inputEL?.nativeElement);
query = this.inputEL?.nativeElement?.value;
if (this.dropdownMode === 'blank')
this.search(event, '', 'dropdown');
else if (this.dropdownMode === 'current')
this.search(event, query, 'dropdown');
}
this.onDropdownClick.emit({ originalEvent: event, query });
}
onInput(event) {
if (this.typeahead) {
const _minLength = this.minQueryLength || this.minLength;
if (this.searchTimeout) {
clearTimeout(this.searchTimeout);
}
let query = event.target.value;
if (this.maxlength() !== null) {
query = query.split('').slice(0, this.maxlength()).join('');
}
if (!this.multiple && !this.forceSelection) {
this.updateModel(query);
}
if (query.length === 0 && !this.multiple) {
this.onClear.emit();
setTimeout(() => {
this.hide();
}, this.delay / 2);
}
else {
if (query.length >= _minLength) {
this.focusedOptionIndex.set(-1);
this.searchTimeout = setTimeout(() => {
this.search(event, query, 'input');
}, this.delay);
}
else {
this.hide();
}
}
}
}
onInputChange(event) {
this.updateInputWithForceSelection(event);
}
onInputFocus(event) {
if (this.$disabled()) {
// For ScreenReaders
return;
}
if (!this.dirty && this.completeOnFocus) {
this.search(event, event.target.value, 'focus');
}
this.dirty = true;
this.focused = true;
const focusedOptionIndex = this.focusedOptionIndex() !== -1 ? this.focusedOptionIndex() : this.overlayVisible && this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;
this.focusedOptionIndex.set(focusedOptionIndex);
this.overlayVisible && this.scrollInView(this.focusedOptionIndex());
this.onFocus.emit(event);
}
onMultipleContainerFocus(event) {
if (this.$disabled()) {
// For ScreenReaders
return;
}
this.focused = true;
}
onMultipleContainerBlur(event) {
this.focusedMultipleOptionIndex.set(-1);
this.focused = false;
}
onMultipleContainerKeyDown(event) {
if (this.$disabled()) {
event.preventDefault();
return;
}
switch (event.code) {
case 'ArrowLeft':
this.onArrowLeftKeyOnMultiple(event);
break;
case 'ArrowRight':
this.onArrowRightKeyOnMultiple(event);
break;
case 'Backspace':
this.onBackspaceKeyOnMultiple(event);
break;
default:
break;
}
}
onInputBlur(event) {
this.dirty = false;
this.focused = false;
this.focusedOptionIndex.set(-1);
if (this.addOnBlur && this.multiple && !this.typeahead) {
const inputValue = (this.multiInputEl?.nativeElement?.value || event.target.value || '').trim();
if (inputValue && !this.isSelected(inputValue)) {
this.updateModel([...(this.modelValue() || []), inputValue]);
this.onAdd.emit({ originalEvent: event, value: inputValue });
if (this.multiInputEl?.nativeElement) {
this.multiInputEl.nativeElement.value = '';
}
else {
event.target.value = '';
}
}
}
this.onModelTouched();
this.onBlur.emit(event);
}
onInputPaste(event) {
if (this.separator && this.multiple && !this.typeahead) {
const pastedData = (event.clipboardData || window['clipboardData'])?.getData('Text');
if (pastedData) {
const values = pastedData.split(this.separator);
const newValues = [...(this.modelValue() || [])];
values.forEach((value) => {
const trimmedValue = value.trim();
if (trimmedValue && !this.isSelected(trimmedValue)) {
newValues.push(trimmedValue);
}
});
if (newValues.length > (this.modelValue() || []).length) {
const addedValues = newValues.slice((this.modelValue() || []).length);
this.updateModel(newValues);
addedValues.forEach((addedValue) => {
this.onAdd.emit({ originalEvent: event, value: addedValue });
});
if (this.multiInputEl?.nativeElement) {
this.multiInputEl.nativeElement.value = '';
}
else {
event.target.value = '';
}
event.preventDefault();
}
}
}
else {
this.onKeyDown(event);
}
}
onInputKeyUp(event) {
this.onKeyUp.emit(event);
}
onKeyDown(event) {
if (this.$disabled()) {
event.preventDefault();
return;
}
// Emit keydown event for external handling
this.onInputKeydown.emit(event);
switch (event.code) {
case 'ArrowDown':
this.onArrowDownKey(event);
break;
case 'ArrowUp':
this.onArrowUpKey(event);
break;
case 'ArrowLeft':
this.onArrowLeftKey(event);
break;
case 'ArrowRight':
this.onArrowRightKey(event);
break;
case 'Home':
this.onHomeKey(event);
break;
case 'End':
this.onEndKey(event);
break;
case 'PageDown':
this.onPageDownKey(event);
break;
case 'PageUp':
this.onPageUpKey(event);
break;
case 'Enter':
case 'NumpadEnter':
this.onEnterKey(event);
break;
case 'Escape':
this.onEscapeKey(event);
break;
case 'Tab':
this.onTabKey(event);
break;
case 'Backspace':
this.onBackspaceKey(event);
break;
case 'ShiftLeft':
case 'ShiftRight':
//NOOP
break;
default:
this.handleSeparatorKey(event);
break;
}
}
handleSeparatorKey(event) {
if (this.separator && this.multiple && !this.typeahead) {
if (this.separator === event.key || (typeof this.separator === 'string' && event.key === this.separator) || (this.separator instanceof RegExp && event.key.match(this.separator))) {
const inputValue = (this.multiInputEl?.nativeElement?.value || event.target.value || '').trim();
if (inputValue && !this.isSelected(inputValue)) {
this.updateModel([...(this.modelValue() || []), inputValue]);
this.onAdd.emit({ originalEvent: event, value: inputValue });
if (this.multiInputEl?.nativeElement) {
this.multiInputEl.nativeElement.value = '';
}
else {
event.target.value = '';
}
event.preventDefault();
}
}
}
}
onArrowDownKey(event) {
if (!this.overlayVisible) {
return;
}
const optionIndex = this.focusedOptionIndex() !== -1 ? this.findNextOptionIndex(this.focusedOptionIndex()) : this.findFirstFocusedOptionIndex();
this.changeFocusedOptionIndex(event, optionIndex);
event.preventDefault();
event.stopPropagation();
}
onArrowUpKey(event) {
if (!this.overlayVisible) {
return;
}
if (event.altKey) {
if (this.focusedOptionIndex() !== -1) {
this.onOptionSelect(event, this.visibleOptions()[this.focusedOptionIndex()]);
}
this.overlayVisible && this.hide();
event.preventDefault();
}
else {
const optionIndex = this.focusedOptionIndex() !== -1 ? this.findPrevOptionIndex(this.focusedOptionIndex()) : this.findLastFocusedOptionIndex();
this.changeFocusedOptionIndex(event, optionIndex);
event.preventDefault();
event.stopPropagation();
}
}
onArrowLeftKey(event) {
const target = event.currentTarget;
this.focusedOptionIndex.set(-1);
if (this.multiple) {
if (isEmpty(target.value) && this.hasSelectedOption()) {
focus(this.multiContainerEL?.nativeElement);
this.focusedMultipleOptionIndex.set(this.modelValue().length);
}
else {
event.stopPropagation(); // To prevent onArrowLeftKeyOnMultiple method
}
}
}
onArrowRightKey(event) {
this.focusedOptionIndex.set(-1);
this.multiple && event.stopPropagation(); // To prevent onArrowRightKeyOnMultiple method
}
onHomeKey(event) {
const { currentTarget } = event;
const len = currentTarget.value.length;
currentTarget.setSelectionRange(0, event.shiftKey ? len : 0);
this.focusedOptionIndex.set(-1);
event.preventDefault();
}
onEndKey(event) {
const { currentTarget } = event;
const len = currentTarget.value.length;
currentTarget.setSelectionRange(event.shiftKey ? 0 : len, len);
this.focusedOptionIndex.set(-1);
event.preventDefault();
}
onPageDownKey(event) {
this.scrollInView(this.visibleOptions().length - 1);
event.preventDefault();
}
onPageUpKey(event) {
this.scrollInView(0);
event.preventDefault();
}
onEnterKey(event) {
if (!this.typeahead && !this.forceSelection) {
if (this.multiple) {
const inputValue = event.target.value?.trim();
if (inputValue && !this.isSelected(inputValue)) {
this.updateModel([...(this.modelValue() || []), inputValue]);
this.inputEL?.nativeElement && (this.inputEL.nativeElement.value = '');
}
}
}
if (!this.overlayVisible) {
return;
}
else {
if (this.focusedOptionIndex() !== -1) {
this.onOptionSelect(event, this.visibleOptions()[this.focusedOptionIndex()]);
}
this.hide();
}
event.preventDefault();
}
onEscapeKey(event) {
this.overlayVisible && this.hide(true);
event.preventDefault();
}
onTabKey(event) {
// If there's a focused option in the dropdown, select it
if (this.focusedOptionIndex() !== -1) {
this.onOptionSelect(event, this.visibleOptions()[this.focusedOptionIndex()]);
return;
}
// Handle tab key behavior for multiple mode without typeahead
if (this.multiple && !this.typeahead) {
const inputValue = (this.multiInputEl?.nativeElement?.value || this.inputEL?.nativeElement?.value || '').trim();
if (this.addOnTab) {
if (inputValue && !this.isSelected(inputValue)) {
// Add the value and keep focus
this.updateModel([...(this.modelValue() || []), inputValue]);
this.onAdd.emit({ originalEvent: event, value: inputValue });
if (this.multiInputEl?.nativeElement) {
this.multiInputEl.nativeElement.value = '';
}
else if (this.inputEL?.nativeElement) {
this.inputEL.nativeElement.value = '';
}
this.updateInputValue();
event.preventDefault(); // Keep focus on the component
this.overlayVisible && this.hide();
return;
}
// If no value or already selected, allow normal tab behavior (blur)
}
// If addOnTab is false or no value to add, allow normal tab behavior
// which will trigger blur and potentially addOnBlur
}
this.overlayVisible && this.hide();
}
onBackspaceKey(event) {
if (this.multiple) {
if (isNotEmpty(this.modelValue()) && !this.inputEL?.nativeElement?.value) {
const removedValue = this.modelValue()[this.modelValue().length - 1];
const newValue = this.modelValue().slice(0, -1);
this.updateModel(newValue);
this.onUnselect.emit({ originalEvent: event, value: removedValue });
}
event.stopPropagation(); // To prevent onBackspaceKeyOnMultiple method
}
}
onArrowLeftKeyOnMultiple(event) {
const optionIndex = this.focusedMultipleOptionIndex() < 1 ? 0 : this.focusedMultipleOptionIndex() - 1;
this.focusedMultipleOptionIndex.set(optionIndex);
}
onArrowRightKeyOnMultiple(event) {
let optionIndex = this.focusedMultipleOptionIndex();
optionIndex++;
this.focusedMultipleOptionIndex.set(optionIndex);
if (optionIndex > this.modelValue().length - 1) {
this.focusedMultipleOptionIndex.set(-1);
focus(this.inputEL?.nativeElement);
}
}
onBackspaceKeyOnMultiple(event) {
if (this.focusedMultipleOptionIndex() !== -1) {
this.removeOption(event, this.focusedMultipleOptionIndex());
}
}
onOptionSelect(event, option, isHide = true) {
if (this.multiple) {
this.inputEL?.nativeElement && (this.inputEL.nativeElement.value = '');
if (!this.isSelected(option)) {
this.updateModel([...(this.modelValue() || []), option]);
}
}
else {
this.updateModel(option);
}
this.onSelect.emit({ originalEvent: event, value: option });
isHide && this.hide(true);
}
onOptionMouseEnter(event, index) {
if (this.focusOnHover) {
this.changeFocusedOptionIndex(event, index);
}
}
search(event, query, source) {
//allow empty string but not undefined or null
if (query === undefined || query === null) {
return;
}
//do not search blank values on input change
if (source === 'input' && query.trim().length === 0) {
return;
}
this.loading = true;
this.completeMethod.emit({ originalEvent: event, query });
}
removeOption(event, index) {
event.stopPropagation();
const removedOption = this.modelValue()[index];
const value = this.modelValue().filter((_, i) => i !== index);
this.updateModel(value);
this.onUnselect.emit({ originalEvent: event, value: removedOption });
focus(this.inputEL?.nativeElement);
}
updateModel(options) {
let value = null;
if (options) {
value = this.multiple ? options.map((option) => this.getOptionValue(option)) : this.getOptionValue(options);
}
this.value = value;
this.writeModelValue(options);
this.onModelChange(value);
this.updateInputValue();
this.cd.markForCheck();
}
updateInputValue() {
if (this.inputEL && this.inputEL.nativeElement) {
if (!this.multiple) {
this.inputEL.nativeElement.value = this.inputValue();
}
else {
this.inputEL.nativeElement.value = '';
}
}
}
updateInputWithForceSelection(event) {
const input = this.inputEL?.nativeElement;
if (!this.forceSelection || this.overlayVisible || !input.value) {
return;
}
const matchedOption = this.visibleOptions()?.find((option) => this.isOptionMatched(option, input.value));
if (!matchedOption) {
input.value = '';
if (!this.multiple) {
this.clear();
}
return;
}
if (matchedOption && !this.isSelected(matchedOption)) {
this.onOptionSelect(event, matchedOption);
}
}
autoUpdateModel() {
if ((this.selectOnFocus || this.autoHighlight) && this.autoOptionFocus && !this.hasSelectedOption()) {
const focusedOptionIndex = this.findFirstFocusedOptionIndex();
this.focusedOptionIndex.set(focusedOptionIndex);
this.onOptionSelect(null, this.visibleOptions()[this.focusedOptionIndex()], false);
}
}
scrollInView(index = -1) {
const id = index !== -1 ? `${this.id}_${index}` : this.focusedOptionId;
if (this.itemsViewChild && this.itemsViewChild.nativeElement) {
const element = findSingle(this.itemsViewChild.nativeElement, `li[id="${id}"]`);
if (element) {
element.scrollIntoView && element.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}
else if (!this.virtualScrollerDisabled) {
setTimeout(() => {
this.virtualScroll && this.scroller?.scrollToIndex(index !== -1 ? index : this.focusedOptionIndex());
}, 0);
}
}
}
changeFocusedOptionIndex(event, index) {
if (this.focusedOptionIndex() !== index) {
this.focusedOptionIndex.set(index);
this.scrollInView();
if (this.selectOnFocus) {
this.onOptionSelect(event, this.visibleOptions()[index], false);
}
}
}
show(isFocus = false) {
this.dirty = true;
this.overlayVisible = true;
const focusedOptionIndex = this.focusedOptionIndex() !== -1 ? this.focusedOptionIndex() : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;
this.focusedOptionIndex.set(focusedOptionIndex);
isFocus && focus(this.inputEL?.nativeElement);
if (isFocus) {
focus(this.inputEL?.nativeElement);
}
this.onShow.emit();
this.cd.markForCheck();
}
hide(isFocus = false) {
const _hide = () => {
this.dirty = isFocus;