/
buffered-input.js
97 lines (86 loc) · 2.58 KB
/
buffered-input.js
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
import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
autofocus: false,
autoSelect: false,
focused: false,
spellcheck: true,
type: 'text',
value: null,
viewValue: null,
didInsertElement() {
if (this.get('focused')) {
Ember.run.schedule('afterRender', () => {
this.send('startEditing');
});
Ember.run.next(this, this.setInputFocus);
}
},
inputId: Ember.computed('elementId', function() {
return this.get('elementId') + '-input';
}),
displayedValue: Ember.computed('value', 'viewValue', 'focused', {
get() {
if (this.get('focused')) {
return this.get('viewValue');
} else {
return this.get('value');
}
},
set(key, value, cachedValue) {
if (this.get('focused')) {
this.set('viewValue', value);
return value;
} else {
return cachedValue;
}
}
}),
updateInputFocus: Ember.observer('focused', function() {
Ember.run.scheduleOnce('afterRender', this, this.setInputFocus);
}),
setInputFocus() {
const inputElement = Ember.$('#' + this.get('inputId')).get(0);
if (this.get('focused')) {
inputElement.focus();
if (this.get('autoSelect')) {
inputElement.select();
}
} else {
if (!this.get('isDestroying')) {
inputElement.blur();
}
}
},
actions: {
startEditing() {
this.setProperties({
focused: true,
viewValue: this.get('value')
});
},
cancelEditing() {
this.setProperties({
focused: false,
viewValue: null
});
},
endEditing(reason) {
const value = this.get('viewValue');
if (typeof this.attrs.validate === 'function' && !this.attrs.validate(value)) {
return Ember.run.next(this, this.setInputFocus);
}
this.setProperties({
focused: false,
value: value,
viewValue: null
});
if (reason === 'enter' && this.attrs.onEnterPress && this.attrs.onEnterPress.call) {
this.attrs.onEnterPress(value);
}
if (this.attrs.onChange && this.attrs.onChange.call) {
this.attrs.onChange(value);
}
}
}
});