forked from mtkopone/zelect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zelect.js
336 lines (301 loc) · 10.8 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
/*
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
*/
(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
}
$.fn.zelect = function(opts) {
opts = $.extend({}, defaults, opts)
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)
var $zelect = $('<div>').addClass('zelect')
var $selected = $('<div>').addClass('zelected')
var $dropdown = $('<div>').addClass('dropdown').hide()
var $noResults = $('<div>').addClass('no-results')
var $search = $('<input>').addClass('zearch')
var $list = $('<ol>')
var listNavigator = navigable($list)
var itemHandler = opts.loader
? infiniteScroll($list, opts.loader, appendItem)
: selectBased($select, $list, opts.regexpMatcher, appendItem)
var filter = throttled(opts.throttle, function() {
var term = searchTerm()
itemHandler.load(term, function() { checkResults(term) })
})
$search.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.keydown(function(e) {
switch (e.which) {
case keys.tab: e.preventDefault(); hide(); return;
case keys.up: e.preventDefault(); listNavigator.prev(); return;
case keys.down: e.preventDefault(); listNavigator.next(); return;
}
})
$list.on('click', 'li', function() { selectItem($(this).data('zelect-item')) })
$zelect.mouseenter(function() { $zelect.addClass('hover') })
$zelect.mouseleave(function() { $zelect.removeClass('hover') })
$zelect.attr("tabindex", $select.attr("tabindex"))
$zelect.blur(function() { if (!$zelect.hasClass('hover')) hide() })
$search.blur(function() { if (!$zelect.hasClass('hover')) hide() })
$selected.click(toggle)
$zelect.insertAfter($select)
.append($selected)
.append($dropdown.append($('<div>').addClass('zearch-container').append($search).append($noResults)).append($list))
itemHandler.load($search.val(), 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('li').each(function() {
if (eq($(this).data('zelect-item'), item)) {
renderContent($(this), opts.renderItem(item, term)).data('zelect-item', item)
}
})
}
function reset() {
$search.val('')
itemHandler.load('', function() {
initialSelection(false)
})
}
function toggle() {
$dropdown.toggle()
$zelect.toggleClass('open')
if ($dropdown.is(':visible')) {
$search.focus().select()
itemHandler.check()
listNavigator.ensure()
}
}
function hide() {
$dropdown.hide()
$zelect.removeClass('open')
}
function renderContent($obj, content) {
$obj[htmlOrText(content)](content)
return $obj
function htmlOrText(x) { return (x instanceof jQuery || x.nodeType != null) ? 'html' : 'text' }
}
function appendItem(item, term) {
$list.append(renderContent($('<li>').data('zelect-item', item), opts.renderItem(item, term)))
}
function checkResults(term) {
if ($list.children().size() === 0) {
$noResults.html(opts.noResults(term)).show()
} else {
$noResults.hide()
listNavigator.ensure()
}
}
function searchTerm() { return $.trim($search.val()) }
function initialSelection(useOptsInitial) {
var $s = $select.find('option[selected="selected"]')
if (useOptsInitial && opts.initial) {
selectItem(opts.initial)
} else if (!opts.loader && $s.size() > 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(':first').data('zelect-item')
first !== undefined ? 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.attr('value'), label: $option.text() }
}
function newTerm(term, callback) {
filter(term)
if (callback) callback()
}
return { load:newTerm, check:function() {} }
}
function infiniteScroll($list, loadFn, appendItemFn) {
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.children(':last')
if ($lastChild.size() === 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')
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) {
var skipMouseEvent = false
$list.on('mouseenter', 'li', onMouseEnter)
function next() {
var $next = current().next('li')
if (set($next)) ensureBottomVisible($next)
}
function prev() {
var $prev = current().prev('li')
if (set($prev)) ensureTopVisible($prev)
}
function current() {
return $list.find('.current')
}
function ensure() {
if (current().size() === 0) {
$list.find('li:first').addClass('current')
}
}
function set($item) {
if ($item.size() === 0) return false
current().removeClass('current')
$item.addClass('current')
return true
}
function onMouseEnter() {
if (skipMouseEvent) {
skipMouseEvent = false
return
}
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 }
}
})(jQuery)