forked from niom/zelect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
zelect.js
435 lines (394 loc) · 14.7 KB
/
zelect.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
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
/*
zelect-0.0.9
opts:
throttle: ms: delay to throttle filtering of results when search term updated, 0 means synchronous
loader: function(term, page, callback): load more items
callback expects an array of items
renderItem: function(item, term): render the content of a single item
initial: "item": arbitrary item to set the initial selection to
placeholder is not required if initial item is provided
placeholder: String/DOM/jQuery: placeholder text/html before anything is selected
zelect automatically selects first item if not provided
noResults: function(term?): function to create no results text
regexpMatcher: function(term): override regexp creation when filtering options
selectOnMouseEnter: set selection when hovering on an item
*/
(function (factory) {
if(typeof define === "function" && define.amd) {
define(["jquery"], factory);
} else if(typeof module === "object" && module.exports) {
module.exports = factory(require("jquery"));
} else {
factory(jQuery);
}
}(function($) {
var keys = { tab:9, enter:13, esc:27, left:37, up:38, right:39, down:40 }
var defaults = {
throttle: 300,
renderItem: defaultRenderItem,
noResults: defaultNoResults,
regexpMatcher: defaultRegexpMatcher,
selectOnMouseEnter: true,
renderSearch: function () { return $('<input>').addClass('zearch') },
renderResultContainer: function () { return $('<ol>')},
queryExtractor: function ($search) {return function () { return $search.val() }},
itemPrefix: 'li.zelect-item',
loadOptionsOnlyWhenNeeded: false
}
$.fn.zelect = function(opts) {
opts = $.extend({}, defaults, opts)
opts.noPlaceholder = opts.noPlaceholder ? true : (opts.placeholder === null || opts.placeholder === undefined)
return this.each(function() {
if ($(this).parent().length === 0) throw new Error('<select> element must have a parent')
var $select = $(this).hide().data('zelectItem', selectItem).data('refreshItem', refreshItem).data('reset', reset).data('refreshZelect', refreshZelect)
var $zelect = $('<div>').addClass('zelect')
var $selected = $('<div>').addClass('zelected')
var $dropdownContainer = $('<div>').addClass('dropdown-container')
var $dropdown = $('<div>').addClass('dropdown').hide()
var $noResults = $('<div>').addClass('no-results')
var $search = opts.renderSearch()
var $list = opts.renderResultContainer()
var itemPrefix = opts.itemPrefix
var queryExtractor = opts.queryExtractor($search)
var listNavigator = navigable($list, opts.selectOnMouseEnter, $select, itemPrefix)
var itemHandler = opts.loader
? infiniteScroll($list, opts.loader, appendItem, itemPrefix)
: selectBased($select, $list, opts.regexpMatcher, appendItem)
var filter = throttled(opts.throttle, function() {
var term = searchTerm()
itemHandler.load(term, function() { checkResults(term) })
})
$search.on('keyup', function(e) {
switch (e.which) {
case keys.esc: hide(); return;
case keys.up: return;
case keys.down: return;
case keys.enter:
var curr = listNavigator.current().data('zelect-item')
if (curr) selectItem(curr)
return
default: filter()
}
})
$search.on('zelect-filter', filter)
$search.on('keydown', function(e) {
switch (e.which) {
case keys.up: e.preventDefault(); listNavigator.prev(); return;
case keys.down: e.preventDefault(); listNavigator.next(); return;
}
})
$list.on('click', itemPrefix + ':not(.disabled)', function() { selectItem($(this).data('zelect-item')) })
$zelect.on('mouseenter', function() { $zelect.addClass('hover') })
$zelect.on('mouseleave', function() { $zelect.removeClass('hover') })
$zelect.attr("tabindex", $select.attr("tabindex"))
$zelect.on('blur', function() { if (!$zelect.hasClass('hover')) hide() })
$search.on('blur', function() { if (!$zelect.hasClass('hover')) hide() })
$selected.on('click', toggle)
$('body').on('click.closeZelect', bodyClickHandler)
function bodyClickHandler(evt) {
if ($zelect.closest('body').length === 0) {
$('body').off('click.closeZelect', bodyClickHandler)
}
var clickWasOutsideZelect = $(evt.target).closest($zelect).length === 0
if (clickWasOutsideZelect) hide()
}
$zelect.insertAfter($select)
.append($selected)
.append(
$dropdownContainer.append(
$dropdown.append($('<div>').addClass('zearch-container').append($search).append($noResults)).append($list)
)
)
if (opts.loadOptionsOnlyWhenNeeded) {
initialSelection(true)
$noResults.hide()
$select.trigger('ready')
} else {
loadInitialOptions()
}
function loadInitialOptions() {
itemHandler.load(queryExtractor(), function() {
initialSelection(true)
$select.trigger('ready')
})
}
function selectItem(item, triggerChange) {
renderContent($selected, opts.renderItem(item)).removeClass('placeholder')
hide()
if (item && item.value !== undefined) $select.val(item.value)
$select.data('zelected', item)
if (triggerChange == null || triggerChange === true) $select.trigger('change', item)
}
function refreshItem(item, identityCheckFn) {
var eq = function(a, b) { return identityCheckFn(a) === identityCheckFn(b) }
if (eq($select.data('zelected'), item)) {
renderContent($selected, opts.renderItem(item))
$select.data('zelected', item)
}
var term = searchTerm()
$list.find(itemPrefix).each(function() {
if (eq($(this).data('zelect-item'), item)) {
renderContent($(this), opts.renderItem(item, term)).data('zelect-item', item)
}
})
}
function reset() {
$search.data().reset ? $search.data().reset() : $search.val('')
$select.prop('selectedIndex',0);
itemHandler.load(queryExtractor($search), function() {
initialSelection(false)
})
}
function refreshZelect(callback) {
itemHandler.load(queryExtractor($search), function() {
callback && callback()
})
}
function toggle() {
if ($zelect.hasClass('open') || $zelect.hasClass('opening')) {
hide()
} else {
open()
}
}
function open() {
$zelect.toggleClass('opening', true)
$dropdown.toggle(true)
$search.data().focus ? $search.data().focus() : $search.focus().select()
itemHandler.check()
listNavigator.ensure()
$zelect.removeClass('closed')
$zelect.removeClass('opening')
$zelect.toggleClass('open', true)
}
function hide() {
$zelect.toggleClass('closing', true)
$dropdown.hide()
$zelect.removeClass('open')
$zelect.removeClass('closing')
$zelect.toggleClass('closed', true)
}
function renderContent($obj, content) {
if(textContent(content)) {
$obj.text(content)
} else {
$obj.empty()
$obj.append(content)
}
return $obj
function textContent(x) {
var b = (!(x instanceof $));
var b2 = x.nodeType == null;
var b3 = !$.isArray(content);
return b && b2 && b3 }
}
function appendItem(item, term) {
var tagName = itemPrefix,
classes
var dotIndex = itemPrefix.indexOf('.')
if (dotIndex !== -1) {
if (itemPrefix[0] === '.') {
tagName = 'li'
classes = itemPrefix.substring(1).replace(/\./g, ' ')
} else {
tagName = itemPrefix.substring(0, dotIndex)
classes = itemPrefix.substring(dotIndex + 1).replace(/\./g, ' ')
}
}
$list.append(renderContent($('<' + tagName + '>').data('zelect-item', item).toggleClass('disabled', !!item.disabled).addClass(classes), opts.renderItem(item, term)))
}
function checkResults(term) {
if ($list.children().length === 0) {
$noResults.html(opts.noResults(term)).show()
} else {
$noResults.hide()
listNavigator.ensure()
}
}
function searchTerm() { return queryExtractor() }
function initialSelection(useOptsInitial) {
var $s = $select.find(opts.noPlaceholder ? 'option:selected' : 'option[selected]')
if (useOptsInitial && opts.initial) {
selectItem(opts.initial)
} else if (!opts.loader && $s.length > 0) {
selectItem($list.children().eq($s.index()).data('zelect-item'))
} else if (opts.placeholder) {
$selected.html(opts.placeholder).addClass('placeholder')
} else {
var first = $list.find(itemPrefix + ':first').data('zelect-item')
first !== undefined && first !== null ? selectItem(first) : $selected.html(opts.noResults()).addClass('placeholder')
}
checkResults()
}
})
}
function selectBased($select, $list, regexpMatcher, appendItemFn) {
var dummyRegexp = { test: function() { return true } }
var options = $select.find('option').map(function() { return itemFromOption($(this)) }).get()
function filter(term) {
var regexp = (term === '') ? dummyRegexp : regexpMatcher(term)
$list.empty()
$.each(options, function(ii, item) {
if (regexp.test(item.label)) appendItemFn(item, term)
})
}
function itemFromOption($option) {
return { value: $option.val(), label: $option.text(), disabled: $option.prop('disabled') }
}
function newTerm(term, callback) {
filter(term)
if (callback) callback()
}
return { load:newTerm, check:function() {} }
}
function infiniteScroll($list, loadFn, appendItemFn, itemPrefix) {
var state = { id:0, term:'', page:0, loading:false, exhausted:false, callback:undefined }
$list.scroll(maybeLoadMore)
function load() {
if (state.loading || state.exhausted) return
state.loading = true
$list.addClass('loading')
var stateId = state.id
loadFn(state.term, state.page, function(items) {
if (stateId !== state.id) return
if (state.page == 0) $list.empty()
state.page++
if (!items || items.length === 0) state.exhausted = true
$.each(items, function(ii, item) { appendItemFn(item, state.term) })
state.loading = false
if (!maybeLoadMore()) {
if (state.callback) state.callback()
state.callback = undefined
$list.removeClass('loading')
}
})
}
function maybeLoadMore() {
if (state.exhausted) return false
var $lastChild = $list.find(itemPrefix + ':last')
if ($lastChild.length === 0) {
load()
return true
} else {
var lastChildTop = $lastChild.offset().top - $list.offset().top
var lastChildVisible = lastChildTop < $list.outerHeight()
if (lastChildVisible) load()
return lastChildVisible
}
}
function newTerm(term, callback) {
state = { id:state.id+1, term:term, page:0, loading:false, exhausted:false, callback:callback }
load()
}
return { load:newTerm, check:maybeLoadMore }
}
$.fn.zelectItem = callInstance('zelectItem')
$.fn.refreshZelectItem = callInstance('refreshItem')
$.fn.resetZelect = callInstance('reset')
$.fn.refreshZelect = callInstance('refreshZelect')
function callInstance(fnName) {
return function() {
var args = [].slice.call(arguments)
return this.each(function() {
var fn = $(this).data(fnName)
fn && fn.apply(undefined, args)
})
}
}
function throttled(ms, callback) {
if (ms <= 0) return callback
var timeout = undefined
return function() {
if (timeout) clearTimeout(timeout)
timeout = setTimeout(callback, ms)
}
}
function defaultRenderItem(item, term) {
if (item == undefined || item == null) {
return ''
} else if ($.type(item) === 'string') {
return item
} else if (item.label) {
return item.label
} else if (item.toString) {
return item.toString()
} else {
return item
}
}
function defaultNoResults(term) {
return "No results for '"+(term || '')+"'"
}
function defaultRegexpMatcher(term) {
return new RegExp('(^|\\s)'+term, 'i')
}
function navigable($list, selectOnMouseEnter, $select, itemPrefix) {
var skipMouseEvent = false
if(selectOnMouseEnter) {
$list.on('mouseenter', itemPrefix + ':not(.disabled)', onMouseEnter)
} else {
$list.on('click', itemPrefix + ':not(.disabled)', onMouseClick)
}
function next() {
var $next = current().next(itemPrefix + ':not(.disabled)')
if (set($next)) ensureBottomVisible($next)
}
function prev() {
var $prev = current().prev(itemPrefix + ':not(.disabled)')
if (set($prev)) ensureTopVisible($prev)
}
function current() {
return $list.find('.current')
}
function ensure() {
if (current().length === 0) {
var selected = $select.data('zelected')
if (selected) {
$list.find(itemPrefix + ':not(.disabled)').filter(function() {
return $(this).data('zelectItem').value === selected.value && selected.value !== undefined
}).addClass('current')
} else {
$list.find(itemPrefix + ':not(.disabled)').eq(0).addClass('current')
}
}
}
function set($item) {
if ($item.length === 0) return false
current().removeClass('current')
$item.addClass('current')
return true
}
function onMouseEnter() {
if (skipMouseEvent) {
skipMouseEvent = false
return
}
set($(this))
}
function onMouseClick() {
set($(this))
}
function itemTop($item) {
return $item.offset().top - $list.offset().top
}
function ensureTopVisible($item) {
var scrollTop = $list.scrollTop()
var offset = itemTop($item) + scrollTop
if (scrollTop > offset) {
moveScroll(offset)
}
}
function ensureBottomVisible($item) {
var scrollBottom = $list.height()
var itemBottom = itemTop($item) + $item.outerHeight()
if (scrollBottom < itemBottom) {
moveScroll($list.scrollTop() + itemBottom - scrollBottom)
}
}
function moveScroll(offset) {
$list.scrollTop(offset)
skipMouseEvent = true
}
return { next:next, prev:prev, current:current, ensure:ensure }
}
}))