source: trip-planner-front/node_modules/@angular/material/fesm2015/autocomplete.js@ 59329aa

Last change on this file since 59329aa was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 41.0 KB
Line 
1import { ActiveDescendantKeyManager } from '@angular/cdk/a11y';
2import { coerceBooleanProperty, coerceStringArray } from '@angular/cdk/coercion';
3import { Platform, _getEventTarget } from '@angular/cdk/platform';
4import { InjectionToken, EventEmitter, Directive, ChangeDetectorRef, ElementRef, Inject, ViewChild, TemplateRef, Input, Output, Component, ViewEncapsulation, ChangeDetectionStrategy, ContentChildren, forwardRef, ViewContainerRef, NgZone, Optional, Host, NgModule } from '@angular/core';
5import { mixinDisableRipple, MAT_OPTION_PARENT_COMPONENT, MAT_OPTGROUP, MatOption, MatOptionSelectionChange, _countGroupLabelsBeforeOption, _getOptionScrollPosition, MatOptionModule, MatCommonModule } from '@angular/material/core';
6import { Subscription, Subject, defer, merge, of, fromEvent } from 'rxjs';
7import { DOCUMENT, CommonModule } from '@angular/common';
8import { Overlay, OverlayConfig, OverlayModule } from '@angular/cdk/overlay';
9import { ViewportRuler, CdkScrollableModule } from '@angular/cdk/scrolling';
10import { Directionality } from '@angular/cdk/bidi';
11import { ESCAPE, hasModifierKey, ENTER, UP_ARROW, DOWN_ARROW, TAB } from '@angular/cdk/keycodes';
12import { TemplatePortal } from '@angular/cdk/portal';
13import { NG_VALUE_ACCESSOR } from '@angular/forms';
14import { MatFormField, MAT_FORM_FIELD } from '@angular/material/form-field';
15import { take, switchMap, filter, map, tap, delay } from 'rxjs/operators';
16
17/**
18 * @license
19 * Copyright Google LLC All Rights Reserved.
20 *
21 * Use of this source code is governed by an MIT-style license that can be
22 * found in the LICENSE file at https://angular.io/license
23 */
24/**
25 * Autocomplete IDs need to be unique across components, so this counter exists outside of
26 * the component definition.
27 */
28let _uniqueAutocompleteIdCounter = 0;
29/** Event object that is emitted when an autocomplete option is selected. */
30class MatAutocompleteSelectedEvent {
31 constructor(
32 /** Reference to the autocomplete panel that emitted the event. */
33 source,
34 /** Option that was selected. */
35 option) {
36 this.source = source;
37 this.option = option;
38 }
39}
40// Boilerplate for applying mixins to MatAutocomplete.
41/** @docs-private */
42const _MatAutocompleteMixinBase = mixinDisableRipple(class {
43});
44/** Injection token to be used to override the default options for `mat-autocomplete`. */
45const MAT_AUTOCOMPLETE_DEFAULT_OPTIONS = new InjectionToken('mat-autocomplete-default-options', {
46 providedIn: 'root',
47 factory: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY,
48});
49/** @docs-private */
50function MAT_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY() {
51 return { autoActiveFirstOption: false };
52}
53/** Base class with all of the `MatAutocomplete` functionality. */
54class _MatAutocompleteBase extends _MatAutocompleteMixinBase {
55 constructor(_changeDetectorRef, _elementRef, defaults, platform) {
56 super();
57 this._changeDetectorRef = _changeDetectorRef;
58 this._elementRef = _elementRef;
59 this._activeOptionChanges = Subscription.EMPTY;
60 /** Whether the autocomplete panel should be visible, depending on option length. */
61 this.showPanel = false;
62 this._isOpen = false;
63 /** Function that maps an option's control value to its display value in the trigger. */
64 this.displayWith = null;
65 /** Event that is emitted whenever an option from the list is selected. */
66 this.optionSelected = new EventEmitter();
67 /** Event that is emitted when the autocomplete panel is opened. */
68 this.opened = new EventEmitter();
69 /** Event that is emitted when the autocomplete panel is closed. */
70 this.closed = new EventEmitter();
71 /** Emits whenever an option is activated using the keyboard. */
72 this.optionActivated = new EventEmitter();
73 this._classList = {};
74 /** Unique ID to be used by autocomplete trigger's "aria-owns" property. */
75 this.id = `mat-autocomplete-${_uniqueAutocompleteIdCounter++}`;
76 // TODO(crisbeto): the problem that the `inertGroups` option resolves is only present on
77 // Safari using VoiceOver. We should occasionally check back to see whether the bug
78 // wasn't resolved in VoiceOver, and if it has, we can remove this and the `inertGroups`
79 // option altogether.
80 this.inertGroups = (platform === null || platform === void 0 ? void 0 : platform.SAFARI) || false;
81 this._autoActiveFirstOption = !!defaults.autoActiveFirstOption;
82 }
83 /** Whether the autocomplete panel is open. */
84 get isOpen() { return this._isOpen && this.showPanel; }
85 /**
86 * Whether the first option should be highlighted when the autocomplete panel is opened.
87 * Can be configured globally through the `MAT_AUTOCOMPLETE_DEFAULT_OPTIONS` token.
88 */
89 get autoActiveFirstOption() { return this._autoActiveFirstOption; }
90 set autoActiveFirstOption(value) {
91 this._autoActiveFirstOption = coerceBooleanProperty(value);
92 }
93 /**
94 * Takes classes set on the host mat-autocomplete element and applies them to the panel
95 * inside the overlay container to allow for easy styling.
96 */
97 set classList(value) {
98 if (value && value.length) {
99 this._classList = coerceStringArray(value).reduce((classList, className) => {
100 classList[className] = true;
101 return classList;
102 }, {});
103 }
104 else {
105 this._classList = {};
106 }
107 this._setVisibilityClasses(this._classList);
108 this._elementRef.nativeElement.className = '';
109 }
110 ngAfterContentInit() {
111 this._keyManager = new ActiveDescendantKeyManager(this.options).withWrap();
112 this._activeOptionChanges = this._keyManager.change.subscribe(index => {
113 if (this.isOpen) {
114 this.optionActivated.emit({ source: this, option: this.options.toArray()[index] || null });
115 }
116 });
117 // Set the initial visibility state.
118 this._setVisibility();
119 }
120 ngOnDestroy() {
121 this._activeOptionChanges.unsubscribe();
122 }
123 /**
124 * Sets the panel scrollTop. This allows us to manually scroll to display options
125 * above or below the fold, as they are not actually being focused when active.
126 */
127 _setScrollTop(scrollTop) {
128 if (this.panel) {
129 this.panel.nativeElement.scrollTop = scrollTop;
130 }
131 }
132 /** Returns the panel's scrollTop. */
133 _getScrollTop() {
134 return this.panel ? this.panel.nativeElement.scrollTop : 0;
135 }
136 /** Panel should hide itself when the option list is empty. */
137 _setVisibility() {
138 this.showPanel = !!this.options.length;
139 this._setVisibilityClasses(this._classList);
140 this._changeDetectorRef.markForCheck();
141 }
142 /** Emits the `select` event. */
143 _emitSelectEvent(option) {
144 const event = new MatAutocompleteSelectedEvent(this, option);
145 this.optionSelected.emit(event);
146 }
147 /** Gets the aria-labelledby for the autocomplete panel. */
148 _getPanelAriaLabelledby(labelId) {
149 if (this.ariaLabel) {
150 return null;
151 }
152 const labelExpression = labelId ? labelId + ' ' : '';
153 return this.ariaLabelledby ? labelExpression + this.ariaLabelledby : labelId;
154 }
155 /** Sets the autocomplete visibility classes on a classlist based on the panel is visible. */
156 _setVisibilityClasses(classList) {
157 classList[this._visibleClass] = this.showPanel;
158 classList[this._hiddenClass] = !this.showPanel;
159 }
160}
161_MatAutocompleteBase.decorators = [
162 { type: Directive }
163];
164_MatAutocompleteBase.ctorParameters = () => [
165 { type: ChangeDetectorRef },
166 { type: ElementRef },
167 { type: undefined, decorators: [{ type: Inject, args: [MAT_AUTOCOMPLETE_DEFAULT_OPTIONS,] }] },
168 { type: Platform }
169];
170_MatAutocompleteBase.propDecorators = {
171 template: [{ type: ViewChild, args: [TemplateRef, { static: true },] }],
172 panel: [{ type: ViewChild, args: ['panel',] }],
173 ariaLabel: [{ type: Input, args: ['aria-label',] }],
174 ariaLabelledby: [{ type: Input, args: ['aria-labelledby',] }],
175 displayWith: [{ type: Input }],
176 autoActiveFirstOption: [{ type: Input }],
177 panelWidth: [{ type: Input }],
178 optionSelected: [{ type: Output }],
179 opened: [{ type: Output }],
180 closed: [{ type: Output }],
181 optionActivated: [{ type: Output }],
182 classList: [{ type: Input, args: ['class',] }]
183};
184class MatAutocomplete extends _MatAutocompleteBase {
185 constructor() {
186 super(...arguments);
187 this._visibleClass = 'mat-autocomplete-visible';
188 this._hiddenClass = 'mat-autocomplete-hidden';
189 }
190}
191MatAutocomplete.decorators = [
192 { type: Component, args: [{
193 selector: 'mat-autocomplete',
194 template: "<ng-template let-formFieldId=\"id\">\n <div class=\"mat-autocomplete-panel\"\n role=\"listbox\"\n [id]=\"id\"\n [attr.aria-label]=\"ariaLabel || null\"\n [attr.aria-labelledby]=\"_getPanelAriaLabelledby(formFieldId)\"\n [ngClass]=\"_classList\"\n #panel>\n <ng-content></ng-content>\n </div>\n</ng-template>\n",
195 encapsulation: ViewEncapsulation.None,
196 changeDetection: ChangeDetectionStrategy.OnPush,
197 exportAs: 'matAutocomplete',
198 inputs: ['disableRipple'],
199 host: {
200 'class': 'mat-autocomplete'
201 },
202 providers: [
203 { provide: MAT_OPTION_PARENT_COMPONENT, useExisting: MatAutocomplete }
204 ],
205 styles: [".mat-autocomplete-panel{min-width:112px;max-width:280px;overflow:auto;-webkit-overflow-scrolling:touch;visibility:hidden;max-width:none;max-height:256px;position:relative;width:100%;border-bottom-left-radius:4px;border-bottom-right-radius:4px}.mat-autocomplete-panel.mat-autocomplete-visible{visibility:visible}.mat-autocomplete-panel.mat-autocomplete-hidden{visibility:hidden}.mat-autocomplete-panel-above .mat-autocomplete-panel{border-radius:0;border-top-left-radius:4px;border-top-right-radius:4px}.mat-autocomplete-panel .mat-divider-horizontal{margin-top:-1px}.cdk-high-contrast-active .mat-autocomplete-panel{outline:solid 1px}mat-autocomplete{display:none}\n"]
206 },] }
207];
208MatAutocomplete.propDecorators = {
209 optionGroups: [{ type: ContentChildren, args: [MAT_OPTGROUP, { descendants: true },] }],
210 options: [{ type: ContentChildren, args: [MatOption, { descendants: true },] }]
211};
212
213/**
214 * @license
215 * Copyright Google LLC All Rights Reserved.
216 *
217 * Use of this source code is governed by an MIT-style license that can be
218 * found in the LICENSE file at https://angular.io/license
219 */
220/** Base class containing all of the functionality for `MatAutocompleteOrigin`. */
221class _MatAutocompleteOriginBase {
222 constructor(
223 /** Reference to the element on which the directive is applied. */
224 elementRef) {
225 this.elementRef = elementRef;
226 }
227}
228_MatAutocompleteOriginBase.decorators = [
229 { type: Directive }
230];
231_MatAutocompleteOriginBase.ctorParameters = () => [
232 { type: ElementRef }
233];
234/**
235 * Directive applied to an element to make it usable
236 * as a connection point for an autocomplete panel.
237 */
238class MatAutocompleteOrigin extends _MatAutocompleteOriginBase {
239}
240MatAutocompleteOrigin.decorators = [
241 { type: Directive, args: [{
242 selector: '[matAutocompleteOrigin]',
243 exportAs: 'matAutocompleteOrigin',
244 },] }
245];
246
247/**
248 * @license
249 * Copyright Google LLC All Rights Reserved.
250 *
251 * Use of this source code is governed by an MIT-style license that can be
252 * found in the LICENSE file at https://angular.io/license
253 */
254/** Injection token that determines the scroll handling while the autocomplete panel is open. */
255const MAT_AUTOCOMPLETE_SCROLL_STRATEGY = new InjectionToken('mat-autocomplete-scroll-strategy');
256/** @docs-private */
257function MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY(overlay) {
258 return () => overlay.scrollStrategies.reposition();
259}
260/** @docs-private */
261const MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER = {
262 provide: MAT_AUTOCOMPLETE_SCROLL_STRATEGY,
263 deps: [Overlay],
264 useFactory: MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY,
265};
266/**
267 * Provider that allows the autocomplete to register as a ControlValueAccessor.
268 * @docs-private
269 */
270const MAT_AUTOCOMPLETE_VALUE_ACCESSOR = {
271 provide: NG_VALUE_ACCESSOR,
272 useExisting: forwardRef(() => MatAutocompleteTrigger),
273 multi: true
274};
275/**
276 * Creates an error to be thrown when attempting to use an autocomplete trigger without a panel.
277 * @docs-private
278 */
279function getMatAutocompleteMissingPanelError() {
280 return Error('Attempting to open an undefined instance of `mat-autocomplete`. ' +
281 'Make sure that the id passed to the `matAutocomplete` is correct and that ' +
282 'you\'re attempting to open it after the ngAfterContentInit hook.');
283}
284/** Base class with all of the `MatAutocompleteTrigger` functionality. */
285class _MatAutocompleteTriggerBase {
286 constructor(_element, _overlay, _viewContainerRef, _zone, _changeDetectorRef, scrollStrategy, _dir, _formField, _document, _viewportRuler, _defaults) {
287 this._element = _element;
288 this._overlay = _overlay;
289 this._viewContainerRef = _viewContainerRef;
290 this._zone = _zone;
291 this._changeDetectorRef = _changeDetectorRef;
292 this._dir = _dir;
293 this._formField = _formField;
294 this._document = _document;
295 this._viewportRuler = _viewportRuler;
296 this._defaults = _defaults;
297 this._componentDestroyed = false;
298 this._autocompleteDisabled = false;
299 /** Whether or not the label state is being overridden. */
300 this._manuallyFloatingLabel = false;
301 /** Subscription to viewport size changes. */
302 this._viewportSubscription = Subscription.EMPTY;
303 /**
304 * Whether the autocomplete can open the next time it is focused. Used to prevent a focused,
305 * closed autocomplete from being reopened if the user switches to another browser tab and then
306 * comes back.
307 */
308 this._canOpenOnNextFocus = true;
309 /** Stream of keyboard events that can close the panel. */
310 this._closeKeyEventStream = new Subject();
311 /**
312 * Event handler for when the window is blurred. Needs to be an
313 * arrow function in order to preserve the context.
314 */
315 this._windowBlurHandler = () => {
316 // If the user blurred the window while the autocomplete is focused, it means that it'll be
317 // refocused when they come back. In this case we want to skip the first focus event, if the
318 // pane was closed, in order to avoid reopening it unintentionally.
319 this._canOpenOnNextFocus =
320 this._document.activeElement !== this._element.nativeElement || this.panelOpen;
321 };
322 /** `View -> model callback called when value changes` */
323 this._onChange = () => { };
324 /** `View -> model callback called when autocomplete has been touched` */
325 this._onTouched = () => { };
326 /**
327 * Position of the autocomplete panel relative to the trigger element. A position of `auto`
328 * will render the panel underneath the trigger if there is enough space for it to fit in
329 * the viewport, otherwise the panel will be shown above it. If the position is set to
330 * `above` or `below`, the panel will always be shown above or below the trigger. no matter
331 * whether it fits completely in the viewport.
332 */
333 this.position = 'auto';
334 /**
335 * `autocomplete` attribute to be set on the input element.
336 * @docs-private
337 */
338 this.autocompleteAttribute = 'off';
339 this._overlayAttached = false;
340 /** Stream of autocomplete option selections. */
341 this.optionSelections = defer(() => {
342 if (this.autocomplete && this.autocomplete.options) {
343 return merge(...this.autocomplete.options.map(option => option.onSelectionChange));
344 }
345 // If there are any subscribers before `ngAfterViewInit`, the `autocomplete` will be undefined.
346 // Return a stream that we'll replace with the real one once everything is in place.
347 return this._zone.onStable
348 .pipe(take(1), switchMap(() => this.optionSelections));
349 });
350 this._scrollStrategy = scrollStrategy;
351 }
352 /**
353 * Whether the autocomplete is disabled. When disabled, the element will
354 * act as a regular input and the user won't be able to open the panel.
355 */
356 get autocompleteDisabled() { return this._autocompleteDisabled; }
357 set autocompleteDisabled(value) {
358 this._autocompleteDisabled = coerceBooleanProperty(value);
359 }
360 ngAfterViewInit() {
361 const window = this._getWindow();
362 if (typeof window !== 'undefined') {
363 this._zone.runOutsideAngular(() => window.addEventListener('blur', this._windowBlurHandler));
364 }
365 }
366 ngOnChanges(changes) {
367 if (changes['position'] && this._positionStrategy) {
368 this._setStrategyPositions(this._positionStrategy);
369 if (this.panelOpen) {
370 this._overlayRef.updatePosition();
371 }
372 }
373 }
374 ngOnDestroy() {
375 const window = this._getWindow();
376 if (typeof window !== 'undefined') {
377 window.removeEventListener('blur', this._windowBlurHandler);
378 }
379 this._viewportSubscription.unsubscribe();
380 this._componentDestroyed = true;
381 this._destroyPanel();
382 this._closeKeyEventStream.complete();
383 }
384 /** Whether or not the autocomplete panel is open. */
385 get panelOpen() {
386 return this._overlayAttached && this.autocomplete.showPanel;
387 }
388 /** Opens the autocomplete suggestion panel. */
389 openPanel() {
390 this._attachOverlay();
391 this._floatLabel();
392 }
393 /** Closes the autocomplete suggestion panel. */
394 closePanel() {
395 this._resetLabel();
396 if (!this._overlayAttached) {
397 return;
398 }
399 if (this.panelOpen) {
400 // Only emit if the panel was visible.
401 this.autocomplete.closed.emit();
402 }
403 this.autocomplete._isOpen = this._overlayAttached = false;
404 if (this._overlayRef && this._overlayRef.hasAttached()) {
405 this._overlayRef.detach();
406 this._closingActionsSubscription.unsubscribe();
407 }
408 // Note that in some cases this can end up being called after the component is destroyed.
409 // Add a check to ensure that we don't try to run change detection on a destroyed view.
410 if (!this._componentDestroyed) {
411 // We need to trigger change detection manually, because
412 // `fromEvent` doesn't seem to do it at the proper time.
413 // This ensures that the label is reset when the
414 // user clicks outside.
415 this._changeDetectorRef.detectChanges();
416 }
417 }
418 /**
419 * Updates the position of the autocomplete suggestion panel to ensure that it fits all options
420 * within the viewport.
421 */
422 updatePosition() {
423 if (this._overlayAttached) {
424 this._overlayRef.updatePosition();
425 }
426 }
427 /**
428 * A stream of actions that should close the autocomplete panel, including
429 * when an option is selected, on blur, and when TAB is pressed.
430 */
431 get panelClosingActions() {
432 return merge(this.optionSelections, this.autocomplete._keyManager.tabOut.pipe(filter(() => this._overlayAttached)), this._closeKeyEventStream, this._getOutsideClickStream(), this._overlayRef ?
433 this._overlayRef.detachments().pipe(filter(() => this._overlayAttached)) :
434 of()).pipe(
435 // Normalize the output so we return a consistent type.
436 map(event => event instanceof MatOptionSelectionChange ? event : null));
437 }
438 /** The currently active option, coerced to MatOption type. */
439 get activeOption() {
440 if (this.autocomplete && this.autocomplete._keyManager) {
441 return this.autocomplete._keyManager.activeItem;
442 }
443 return null;
444 }
445 /** Stream of clicks outside of the autocomplete panel. */
446 _getOutsideClickStream() {
447 return merge(fromEvent(this._document, 'click'), fromEvent(this._document, 'auxclick'), fromEvent(this._document, 'touchend'))
448 .pipe(filter(event => {
449 // If we're in the Shadow DOM, the event target will be the shadow root, so we have to
450 // fall back to check the first element in the path of the click event.
451 const clickTarget = _getEventTarget(event);
452 const formField = this._formField ? this._formField._elementRef.nativeElement : null;
453 const customOrigin = this.connectedTo ? this.connectedTo.elementRef.nativeElement : null;
454 return this._overlayAttached && clickTarget !== this._element.nativeElement &&
455 (!formField || !formField.contains(clickTarget)) &&
456 (!customOrigin || !customOrigin.contains(clickTarget)) &&
457 (!!this._overlayRef && !this._overlayRef.overlayElement.contains(clickTarget));
458 }));
459 }
460 // Implemented as part of ControlValueAccessor.
461 writeValue(value) {
462 Promise.resolve(null).then(() => this._setTriggerValue(value));
463 }
464 // Implemented as part of ControlValueAccessor.
465 registerOnChange(fn) {
466 this._onChange = fn;
467 }
468 // Implemented as part of ControlValueAccessor.
469 registerOnTouched(fn) {
470 this._onTouched = fn;
471 }
472 // Implemented as part of ControlValueAccessor.
473 setDisabledState(isDisabled) {
474 this._element.nativeElement.disabled = isDisabled;
475 }
476 _handleKeydown(event) {
477 const keyCode = event.keyCode;
478 // Prevent the default action on all escape key presses. This is here primarily to bring IE
479 // in line with other browsers. By default, pressing escape on IE will cause it to revert
480 // the input value to the one that it had on focus, however it won't dispatch any events
481 // which means that the model value will be out of sync with the view.
482 if (keyCode === ESCAPE && !hasModifierKey(event)) {
483 event.preventDefault();
484 }
485 if (this.activeOption && keyCode === ENTER && this.panelOpen) {
486 this.activeOption._selectViaInteraction();
487 this._resetActiveItem();
488 event.preventDefault();
489 }
490 else if (this.autocomplete) {
491 const prevActiveItem = this.autocomplete._keyManager.activeItem;
492 const isArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW;
493 if (this.panelOpen || keyCode === TAB) {
494 this.autocomplete._keyManager.onKeydown(event);
495 }
496 else if (isArrowKey && this._canOpen()) {
497 this.openPanel();
498 }
499 if (isArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) {
500 this._scrollToOption(this.autocomplete._keyManager.activeItemIndex || 0);
501 }
502 }
503 }
504 _handleInput(event) {
505 let target = event.target;
506 let value = target.value;
507 // Based on `NumberValueAccessor` from forms.
508 if (target.type === 'number') {
509 value = value == '' ? null : parseFloat(value);
510 }
511 // If the input has a placeholder, IE will fire the `input` event on page load,
512 // focus and blur, in addition to when the user actually changed the value. To
513 // filter out all of the extra events, we save the value on focus and between
514 // `input` events, and we check whether it changed.
515 // See: https://connect.microsoft.com/IE/feedback/details/885747/
516 if (this._previousValue !== value) {
517 this._previousValue = value;
518 this._onChange(value);
519 if (this._canOpen() && this._document.activeElement === event.target) {
520 this.openPanel();
521 }
522 }
523 }
524 _handleFocus() {
525 if (!this._canOpenOnNextFocus) {
526 this._canOpenOnNextFocus = true;
527 }
528 else if (this._canOpen()) {
529 this._previousValue = this._element.nativeElement.value;
530 this._attachOverlay();
531 this._floatLabel(true);
532 }
533 }
534 /**
535 * In "auto" mode, the label will animate down as soon as focus is lost.
536 * This causes the value to jump when selecting an option with the mouse.
537 * This method manually floats the label until the panel can be closed.
538 * @param shouldAnimate Whether the label should be animated when it is floated.
539 */
540 _floatLabel(shouldAnimate = false) {
541 if (this._formField && this._formField.floatLabel === 'auto') {
542 if (shouldAnimate) {
543 this._formField._animateAndLockLabel();
544 }
545 else {
546 this._formField.floatLabel = 'always';
547 }
548 this._manuallyFloatingLabel = true;
549 }
550 }
551 /** If the label has been manually elevated, return it to its normal state. */
552 _resetLabel() {
553 if (this._manuallyFloatingLabel) {
554 this._formField.floatLabel = 'auto';
555 this._manuallyFloatingLabel = false;
556 }
557 }
558 /**
559 * This method listens to a stream of panel closing actions and resets the
560 * stream every time the option list changes.
561 */
562 _subscribeToClosingActions() {
563 const firstStable = this._zone.onStable.pipe(take(1));
564 const optionChanges = this.autocomplete.options.changes.pipe(tap(() => this._positionStrategy.reapplyLastPosition()),
565 // Defer emitting to the stream until the next tick, because changing
566 // bindings in here will cause "changed after checked" errors.
567 delay(0));
568 // When the zone is stable initially, and when the option list changes...
569 return merge(firstStable, optionChanges)
570 .pipe(
571 // create a new stream of panelClosingActions, replacing any previous streams
572 // that were created, and flatten it so our stream only emits closing events...
573 switchMap(() => {
574 const wasOpen = this.panelOpen;
575 this._resetActiveItem();
576 this.autocomplete._setVisibility();
577 if (this.panelOpen) {
578 this._overlayRef.updatePosition();
579 // If the `panelOpen` state changed, we need to make sure to emit the `opened`
580 // event, because we may not have emitted it when the panel was attached. This
581 // can happen if the users opens the panel and there are no options, but the
582 // options come in slightly later or as a result of the value changing.
583 if (wasOpen !== this.panelOpen) {
584 this.autocomplete.opened.emit();
585 }
586 }
587 return this.panelClosingActions;
588 }),
589 // when the first closing event occurs...
590 take(1))
591 // set the value, close the panel, and complete.
592 .subscribe(event => this._setValueAndClose(event));
593 }
594 /** Destroys the autocomplete suggestion panel. */
595 _destroyPanel() {
596 if (this._overlayRef) {
597 this.closePanel();
598 this._overlayRef.dispose();
599 this._overlayRef = null;
600 }
601 }
602 _setTriggerValue(value) {
603 const toDisplay = this.autocomplete && this.autocomplete.displayWith ?
604 this.autocomplete.displayWith(value) :
605 value;
606 // Simply falling back to an empty string if the display value is falsy does not work properly.
607 // The display value can also be the number zero and shouldn't fall back to an empty string.
608 const inputValue = toDisplay != null ? toDisplay : '';
609 // If it's used within a `MatFormField`, we should set it through the property so it can go
610 // through change detection.
611 if (this._formField) {
612 this._formField._control.value = inputValue;
613 }
614 else {
615 this._element.nativeElement.value = inputValue;
616 }
617 this._previousValue = inputValue;
618 }
619 /**
620 * This method closes the panel, and if a value is specified, also sets the associated
621 * control to that value. It will also mark the control as dirty if this interaction
622 * stemmed from the user.
623 */
624 _setValueAndClose(event) {
625 if (event && event.source) {
626 this._clearPreviousSelectedOption(event.source);
627 this._setTriggerValue(event.source.value);
628 this._onChange(event.source.value);
629 this._element.nativeElement.focus();
630 this.autocomplete._emitSelectEvent(event.source);
631 }
632 this.closePanel();
633 }
634 /**
635 * Clear any previous selected option and emit a selection change event for this option
636 */
637 _clearPreviousSelectedOption(skip) {
638 this.autocomplete.options.forEach(option => {
639 if (option !== skip && option.selected) {
640 option.deselect();
641 }
642 });
643 }
644 _attachOverlay() {
645 var _a;
646 if (!this.autocomplete && (typeof ngDevMode === 'undefined' || ngDevMode)) {
647 throw getMatAutocompleteMissingPanelError();
648 }
649 let overlayRef = this._overlayRef;
650 if (!overlayRef) {
651 this._portal = new TemplatePortal(this.autocomplete.template, this._viewContainerRef, { id: (_a = this._formField) === null || _a === void 0 ? void 0 : _a.getLabelId() });
652 overlayRef = this._overlay.create(this._getOverlayConfig());
653 this._overlayRef = overlayRef;
654 // Use the `keydownEvents` in order to take advantage of
655 // the overlay event targeting provided by the CDK overlay.
656 overlayRef.keydownEvents().subscribe(event => {
657 // Close when pressing ESCAPE or ALT + UP_ARROW, based on the a11y guidelines.
658 // See: https://www.w3.org/TR/wai-aria-practices-1.1/#textbox-keyboard-interaction
659 if ((event.keyCode === ESCAPE && !hasModifierKey(event)) ||
660 (event.keyCode === UP_ARROW && hasModifierKey(event, 'altKey'))) {
661 this._closeKeyEventStream.next();
662 this._resetActiveItem();
663 // We need to stop propagation, otherwise the event will eventually
664 // reach the input itself and cause the overlay to be reopened.
665 event.stopPropagation();
666 event.preventDefault();
667 }
668 });
669 this._viewportSubscription = this._viewportRuler.change().subscribe(() => {
670 if (this.panelOpen && overlayRef) {
671 overlayRef.updateSize({ width: this._getPanelWidth() });
672 }
673 });
674 }
675 else {
676 // Update the trigger, panel width and direction, in case anything has changed.
677 this._positionStrategy.setOrigin(this._getConnectedElement());
678 overlayRef.updateSize({ width: this._getPanelWidth() });
679 }
680 if (overlayRef && !overlayRef.hasAttached()) {
681 overlayRef.attach(this._portal);
682 this._closingActionsSubscription = this._subscribeToClosingActions();
683 }
684 const wasOpen = this.panelOpen;
685 this.autocomplete._setVisibility();
686 this.autocomplete._isOpen = this._overlayAttached = true;
687 // We need to do an extra `panelOpen` check in here, because the
688 // autocomplete won't be shown if there are no options.
689 if (this.panelOpen && wasOpen !== this.panelOpen) {
690 this.autocomplete.opened.emit();
691 }
692 }
693 _getOverlayConfig() {
694 var _a;
695 return new OverlayConfig({
696 positionStrategy: this._getOverlayPosition(),
697 scrollStrategy: this._scrollStrategy(),
698 width: this._getPanelWidth(),
699 direction: this._dir,
700 panelClass: (_a = this._defaults) === null || _a === void 0 ? void 0 : _a.overlayPanelClass,
701 });
702 }
703 _getOverlayPosition() {
704 const strategy = this._overlay.position()
705 .flexibleConnectedTo(this._getConnectedElement())
706 .withFlexibleDimensions(false)
707 .withPush(false);
708 this._setStrategyPositions(strategy);
709 this._positionStrategy = strategy;
710 return strategy;
711 }
712 /** Sets the positions on a position strategy based on the directive's input state. */
713 _setStrategyPositions(positionStrategy) {
714 // Note that we provide horizontal fallback positions, even though by default the dropdown
715 // width matches the input, because consumers can override the width. See #18854.
716 const belowPositions = [
717 { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top' },
718 { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top' }
719 ];
720 // The overlay edge connected to the trigger should have squared corners, while
721 // the opposite end has rounded corners. We apply a CSS class to swap the
722 // border-radius based on the overlay position.
723 const panelClass = this._aboveClass;
724 const abovePositions = [
725 { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', panelClass },
726 { originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom', panelClass }
727 ];
728 let positions;
729 if (this.position === 'above') {
730 positions = abovePositions;
731 }
732 else if (this.position === 'below') {
733 positions = belowPositions;
734 }
735 else {
736 positions = [...belowPositions, ...abovePositions];
737 }
738 positionStrategy.withPositions(positions);
739 }
740 _getConnectedElement() {
741 if (this.connectedTo) {
742 return this.connectedTo.elementRef;
743 }
744 return this._formField ? this._formField.getConnectedOverlayOrigin() : this._element;
745 }
746 _getPanelWidth() {
747 return this.autocomplete.panelWidth || this._getHostWidth();
748 }
749 /** Returns the width of the input element, so the panel width can match it. */
750 _getHostWidth() {
751 return this._getConnectedElement().nativeElement.getBoundingClientRect().width;
752 }
753 /**
754 * Resets the active item to -1 so arrow events will activate the
755 * correct options, or to 0 if the consumer opted into it.
756 */
757 _resetActiveItem() {
758 const autocomplete = this.autocomplete;
759 if (autocomplete.autoActiveFirstOption) {
760 // Note that we go through `setFirstItemActive`, rather than `setActiveItem(0)`, because
761 // the former will find the next enabled option, if the first one is disabled.
762 autocomplete._keyManager.setFirstItemActive();
763 }
764 else {
765 autocomplete._keyManager.setActiveItem(-1);
766 }
767 }
768 /** Determines whether the panel can be opened. */
769 _canOpen() {
770 const element = this._element.nativeElement;
771 return !element.readOnly && !element.disabled && !this._autocompleteDisabled;
772 }
773 /** Use defaultView of injected document if available or fallback to global window reference */
774 _getWindow() {
775 var _a;
776 return ((_a = this._document) === null || _a === void 0 ? void 0 : _a.defaultView) || window;
777 }
778 /** Scrolls to a particular option in the list. */
779 _scrollToOption(index) {
780 // Given that we are not actually focusing active options, we must manually adjust scroll
781 // to reveal options below the fold. First, we find the offset of the option from the top
782 // of the panel. If that offset is below the fold, the new scrollTop will be the offset -
783 // the panel height + the option height, so the active option will be just visible at the
784 // bottom of the panel. If that offset is above the top of the visible panel, the new scrollTop
785 // will become the offset. If that offset is visible within the panel already, the scrollTop is
786 // not adjusted.
787 const autocomplete = this.autocomplete;
788 const labelCount = _countGroupLabelsBeforeOption(index, autocomplete.options, autocomplete.optionGroups);
789 if (index === 0 && labelCount === 1) {
790 // If we've got one group label before the option and we're at the top option,
791 // scroll the list to the top. This is better UX than scrolling the list to the
792 // top of the option, because it allows the user to read the top group's label.
793 autocomplete._setScrollTop(0);
794 }
795 else if (autocomplete.panel) {
796 const option = autocomplete.options.toArray()[index];
797 if (option) {
798 const element = option._getHostElement();
799 const newScrollPosition = _getOptionScrollPosition(element.offsetTop, element.offsetHeight, autocomplete._getScrollTop(), autocomplete.panel.nativeElement.offsetHeight);
800 autocomplete._setScrollTop(newScrollPosition);
801 }
802 }
803 }
804}
805_MatAutocompleteTriggerBase.decorators = [
806 { type: Directive }
807];
808_MatAutocompleteTriggerBase.ctorParameters = () => [
809 { type: ElementRef },
810 { type: Overlay },
811 { type: ViewContainerRef },
812 { type: NgZone },
813 { type: ChangeDetectorRef },
814 { type: undefined, decorators: [{ type: Inject, args: [MAT_AUTOCOMPLETE_SCROLL_STRATEGY,] }] },
815 { type: Directionality, decorators: [{ type: Optional }] },
816 { type: MatFormField, decorators: [{ type: Optional }, { type: Inject, args: [MAT_FORM_FIELD,] }, { type: Host }] },
817 { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [DOCUMENT,] }] },
818 { type: ViewportRuler },
819 { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_AUTOCOMPLETE_DEFAULT_OPTIONS,] }] }
820];
821_MatAutocompleteTriggerBase.propDecorators = {
822 autocomplete: [{ type: Input, args: ['matAutocomplete',] }],
823 position: [{ type: Input, args: ['matAutocompletePosition',] }],
824 connectedTo: [{ type: Input, args: ['matAutocompleteConnectedTo',] }],
825 autocompleteAttribute: [{ type: Input, args: ['autocomplete',] }],
826 autocompleteDisabled: [{ type: Input, args: ['matAutocompleteDisabled',] }]
827};
828class MatAutocompleteTrigger extends _MatAutocompleteTriggerBase {
829 constructor() {
830 super(...arguments);
831 this._aboveClass = 'mat-autocomplete-panel-above';
832 }
833}
834MatAutocompleteTrigger.decorators = [
835 { type: Directive, args: [{
836 selector: `input[matAutocomplete], textarea[matAutocomplete]`,
837 host: {
838 'class': 'mat-autocomplete-trigger',
839 '[attr.autocomplete]': 'autocompleteAttribute',
840 '[attr.role]': 'autocompleteDisabled ? null : "combobox"',
841 '[attr.aria-autocomplete]': 'autocompleteDisabled ? null : "list"',
842 '[attr.aria-activedescendant]': '(panelOpen && activeOption) ? activeOption.id : null',
843 '[attr.aria-expanded]': 'autocompleteDisabled ? null : panelOpen.toString()',
844 '[attr.aria-owns]': '(autocompleteDisabled || !panelOpen) ? null : autocomplete?.id',
845 '[attr.aria-haspopup]': '!autocompleteDisabled',
846 // Note: we use `focusin`, as opposed to `focus`, in order to open the panel
847 // a little earlier. This avoids issues where IE delays the focusing of the input.
848 '(focusin)': '_handleFocus()',
849 '(blur)': '_onTouched()',
850 '(input)': '_handleInput($event)',
851 '(keydown)': '_handleKeydown($event)',
852 },
853 exportAs: 'matAutocompleteTrigger',
854 providers: [MAT_AUTOCOMPLETE_VALUE_ACCESSOR]
855 },] }
856];
857
858/**
859 * @license
860 * Copyright Google LLC All Rights Reserved.
861 *
862 * Use of this source code is governed by an MIT-style license that can be
863 * found in the LICENSE file at https://angular.io/license
864 */
865class MatAutocompleteModule {
866}
867MatAutocompleteModule.decorators = [
868 { type: NgModule, args: [{
869 imports: [
870 OverlayModule,
871 MatOptionModule,
872 MatCommonModule,
873 CommonModule
874 ],
875 exports: [
876 MatAutocomplete,
877 MatAutocompleteTrigger,
878 MatAutocompleteOrigin,
879 CdkScrollableModule,
880 MatOptionModule,
881 MatCommonModule,
882 ],
883 declarations: [MatAutocomplete, MatAutocompleteTrigger, MatAutocompleteOrigin],
884 providers: [MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER],
885 },] }
886];
887
888/**
889 * @license
890 * Copyright Google LLC All Rights Reserved.
891 *
892 * Use of this source code is governed by an MIT-style license that can be
893 * found in the LICENSE file at https://angular.io/license
894 */
895
896/**
897 * Generated bundle index. Do not edit.
898 */
899
900export { MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, MAT_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY, MAT_AUTOCOMPLETE_SCROLL_STRATEGY, MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY, MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER, MAT_AUTOCOMPLETE_VALUE_ACCESSOR, MatAutocomplete, MatAutocompleteModule, MatAutocompleteOrigin, MatAutocompleteSelectedEvent, MatAutocompleteTrigger, _MatAutocompleteBase, _MatAutocompleteOriginBase, _MatAutocompleteTriggerBase, getMatAutocompleteMissingPanelError };
901//# sourceMappingURL=autocomplete.js.map
Note: See TracBrowser for help on using the repository browser.