/
msac.jquery.js
266 lines (221 loc) · 8.45 KB
/
msac.jquery.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
(function($) {
"use strict";
$.fn.msac = function(opts) {
// Let each closure has its own options
var msac = new Msac(opts);
return this.each(msac);
};
$.fn.msac.version = '1.0.1';
function Msac(opts) {
opts = $.extend({
maxItems: 20,
flashDelay: 2000,
maxItemsMessage: 'There are more than %d suggestions.'
}, opts);
return msac;
function msac() {
/*jshint validthis: true */
// Or jshint complains about "this" being used in a function.
// @see https://github.com/jshint/jshint/issues/621
var $s = $(this),
options = [],
currIdx = 0,
suggNb,
keyBindings,
$input,
$suggestions,
$sugg,
$selection,
$delBtn,
$flashMessage;
// Hide the original select
$s.hide();
// Get all the options
$('option', $s).each(function() {
options.push(this.text);
});
// Place all the elements for the auto completion
placeElements();
// Listen for every key press
$input.on('keyup', function() {
var idxs;
// Remove the children on each iteration
$suggestions.children().remove();
idxs = findInOptions(this.value);
if (idxs) {
addSuggestions(idxs);
}
});
/**
* Creates the suggestions and adds them to the list
*/
function addSuggestions(idxs) {
var message;
suggNb = idxs.length;
if (suggNb > opts.maxItems) {
message = opts.maxItemsMessage.replace('%d', opts.maxItems);
flash(message);
return;
}
$.each(idxs, function(i) {
// Add each suggestion
var $newSugg = $sugg.clone();
if (i === currIdx) {
$newSugg.addClass('suggested');
}
// The data will be used when selecting the element
$newSugg.data('idx', this);
$newSugg.text(options[this]).appendTo($suggestions);
});
}
/**
* Flash message
*/
function flash(message) {
$flashMessage.text(message);
$flashMessage.show();
// It's a flash message: hide after some delay
setTimeout(function() {
$flashMessage.fadeOut();
}, opts.flashDelay);
}
// Key bindings: each keyCode has its own function. Allows us to keep
// the onkeydown callback clean.
keyBindings = {
13: function() {
// Pressing enter: add the selection
addToSelection($('.suggested', $suggestions));
currIdx = 0;
return false;
},
38: function() {
// Up arrow
if (currIdx > 0) {
currIdx--;
}
return false;
},
40: function() {
// Down arrow
if (currIdx < (suggNb - 1)) {
currIdx++;
}
return false;
}
};
// We need keydown for up/down arrows to prevent default behavior
$input.on('keydown', function(e) {
return keyBindings[e.keyCode] ? keyBindings[e.keyCode]() : true;
});
$suggestions.on('mouseover', 'div', function() {
$('.suggested').removeClass('suggested');
$(this).addClass('suggested');
});
$suggestions.on('click', 'div', function() {
addToSelection($(this));
});
// The delete button needs to have its handler
$('.msac-wrapper').on('click', '.delete', deleteBtn);
/**
* Delete from selection, put back into js array, and deselect
* from original select
*/
function deleteBtn() {
var $selection = $(this.parentNode),
idx = $selection.data('idx'),
text;
// Remove the delete button before copying the text
$(this).remove();
text = $selection.text();
// And do what's in the function's doc
$selection.remove();
options[idx] = text;
$s[0].options[idx].selected = false;
}
/**
* Places the elements necessary for the auto completion
* to work.
*/
function placeElements() {
var $wrapper = $('<div></div>', { 'class': 'msac-wrapper' });
// Create elements for the variables in closure
$input = $('<input />', { type: 'text' });
$suggestions = $('<div></div>', { 'class': 'suggestions' });
$sugg = $suggestions.clone();
$selection = $sugg.clone();
// Input for the text search
$input.appendTo($wrapper);
// Div for the suggestions
$suggestions.appendTo($wrapper);
// and one for cloning
$sugg[0].className = 'suggestion';
// Div for selection
$selection[0].className = 'selection';
$selection.appendTo($wrapper);
// And insert the wrapper after the hidden select
$wrapper.insertAfter($s);
// Creates some elements but don't use them yet
$delBtn = $('<span></span>', {
'class': 'delete',
'html': '×'
});
$flashMessage = $('<div></div>', { 'class': 'flash' });
$flashMessage.hide().insertAfter($input);
}
/**
* Empties the input, adds the element to selected,
* remove the item from the array of options, and
* empty the list of suggestions.
*
* This function does way too much. But I'm too lazy to refactor it.
*/
function addToSelection($el) {
var idx = $el.data('idx'),
$delClone;
// Clear up the input
$input[0].value = '';
// Reset the index of current selected index
currIdx = 0;
// Remove the option from the js array
// And yes, we definitely want a sparse array.
delete options[idx];
// Set the correct class
$el[0].className = 'selected';
// Adds the delete button
$delClone = $delBtn.clone();
$el.append($delClone);
// Append the element to the selection
$selection.append($el);
// Set the selected property on the hidden select
$s[0].options[idx].selected = true;
// And remove the suggestions
$suggestions.children().remove();
}
/**
* Find the indexes where the text matches.
*/
function findInOptions(text) {
var idxs = [],
t = text.toLowerCase();
if (t) {
$.each(options, function(i) {
// Sparse array, let's be careful
if (!this) {
return;
}
var opt = this.toLowerCase(),
idx = opt.indexOf(t);
if (~idx) {
idxs.push(i);
}
});
}
else {
currIdx = 0;
}
// "if ([])" passes... we don't want that
return idxs.length ? idxs : null;
}
}
}
}(jQuery));