forked from twitter/typeahead.js
/
dataset.js
330 lines (248 loc) · 8.61 KB
/
dataset.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
/*
* typeahead.js
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/
var Dataset = (function() {
'use strict';
var keys, nameGenerator;
keys = {
val: 'tt-selectable-display',
obj: 'tt-selectable-object'
};
nameGenerator = _.getIdGenerator();
// constructor
// -----------
function Dataset(o, www) {
o = o || {};
o.templates = o.templates || {};
// DEPRECATED: empty will be dropped in v1
o.templates.notFound = o.templates.notFound || o.templates.empty;
if (!o.source) {
$.error('missing source');
}
if (!o.node) {
$.error('missing node');
}
if (o.name && !isValidName(o.name)) {
$.error('invalid dataset name: ' + o.name);
}
www.mixin(this);
this.highlight = !!o.highlight;
this.name = o.name || nameGenerator();
this.limit = o.limit || 5;
this.displayFn = getDisplayFn(o.display || o.displayKey);
this.templates = getTemplates(o.templates, this.displayFn);
// use duck typing to see if source is a bloodhound instance by checking
// for the __ttAdapter property; otherwise assume it is a function
this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source;
// if the async option is undefined, inspect the source signature as
// a hint to figuring out of the source will return async suggestions
this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async;
this._resetLastSuggestion();
this.$el = $(o.node)
.addClass(this.classes.dataset)
.addClass(this.classes.dataset + '-' + this.name);
}
// static methods
// --------------
Dataset.extractData = function extractData(el) {
var $el = $(el);
if ($el.data(keys.obj)) {
return {
val: $el.data(keys.val) || '',
obj: $el.data(keys.obj) || null
};
}
return null;
};
// instance methods
// ----------------
_.mixin(Dataset.prototype, EventEmitter, {
// ### private
_overwrite: function overwrite(query, suggestions) {
suggestions = suggestions || [];
// got suggestions: overwrite dom with suggestions
if (suggestions.length) {
this._renderSuggestions(query, suggestions);
}
// no suggestions, expecting async: overwrite dom with pending
else if (this.async && this.templates.pending) {
this._renderPending(query);
}
// no suggestions, not expecting async: overwrite dom with not found
else if (!this.async && this.templates.notFound) {
this._renderNotFound(query);
}
// nothing to render: empty dom
else {
this._empty();
}
this.trigger('rendered', this.name, suggestions, false);
},
_append: function append(query, suggestions) {
suggestions = suggestions || [];
// got suggestions, sync suggestions exist: append suggestions to dom
if (suggestions.length && this.$lastSuggestion.length) {
this._appendSuggestions(query, suggestions);
}
// got suggestions, no sync suggestions: overwrite dom with suggestions
else if (suggestions.length) {
this._renderSuggestions(query, suggestions);
}
// no async/sync suggestions: overwrite dom with not found
else if (!this.$lastSuggestion.length && this.templates.notFound) {
this._renderNotFound(query);
}
this.trigger('rendered', this.name, suggestions, true);
},
_renderSuggestions: function renderSuggestions(query, suggestions) {
var $fragment;
$fragment = this._getSuggestionsFragment(query, suggestions);
this.$lastSuggestion = $fragment.children().last();
this.$el.html($fragment)
.prepend(this._getHeader(query, suggestions))
.append(this._getFooter(query, suggestions));
},
_appendSuggestions: function appendSuggestions(query, suggestions) {
var $fragment, $lastSuggestion;
$fragment = this._getSuggestionsFragment(query, suggestions);
$lastSuggestion = $fragment.children().last();
this.$lastSuggestion.after($fragment);
this.$lastSuggestion = $lastSuggestion;
},
_renderPending: function renderPending(query) {
var template = this.templates.pending;
this._resetLastSuggestion();
template && this.$el.html(template({
query: query,
dataset: this.name,
}));
},
_renderNotFound: function renderNotFound(query) {
var template = this.templates.notFound;
this._resetLastSuggestion();
template && this.$el.html(template({
query: query,
dataset: this.name,
}));
},
_empty: function empty() {
this.$el.empty();
this._resetLastSuggestion();
},
_getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) {
var that = this, fragment;
fragment = document.createDocumentFragment();
_.each(suggestions, function getSuggestionNode(suggestion) {
var $el, context;
context = that._injectQuery(query, suggestion);
$el = $(that.templates.suggestion(context))
.data(keys.obj, suggestion)
.data(keys.val, that.displayFn(suggestion))
.addClass(that.classes.suggestion + ' ' + that.classes.selectable);
fragment.appendChild($el[0]);
});
this.highlight && highlight({
className: this.classes.highlight,
node: fragment,
pattern: query
});
return $(fragment);
},
_getFooter: function getFooter(query, suggestions) {
return this.templates.footer ?
this.templates.footer({
query: query,
suggestions: suggestions,
dataset: this.name
}) : null;
},
_getHeader: function getHeader(query, suggestions) {
return this.templates.header ?
this.templates.header({
query: query,
suggestions: suggestions,
dataset: this.name
}) : null;
},
_resetLastSuggestion: function resetLastSuggestion() {
this.$lastSuggestion = $();
},
_injectQuery: function injectQuery(query, obj) {
return _.isObject(obj) ? _.mixin({ _query: query }, obj) : obj;
},
// ### public
update: function update(query) {
var that = this, canceled = false, syncCalled = false, rendered = 0;
// cancel possible pending update
this.cancel();
this.cancel = function cancel() {
canceled = true;
that.cancel = $.noop;
that.async && that.trigger('asyncCanceled', query);
};
this.source(query, sync, async);
!syncCalled && sync([]);
function sync(suggestions) {
if (syncCalled) { return; }
syncCalled = true;
suggestions = (suggestions || []).slice(0, that.limit);
rendered = suggestions.length;
that._overwrite(query, suggestions);
if (rendered < that.limit && that.async) {
that.trigger('asyncRequested', query);
}
}
function async(suggestions) {
suggestions = suggestions || [];
// if the update has been canceled or if the query has changed
// do not render the suggestions as they've become outdated
if (!canceled && rendered < that.limit) {
that.cancel = $.noop;
that._append(query, suggestions.slice(0, that.limit - rendered));
rendered += suggestions.length;
that.async && that.trigger('asyncReceived', query);
}
}
},
// cancel function gets set in #update
cancel: $.noop,
clear: function clear() {
this._empty();
this.cancel();
this.trigger('cleared');
},
isEmpty: function isEmpty() {
return this.$el.is(':empty');
},
destroy: function destroy() {
// #970
this.$el = $('<div>');
}
});
return Dataset;
// helper functions
// ----------------
function getDisplayFn(display) {
display = display || _.stringify;
return _.isFunction(display) ? display : displayFn;
function displayFn(obj) { return obj[display]; }
}
function getTemplates(templates, displayFn) {
return {
notFound: templates.notFound && _.templatify(templates.notFound),
pending: templates.pending && _.templatify(templates.pending),
header: templates.header && _.templatify(templates.header),
footer: templates.footer && _.templatify(templates.footer),
suggestion: templates.suggestion || suggestionTemplate
};
function suggestionTemplate(context) {
return $('<div>').text(displayFn(context));
}
}
function isValidName(str) {
// dashes, underscores, letters, and numbers
return (/^[_a-zA-Z0-9-]+$/).test(str);
}
})();