-
Notifications
You must be signed in to change notification settings - Fork 331
/
Copy pathdataset.js
298 lines (239 loc) · 8.55 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
'use strict';
var datasetKey = 'aaDataset';
var valueKey = 'aaValue';
var datumKey = 'aaDatum';
var _ = require('../common/utils.js');
var DOM = require('../common/dom.js');
var html = require('./html.js');
var css = require('./css.js');
var EventEmitter = require('./event_emitter.js');
// constructor
// -----------
function Dataset(o) {
o = o || {};
o.templates = o.templates || {};
if (!o.source) {
_.error('missing source');
}
if (o.name && !isValidName(o.name)) {
_.error('invalid dataset name: ' + o.name);
}
// tracks the last query the dataset was updated for
this.query = null;
this._isEmpty = true;
this.highlight = !!o.highlight;
this.name = typeof o.name === 'undefined' || o.name === null ? _.getUniqueId() : o.name;
this.source = o.source;
this.displayFn = getDisplayFn(o.display || o.displayKey);
this.debounce = o.debounce;
this.templates = getTemplates(o.templates, this.displayFn);
this.css = _.mixin({}, css, o.appendTo ? css.appendTo : {});
this.cssClasses = o.cssClasses = _.mixin({}, css.defaultClasses, o.cssClasses || {});
this.cssClasses.prefix =
o.cssClasses.formattedPrefix || _.formatPrefix(this.cssClasses.prefix, this.cssClasses.noPrefix);
var clazz = _.className(this.cssClasses.prefix, this.cssClasses.dataset);
this.$el = o.$menu && o.$menu.find(clazz + '-' + this.name).length > 0 ?
DOM.element(o.$menu.find(clazz + '-' + this.name)[0]) :
DOM.element(
html.dataset.replace('%CLASS%', this.name)
.replace('%PREFIX%', this.cssClasses.prefix)
.replace('%DATASET%', this.cssClasses.dataset)
);
this.$menu = o.$menu;
this.clearCachedSuggestions();
}
// static methods
// --------------
Dataset.extractDatasetName = function extractDatasetName(el) {
return DOM.element(el).data(datasetKey);
};
Dataset.extractValue = function extractValue(el) {
return DOM.element(el).data(valueKey);
};
Dataset.extractDatum = function extractDatum(el) {
var datum = DOM.element(el).data(datumKey);
if (typeof datum === 'string') {
// Zepto has an automatic deserialization of the
// JSON encoded data attribute
datum = JSON.parse(datum);
}
return datum;
};
// instance methods
// ----------------
_.mixin(Dataset.prototype, EventEmitter, {
// ### private
_render: function render(query, suggestions) {
if (!this.$el) {
return;
}
var that = this;
var hasSuggestions;
var renderArgs = [].slice.call(arguments, 2);
this.$el.empty();
hasSuggestions = suggestions && suggestions.length;
this._isEmpty = !hasSuggestions;
if (!hasSuggestions && this.templates.empty) {
this.$el
.html(getEmptyHtml.apply(this, renderArgs))
.prepend(that.templates.header ? getHeaderHtml.apply(this, renderArgs) : null)
.append(that.templates.footer ? getFooterHtml.apply(this, renderArgs) : null);
} else if (hasSuggestions) {
this.$el
.html(getSuggestionsHtml.apply(this, renderArgs))
.prepend(that.templates.header ? getHeaderHtml.apply(this, renderArgs) : null)
.append(that.templates.footer ? getFooterHtml.apply(this, renderArgs) : null);
}
if (this.$menu) {
this.$menu.addClass(
this.cssClasses.prefix + (hasSuggestions ? 'with' : 'without') + '-' + this.name
).removeClass(
this.cssClasses.prefix + (hasSuggestions ? 'without' : 'with') + '-' + this.name
);
}
this.trigger('rendered', query);
function getEmptyHtml() {
var args = [].slice.call(arguments, 0);
args = [{query: query, isEmpty: true}].concat(args);
return that.templates.empty.apply(this, args);
}
function getSuggestionsHtml() {
var args = [].slice.call(arguments, 0);
var $suggestions;
var nodes;
var self = this;
var suggestionsHtml = html.suggestions.
replace('%PREFIX%', this.cssClasses.prefix).
replace('%SUGGESTIONS%', this.cssClasses.suggestions);
$suggestions = DOM
.element(suggestionsHtml)
.css(this.css.suggestions);
// jQuery#append doesn't support arrays as the first argument
// until version 1.8, see http://bugs.jquery.com/ticket/11231
nodes = _.map(suggestions, getSuggestionNode);
$suggestions.append.apply($suggestions, nodes);
return $suggestions;
function getSuggestionNode(suggestion) {
var $el;
var suggestionHtml = html.suggestion.
replace('%PREFIX%', self.cssClasses.prefix).
replace('%SUGGESTION%', self.cssClasses.suggestion);
$el = DOM.element(suggestionHtml)
.attr({
role: 'option',
id: ['option', Math.floor(Math.random() * 100000000)].join('-')
})
.append(that.templates.suggestion.apply(this, [suggestion].concat(args)));
$el.data(datasetKey, that.name);
$el.data(valueKey, that.displayFn(suggestion) || undefined); // this led to undefined return value
$el.data(datumKey, JSON.stringify(suggestion));
$el.children().each(function() { DOM.element(this).css(self.css.suggestionChild); });
return $el;
}
}
function getHeaderHtml() {
var args = [].slice.call(arguments, 0);
args = [{query: query, isEmpty: !hasSuggestions}].concat(args);
return that.templates.header.apply(this, args);
}
function getFooterHtml() {
var args = [].slice.call(arguments, 0);
args = [{query: query, isEmpty: !hasSuggestions}].concat(args);
return that.templates.footer.apply(this, args);
}
},
// ### public
getRoot: function getRoot() {
return this.$el;
},
update: function update(query) {
function handleSuggestions(suggestions) {
// if the update has been canceled or if the query has changed
// do not render the suggestions as they've become outdated
if (!this.canceled && query === this.query) {
// concat all the other arguments that could have been passed
// to the render function, and forward them to _render
var extraArgs = [].slice.call(arguments, 1);
this.cacheSuggestions(query, suggestions, extraArgs);
this._render.apply(this, [query, suggestions].concat(extraArgs));
}
}
this.query = query;
this.canceled = false;
if (this.shouldFetchFromCache(query)) {
handleSuggestions.apply(this, [this.cachedSuggestions].concat(this.cachedRenderExtraArgs));
} else {
var that = this;
var execSource = function() {
// When the call is debounced the condition avoid to do a useless
// request with the last character when the input has been cleared
if (!that.canceled) {
that.source(query, handleSuggestions.bind(that));
}
};
if (this.debounce) {
var later = function() {
that.debounceTimeout = null;
execSource();
};
clearTimeout(this.debounceTimeout);
this.debounceTimeout = setTimeout(later, this.debounce);
} else {
execSource();
}
}
},
cacheSuggestions: function cacheSuggestions(query, suggestions, extraArgs) {
this.cachedQuery = query;
this.cachedSuggestions = suggestions;
this.cachedRenderExtraArgs = extraArgs;
},
shouldFetchFromCache: function shouldFetchFromCache(query) {
return this.cachedQuery === query && this.cachedSuggestions && this.cachedSuggestions.length;
},
clearCachedSuggestions: function clearCachedSuggestions() {
delete this.cachedQuery;
delete this.cachedSuggestions;
delete this.cachedRenderExtraArgs;
},
cancel: function cancel() {
this.canceled = true;
},
clear: function clear() {
this.cancel();
this.$el.empty();
this.trigger('rendered', '');
},
isEmpty: function isEmpty() {
return this._isEmpty;
},
destroy: function destroy() {
this.clearCachedSuggestions();
this.$el = null;
}
});
// helper functions
// ----------------
function getDisplayFn(display) {
display = display || 'value';
return _.isFunction(display) ? display : displayFn;
function displayFn(obj) {
return obj[display];
}
}
function getTemplates(templates, displayFn) {
return {
empty: templates.empty && _.templatify(templates.empty),
header: templates.header && _.templatify(templates.header),
footer: templates.footer && _.templatify(templates.footer),
suggestion: templates.suggestion || suggestionTemplate
};
function suggestionTemplate(context) {
return '<p>' + displayFn(context) + '</p>';
}
}
function isValidName(str) {
// dashes, underscores, letters, and numbers
return (/^[_a-zA-Z0-9-]+$/).test(str);
}
module.exports = Dataset;