This repository has been archived by the owner on May 6, 2021. It is now read-only.
forked from nytimes/pourover
-
Notifications
You must be signed in to change notification settings - Fork 8
/
pourover.js
2343 lines (2170 loc) · 75.5 KB
/
pourover.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var PourOver = (function() {
var deprecationWarn = function(name, nextName) {
console.warn("Deprecation warning: " + name + " will be renamed to " + nextName + " in the next major release.");
};
var ctor = function() {};
var create = _.create || function(prototype) {
ctor.prototype = prototype;
var result = new ctor();
ctor.prototype = null;
return result;
};
PourOver = {
// Utility functions. Skip down to "Collections" for the real meat of PourOver.
//
// # The basic sorted set operations
//
union_sorted: function(a, b) {
deprecationWarn("union_sorted", "unionSort");
return this.unionSort(a,b);
},
unionSort: function(a, b) {
// Make more efficient by just copying at Infinity
var lowa = 0,
lowb = 0,
higha = a.length,
highb = b.length,
result = [],
la, lb;
while (higha > lowa || highb > lowb) {
la = a[lowa];
lb = b[lowb];
if (_.isUndefined(la)) la = Infinity;
if (_.isUndefined(lb)) lb = Infinity;
if (lowa == higha) {
return result.concat(b.slice(lowb, highb));
}
if (lowb == highb) {
return result.concat(a.slice(lowa, higha));
}
if (la == lb) {
result.push(la);
lowa++;
lowb++;
} else if (la < lb) {
result.push(la);
lowa++;
} else {
result.push(lb);
lowb++;
}
}
return result;
},
intersect_sorted: function(a, b) {
deprecationWarn("intersect_sorted", "intersectSort");
return this.intersectSort(a, b);
},
intersectSort: function(a, b) {
var lowa = 0,
lowb = 0,
higha = a.length,
highb = b.length,
result = [],
la, lb;
while (higha > lowa && highb > lowb) {
la = a[lowa];
lb = b[lowb];
if (la == lb) {
result.push(la);
lowa++;
lowb++;
} else if (la < lb) {
lowa++;
} else {
lowb++;
}
}
return result;
},
subtract_sorted: function(a, b) {
deprecationWarn("subtract_sorted", "subtractSort");
return this.subtractSort(a, b);
},
subtractSort: function(a, b) {
var lowa = 0,
lowb = 0,
higha = a.length,
highb = b.length,
result = [],
la, lb;
while (higha > lowa || highb > lowb) {
la = a[lowa];
lb = b[lowb];
if (higha == lowa) {
return result;
}
if (highb == lowb) {
return result.concat(a.slice(lowa, higha));
}
if (la == lb) {
lowa++;
lowb++;
} else if (la < lb) {
result.push(la);
lowa++;
} else {
lowb++;
}
}
return result;
},
insert_sorted: function(a, b) {
deprecationWarn("insert_sorted", "insertSort");
return this.insertSort(a, b);
},
insertSort: function(set, element) {
var length = set.length,
i = 0,
last_elem = set[length - 1];
if (element > last_elem) {
set.push(element);
return set;
}
while (i < length) {
if (element < set[i]) {
return set.slice(0, i).concat([element]).concat(set.slice(i, length));
} else {
i++;
}
}
set.push(element);
return set;
},
//
// # Sort support
//
// Sort the set according to some function and then store an array of the translations
// of the indicies. So if the first item went to index 2 after being sorted, put 2 in
// the first spot of the permutation array.
build_permutation_array: function(a, b) {
deprecationWarn("build_permutation_array", "buildPermutationArray");
return this.buildPermutationArray(a, b);
},
buildPermutationArray: function(set, sort) {
var sorted_set = _.clone(set),
perm = [];
if (typeof(sort) === "function") {
sorted_set.sort(sort);
} else {
sorted_set.sort(function(a, b) {
return sort.fn.call(sort, a, b);
});
}
_.each(sorted_set, function(m, i) {
perm[m.cid] = i;
});
return perm;
},
// Use a permutation array to resort a subset of a collection.
permute_from_array: function(a, b) {
deprecationWarn("permute_from_array", "permuteFromArray");
return this.permuteFromArray(a, b);
},
permuteFromArray: function(collection, perm) {
var output = [];
if (typeof(collection[0]) === "number") {
_.each(collection, function(i) {
output[perm[i]] = i;
});
} else {
_.each(collection, function(i) {
output[perm[i.cid]] = i;
});
}
return _.without(output, undefined);
},
// Remove an element from a sorted set.
remove_sorted: function(a, b) {
deprecationWarn("remove_sorted", "removeSort");
return this.removeSort(a, b);
},
removeSort: function(set, element) {
var length = set.length,
i = 0;
while (i < length) {
if (element == set[i]) {
return set.slice(0, i).concat(set.slice(i + 1, length));
} else {
i++;
}
}
return set;
},
bisect_by: function(f) {
deprecationWarn("bisect_by", "bisectBy");
return this.bisectBy(f);
},
bisectBy: function(f) {
// Thanks to crossfilter (https://github.com/square/crossfilter) for this implementation.
function bisectLeft(a, x, lo, hi) {
while (lo < hi) {
var mid = lo + hi >>> 1;
if (f(a[mid]) < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
function bisectRight(a, x, lo, hi) {
while (lo < hi) {
var mid = lo + hi >>> 1;
if (x < f(a[mid])) hi = mid;
else lo = mid + 1;
}
return lo;
}
bisectRight.right = bisectRight;
bisectRight.left = bisectLeft;
return bisectRight;
},
// # Pre-defined cache methods
// Caching is really the raison d'etre of Pourover. Every filter has two cache methods: one for rebuilding the whole filter from scratch
// and one for adding new items. As Pourover grows it will gain more pre-defined cache methods that correlate with common UI and data patterns.
cacheMethods: {
// ### Default: the dumb caches.
// Just goes through each possible value for the filter and tests every item in the collection against it. As expensive as
// possibile, but simple.
defaultCache: function(items) {
var that = this;
_.each(that.possibilities, function(p) {
var matching_items = _.filter(items, function(i) {
return that.fn(p, i);
}),
matching_cids = _.pluck(matching_items, 'cid');
p.matching_cids = matching_cids;
});
},
defaultAddCache: function(items) {
var that = this;
_.each(that.possibilities, function(p) {
var matching_items = _.filter(items, function(i) {
return that.fn(p, i);
}),
matching_cids = _.pluck(matching_items, 'cid');
p.matching_cids = PourOver.unionSort(p.matching_cids, matching_cids);
});
},
// ### Exact: the fastest caches.
// For filters that evaluate by strict equality (this property === this value). The name of the filter must
// match the name of the property for exact cache to work.
exactCache: function(items) {
var that = this,
attr = this.attr || this.name;
_.each(items, function(i) {
var p = that.possibilities[i[attr]];
if (p) {
p.matching_cids = PourOver.insertSort(p.matching_cids, i.cid);
}
});
},
exactAddCache: function(items) {
PourOver.cacheMethods.exactCache.call(this, items);
},
inclusionCache: function(items) {
var that = this,
attr = this.attr || this.name;
_.each(items, function(i) {
_.each(i[attr], function(v) {
var p = that.possibilities[v];
if (p) {
p.matching_cids = PourOver.insertSort(p.matching_cids, i.cid);
}
});
});
},
inclusionAddCache: function(items) {
PourOver.cacheMethods.inclusionCache.call(this, items);
}
}
};
// Copied from Backbone
var array = [];
var push = array.push;
var slice = array.slice;
var splice = array.splice;
var Events = PourOver.Events = {
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({
callback: callback,
context: context,
ctx: context || this
});
return this;
},
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events == this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo) return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object') callback = this;
if (obj)(listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
}
return this;
}
};
// Regular expression used to split event strings.
var eventSplitter = /\s+/;
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// PourOver events have 3 arguments).
var triggerEvents = function(events, args) {
var ev, i = -1,
l = events.length,
a1 = args[0],
a2 = args[1],
a3 = args[2];
switch (args.length) {
case 0:
while (++i < l)(ev = events[i]).callback.call(ev.ctx);
return;
case 1:
while (++i < l)(ev = events[i]).callback.call(ev.ctx, a1);
return;
case 2:
while (++i < l)(ev = events[i]).callback.call(ev.ctx, a1, a2);
return;
case 3:
while (++i < l)(ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
return;
default:
while (++i < l)(ev = events[i]).callback.apply(ev.ctx, args);
return;
}
};
var listenMethods = {
listenTo: 'on',
listenToOnce: 'once'
};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function(implementation, method) {
Events[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Allow the `PourOver` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(PourOver, Events);
// #Collections
//The main kind of object in Pourover. A collection is basically a wrapper around an array of objects.
//It adds collection ids to its members and has support for various ways of retrieving all or a part of
//its members.
PourOver.Collection = function(items, opts) {
if (typeof(items) == "undefined") {
items = [];
}
this.items = [];
this.filters = {};
this.sorts = {};
this.addItems(items);
this.on("change", function() {
_.each(this.filters, function(f) {
if (f.current_query) {
f.current_query.refresh();
}
});
});
this.initialize.apply(this, arguments);
};
_.extend(PourOver.Collection.prototype, PourOver.Events, {
initialize: function() {},
// Force the filters and sorts of a collection to refresh. Generally most useful if you have batched
// up a bunch of silented actions and you want to refresh once at the end.
refresh: function() {
this.trigger("queryChange");
},
// Retrive the objects associated with an array of cids. Like everything in Pourover, the cids must be sorted.
// This is not ususally an issue as you generally will not be calling `collection.get` with an array you
// manually create. You will probably be using the output of some function that keeps it sorted for you.
get: function(cids) {
return PourOver.Collection.prototype.getBy.call(this, "cid", cids, true);
},
// Similar to get, except -- rather than getting items by cid -- you are getting them by [attr_name].
// Here vals is an array of [attr_names]s.
getBy: function(attr_name, vals, sorted) {
if (!_.isArray(vals)) {
var vals = [vals];
}
if (typeof(sorted) == "undefined") {
sorted = false;
}
var low = 0,
high = this.items.length,
lc = 0,
hc = vals.length,
output = [],
items = this.items,
i;
if (sorted === true) {
while (low < high && lc < hc) {
if (vals[lc] == (i = items[low])[attr_name]) {
output.push(i);
low++;
lc++;
} else if (vals[lc] < i[attr_name]) {
lc++;
} else {
low++;
}
}
} else if (sorted == "reverse") {
while (low < high && lc < hc) {
if (vals[lc] == (i = items[low])[attr_name]) {
output.push(i);
low++;
lc++;
} else if (vals[lc] > i[attr_name]) {
lc++;
} else {
low++;
}
}
} else {
while (low < high && lc < hc) {
if (_.include(vals, (i = items[low])[attr_name])) {
output.push(i);
vals = _.without(vals, i[attr_name]);
low++;
lc++;
} else {
low++;
}
}
}
return output;
},
getByFirst: function(attr_name, val, sorted) {
if (typeof(sorted) == "undefined") {
sorted = false;
}
var low = 0,
high = this.items.length,
items = this.items,
output,
i;
if (sorted === true) {
while (low < high) {
if (val == (i = items[low])[attr_name]) {
output = i;
break;
} else if (val < i[attr_name]) {
break;
} else {
low++;
}
}
} else if (sorted == "reverse") {
while (low < high) {
if (val == (i = items[low])[attr_name]) {
output = i;
break;
} else if (val > i[attr_name]) {
break;
} else {
low++;
}
}
} else {
while (low < high) {
if (val == (i = items[low])[attr_name]) {
output = i;
break;
} else {
low++;
}
}
}
return output;
},
// Add items to the collection, triggering the appropriate events to keep all dependent sort and filter sets up-to-date.
addItems: function(i) {
this.trigger("will_change");
if (!_.isArray(i)) {
i = [i];
}
var last_id = this.items.length > 0 ? _.last(this.items).cid + 1 : 0,
new_items;
new_items = _.map(i, function(c) {
var n = PourOver.Item(c);
n.cid = last_id++;
return n;
});
this.items = this.items.concat(new_items);
this.regenerateFilterSets(new_items);
this.trigger("change", _(new_items).pluck("cid"));
},
// Remove items from the collection, triggering the appropriate events to keep all dependent sort and filter sets up-to-date.
// This functionality is only included begrudgingly. Pourover is best for collections that rarely remove members.
// TODO: Optimize
removeItems: function(i, isSorted) {
this.trigger("will_change");
if (typeof(isSorted) === "undefined") {
var isSorted = false;
}
if (!_.isArray(i)) {
var i = [i];
}
if (isSorted) {
i = i.sort(function(a, b) {
return a.cid - b.cid;
});
var new_items = [],
old_items = this.items,
new_length = i.length,
old_length = this.items.length,
newi = 0,
oldi = 0;
while (oldi < old_length) {
if (!newi < new_length) {
new_items = new_items.concat(old_items.slice(oldi));
break;
} else if (old_items[oldi].cid === i[newi].cid) {
newi++;
oldi++;
} else {
new_items.push(old_items[oldi]);
oldi++;
}
}
} else {
var new_items = [],
old_items = this.items,
old_length = this.items.length,
oldi = 0,
delete_cids = _.pluck(i, "cid");
while (oldi < old_length && delete_cids.length > 0) {
if (_.include(delete_cids, old_items[oldi].cid)) {
} else {
new_items.push(old_items[oldi]);
}
oldi++;
}
}
this.items = new_items;
this.regenerateFilterSets();
this.trigger("change", _(i).pluck("cid"));
},
// # Collection filter functions
// All filters are associated to collections rather than views. This allows for multiple views to share the same filter.
// This is especially useful for modal situations in which you can set filters on a grid view that are reflected in the
// one up view as well.
addFilters: function(f) {
var that = this,
new_filters;
if (!_.isArray(f)) {
f = [f];
}
new_filters = _.reduce(f, function(m, i) {
m[i.name] = create(i);
m[i.name].collection = that;
return m;
}, {});
this.filters = _.extend(this.filters, new_filters);
// Bubble all query change events up from the individual filters to the collection. This allows a developers to
// specify events that should be triggered whenever any filter's query is changed.
_.each(new_filters, function(f) {
f.on("queryChange", function() {
that.trigger("queryChange");
});
// All filters precache the result of their filtering. This is the source of pourover's speed optimizations.
f.cacheResults(that.items);
// If a user passes in an `associated_attrs` property on a filter, that filter will re-cache its result whenever
// any object in the collection has an attribute changed. Setting `associated_attrs` is essential for admins or
// other uses in which filterable values can change.
if (f.associated_attrs) {
_.each(f.associated_attrs, function(a) {
that.on("change:" + a, function(objs) {
f.removeFromCache(objs);
f.addCacheResults(objs);
if (f.current_query) {
f.current_query.refresh();
}
});
});
}
});
},
// A shortcut to re-calculate the results of every filter. This is expensive if you do not pass in `new_items`, in which cases
// only the new_items will be cached and the filters updated.
regenerateFilterSets: function(new_items) {
var that = this;
// If no new items are passed in, regenerate filters for all items in the collection
if (typeof(new_items) == "undefined") {
_.each(this.filters, function(f) {
f.cacheResults(that.items);
});
} else {
_.each(this.filters, function(f) {
f.addCacheResults(new_items);
});
}
},
// A shortcut for returning a match object containing all the items in a collection. More on matches below.
getAllItems: function() {
var cids = _.pluck(this.items, "cid");
return new PourOver.MatchSet(cids, this, ["all"]);
},
// Get the currently cached results for the last stateful query on a filter (the last time a `setQuery` was called on that filter.)
// If `empty_default` is set to true, the function will return no items if the filter does not have a current query set. Otherwise,
// the function will return all items in the collection. The former `empty_default` setting is useful when OR-ing filters together, when
// you want an unset filter to represent an unselected dimension. The latter is useful when AND-ing filters together, when you
// want an unset filter to comprise all objects in the collection.
getCurrentFilteredItems: function(filter_name, empty_default) {
if (typeof(empty_default) === "undefined") {
empty_default = false;
}
if (this.filters[filter_name].current_query && this.filters[filter_name].current_query.stack.length > 0) {
return this.filters[filter_name].current_query;
} else {
if (empty_default) {
return new PourOver.MatchSet([], this, []);
} else {
return this.getAllItems();
}
}
},
// The non-stateful way to query a filter. Simply returns the result of the query but does not store the query on the filter.
getFilteredItems: function(filter_name, query) {
var filter = this.filters[filter_name],
possibility;
if (_.isUndefined(filter)) throw "The filter " + filter_name + " does not exist.";
return filter.getFn(query);
},
// # Sort functions
// Sorts, like filters, are generally stored on collections for the same reason that filters are stored on the collection rather than the view.
// However, whereas filters keep track of their own state and this is shared between views, the state of which sort is enabled is stored on the view.
addSort: function(sort) {
var that = this;
this.sorts[sort.name] = sort;
sort.collection = this;
sort.rebuildSort();
this.on("change", function() {
sort.rebuildSort(true);
});
// Like filters, if you set `associated_attrs` on a sort, they will rebuild themselves whenever any item in the collection undergoes a change
// on that attribute.
// TODO: Consider cloning on add. Also, bring in line with addFilter (events or not!?)
if (sort.associated_attrs) {
_.each(sort.associated_attrs, function(a) {
that.on("change:" + a, function(objs) {
sort.rebuildSort();
});
});
}
},
// Add multiple sorts.
addSorts: function(sorts) {
if (typeof(opts) === "undefined") {
opts = {};
}
if (!_.isArray(sorts)) {
sorts = [sorts];
}
var that = this;
_.each(sorts, function(s) {
that.addSort(s);
});
},
// The non-stateful way to retrieve all the items in the collection, sorted.
getSortedItems: function(sort_name) {
var s = this.sorts[sort_name],
that = this,
output;
return s.sort(this.items);
},
// A silly shortcut, pass in a cid and an attribute, retrieve its value. Useful for template helpers.
getItemValue: function(cid, attribute) {
var item = _.find(this.items, function(i) {
return i.cid === Number(cid);
});
return item[attribute];
},
// Update the value of one attribute of one item in the collection.
updateItem: function(cid, attribute, value) {
this.trigger("will_incremental_change");
var item = _.find(this.items, function(i) {
return i.cid === Number(cid);
});
item[attribute] = value;
this.trigger("change:" + attribute, [item]);
this.trigger("incremental_change", [attribute]);
this.trigger("update", "updateItem");
return item.guid;
},
// Delete an attribute of one item in the collection.
removeItemAttribute: function(cid, attribute, value) {
this.trigger("will_incremental_change");
var item = _.find(this.items, function(i) {
return i.cid === Number(cid);
});
delete item[attribute];
this.trigger("change:" + attribute, [item]);
this.trigger("incremental_change", [attribute]);
this.trigger("update", "updateItem");
return item.guid;
},
// Change the value of one attribute of many items to the same value.
batchUpdateItems: function(cids, attribute, value) {
this.trigger("will_incremental_change");
var items = this.get(cids, true);
_.each(items, function(i) {
i[attribute] = value;
});
this.trigger("change:" + attribute, items);
this.trigger("incremental_change", [attribute]);
this.trigger("update", "batchUpdate");
return _.pluck(items, "guid");
},
// Change the value of several attributes of a single item in the collection.
updateAttributes: function(cid, updates, silent) {
if (typeof(silent) === "undefined") {
var silent = false;
}
this.trigger("will_incremental_change");
var item = _.find(this.items, function(i) {
return i.cid === Number(cid);
});
var that = this;
_.each(updates, function(v, k) {
item[k] = v;
that.trigger("change:" + k, [item]);
});
this.trigger("incremental_change", _.keys(updates));
if (!silent) {
this.trigger("update", "updateAttribute");
}
return item.guid;
},
// Change the value of several attributes of several items in the collection. Here 'updates'
// is a hash of attributes -> new values.
batchUpdateAttributes: function(cids, updates, silent) {
if (typeof(silent) === "undefined") {
var silent = false;
}
this.trigger("will_incremental_change");
var items = this.get(cids, true);
var that = this;
_.each(items, function(item) {
_.each(updates, function(v, k) {
item[k] = v;
});
});
_.each(updates, function(v, k) {
that.trigger("change:" + k, items);
});
this.trigger("incremental_change", _.keys(updates));
if (!silent) {
this.trigger("update", "batchUpdate");
this.trigger("batchUpdateAttribute");
}
return _.pluck(items, "guid");
},
batchLoadItems: function(data) {
this.trigger("will_incremental_change");
var new_cids = [],
guids = _.pluck(data, "guid"),
old_items = this.getBy("guid", guids),
old_item_dict = {};
_(old_items).each(function(item) {
old_item_dict[item.guid] = item;
});
_.each(data, _.bind(function(d) {
var item = old_item_dict[d.guid],
last_id = this.items.length > 0 ? _(this.items).last().cid + 1 : 0,
current_item;
if (item) {
current_item = item;
// update the item's attrs
_.each(d, function(v, k) {
current_item[k] = v;
});
} else {
item = PourOver.Item(d);
item.cid = last_id++;
new_cids.push(item.cid);
this.items = this.items.concat([item]);
// add this to the list of existing items so that
// if data contains the same guid multiple times,
// the second instance will be treated as an update.
old_items[item.guid] = item;
}
}, this));
this.regenerateFilterSets();
this.trigger("incremental_change", "*");
this.trigger("change", new_cids);
this.trigger("update", "batchLoad");
this.trigger("batchLoadItems");
}
});
// #Items
// If we ever need to add properties to items in a collection, the code would go here.
PourOver.Item = function(i) {
return i;
},
// #Filters
// A filter is basically a rule for mapping items of a collection into groups based on attribute
// values. It caches the results and can be queried either statefully or non-statefully, depending
// on developer preference.
PourOver.Filter = function(name, values, opts) {
if (typeof(opts) === "undefined") {
opts = {};
}
this.name = name;
this.possibilities = this.createPossibilities(values);
this.values = _.pluck(values, "value");
_.extend(this, opts);
this.initialize.apply(this, arguments);
};
_.extend(PourOver.Filter.prototype, PourOver.Events, {
// Initialize is a no-op by default.
initialize: function() {},
// Given an array of possible values, initializes the object that will store the cached results
// of querying for that possibility.
create_possibilities: function(a) {
deprecationWarn("create_possibilities", "createPossibilities");
return this.createPossibilities(a);
},
createPossibilities: function(vs) {
var o = {};
_.each(vs, function(v) {
var name = v.name || String(v.value);
o[name] = v;
o[name].matching_cids = [];
});
return o;
},