forked from AmpersandJS/ampersand-select-view
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathampersand-select-view.js
296 lines (236 loc) · 8.52 KB
/
ampersand-select-view.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
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
/* $AMPERSAND_VERSION */
var domify = require('domify');
var dom = require('ampersand-dom');
var matches = require('matches-selector');
var Events = require('ampersand-events');
var extend = require('amp-extend');
//Replaceable with anything with label, message-container, message-text data-hooks and a <select>
var defaultTemplate = [
'<label class="select">',
'<span data-hook="label"></span>',
'<select></select>',
'<span data-hook="message-container" class="message message-below message-error">',
'<p data-hook="message-text"></p>',
'</span>',
'</label>'
].join('\n');
/* opts:
* - name: name of the field
* - parent: parent form reference
* - options: array/collection of options to render into the select box
* - [unselectedText]: text to display if unselected
* - [value]: initial value for the field
* - [el]: dom node to use for the view
* - [required]: is field required
*
* - [validClass]: class to apply to root element if valid
* - [invalidClass]: class to apply to root element if invalid
* - [requiredMessage]: message to display if invalid and required
*
* Additional opts, if options is a collection:
* - [idAttribute]: model attribute to use as the id for the option node
* - [textAttribute]: model attribute to use as the text of the option node in the select box
* - [yieldModel]: (defaults true) if options is a collection, yields the full model rather than just it's id to .value
*/
function SelectView (opts) {
opts = opts || {};
if (typeof opts.name !== 'string') throw new Error('SelectView requires a name property.');
this.name = opts.name;
if (!Array.isArray(opts.options) && !opts.options.isCollection) {
throw new Error('SelectView requires select options.');
}
this.options = opts.options;
if (this.options.isCollection) {
this.idAttribute = opts.idAttribute || this.options.mainIndex || 'id';
this.textAttribute = opts.textAttribute || 'text';
}
this.el = opts.el;
this.value = null;
this.label = opts.label || this.name;
this.parent = opts.parent;
this.template = opts.template || defaultTemplate;
this.unselectedText = opts.unselectedText;
this.yieldModel = (opts.yieldModel === false) ? false : true;
this.required = opts.required || false;
this.validClass = opts.validClass || 'input-valid';
this.invalidClass = opts.invalidClass || 'input-invalid';
this.requiredMessage = opts.requiredMessage || 'Selection required';
this.onChange = this.onChange.bind(this);
this.render();
this.setValue(opts.value);
}
extend(SelectView.prototype, Events);
SelectView.prototype.render = function () {
if (this.rendered) return;
if (!this.el) this.el = domify(this.template);
var label = this.el.querySelector('[data-hook~=label]');
if (label) {
label.textContent = this.label;
}
this.select = this.el.querySelector('select');
if (matches(this.el, 'select')) this.select = this.el;
if (this.select) this.select.setAttribute('name', this.name);
this.bindDOMEvents();
this.renderOptions();
this.updateSelectedOption();
if (this.options.isCollection) {
this.options.on('add remove reset', function () {
this.renderOptions();
this.updateSelectedOption();
}.bind(this));
}
this.rendered = true;
};
SelectView.prototype.onChange = function () {
var value = this.select.options[this.select.selectedIndex].value;
if (this.options.isCollection && this.yieldModel) {
value = this.findModelForId(value);
}
this.setValue(value);
};
SelectView.prototype.findModelForId = function (id) {
return this.options.filter(function (model) {
if (!model[this.idAttribute]) return false;
//intentionally coerce for '1' == 1
return model[this.idAttribute] == id;
}.bind(this))[0];
};
SelectView.prototype.bindDOMEvents = function () {
this.el.addEventListener('change', this.onChange, false);
};
SelectView.prototype.renderOptions = function () {
if (!this.select) return;
this.select.innerHTML = '';
if (this.unselectedText) {
this.select.appendChild(
this.createOption(null, this.unselectedText)
);
}
this.options.forEach(function (option) {
var option;
if (Array.isArray(option))
{
option = this.createOption(option[0], option[1]);
}
else
{
if (this.options.isCollection) {
if (this.idAttribute && option[this.idAttribute]) {
value = option[this.idAttribute];
}
if (this.textAttribute && option[this.textAttribute]) {
text = option[this.textAttribute];
}
}
option = this.createOption(value, text, option);
}
this.select.appendChild(option);
}.bind(this));
};
SelectView.prototype.updateSelectedOption = function () {
var lookupValue = this.value;
if (!this.select) return;
if (!lookupValue) {
this.select.selectedIndex = 0;
return;
}
//Pull out the id if it's a model
if (this.options.isCollection && this.yieldModel) {
lookupValue = lookupValue && lookupValue[this.idAttribute];
}
if (lookupValue) {
for (var i = this.select.options.length; i--; i) {
if (this.select.options[i].value === lookupValue.toString()) {
this.select.selectedIndex = i;
return;
}
}
}
//If failed to match any
this.select.selectedIndex = 0;
};
SelectView.prototype.remove = function () {
if (this.el) this.el.parentNode.removeChild(this.el);
this.el.removeEventListener('change', this.onChange, false);
};
SelectView.prototype.setValue = function (value) {
if (value === this.value) return;
//Coerce and find the right value based on yieldModel
if (this.options.isCollection) {
var model;
if (this.options.indexOf(value) === -1) {
model = this.findModelForId(value);
} else {
model = value;
}
if (this.yieldModel) {
value = model;
} else {
if (model) {
value = model[this.idAttribute];
} else {
value = void 0;
}
}
}
this.value = value;
this.validate();
this.updateSelectedOption();
if (this.parent) this.parent.update(this);
};
SelectView.prototype.validate = function () {
this.valid = this.options.some(function (element) {
//If it's a collection, ensure it's in the collection
if (this.options.isCollection) {
if (this.yieldModel) {
return this.options.indexOf(this.value) > -1;
} else {
return !!this.findModelForId(this.value);
}
}
//[ ['foo', 'Foo Text'], ['bar', 'Bar Text'] ]
if (Array.isArray(element) && element.length === 2) {
return element[0] === this.value;
}
//[ 'foo', 'bar', 'baz' ]
return element === this.value;
}.bind(this));
if (!this.valid && this.required) {
this.setMessage(this.requiredMessage);
} else {
this.setMessage();
}
return this.valid;
};
SelectView.prototype.setMessage = function (message) {
var mContainer = this.el.querySelector('[data-hook~=message-container]');
var mText = this.el.querySelector('[data-hook~=message-text]');
if (!mContainer || !mText) return;
if (message) {
dom.show(mContainer);
mText.textContent = message;
dom.addClass(this.el, this.invalidClass);
dom.removeClass(this.el, this.validClass);
} else {
dom.hide(mContainer);
mText.textContent = '';
dom.addClass(this.el, this.validClass);
dom.removeClass(this.el, this.invalidClass);
}
};
SelectView.prototype.createOption = function (value, text, model) {
var node = document.createElement('option');
//Set to empty-string if undefined or null, but not if 0, false, etc
if (value === null || value === undefined) { value = ''; }
node.innerHTML = text;
node.value = value;
if(model)
{
this.listenTo(model, 'change:' + this.textAttribute, _.bind(_.partial(
function(model, element) {
node.innerHTML = model[this.textAttribute];
}, model, node), this));
}
return node;
}
module.exports = SelectView;