autocomplete.mjs 65 KB

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