UNPKG

24.1 kBJavaScriptView Raw
1/**
2 * @license
3 * Copyright 2016 Google Inc.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 * THE SOFTWARE.
22 */
23import { __assign, __extends, __values } from "tslib";
24import { MDCFoundation } from '@material/base/foundation';
25import { ALWAYS_FLOAT_TYPES, cssClasses, numbers, strings, VALIDATION_ATTR_WHITELIST } from './constants';
26var POINTERDOWN_EVENTS = ['mousedown', 'touchstart'];
27var INTERACTION_EVENTS = ['click', 'keydown'];
28var MDCTextFieldFoundation = /** @class */ (function (_super) {
29 __extends(MDCTextFieldFoundation, _super);
30 /**
31 * @param adapter
32 * @param foundationMap Map from subcomponent names to their subfoundations.
33 */
34 function MDCTextFieldFoundation(adapter, foundationMap) {
35 if (foundationMap === void 0) { foundationMap = {}; }
36 var _this = _super.call(this, __assign(__assign({}, MDCTextFieldFoundation.defaultAdapter), adapter)) || this;
37 _this.isFocused = false;
38 _this.receivedUserInput = false;
39 _this.valid = true;
40 _this.useNativeValidation = true;
41 _this.validateOnValueChange = true;
42 _this.helperText = foundationMap.helperText;
43 _this.characterCounter = foundationMap.characterCounter;
44 _this.leadingIcon = foundationMap.leadingIcon;
45 _this.trailingIcon = foundationMap.trailingIcon;
46 _this.inputFocusHandler = function () {
47 _this.activateFocus();
48 };
49 _this.inputBlurHandler = function () {
50 _this.deactivateFocus();
51 };
52 _this.inputInputHandler = function () {
53 _this.handleInput();
54 };
55 _this.setPointerXOffset = function (evt) {
56 _this.setTransformOrigin(evt);
57 };
58 _this.textFieldInteractionHandler = function () {
59 _this.handleTextFieldInteraction();
60 };
61 _this.validationAttributeChangeHandler = function (attributesList) {
62 _this.handleValidationAttributeChange(attributesList);
63 };
64 return _this;
65 }
66 Object.defineProperty(MDCTextFieldFoundation, "cssClasses", {
67 get: function () {
68 return cssClasses;
69 },
70 enumerable: false,
71 configurable: true
72 });
73 Object.defineProperty(MDCTextFieldFoundation, "strings", {
74 get: function () {
75 return strings;
76 },
77 enumerable: false,
78 configurable: true
79 });
80 Object.defineProperty(MDCTextFieldFoundation, "numbers", {
81 get: function () {
82 return numbers;
83 },
84 enumerable: false,
85 configurable: true
86 });
87 Object.defineProperty(MDCTextFieldFoundation.prototype, "shouldAlwaysFloat", {
88 get: function () {
89 var type = this.getNativeInput().type;
90 return ALWAYS_FLOAT_TYPES.indexOf(type) >= 0;
91 },
92 enumerable: false,
93 configurable: true
94 });
95 Object.defineProperty(MDCTextFieldFoundation.prototype, "shouldFloat", {
96 get: function () {
97 return this.shouldAlwaysFloat || this.isFocused || !!this.getValue() ||
98 this.isBadInput();
99 },
100 enumerable: false,
101 configurable: true
102 });
103 Object.defineProperty(MDCTextFieldFoundation.prototype, "shouldShake", {
104 get: function () {
105 return !this.isFocused && !this.isValid() && !!this.getValue();
106 },
107 enumerable: false,
108 configurable: true
109 });
110 Object.defineProperty(MDCTextFieldFoundation, "defaultAdapter", {
111 /**
112 * See {@link MDCTextFieldAdapter} for typing information on parameters and
113 * return types.
114 */
115 get: function () {
116 // tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
117 return {
118 addClass: function () { return undefined; },
119 removeClass: function () { return undefined; },
120 hasClass: function () { return true; },
121 setInputAttr: function () { return undefined; },
122 removeInputAttr: function () { return undefined; },
123 registerTextFieldInteractionHandler: function () { return undefined; },
124 deregisterTextFieldInteractionHandler: function () { return undefined; },
125 registerInputInteractionHandler: function () { return undefined; },
126 deregisterInputInteractionHandler: function () { return undefined; },
127 registerValidationAttributeChangeHandler: function () {
128 return new MutationObserver(function () { return undefined; });
129 },
130 deregisterValidationAttributeChangeHandler: function () { return undefined; },
131 getNativeInput: function () { return null; },
132 isFocused: function () { return false; },
133 activateLineRipple: function () { return undefined; },
134 deactivateLineRipple: function () { return undefined; },
135 setLineRippleTransformOrigin: function () { return undefined; },
136 shakeLabel: function () { return undefined; },
137 floatLabel: function () { return undefined; },
138 setLabelRequired: function () { return undefined; },
139 hasLabel: function () { return false; },
140 getLabelWidth: function () { return 0; },
141 hasOutline: function () { return false; },
142 notchOutline: function () { return undefined; },
143 closeOutline: function () { return undefined; },
144 };
145 // tslint:enable:object-literal-sort-keys
146 },
147 enumerable: false,
148 configurable: true
149 });
150 MDCTextFieldFoundation.prototype.init = function () {
151 var e_1, _a, e_2, _b;
152 if (this.adapter.hasLabel() && this.getNativeInput().required) {
153 this.adapter.setLabelRequired(true);
154 }
155 if (this.adapter.isFocused()) {
156 this.inputFocusHandler();
157 }
158 else if (this.adapter.hasLabel() && this.shouldFloat) {
159 this.notchOutline(true);
160 this.adapter.floatLabel(true);
161 this.styleFloating(true);
162 }
163 this.adapter.registerInputInteractionHandler('focus', this.inputFocusHandler);
164 this.adapter.registerInputInteractionHandler('blur', this.inputBlurHandler);
165 this.adapter.registerInputInteractionHandler('input', this.inputInputHandler);
166 try {
167 for (var POINTERDOWN_EVENTS_1 = __values(POINTERDOWN_EVENTS), POINTERDOWN_EVENTS_1_1 = POINTERDOWN_EVENTS_1.next(); !POINTERDOWN_EVENTS_1_1.done; POINTERDOWN_EVENTS_1_1 = POINTERDOWN_EVENTS_1.next()) {
168 var evtType = POINTERDOWN_EVENTS_1_1.value;
169 this.adapter.registerInputInteractionHandler(evtType, this.setPointerXOffset);
170 }
171 }
172 catch (e_1_1) { e_1 = { error: e_1_1 }; }
173 finally {
174 try {
175 if (POINTERDOWN_EVENTS_1_1 && !POINTERDOWN_EVENTS_1_1.done && (_a = POINTERDOWN_EVENTS_1.return)) _a.call(POINTERDOWN_EVENTS_1);
176 }
177 finally { if (e_1) throw e_1.error; }
178 }
179 try {
180 for (var INTERACTION_EVENTS_1 = __values(INTERACTION_EVENTS), INTERACTION_EVENTS_1_1 = INTERACTION_EVENTS_1.next(); !INTERACTION_EVENTS_1_1.done; INTERACTION_EVENTS_1_1 = INTERACTION_EVENTS_1.next()) {
181 var evtType = INTERACTION_EVENTS_1_1.value;
182 this.adapter.registerTextFieldInteractionHandler(evtType, this.textFieldInteractionHandler);
183 }
184 }
185 catch (e_2_1) { e_2 = { error: e_2_1 }; }
186 finally {
187 try {
188 if (INTERACTION_EVENTS_1_1 && !INTERACTION_EVENTS_1_1.done && (_b = INTERACTION_EVENTS_1.return)) _b.call(INTERACTION_EVENTS_1);
189 }
190 finally { if (e_2) throw e_2.error; }
191 }
192 this.validationObserver =
193 this.adapter.registerValidationAttributeChangeHandler(this.validationAttributeChangeHandler);
194 this.setcharacterCounter(this.getValue().length);
195 };
196 MDCTextFieldFoundation.prototype.destroy = function () {
197 var e_3, _a, e_4, _b;
198 this.adapter.deregisterInputInteractionHandler('focus', this.inputFocusHandler);
199 this.adapter.deregisterInputInteractionHandler('blur', this.inputBlurHandler);
200 this.adapter.deregisterInputInteractionHandler('input', this.inputInputHandler);
201 try {
202 for (var POINTERDOWN_EVENTS_2 = __values(POINTERDOWN_EVENTS), POINTERDOWN_EVENTS_2_1 = POINTERDOWN_EVENTS_2.next(); !POINTERDOWN_EVENTS_2_1.done; POINTERDOWN_EVENTS_2_1 = POINTERDOWN_EVENTS_2.next()) {
203 var evtType = POINTERDOWN_EVENTS_2_1.value;
204 this.adapter.deregisterInputInteractionHandler(evtType, this.setPointerXOffset);
205 }
206 }
207 catch (e_3_1) { e_3 = { error: e_3_1 }; }
208 finally {
209 try {
210 if (POINTERDOWN_EVENTS_2_1 && !POINTERDOWN_EVENTS_2_1.done && (_a = POINTERDOWN_EVENTS_2.return)) _a.call(POINTERDOWN_EVENTS_2);
211 }
212 finally { if (e_3) throw e_3.error; }
213 }
214 try {
215 for (var INTERACTION_EVENTS_2 = __values(INTERACTION_EVENTS), INTERACTION_EVENTS_2_1 = INTERACTION_EVENTS_2.next(); !INTERACTION_EVENTS_2_1.done; INTERACTION_EVENTS_2_1 = INTERACTION_EVENTS_2.next()) {
216 var evtType = INTERACTION_EVENTS_2_1.value;
217 this.adapter.deregisterTextFieldInteractionHandler(evtType, this.textFieldInteractionHandler);
218 }
219 }
220 catch (e_4_1) { e_4 = { error: e_4_1 }; }
221 finally {
222 try {
223 if (INTERACTION_EVENTS_2_1 && !INTERACTION_EVENTS_2_1.done && (_b = INTERACTION_EVENTS_2.return)) _b.call(INTERACTION_EVENTS_2);
224 }
225 finally { if (e_4) throw e_4.error; }
226 }
227 this.adapter.deregisterValidationAttributeChangeHandler(this.validationObserver);
228 };
229 /**
230 * Handles user interactions with the Text Field.
231 */
232 MDCTextFieldFoundation.prototype.handleTextFieldInteraction = function () {
233 var nativeInput = this.adapter.getNativeInput();
234 if (nativeInput && nativeInput.disabled) {
235 return;
236 }
237 this.receivedUserInput = true;
238 };
239 /**
240 * Handles validation attribute changes
241 */
242 MDCTextFieldFoundation.prototype.handleValidationAttributeChange = function (attributesList) {
243 var _this = this;
244 attributesList.some(function (attributeName) {
245 if (VALIDATION_ATTR_WHITELIST.indexOf(attributeName) > -1) {
246 _this.styleValidity(true);
247 _this.adapter.setLabelRequired(_this.getNativeInput().required);
248 return true;
249 }
250 return false;
251 });
252 if (attributesList.indexOf('maxlength') > -1) {
253 this.setcharacterCounter(this.getValue().length);
254 }
255 };
256 /**
257 * Opens/closes the notched outline.
258 */
259 MDCTextFieldFoundation.prototype.notchOutline = function (openNotch) {
260 if (!this.adapter.hasOutline() || !this.adapter.hasLabel()) {
261 return;
262 }
263 if (openNotch) {
264 var labelWidth = this.adapter.getLabelWidth() * numbers.LABEL_SCALE;
265 this.adapter.notchOutline(labelWidth);
266 }
267 else {
268 this.adapter.closeOutline();
269 }
270 };
271 /**
272 * Activates the text field focus state.
273 */
274 MDCTextFieldFoundation.prototype.activateFocus = function () {
275 this.isFocused = true;
276 this.styleFocused(this.isFocused);
277 this.adapter.activateLineRipple();
278 if (this.adapter.hasLabel()) {
279 this.notchOutline(this.shouldFloat);
280 this.adapter.floatLabel(this.shouldFloat);
281 this.styleFloating(this.shouldFloat);
282 this.adapter.shakeLabel(this.shouldShake);
283 }
284 if (this.helperText &&
285 (this.helperText.isPersistent() || !this.helperText.isValidation() ||
286 !this.valid)) {
287 this.helperText.showToScreenReader();
288 }
289 };
290 /**
291 * Sets the line ripple's transform origin, so that the line ripple activate
292 * animation will animate out from the user's click location.
293 */
294 MDCTextFieldFoundation.prototype.setTransformOrigin = function (evt) {
295 if (this.isDisabled() || this.adapter.hasOutline()) {
296 return;
297 }
298 var touches = evt.touches;
299 var targetEvent = touches ? touches[0] : evt;
300 var targetClientRect = targetEvent.target.getBoundingClientRect();
301 var normalizedX = targetEvent.clientX - targetClientRect.left;
302 this.adapter.setLineRippleTransformOrigin(normalizedX);
303 };
304 /**
305 * Handles input change of text input and text area.
306 */
307 MDCTextFieldFoundation.prototype.handleInput = function () {
308 this.autoCompleteFocus();
309 this.setcharacterCounter(this.getValue().length);
310 };
311 /**
312 * Activates the Text Field's focus state in cases when the input value
313 * changes without user input (e.g. programmatically).
314 */
315 MDCTextFieldFoundation.prototype.autoCompleteFocus = function () {
316 if (!this.receivedUserInput) {
317 this.activateFocus();
318 }
319 };
320 /**
321 * Deactivates the Text Field's focus state.
322 */
323 MDCTextFieldFoundation.prototype.deactivateFocus = function () {
324 this.isFocused = false;
325 this.adapter.deactivateLineRipple();
326 var isValid = this.isValid();
327 this.styleValidity(isValid);
328 this.styleFocused(this.isFocused);
329 if (this.adapter.hasLabel()) {
330 this.notchOutline(this.shouldFloat);
331 this.adapter.floatLabel(this.shouldFloat);
332 this.styleFloating(this.shouldFloat);
333 this.adapter.shakeLabel(this.shouldShake);
334 }
335 if (!this.shouldFloat) {
336 this.receivedUserInput = false;
337 }
338 };
339 MDCTextFieldFoundation.prototype.getValue = function () {
340 return this.getNativeInput().value;
341 };
342 /**
343 * @param value The value to set on the input Element.
344 */
345 MDCTextFieldFoundation.prototype.setValue = function (value) {
346 // Prevent Safari from moving the caret to the end of the input when the
347 // value has not changed.
348 if (this.getValue() !== value) {
349 this.getNativeInput().value = value;
350 }
351 this.setcharacterCounter(value.length);
352 if (this.validateOnValueChange) {
353 var isValid = this.isValid();
354 this.styleValidity(isValid);
355 }
356 if (this.adapter.hasLabel()) {
357 this.notchOutline(this.shouldFloat);
358 this.adapter.floatLabel(this.shouldFloat);
359 this.styleFloating(this.shouldFloat);
360 if (this.validateOnValueChange) {
361 this.adapter.shakeLabel(this.shouldShake);
362 }
363 }
364 };
365 /**
366 * @return The custom validity state, if set; otherwise, the result of a
367 * native validity check.
368 */
369 MDCTextFieldFoundation.prototype.isValid = function () {
370 return this.useNativeValidation ? this.isNativeInputValid() : this.valid;
371 };
372 /**
373 * @param isValid Sets the custom validity state of the Text Field.
374 */
375 MDCTextFieldFoundation.prototype.setValid = function (isValid) {
376 this.valid = isValid;
377 this.styleValidity(isValid);
378 var shouldShake = !isValid && !this.isFocused && !!this.getValue();
379 if (this.adapter.hasLabel()) {
380 this.adapter.shakeLabel(shouldShake);
381 }
382 };
383 /**
384 * @param shouldValidate Whether or not validity should be updated on
385 * value change.
386 */
387 MDCTextFieldFoundation.prototype.setValidateOnValueChange = function (shouldValidate) {
388 this.validateOnValueChange = shouldValidate;
389 };
390 /**
391 * @return Whether or not validity should be updated on value change. `true`
392 * by default.
393 */
394 MDCTextFieldFoundation.prototype.getValidateOnValueChange = function () {
395 return this.validateOnValueChange;
396 };
397 /**
398 * Enables or disables the use of native validation. Use this for custom
399 * validation.
400 * @param useNativeValidation Set this to false to ignore native input
401 * validation.
402 */
403 MDCTextFieldFoundation.prototype.setUseNativeValidation = function (useNativeValidation) {
404 this.useNativeValidation = useNativeValidation;
405 };
406 MDCTextFieldFoundation.prototype.isDisabled = function () {
407 return this.getNativeInput().disabled;
408 };
409 /**
410 * @param disabled Sets the text-field disabled or enabled.
411 */
412 MDCTextFieldFoundation.prototype.setDisabled = function (disabled) {
413 this.getNativeInput().disabled = disabled;
414 this.styleDisabled(disabled);
415 };
416 /**
417 * @param content Sets the content of the helper text.
418 */
419 MDCTextFieldFoundation.prototype.setHelperTextContent = function (content) {
420 if (this.helperText) {
421 this.helperText.setContent(content);
422 }
423 };
424 /**
425 * Sets the aria label of the leading icon.
426 */
427 MDCTextFieldFoundation.prototype.setLeadingIconAriaLabel = function (label) {
428 if (this.leadingIcon) {
429 this.leadingIcon.setAriaLabel(label);
430 }
431 };
432 /**
433 * Sets the text content of the leading icon.
434 */
435 MDCTextFieldFoundation.prototype.setLeadingIconContent = function (content) {
436 if (this.leadingIcon) {
437 this.leadingIcon.setContent(content);
438 }
439 };
440 /**
441 * Sets the aria label of the trailing icon.
442 */
443 MDCTextFieldFoundation.prototype.setTrailingIconAriaLabel = function (label) {
444 if (this.trailingIcon) {
445 this.trailingIcon.setAriaLabel(label);
446 }
447 };
448 /**
449 * Sets the text content of the trailing icon.
450 */
451 MDCTextFieldFoundation.prototype.setTrailingIconContent = function (content) {
452 if (this.trailingIcon) {
453 this.trailingIcon.setContent(content);
454 }
455 };
456 /**
457 * Sets character counter values that shows characters used and the total
458 * character limit.
459 */
460 MDCTextFieldFoundation.prototype.setcharacterCounter = function (currentLength) {
461 if (!this.characterCounter) {
462 return;
463 }
464 var maxLength = this.getNativeInput().maxLength;
465 if (maxLength === -1) {
466 throw new Error('MDCTextFieldFoundation: Expected maxlength html property on text input or textarea.');
467 }
468 this.characterCounter.setCounterValue(currentLength, maxLength);
469 };
470 /**
471 * @return True if the Text Field input fails in converting the user-supplied
472 * value.
473 */
474 MDCTextFieldFoundation.prototype.isBadInput = function () {
475 // The badInput property is not supported in IE 11 💩.
476 return this.getNativeInput().validity.badInput || false;
477 };
478 /**
479 * @return The result of native validity checking (ValidityState.valid).
480 */
481 MDCTextFieldFoundation.prototype.isNativeInputValid = function () {
482 return this.getNativeInput().validity.valid;
483 };
484 /**
485 * Styles the component based on the validity state.
486 */
487 MDCTextFieldFoundation.prototype.styleValidity = function (isValid) {
488 var INVALID = MDCTextFieldFoundation.cssClasses.INVALID;
489 if (isValid) {
490 this.adapter.removeClass(INVALID);
491 }
492 else {
493 this.adapter.addClass(INVALID);
494 }
495 if (this.helperText) {
496 this.helperText.setValidity(isValid);
497 // We dynamically set or unset aria-describedby for validation helper text
498 // only, based on whether the field is valid
499 var helperTextValidation = this.helperText.isValidation();
500 if (!helperTextValidation) {
501 return;
502 }
503 var helperTextVisible = this.helperText.isVisible();
504 var helperTextId = this.helperText.getId();
505 if (helperTextVisible && helperTextId) {
506 this.adapter.setInputAttr(strings.ARIA_DESCRIBEDBY, helperTextId);
507 }
508 else {
509 this.adapter.removeInputAttr(strings.ARIA_DESCRIBEDBY);
510 }
511 }
512 };
513 /**
514 * Styles the component based on the focused state.
515 */
516 MDCTextFieldFoundation.prototype.styleFocused = function (isFocused) {
517 var FOCUSED = MDCTextFieldFoundation.cssClasses.FOCUSED;
518 if (isFocused) {
519 this.adapter.addClass(FOCUSED);
520 }
521 else {
522 this.adapter.removeClass(FOCUSED);
523 }
524 };
525 /**
526 * Styles the component based on the disabled state.
527 */
528 MDCTextFieldFoundation.prototype.styleDisabled = function (isDisabled) {
529 var _a = MDCTextFieldFoundation.cssClasses, DISABLED = _a.DISABLED, INVALID = _a.INVALID;
530 if (isDisabled) {
531 this.adapter.addClass(DISABLED);
532 this.adapter.removeClass(INVALID);
533 }
534 else {
535 this.adapter.removeClass(DISABLED);
536 }
537 if (this.leadingIcon) {
538 this.leadingIcon.setDisabled(isDisabled);
539 }
540 if (this.trailingIcon) {
541 this.trailingIcon.setDisabled(isDisabled);
542 }
543 };
544 /**
545 * Styles the component based on the label floating state.
546 */
547 MDCTextFieldFoundation.prototype.styleFloating = function (isFloating) {
548 var LABEL_FLOATING = MDCTextFieldFoundation.cssClasses.LABEL_FLOATING;
549 if (isFloating) {
550 this.adapter.addClass(LABEL_FLOATING);
551 }
552 else {
553 this.adapter.removeClass(LABEL_FLOATING);
554 }
555 };
556 /**
557 * @return The native text input element from the host environment, or an
558 * object with the same shape for unit tests.
559 */
560 MDCTextFieldFoundation.prototype.getNativeInput = function () {
561 // this.adapter may be undefined in foundation unit tests. This happens when
562 // testdouble is creating a mock object and invokes the
563 // shouldShake/shouldFloat getters (which in turn call getValue(), which
564 // calls this method) before init() has been called from the MDCTextField
565 // constructor. To work around that issue, we return a dummy object.
566 var nativeInput = this.adapter ? this.adapter.getNativeInput() : null;
567 return nativeInput || {
568 disabled: false,
569 maxLength: -1,
570 required: false,
571 type: 'input',
572 validity: {
573 badInput: false,
574 valid: true,
575 },
576 value: '',
577 };
578 };
579 return MDCTextFieldFoundation;
580}(MDCFoundation));
581export { MDCTextFieldFoundation };
582// tslint:disable-next-line:no-default-export Needed for backward compatibility with MDC Web v0.44.0 and earlier.
583export default MDCTextFieldFoundation;
584//# sourceMappingURL=foundation.js.map
\No newline at end of file