forked from ionic-team/ionic-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput-base.ts
More file actions
596 lines (495 loc) · 18.5 KB
/
input-base.ts
File metadata and controls
596 lines (495 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
import { ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { NgControl } from '@angular/forms';
import { App } from '../app/app';
import { closest, copyInputAttributes, Coordinates, hasPointerMoved, pointerCoord } from '../../util/dom';
import { Config } from '../../config/config';
import { Content } from '../content/content';
import { Form } from '../../util/form';
import { isTrueProperty } from '../../util/util';
import { Item } from '../item/item';
import { NativeInput, NextInput } from './native-input';
import { NavController } from '../nav/nav-controller';
import { Platform } from '../../platform/platform';
export class InputBase {
protected _coord: Coordinates;
protected _deregScroll: Function;
protected _disabled: boolean = false;
protected _keyboardHeight: number;
protected _scrollMove: EventListener;
protected _type: string = 'text';
protected _useAssist: boolean;
protected _usePadding: boolean;
protected _value: any = '';
protected _isTouch: boolean;
protected _autoFocusAssist: string;
protected _autoComplete: string;
protected _autoCorrect: string;
inputControl: NgControl;
@Input() clearInput: any;
@Input() placeholder: string = '';
@ViewChild(NativeInput) protected _native: NativeInput;
@Output() blur: EventEmitter<Event> = new EventEmitter<Event>();
@Output() focus: EventEmitter<Event> = new EventEmitter<Event>();
constructor(
config: Config,
protected _form: Form,
protected _item: Item,
protected _app: App,
protected _platform: Platform,
protected _elementRef: ElementRef,
protected _scrollView: Content,
protected _nav: NavController,
ngControl: NgControl
) {
this._useAssist = config.getBoolean('scrollAssist', false);
this._usePadding = config.getBoolean('scrollPadding', this._useAssist);
this._keyboardHeight = config.getNumber('keyboardHeight');
this._autoFocusAssist = config.get('autoFocusAssist', 'delay');
this._autoComplete = config.get('autocomplete', 'off');
this._autoCorrect = config.get('autocorrect', 'off');
if (ngControl) {
ngControl.valueAccessor = this;
this.inputControl = ngControl;
}
_form.register(this);
}
ngOnInit() {
if (this._item) {
this._item.setCssClass('item-input', true);
this._item.registerInput(this._type);
}
let clearInput = this.clearInput;
if (typeof clearInput === 'string') {
this.clearInput = (clearInput === '' || clearInput === 'true');
}
}
ngAfterContentInit() {
let self = this;
self._scrollMove = function(ev: UIEvent) {
// scroll move event listener this instance can reuse
if (!(self._nav && self._nav.isTransitioning())) {
self.deregScrollMove();
if (self.hasFocus()) {
self._native.hideFocus(true);
self._scrollView.onScrollEnd(function() {
self._native.hideFocus(false);
if (self.hasFocus()) {
// if it still has focus then keep listening
self.regScrollMove();
}
});
}
}
};
this.setItemInputControlCss();
}
ngAfterContentChecked() {
this.setItemInputControlCss();
}
private setItemInputControlCss() {
let item = this._item;
let nativeInput = this._native;
let inputControl = this.inputControl;
// Set the control classes on the item
if (item && inputControl) {
this.setControlCss(item, inputControl);
}
// Set the control classes on the native input
if (nativeInput && inputControl) {
this.setControlCss(nativeInput, inputControl);
}
}
private setControlCss(element: any, control: any) {
element.setCssClass('ng-untouched', control.untouched);
element.setCssClass('ng-touched', control.touched);
element.setCssClass('ng-pristine', control.pristine);
element.setCssClass('ng-dirty', control.dirty);
element.setCssClass('ng-valid', control.valid);
element.setCssClass('ng-invalid', !control.valid);
}
ngOnDestroy() {
this._form.deregister(this);
}
@Input()
get value() {
return this._value;
}
set value(val: any) {
this._value = val;
this.checkHasValue(val);
}
@Input()
get type() {
return this._type;
}
set type(val) {
this._type = 'text';
if (val) {
val = val.toLowerCase();
if (/password|email|number|search|tel|url|date|month|time|week/.test(val)) {
this._type = val;
}
}
}
@Input()
get disabled() {
return this._disabled;
}
set disabled(val) {
this._disabled = isTrueProperty(val);
this._item && this._item.setCssClass('item-input-disabled', this._disabled);
this._native && this._native.isDisabled(this._disabled);
}
/**
* @private
*/
@ViewChild(NativeInput)
private set _nativeInput(nativeInput: NativeInput) {
this._native = nativeInput;
if (this._item && this._item.labelId !== null) {
nativeInput.labelledBy(this._item.labelId);
}
nativeInput.valueChange.subscribe((inputValue: any) => {
this.onChange(inputValue);
});
this.focusChange(this.hasFocus());
nativeInput.focusChange.subscribe((textInputHasFocus: any) => {
this.focusChange(textInputHasFocus);
this.checkHasValue(nativeInput.getValue());
if (!textInputHasFocus) {
this.onTouched(textInputHasFocus);
}
});
this.checkHasValue(nativeInput.getValue());
this.disabled = this._disabled;
var ionInputEle: HTMLElement = this._elementRef.nativeElement;
let nativeInputEle: HTMLElement = nativeInput.element();
// copy ion-input attributes to the native input element
copyInputAttributes(ionInputEle, nativeInputEle);
if (ionInputEle.hasAttribute('autofocus')) {
// the ion-input element has the autofocus attributes
ionInputEle.removeAttribute('autofocus');
if (this._autoFocusAssist === 'immediate') {
// config says to immediate focus on the input
// works best on android devices
nativeInputEle.focus();
} else if (this._autoFocusAssist === 'delay') {
// config says to chill out a bit and focus on the input after transitions
// works best on desktop
setTimeout(() => {
nativeInputEle.focus();
}, 650);
}
// traditionally iOS has big issues with autofocus on actual devices
// autoFocus is disabled by default with the iOS mode config
}
// by default set autocomplete="off" unless specified by the input
if (ionInputEle.hasAttribute('autocomplete')) {
this._autoComplete = ionInputEle.getAttribute('autocomplete');
}
nativeInputEle.setAttribute('autocomplete', this._autoComplete);
// by default set autocorrect="off" unless specified by the input
if (ionInputEle.hasAttribute('autocorrect')) {
this._autoCorrect = ionInputEle.getAttribute('autocorrect');
}
nativeInputEle.setAttribute('autocorrect', this._autoCorrect);
}
/**
* @private
*/
@ViewChild(NextInput)
private set _nextInput(nextInput: NextInput) {
if (nextInput) {
nextInput.focused.subscribe(() => {
this._form.tabFocus(this);
});
}
}
/**
* @private
* Angular2 Forms API method called by the model (Control) on change to update
* the checked value.
* https://github.com/angular/angular/blob/master/modules/angular2/src/forms/directives/shared.ts#L34
*/
writeValue(val: any) {
this._value = val;
this.checkHasValue(val);
}
/**
* @private
*/
onChange(val: any) {
this.checkHasValue(val);
}
/**
* @private
*/
onTouched(val: any) {}
/**
* @private
*/
hasFocus(): boolean {
// check if an input has focus or not
return this._native.hasFocus();
}
/**
* @private
*/
checkHasValue(inputValue: any) {
if (this._item) {
this._item.setCssClass('input-has-value', !!(inputValue && inputValue !== ''));
}
}
/**
* @private
*/
focusChange(inputHasFocus: boolean) {
if (this._item) {
this._item.setCssClass('input-has-focus', inputHasFocus);
}
if (!inputHasFocus) {
this.deregScrollMove();
}
}
private pointerStart(ev: any) {
// input cover touchstart
console.debug('scroll assist pointerStart', ev.type);
if (ev.type === 'touchstart') {
this._isTouch = true;
}
if ((this._isTouch || (!this._isTouch && ev.type === 'mousedown')) && this._app.isEnabled()) {
// remember where the touchstart/mousedown started
this._coord = pointerCoord(ev);
}
}
private pointerEnd(ev: any) {
// input cover touchend/mouseup
console.debug('scroll assist pointerEnd', ev.type);
if ((this._isTouch && ev.type === 'mouseup') || !this._app.isEnabled()) {
// the app is actively doing something right now
// don't try to scroll in the input
ev.preventDefault();
ev.stopPropagation();
} else if (this._coord) {
// get where the touchend/mouseup ended
let endCoord = pointerCoord(ev);
// focus this input if the pointer hasn't moved XX pixels
// and the input doesn't already have focus
if (!hasPointerMoved(8, this._coord, endCoord) && !this.hasFocus()) {
ev.preventDefault();
ev.stopPropagation();
// begin the input focus process
console.debug('initFocus', ev.type);
this.initFocus();
}
}
this._coord = null;
}
/**
* @private
*/
initFocus() {
// begin the process of setting focus to the inner input element
var scrollView = this._scrollView;
if (scrollView) {
// this input is inside of a scroll view
// find out if text input should be manually scrolled into view
// get container of this input, probably an ion-item a few nodes up
var ele = this._elementRef.nativeElement;
ele = closest(ele, 'ion-item,[ion-item]') || ele;
var scrollData = InputBase.getScrollData(ele.offsetTop, ele.offsetHeight, scrollView.getContentDimensions(), this._keyboardHeight, this._platform.height());
if (scrollData.scrollAmount > -3 && scrollData.scrollAmount < 3) {
// the text input is in a safe position that doesn't
// require it to be scrolled into view, just set focus now
this.setFocus();
this.regScrollMove();
return;
}
if (this._usePadding) {
// add padding to the bottom of the scroll view (if needed)
scrollView.addScrollPadding(scrollData.scrollPadding);
}
// manually scroll the text input to the top
// do not allow any clicks while it's scrolling
var scrollDuration = getScrollAssistDuration(scrollData.scrollAmount);
this._app.setEnabled(false, scrollDuration);
this._nav && this._nav.setTransitioning(true, scrollDuration);
// temporarily move the focus to the focus holder so the browser
// doesn't freak out while it's trying to get the input in place
// at this point the native text input still does not have focus
this._native.beginFocus(true, scrollData.inputSafeY);
// scroll the input into place
scrollView.scrollTo(0, scrollData.scrollTo, scrollDuration).then(() => {
// the scroll view is in the correct position now
// give the native text input focus
this._native.beginFocus(false, 0);
// ensure this is the focused input
this.setFocus();
// all good, allow clicks again
this._app.setEnabled(true);
this._nav && this._nav.setTransitioning(false);
this.regScrollMove();
if (this._usePadding) {
this._scrollView.clearScrollPaddingFocusOut();
}
});
} else {
// not inside of a scroll view, just focus it
this.setFocus();
this.regScrollMove();
}
}
/**
* @private
*/
private setFocus() {
// immediately set focus
this._form.setAsFocused(this);
// set focus on the actual input element
console.debug(`input-base, setFocus ${this._native.element().value}`);
this._native.setFocus();
// ensure the body hasn't scrolled down
document.body.scrollTop = 0;
}
/**
* @private
* Angular2 Forms API method called by the view (formControlName) to register the
* onChange event handler that updates the model (Control).
* @param {Function} fn the onChange event handler.
*/
registerOnChange(fn: any) { this.onChange = fn; }
/**
* @private
* Angular2 Forms API method called by the view (formControlName) to register
* the onTouched event handler that marks model (Control) as touched.
* @param {Function} fn onTouched event handler.
*/
registerOnTouched(fn: any) { this.onTouched = fn; }
/**
* @private
*/
private regScrollMove() {
// register scroll move listener
if (this._useAssist && this._scrollView) {
setTimeout(() => {
this.deregScrollMove();
this._deregScroll = this._scrollView.addScrollListener(this._scrollMove);
}, 80);
}
}
/**
* @private
*/
private deregScrollMove() {
// deregister the scroll move listener
this._deregScroll && this._deregScroll();
}
focusNext() {
this._form.tabFocus(this);
}
/**
* @private
*/
static getScrollData(inputOffsetTop: number, inputOffsetHeight: number, scrollViewDimensions: any, keyboardHeight: number, plaformHeight: number) {
// compute input's Y values relative to the body
let inputTop = (inputOffsetTop + scrollViewDimensions.contentTop - scrollViewDimensions.scrollTop);
let inputBottom = (inputTop + inputOffsetHeight);
// compute the safe area which is the viewable content area when the soft keyboard is up
let safeAreaTop = scrollViewDimensions.contentTop;
let safeAreaHeight = plaformHeight - keyboardHeight - safeAreaTop;
safeAreaHeight /= 2;
let safeAreaBottom = safeAreaTop + safeAreaHeight;
let inputTopWithinSafeArea = (inputTop >= safeAreaTop && inputTop <= safeAreaBottom);
let inputTopAboveSafeArea = (inputTop < safeAreaTop);
let inputTopBelowSafeArea = (inputTop > safeAreaBottom);
let inputBottomWithinSafeArea = (inputBottom >= safeAreaTop && inputBottom <= safeAreaBottom);
let inputBottomBelowSafeArea = (inputBottom > safeAreaBottom);
/*
Text Input Scroll To Scenarios
---------------------------------------
1) Input top within safe area, bottom within safe area
2) Input top within safe area, bottom below safe area, room to scroll
3) Input top above safe area, bottom within safe area, room to scroll
4) Input top below safe area, no room to scroll, input smaller than safe area
5) Input top within safe area, bottom below safe area, no room to scroll, input smaller than safe area
6) Input top within safe area, bottom below safe area, no room to scroll, input larger than safe area
7) Input top below safe area, no room to scroll, input larger than safe area
*/
let scrollData = {
scrollAmount: 0,
scrollTo: 0,
scrollPadding: 0,
inputSafeY: 0
};
if (inputTopWithinSafeArea && inputBottomWithinSafeArea) {
// Input top within safe area, bottom within safe area
// no need to scroll to a position, it's good as-is
return scrollData;
}
// looks like we'll have to do some auto-scrolling
if (inputTopBelowSafeArea || inputBottomBelowSafeArea) {
// Input top and bottom below safe area
// auto scroll the input up so at least the top of it shows
if (safeAreaHeight > inputOffsetHeight) {
// safe area height is taller than the input height, so we
// can bring it up the input just enough to show the input bottom
scrollData.scrollAmount = Math.round(safeAreaBottom - inputBottom);
} else {
// safe area height is smaller than the input height, so we can
// only scroll it up so the input top is at the top of the safe area
// however the input bottom will be below the safe area
scrollData.scrollAmount = Math.round(safeAreaTop - inputTop);
}
scrollData.inputSafeY = -(inputTop - safeAreaTop) + 4;
} else if (inputTopAboveSafeArea) {
// Input top above safe area
// auto scroll the input down so at least the top of it shows
scrollData.scrollAmount = Math.round(safeAreaTop - inputTop);
scrollData.inputSafeY = (safeAreaTop - inputTop) + 4;
}
// figure out where it should scroll to for the best position to the input
scrollData.scrollTo = (scrollViewDimensions.scrollTop - scrollData.scrollAmount);
if (scrollData.scrollAmount < 0) {
// when auto-scrolling up, there also needs to be enough
// content padding at the bottom of the scroll view
// manually add it if there isn't enough scrollable area
// figure out how many scrollable area is left to scroll up
let availablePadding = (scrollViewDimensions.scrollHeight - scrollViewDimensions.scrollTop) - scrollViewDimensions.contentHeight;
let paddingSpace = availablePadding + scrollData.scrollAmount;
if (paddingSpace < 0) {
// there's not enough scrollable area at the bottom, so manually add more
scrollData.scrollPadding = (scrollViewDimensions.contentHeight - safeAreaHeight);
}
}
// if (!window.safeAreaEle) {
// window.safeAreaEle = document.createElement('div');
// window.safeAreaEle.style.position = 'absolute';
// window.safeAreaEle.style.background = 'rgba(0, 128, 0, 0.7)';
// window.safeAreaEle.style.padding = '2px 5px';
// window.safeAreaEle.style.textShadow = '1px 1px white';
// window.safeAreaEle.style.left = '0px';
// window.safeAreaEle.style.right = '0px';
// window.safeAreaEle.style.fontWeight = 'bold';
// window.safeAreaEle.style.pointerEvents = 'none';
// document.body.appendChild(window.safeAreaEle);
// }
// window.safeAreaEle.style.top = safeAreaTop + 'px';
// window.safeAreaEle.style.height = safeAreaHeight + 'px';
// window.safeAreaEle.innerHTML = `
// <div>scrollTo: ${scrollData.scrollTo}</div>
// <div>scrollAmount: ${scrollData.scrollAmount}</div>
// <div>scrollPadding: ${scrollData.scrollPadding}</div>
// <div>inputSafeY: ${scrollData.inputSafeY}</div>
// <div>scrollHeight: ${scrollViewDimensions.scrollHeight}</div>
// <div>scrollTop: ${scrollViewDimensions.scrollTop}</div>
// <div>contentHeight: ${scrollViewDimensions.contentHeight}</div>
// `;
return scrollData;
}
}
const SCROLL_ASSIST_SPEED = 0.3;
function getScrollAssistDuration(distanceToScroll: number) {
distanceToScroll = Math.abs(distanceToScroll);
let duration = distanceToScroll / SCROLL_ASSIST_SPEED;
return Math.min(400, Math.max(150, duration));
}