text-field.mjs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import * as i1 from '@angular/cdk/platform';
  2. import { normalizePassiveListenerOptions } from '@angular/cdk/platform';
  3. import * as i0 from '@angular/core';
  4. import { Injectable, EventEmitter, Directive, Output, Optional, Inject, Input, NgModule } from '@angular/core';
  5. import { coerceElement, coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
  6. import { EMPTY, Subject, fromEvent } from 'rxjs';
  7. import { auditTime, takeUntil } from 'rxjs/operators';
  8. import { DOCUMENT } from '@angular/common';
  9. /** Options to pass to the animationstart listener. */
  10. const listenerOptions = normalizePassiveListenerOptions({ passive: true });
  11. /**
  12. * An injectable service that can be used to monitor the autofill state of an input.
  13. * Based on the following blog post:
  14. * https://medium.com/@brunn/detecting-autofilled-fields-in-javascript-aed598d25da7
  15. */
  16. class AutofillMonitor {
  17. constructor(_platform, _ngZone) {
  18. this._platform = _platform;
  19. this._ngZone = _ngZone;
  20. this._monitoredElements = new Map();
  21. }
  22. monitor(elementOrRef) {
  23. if (!this._platform.isBrowser) {
  24. return EMPTY;
  25. }
  26. const element = coerceElement(elementOrRef);
  27. const info = this._monitoredElements.get(element);
  28. if (info) {
  29. return info.subject;
  30. }
  31. const result = new Subject();
  32. const cssClass = 'cdk-text-field-autofilled';
  33. const listener = ((event) => {
  34. // Animation events fire on initial element render, we check for the presence of the autofill
  35. // CSS class to make sure this is a real change in state, not just the initial render before
  36. // we fire off events.
  37. if (event.animationName === 'cdk-text-field-autofill-start' &&
  38. !element.classList.contains(cssClass)) {
  39. element.classList.add(cssClass);
  40. this._ngZone.run(() => result.next({ target: event.target, isAutofilled: true }));
  41. }
  42. else if (event.animationName === 'cdk-text-field-autofill-end' &&
  43. element.classList.contains(cssClass)) {
  44. element.classList.remove(cssClass);
  45. this._ngZone.run(() => result.next({ target: event.target, isAutofilled: false }));
  46. }
  47. });
  48. this._ngZone.runOutsideAngular(() => {
  49. element.addEventListener('animationstart', listener, listenerOptions);
  50. element.classList.add('cdk-text-field-autofill-monitored');
  51. });
  52. this._monitoredElements.set(element, {
  53. subject: result,
  54. unlisten: () => {
  55. element.removeEventListener('animationstart', listener, listenerOptions);
  56. },
  57. });
  58. return result;
  59. }
  60. stopMonitoring(elementOrRef) {
  61. const element = coerceElement(elementOrRef);
  62. const info = this._monitoredElements.get(element);
  63. if (info) {
  64. info.unlisten();
  65. info.subject.complete();
  66. element.classList.remove('cdk-text-field-autofill-monitored');
  67. element.classList.remove('cdk-text-field-autofilled');
  68. this._monitoredElements.delete(element);
  69. }
  70. }
  71. ngOnDestroy() {
  72. this._monitoredElements.forEach((_info, element) => this.stopMonitoring(element));
  73. }
  74. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: AutofillMonitor, deps: [{ token: i1.Platform }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Injectable }); }
  75. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: AutofillMonitor, providedIn: 'root' }); }
  76. }
  77. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: AutofillMonitor, decorators: [{
  78. type: Injectable,
  79. args: [{ providedIn: 'root' }]
  80. }], ctorParameters: function () { return [{ type: i1.Platform }, { type: i0.NgZone }]; } });
  81. /** A directive that can be used to monitor the autofill state of an input. */
  82. class CdkAutofill {
  83. constructor(_elementRef, _autofillMonitor) {
  84. this._elementRef = _elementRef;
  85. this._autofillMonitor = _autofillMonitor;
  86. /** Emits when the autofill state of the element changes. */
  87. this.cdkAutofill = new EventEmitter();
  88. }
  89. ngOnInit() {
  90. this._autofillMonitor
  91. .monitor(this._elementRef)
  92. .subscribe(event => this.cdkAutofill.emit(event));
  93. }
  94. ngOnDestroy() {
  95. this._autofillMonitor.stopMonitoring(this._elementRef);
  96. }
  97. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkAutofill, deps: [{ token: i0.ElementRef }, { token: AutofillMonitor }], target: i0.ɵɵFactoryTarget.Directive }); }
  98. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkAutofill, selector: "[cdkAutofill]", outputs: { cdkAutofill: "cdkAutofill" }, ngImport: i0 }); }
  99. }
  100. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkAutofill, decorators: [{
  101. type: Directive,
  102. args: [{
  103. selector: '[cdkAutofill]',
  104. }]
  105. }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: AutofillMonitor }]; }, propDecorators: { cdkAutofill: [{
  106. type: Output
  107. }] } });
  108. /** Directive to automatically resize a textarea to fit its content. */
  109. class CdkTextareaAutosize {
  110. /** Minimum amount of rows in the textarea. */
  111. get minRows() {
  112. return this._minRows;
  113. }
  114. set minRows(value) {
  115. this._minRows = coerceNumberProperty(value);
  116. this._setMinHeight();
  117. }
  118. /** Maximum amount of rows in the textarea. */
  119. get maxRows() {
  120. return this._maxRows;
  121. }
  122. set maxRows(value) {
  123. this._maxRows = coerceNumberProperty(value);
  124. this._setMaxHeight();
  125. }
  126. /** Whether autosizing is enabled or not */
  127. get enabled() {
  128. return this._enabled;
  129. }
  130. set enabled(value) {
  131. value = coerceBooleanProperty(value);
  132. // Only act if the actual value changed. This specifically helps to not run
  133. // resizeToFitContent too early (i.e. before ngAfterViewInit)
  134. if (this._enabled !== value) {
  135. (this._enabled = value) ? this.resizeToFitContent(true) : this.reset();
  136. }
  137. }
  138. get placeholder() {
  139. return this._textareaElement.placeholder;
  140. }
  141. set placeholder(value) {
  142. this._cachedPlaceholderHeight = undefined;
  143. if (value) {
  144. this._textareaElement.setAttribute('placeholder', value);
  145. }
  146. else {
  147. this._textareaElement.removeAttribute('placeholder');
  148. }
  149. this._cacheTextareaPlaceholderHeight();
  150. }
  151. constructor(_elementRef, _platform, _ngZone,
  152. /** @breaking-change 11.0.0 make document required */
  153. document) {
  154. this._elementRef = _elementRef;
  155. this._platform = _platform;
  156. this._ngZone = _ngZone;
  157. this._destroyed = new Subject();
  158. this._enabled = true;
  159. /**
  160. * Value of minRows as of last resize. If the minRows has decreased, the
  161. * height of the textarea needs to be recomputed to reflect the new minimum. The maxHeight
  162. * does not have the same problem because it does not affect the textarea's scrollHeight.
  163. */
  164. this._previousMinRows = -1;
  165. this._isViewInited = false;
  166. /** Handles `focus` and `blur` events. */
  167. this._handleFocusEvent = (event) => {
  168. this._hasFocus = event.type === 'focus';
  169. };
  170. this._document = document;
  171. this._textareaElement = this._elementRef.nativeElement;
  172. }
  173. /** Sets the minimum height of the textarea as determined by minRows. */
  174. _setMinHeight() {
  175. const minHeight = this.minRows && this._cachedLineHeight ? `${this.minRows * this._cachedLineHeight}px` : null;
  176. if (minHeight) {
  177. this._textareaElement.style.minHeight = minHeight;
  178. }
  179. }
  180. /** Sets the maximum height of the textarea as determined by maxRows. */
  181. _setMaxHeight() {
  182. const maxHeight = this.maxRows && this._cachedLineHeight ? `${this.maxRows * this._cachedLineHeight}px` : null;
  183. if (maxHeight) {
  184. this._textareaElement.style.maxHeight = maxHeight;
  185. }
  186. }
  187. ngAfterViewInit() {
  188. if (this._platform.isBrowser) {
  189. // Remember the height which we started with in case autosizing is disabled
  190. this._initialHeight = this._textareaElement.style.height;
  191. this.resizeToFitContent();
  192. this._ngZone.runOutsideAngular(() => {
  193. const window = this._getWindow();
  194. fromEvent(window, 'resize')
  195. .pipe(auditTime(16), takeUntil(this._destroyed))
  196. .subscribe(() => this.resizeToFitContent(true));
  197. this._textareaElement.addEventListener('focus', this._handleFocusEvent);
  198. this._textareaElement.addEventListener('blur', this._handleFocusEvent);
  199. });
  200. this._isViewInited = true;
  201. this.resizeToFitContent(true);
  202. }
  203. }
  204. ngOnDestroy() {
  205. this._textareaElement.removeEventListener('focus', this._handleFocusEvent);
  206. this._textareaElement.removeEventListener('blur', this._handleFocusEvent);
  207. this._destroyed.next();
  208. this._destroyed.complete();
  209. }
  210. /**
  211. * Cache the height of a single-row textarea if it has not already been cached.
  212. *
  213. * We need to know how large a single "row" of a textarea is in order to apply minRows and
  214. * maxRows. For the initial version, we will assume that the height of a single line in the
  215. * textarea does not ever change.
  216. */
  217. _cacheTextareaLineHeight() {
  218. if (this._cachedLineHeight) {
  219. return;
  220. }
  221. // Use a clone element because we have to override some styles.
  222. let textareaClone = this._textareaElement.cloneNode(false);
  223. textareaClone.rows = 1;
  224. // Use `position: absolute` so that this doesn't cause a browser layout and use
  225. // `visibility: hidden` so that nothing is rendered. Clear any other styles that
  226. // would affect the height.
  227. textareaClone.style.position = 'absolute';
  228. textareaClone.style.visibility = 'hidden';
  229. textareaClone.style.border = 'none';
  230. textareaClone.style.padding = '0';
  231. textareaClone.style.height = '';
  232. textareaClone.style.minHeight = '';
  233. textareaClone.style.maxHeight = '';
  234. // In Firefox it happens that textarea elements are always bigger than the specified amount
  235. // of rows. This is because Firefox tries to add extra space for the horizontal scrollbar.
  236. // As a workaround that removes the extra space for the scrollbar, we can just set overflow
  237. // to hidden. This ensures that there is no invalid calculation of the line height.
  238. // See Firefox bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=33654
  239. textareaClone.style.overflow = 'hidden';
  240. this._textareaElement.parentNode.appendChild(textareaClone);
  241. this._cachedLineHeight = textareaClone.clientHeight;
  242. textareaClone.remove();
  243. // Min and max heights have to be re-calculated if the cached line height changes
  244. this._setMinHeight();
  245. this._setMaxHeight();
  246. }
  247. _measureScrollHeight() {
  248. const element = this._textareaElement;
  249. const previousMargin = element.style.marginBottom || '';
  250. const isFirefox = this._platform.FIREFOX;
  251. const needsMarginFiller = isFirefox && this._hasFocus;
  252. const measuringClass = isFirefox
  253. ? 'cdk-textarea-autosize-measuring-firefox'
  254. : 'cdk-textarea-autosize-measuring';
  255. // In some cases the page might move around while we're measuring the `textarea` on Firefox. We
  256. // work around it by assigning a temporary margin with the same height as the `textarea` so that
  257. // it occupies the same amount of space. See #23233.
  258. if (needsMarginFiller) {
  259. element.style.marginBottom = `${element.clientHeight}px`;
  260. }
  261. // Reset the textarea height to auto in order to shrink back to its default size.
  262. // Also temporarily force overflow:hidden, so scroll bars do not interfere with calculations.
  263. element.classList.add(measuringClass);
  264. // The measuring class includes a 2px padding to workaround an issue with Chrome,
  265. // so we account for that extra space here by subtracting 4 (2px top + 2px bottom).
  266. const scrollHeight = element.scrollHeight - 4;
  267. element.classList.remove(measuringClass);
  268. if (needsMarginFiller) {
  269. element.style.marginBottom = previousMargin;
  270. }
  271. return scrollHeight;
  272. }
  273. _cacheTextareaPlaceholderHeight() {
  274. if (!this._isViewInited || this._cachedPlaceholderHeight != undefined) {
  275. return;
  276. }
  277. if (!this.placeholder) {
  278. this._cachedPlaceholderHeight = 0;
  279. return;
  280. }
  281. const value = this._textareaElement.value;
  282. this._textareaElement.value = this._textareaElement.placeholder;
  283. this._cachedPlaceholderHeight = this._measureScrollHeight();
  284. this._textareaElement.value = value;
  285. }
  286. ngDoCheck() {
  287. if (this._platform.isBrowser) {
  288. this.resizeToFitContent();
  289. }
  290. }
  291. /**
  292. * Resize the textarea to fit its content.
  293. * @param force Whether to force a height recalculation. By default the height will be
  294. * recalculated only if the value changed since the last call.
  295. */
  296. resizeToFitContent(force = false) {
  297. // If autosizing is disabled, just skip everything else
  298. if (!this._enabled) {
  299. return;
  300. }
  301. this._cacheTextareaLineHeight();
  302. this._cacheTextareaPlaceholderHeight();
  303. // If we haven't determined the line-height yet, we know we're still hidden and there's no point
  304. // in checking the height of the textarea.
  305. if (!this._cachedLineHeight) {
  306. return;
  307. }
  308. const textarea = this._elementRef.nativeElement;
  309. const value = textarea.value;
  310. // Only resize if the value or minRows have changed since these calculations can be expensive.
  311. if (!force && this._minRows === this._previousMinRows && value === this._previousValue) {
  312. return;
  313. }
  314. const scrollHeight = this._measureScrollHeight();
  315. const height = Math.max(scrollHeight, this._cachedPlaceholderHeight || 0);
  316. // Use the scrollHeight to know how large the textarea *would* be if fit its entire value.
  317. textarea.style.height = `${height}px`;
  318. this._ngZone.runOutsideAngular(() => {
  319. if (typeof requestAnimationFrame !== 'undefined') {
  320. requestAnimationFrame(() => this._scrollToCaretPosition(textarea));
  321. }
  322. else {
  323. setTimeout(() => this._scrollToCaretPosition(textarea));
  324. }
  325. });
  326. this._previousValue = value;
  327. this._previousMinRows = this._minRows;
  328. }
  329. /**
  330. * Resets the textarea to its original size
  331. */
  332. reset() {
  333. // Do not try to change the textarea, if the initialHeight has not been determined yet
  334. // This might potentially remove styles when reset() is called before ngAfterViewInit
  335. if (this._initialHeight !== undefined) {
  336. this._textareaElement.style.height = this._initialHeight;
  337. }
  338. }
  339. _noopInputHandler() {
  340. // no-op handler that ensures we're running change detection on input events.
  341. }
  342. /** Access injected document if available or fallback to global document reference */
  343. _getDocument() {
  344. return this._document || document;
  345. }
  346. /** Use defaultView of injected document if available or fallback to global window reference */
  347. _getWindow() {
  348. const doc = this._getDocument();
  349. return doc.defaultView || window;
  350. }
  351. /**
  352. * Scrolls a textarea to the caret position. On Firefox resizing the textarea will
  353. * prevent it from scrolling to the caret position. We need to re-set the selection
  354. * in order for it to scroll to the proper position.
  355. */
  356. _scrollToCaretPosition(textarea) {
  357. const { selectionStart, selectionEnd } = textarea;
  358. // IE will throw an "Unspecified error" if we try to set the selection range after the
  359. // element has been removed from the DOM. Assert that the directive hasn't been destroyed
  360. // between the time we requested the animation frame and when it was executed.
  361. // Also note that we have to assert that the textarea is focused before we set the
  362. // selection range. Setting the selection range on a non-focused textarea will cause
  363. // it to receive focus on IE and Edge.
  364. if (!this._destroyed.isStopped && this._hasFocus) {
  365. textarea.setSelectionRange(selectionStart, selectionEnd);
  366. }
  367. }
  368. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTextareaAutosize, deps: [{ token: i0.ElementRef }, { token: i1.Platform }, { token: i0.NgZone }, { token: DOCUMENT, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  369. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkTextareaAutosize, selector: "textarea[cdkTextareaAutosize]", inputs: { minRows: ["cdkAutosizeMinRows", "minRows"], maxRows: ["cdkAutosizeMaxRows", "maxRows"], enabled: ["cdkTextareaAutosize", "enabled"], placeholder: "placeholder" }, host: { attributes: { "rows": "1" }, listeners: { "input": "_noopInputHandler()" }, classAttribute: "cdk-textarea-autosize" }, exportAs: ["cdkTextareaAutosize"], ngImport: i0 }); }
  370. }
  371. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTextareaAutosize, decorators: [{
  372. type: Directive,
  373. args: [{
  374. selector: 'textarea[cdkTextareaAutosize]',
  375. exportAs: 'cdkTextareaAutosize',
  376. host: {
  377. 'class': 'cdk-textarea-autosize',
  378. // Textarea elements that have the directive applied should have a single row by default.
  379. // Browsers normally show two rows by default and therefore this limits the minRows binding.
  380. 'rows': '1',
  381. '(input)': '_noopInputHandler()',
  382. },
  383. }]
  384. }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i1.Platform }, { type: i0.NgZone }, { type: undefined, decorators: [{
  385. type: Optional
  386. }, {
  387. type: Inject,
  388. args: [DOCUMENT]
  389. }] }]; }, propDecorators: { minRows: [{
  390. type: Input,
  391. args: ['cdkAutosizeMinRows']
  392. }], maxRows: [{
  393. type: Input,
  394. args: ['cdkAutosizeMaxRows']
  395. }], enabled: [{
  396. type: Input,
  397. args: ['cdkTextareaAutosize']
  398. }], placeholder: [{
  399. type: Input
  400. }] } });
  401. class TextFieldModule {
  402. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: TextFieldModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
  403. static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.0.0", ngImport: i0, type: TextFieldModule, declarations: [CdkAutofill, CdkTextareaAutosize], exports: [CdkAutofill, CdkTextareaAutosize] }); }
  404. static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: TextFieldModule }); }
  405. }
  406. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: TextFieldModule, decorators: [{
  407. type: NgModule,
  408. args: [{
  409. declarations: [CdkAutofill, CdkTextareaAutosize],
  410. exports: [CdkAutofill, CdkTextareaAutosize],
  411. }]
  412. }] });
  413. /**
  414. * Generated bundle index. Do not edit.
  415. */
  416. export { AutofillMonitor, CdkAutofill, CdkTextareaAutosize, TextFieldModule };
  417. //# sourceMappingURL=text-field.mjs.map