autocomplete.mjs 59 KB

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