-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.bundled.js
8942 lines (7129 loc) · 269 KB
/
main.bundled.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
'use strict';
var helpers = {};
var templates = {};
var models = {};
var collections = {};
var app = {};
var views = {};
var routing = {};
helpers.common = {
sortNumber: function(a,b) {
return a - b;
},
htmlDecode: function(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
},
toUserTimezone: function(utcDatestamp){
var utc_moment = moment(utcDatestamp),
user_timezone_moment = utc_moment.tz(pageData.timezone);
return user_timezone_moment;
},
conciseDate: function(utcDatestamp){
var user_timezone_moment = helpers.common.toUserTimezone(utcDatestamp),
user_timezone_string = user_timezone_moment.format('MM-DD-YY');
return user_timezone_string; // returns `6-24-14`
},
addCommas: function(x){
if (x || x === 0){
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
console.log('Warning: Expected string, found', x);
return '';
}
},
zeroIfNull: function(x) {
console.log(x)
if (!x) {
return 0
} else {
return x
}
},
prettyDatestamp: function(utcDatestamp){
var user_timezone_moment = helpers.common.toUserTimezone(utcDatestamp),
user_timezone_string = user_timezone_moment.format('M/D/YYYY, h:mm a');
return user_timezone_string; // returns `9/6/2014, 9:13 am`
},
toTitleCase: function(str){
return (str.charAt(0).toUpperCase() + str.slice(1, str.length));
},
boolToStr: function(bool, str){
var response;
if (bool){
response = str;
} else {
response = '';
}
return response;
},
// http://momentjs.com/docs/#/displaying/format/
prettyDate: function(utcDatestamp){
var user_timezone_moment = helpers.common.toUserTimezone(utcDatestamp),
user_timezone_string = user_timezone_moment.format('MMM D, YYYY');
return user_timezone_string; // returns `Jun 23, 2014`
},
}
helpers.modelsAndCollections = {
toggle: function(key){
this.set(key, !this.get(key));
},
setBoolByIds: function(trueKey, idKey, ids, bool){
ids = ids.split('+').map(function(id){ return +id });
ids.forEach(function(id){
var where_obj = {}; where_obj[idKey] = id;
if (this.where(where_obj).length) this.where(where_obj)[0].set(trueKey, bool);
}, this);
},
addTagsFromId: function(objectList){
objectList.forEach(function(item){
item.subject_tags = $.extend(true, [], item.subject_tags.map(function(d) {return pageData.org['subject_tags'].filter(function(f){ return f.id == d })[0] }) );
item.events.forEach(function(ev){
// console.log(pageData.org['impact_tags'])
ev.impact_tags = $.extend(true, [], ev.impact_tags.map(function(d) {return pageData.org['impact_tags'].filter(function(f){ return f.id == d })[0] }) );
})
});
return objectList;
},
metadata: function(prop, value) {
if (!this.metadataHash){
this.metadataHash = {};
}
if (value === undefined) {
return this.metadataHash[prop];
} else {
this.metadataHash[prop] = value;
}
}
}
helpers.templates = {
addCommas: helpers.common.addCommas,
zeroIfNull: helpers.common.zeroIfNull,
autolink: function(text){
return Autolinker.link(text);
},
toLowerCase: function(str){
return str.toLowerCase();
},
toTitleCase: helpers.common.toTitleCase,
serviceFromSousChef: function(sousChef){
// TODO, For now this works but will need to be changed if we have services that are more than one word
// Ideally the icon should be stored as base64 on the sous_chef
// source data is stored as `:service-:task` name, e.g. `google-alert`, `reddit-search`. Split by `-` and return the first node.
return sousChef.split('-')[0];
},
serviceFromRecipeSlug: function(recipeSlug){
var sous_chef = collections.recipes.instance.findWhere({slug: recipeSlug})
return sous_chef.get('sous_chef').split('-')[0]
},
methodFromSousChef: function(sousChef){
// source data is stored as `:service-:task` name, e.g. `google-alert`, `reddit-search`. Split by `-` and return the second node.
// TODO, For now this works but will need to be changed if we have services that are more than one word
// Ideally the icon should be stored as base64 on the sous_chef
return this.prettyName(sousChef.split('-')[1]);
},
alertSourceIdToRecipeSlug: function(sourceId){
// "facebook-page-to-event-promotion:14947c7a-11fe-11e5-aebc-c82a14194035"
return sourceId.split(':')[0];
},
alertSourceIdToService: function(sourceId){
var recipe_slug = helpers.templates.alertSourceIdToRecipeSlug(sourceId);
return helpers.templates.serviceFromRecipeSlug(recipe_slug);
},
getRecipeFromId: function(recipe_id){
// For manual alert creation
// Those alerts will have a `recipe_id` of null, change that to `-1`, which is the id of our manual recipe
// This isn't done in the database due to foreign key constraints
// per issue #395 https://github.com/newslynx/issue-tracker/issues/395
if (recipe_id === null){
recipe_id = -1;
}
var recipe = collections.recipes.instance.findWhere({id: recipe_id});
var recipe_json;
if (recipe){
recipe_json = recipe.toJSON();
} else {
console.log('ERROR, could not find recipe of id', recipe_id, 'in', collections.recipes.instance.models)
console.log(recipe)
}
return recipe_json;
},
prettyPrintSource: function(src){
src = src.replace(/-/g, ' ').replace(/_/g, ' ');
return helpers.templates.toTitleCase(src);
},
// toUserTimezone: helpers.common.toUserTimezone,
prettyDateTimeFormat: 'MMM D, YYYY, h:mm a',
prettyDatestamp: helpers.common.prettyDatestamp,
conciseDate: helpers.common.conciseDate,
fullIsoDate: function(utcDatestamp){
var user_timezone_moment = helpers.common.toUserTimezone(utcDatestamp),
user_timezone_string = user_timezone_moment.format();
return user_timezone_string; // returns
},
formatEnabled: function(bool){
if (bool) return 'Recipe is active';
return 'Recipe not active';
},
formatDefaultEventEnabled: function(bool){
if (bool) return 'Enabled';
return 'Disabled';
},
getAssociatedItems: function(id, itemKey, itemsObj){
itemsObj = pageData[itemsObj];
return _.filter(itemsObj, function(obj) { return obj[itemKey] == id });
},
prettyName: function(name){
// Make any name changes here to prettify things that might not be terribly evident what they do from their API slug.
name = name.replace(/_/g, ' ');
return name.charAt(0).toUpperCase() + name.slice(1);
},
escapeQuotes: function(term){
if (!term) { return false; }
if (typeof term !== 'string') { return term };
return term.replace(/"/g,'"')
},
displayRecipeParams: function(recipeId){
var recipe = helpers.templates.getRecipeFromId(recipeId);
var text = '';
text += recipe.name
if (recipe.options && recipe.options.search_query){
text += ',<br/>' + recipe.options.search_query;
}
return text;
},
htmlDecode: helpers.common.htmlDecode,
boolToStr: helpers.common.boolToStr,
extractDomain: function(url){
var begins_with_http = /^http/;
if (!begins_with_http.test(url)){
url = 'http://'+url;
}
var domain = '';
var match;
if (url) {
match = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i)
if (match) {
domain = match[0].replace('www.', '')
.replace('://', '')
.replace(/https?/, '')
.replace('/', '')
} else {
console.log('WARNING: No URL match for', url, 'MATCH:', match)
domain = ''
}
} else {
console.log('WARNING: No URL', url)
domain = ''
}
return domain;
},
handleEventCounts: function(lastRun, scheduleBy, eventCountsInfo, status, traceback){
var msg = '';
var pending_count
if (_.isObject(eventCountsInfo)) {
pending_count = helpers.templates.addCommas(eventCountsInfo.pending) || 0
}
if (status == 'error'){
msg = 'error (inspect element for info)<span class="error-report" style="display:none;">'+traceback+'</span>'
} else if (status == 'uninitialized'){
msg = 'uninitialized'
} else if (eventCountsInfo && scheduleBy == 'unscheduled'){
msg = 'Not scheduled,' + pending_count + ' pending';
} else if (eventCountsInfo && scheduleBy){
msg = pending_count + ' pending';
} else if (!lastRun && scheduleBy){
msg = 'Scheduled to run, 0 pending';
} else if (!eventCountsInfo && scheduleBy == 'unscheduled'){
msg = 'Not scheduled. 0 pending';
} else if (!eventCountsInfo) {
msg = '0 pending'
}
return msg;
},
prettyDate: helpers.common.prettyDate,
articles: {
prettyMetricName: function(name, superPretty){
var super_pretty_names = {
subject_tags: 'subj.',
impact_tags: 'imp.'
};
// This is used in the comparison grid header when we want really short names
if (superPretty && super_pretty_names[name]){
name = super_pretty_names[name];
}
// Make any name changes here to prettify things that might not be terribly evident what they do from their API slug.
name = name.replace(/_/g, ' ').replace('ga ', 'GA ').replace('facebook', 'FB');
return name.charAt(0).toUpperCase() + name.slice(1);
},
isActiveMetric: function(metricName, sortKey){
var sort_name = sortKey.replace('-metrics.','');
var class_name = (sort_name == metricName) ? 'active' : '';
return class_name;
},
htmlDecode: helpers.common.htmlDecode,
prettyDate: helpers.common.prettyDate,
prettyDatestamp: helpers.common.prettyDatestamp,
toUserTimezone: helpers.common.toUserTimezone,
conciseDate: helpers.common.conciseDate,
prettyMetricValue: function(value, aggregationOperation){
if (aggregationOperation == 'avg'){
value = value.toFixed(2);
}
return helpers.common.addCommas(value);
},
convertLineBreaksToHtml: function(str){
str = str || '';
return str.replace(/\n/g, '<br/>');
},
toTitleCase: helpers.common.toTitleCase,
boolToStr: helpers.common.boolToStr,
getIdsFromHash: function() {
return collections.article_comparisons.instance.getHash()
}
}
}
models.aa_base_article = {
"Model": Backbone.Model.extend({
toggle: helpers.modelsAndCollections.toggle,
urlRoot:'/api/_VERSION/content',
parse: function(articleSummaryJson){
var articles_with_data = this.addInfo(articleSummaryJson);
return articles_with_data;
},
// What orchestrates everything to get some the messiness out of `parse`
addInfo: function(articleSummaryJson){
articleSummaryJson = this.hydrateTagsInfo(articleSummaryJson, pageData.tags, ['subject_tag_ids', 'impact_tag_ids']);
articleSummaryJson = this.nestTags(articleSummaryJson);
articleSummaryJson = this.addTagInputOptions(articleSummaryJson);
return articleSummaryJson;
},
addTagInputOptions: function(articleJson){
// // Add a url so we can add/remove these
// // These models don't exist in a collection so that's why we use urlRoot
var subject_tag_models = collections.subject_tags.instance.models.map(function(tagModel){
var tag_model = tagModel.clone();
tag_model.urlRoot = 'api/_VERSION/content/'+articleJson.id+'/tags/';
return tag_model;
});
articleJson.subject_tag_input_options = subject_tag_models;
return articleJson;
},
// For general display
hydrateTagsInfo: function(dehydratedObj, tags, tagKeys){
tagKeys.forEach(function(key){
// Add the full info on a key name with `full` in the title
// This will take take ids in `obj['impact']` or `obj['subject']` and map them like to
// `subject_tag_ids` => `subject_tags_full`
if (dehydratedObj[key]){
var full_key = key.replace('_ids', 's_full');
dehydratedObj[full_key] = dehydratedObj[key].map(function(id){
var tag_key = key.replace('_tag_ids',''); // They're stored on our tags object just as `subject` and and `impact`
return _.findWhere(tags[tag_key], {id: id});
}).sort(function(a,b){
return a.name.localeCompare(b.name);
});
}
// Add `impact_tag_categories` and `impact_tag_levels` as their own items
var impact_tag_categories = _.chain(dehydratedObj.impact_tags_full)
.pluck('category')
.uniq()
.map(function(nameText){
var attr = {};
attr.name = nameText;
attr.color = pageData.attributeColorLookup[nameText];
return attr;
})
.value();
var impact_tag_levels = _.chain(dehydratedObj.impact_tags_full)
.pluck('level')
.uniq()
.map(function(nameText){
var attr = {};
attr.name = nameText;
attr.color = pageData.attributeColorLookup[nameText];
return attr;
})
.value();
dehydratedObj['impact_tag_categories'] = _.sortBy(impact_tag_categories, 'name');
dehydratedObj['impact_tag_levels'] = _.sortBy(impact_tag_levels, 'name');
});
return dehydratedObj;
},
// For display in article comparison row
nestTags: function(unnestedObj){
// For subject tags, chunk them into groups of three so they will be displayed as columns of no more than three. Each one looks like this and they're stored under `subject_tags_full`.
/*
{
"articles": 2,
"domain": "propalpatine.org",
"name": "Fracking",
"color": "#6a3d9a",
"id": 5,
"events": 2
}
*/
// `tag_columns` will be a list of lists, each containing no more than three tags
var subject_tag_columns = [],
chunk = 3;
if (unnestedObj.subject_tags_full){
for (var i = 0; i < unnestedObj.subject_tags_full.length; i += chunk) {
subject_tag_columns.push( unnestedObj.subject_tags_full.slice(i,i+chunk) );
}
}
// This on the object, which will either be an empty array or one with our groups
unnestedObj.subject_tags_grouped = subject_tag_columns;
var impact_tag_columns = [];
if (unnestedObj.impact_tags_full){
// Impact tags need more nesting. It makes most sense to group them by category
// These tags look like this and they're found under `impact_tags_full`.
/*
{
"category": "change",
"articles": 2,
"domain": "propalpatine.org",
"name": "legislative impact",
"level": "Institution",
"color": "#fb8072",
"events": 2,
"id": 1
}
*/
impact_tag_columns = d3.nest()
.key(function(d) { return d.category; })
.key(function(d) { return d.name; })
.rollup(function(list) {
return {
name: list[0].name,
color: list[0].color,
category: list[0].category,
level: list[0].level,
count: list.length
}
})
.entries(unnestedObj.impact_tags_full);
}
unnestedObj.impact_tags_grouped = impact_tag_columns;
return unnestedObj;
},
})
}
// This model gets a urlRoot when it's used to create an event from an alert
models.alert = {
"Model": Backbone.Model.extend({
urlRoot: 'api/_VERSION/events'
})
}
models.article_detailed = {
"Model": models.aa_base_article.Model.extend({
getGaMetrics: function(){
var ga_metrics = {};
_.each(this.get('metrics'), function(val, key){
if (/^ga_/.test(key)) {
ga_metrics[key] = val;
}
});
return ga_metrics;
}
})
}
models.article_summary = {
"Model": models.aa_base_article.Model.extend({
defaults: {
active_selected: false,
selected_for_compare: false,
selected_for_detail: false
},
url: 'api/_VERSION/content'
})
}
models.filters = {
"Model": Backbone.Model.extend({
metadata: helpers.modelsAndCollections.metadata,
initialize: function(){
this.on('filter', this.checkChanged);
this.assembleQueryParams();
return this;
},
checkChanged: function(){
var previous = this.metadata('previousParams'),
current = JSON.stringify(this.assembleQueryParams(true));
if (previous != current){
this.trigger('hasChanged');
}
return this;
},
assembleQueryParams: function(silent){
var model_json = $.extend(true, {}, this.toJSON());
_.each(model_json, function(val, key){
if (_.isArray(val)){
model_json[key] = val.join(',');
}
});
if (model_json.sort_by){
model_json.sort = model_json.sort_by;
delete model_json.sort_by;
}
if (!silent){
this.metadata('previousParams', JSON.stringify(model_json));
}
return model_json;
}
})
}
models.event = {
"Model": Backbone.Model.extend({
urlRoot: '/api/_VERSION/events',
parse: function(eventModel){
var events_with_hydrated_tags = this.hydrateTags(eventModel);
return events_with_hydrated_tags;
},
hydrateTags: function(eventModel){
var hydrated_tags = eventModel.tag_ids.map(function(id){
return collections.impact_tags.instance.findWhere({id: id});
});
eventModel.impact_tags_full = hydrated_tags;
return eventModel;
}
})
}
models.exports = {
"Model": Backbone.Model.extend({
url: 'exports'
})
}
// Just a plain old model
models.generic = {
"Model": Backbone.Model.extend({})
}
models.impact_tag = {
"Model": Backbone.Model.extend({
defaults: {
type: 'impact',
color: '#6699cc',
active: false,
category: null,
level: null
},
toggle: helpers.modelsAndCollections.toggle
})
}
models.new_article = {
"Model": Backbone.Model.extend({
urlRoot: '/api/articles'
})
}
models.org = {
"Model": Backbone.Model.extend({
urlRoot: '/api/_VERSION/orgs/settings'
})
}
models.recipe = {
"Model": Backbone.Model.extend({
toggle: helpers.modelsAndCollections.toggle,
defaults: {
viewing: false,
enabled: true // TODO, we're not using this but could implement, it's used to turn the recipe on and off
},
initialize: function(itemObj){
var keys = _.chain(itemObj.options).keys().filter(function(key){
var val = _.clone(itemObj.options[key])
if (_.isObject(val) && val.input_options) {
delete val.input_options;
}
return /^set_event_/.test(key) && !_.isEmpty(val);
}).value();
var set_val = keys.length ? true : false;
this.set('set_default_event', set_val);
}
})
}
models.recipe_creator = {
"Model": Backbone.Model.extend({
urlRoot: '/api/_VERSION/recipes'
})
}
models.setting = {
"Model": Backbone.Model.extend({})
}
models.sous_chef = {
"Model": Backbone.Model.extend({
toggle: helpers.modelsAndCollections.toggle
})
}
models.subject_tag = {
"Model": Backbone.Model.extend({
toggle: helpers.modelsAndCollections.toggle,
defaults: {
type: 'subject',
color: '#1f78b4'
}
})
}
models.user_setting = {
"Model": Backbone.Model.extend({
metadata: helpers.modelsAndCollections.metadata,
url: function(){
return 'api/_VERSION/me/settings/' + this.get('name')
}
})
}
models.user_value = {
"Model": Backbone.Model.extend({
url: 'api/_VERSION/me'
})
}
// This is the model that holds our selected alerts
// If it is added to this collection, it's baked to the dom
// If it is removed from this collection, it's removed from the dom
collections.active_alerts = {
"instance": null,
"Collection": Backbone.Collection.extend({
model: models.alert.Model,
metadata: helpers.modelsAndCollections.metadata,
url: 'api/_VERSION/events', // This doesn't need any query paremeters because it isn't used to fetch, just to delete or POST
comparator: function(alert){
return alert.created;
}
})
}
collections.article_comparisons = {
"instance": null,
"Collection": Backbone.Collection.extend({
model: models.article_summary.Model,
metadata: helpers.modelsAndCollections.metadata,
url: 'api/_VERSION/content?facets=subject_tags,impact_tags,categories,levels&incl_body=false',
// Set our default options, these all correspond to keys in the article comparisons object. Essentially, what values should we pluck out of that to use as our comparison point
initialize: function(){
this.metadata('operation', 'mean');
this.metadata('group', 'all');
this.metadata('max', 'per_97_5');
this.metadata('delimiter', '+');
return this;
},
parse: function(response){
return response.content_items;
},
// http://stackoverflow.com/questions/17753561/update-a-backbone-collection-property-on-add-remove-reset
set: function() {
Backbone.Collection.prototype.set.apply(this,arguments);
this.updateHash();
},
// updateHash on a remove
remove: function() {
Backbone.Collection.prototype.remove.apply(this,arguments);
this.updateHash();
},
// updateHash on a add
add: function() {
Backbone.Collection.prototype.add.apply(this,arguments);
this.updateHash();
},
// Also update hash on sort
sort: function(options) {
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options = options || {};
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}
if (!options.silent) this.trigger('sort', this, options);
this.updateHash();
return this;
},
setComparator: function(dimensionName){
var sort_ascending = this.metadata('sort_ascending');
var comparators = {};
comparators.text = function(articleComparisonModel){
var comparison_value = articleComparisonModel.get(dimensionName);
return comparison_value;
}
comparators.date = comparators.text;
comparators.metric = function(articleComparisonModel){
var comparison_value = articleComparisonModel.get('metrics')[dimensionName];
if (!sort_ascending){
comparison_value = comparison_value*-1;
}
return comparison_value;
}
comparators.bars = function(articleComparisonModel){
// These are stored as `subject_tags_full` and `impact_tags_full` on the model, do some string formatting to our metric name
// TODO, subject_tags should be sorted alphabetically
var comparison_value = articleComparisonModel.get(dimensionName + '_full').length
if (!sort_ascending){
comparison_value = comparison_value*-1;
}
return comparison_value;
}
var dimensionKind = _.findWhere( collections.dimensions.instance.getSelectDimensions() , {name: dimensionName}).kind;
this.comparator = comparators[dimensionKind];
// Adapted from this http://stackoverflow.com/questions/5013819/reverse-sort-order-with-backbone-js
// Backbone won't sort non-numerical fields, `this.reverseSortBy` fixes that.
if ((dimensionKind == 'text' || dimensionKind == 'date') && !sort_ascending){
this.comparator = this.reverseSortBy(this.comparator);
}
return this;
},
reverseSortBy: function(sortByFunction) {
return function(left, right) {
var l = sortByFunction(left);
var r = sortByFunction(right);
if (l === void 0) return -1;
if (r === void 0) return 1;
return l < r ? 1 : l > r ? -1 : 0;
};
},
updateHash: function() {
var delimiter = this.metadata('delimiter');
var sort_by = this.metadata('sort_by'),
ascending = this.metadata('sort_ascending');
var query_params = '?sort=' + sort_by + '&asc=' + ascending;
this.hash = this.pluck('id').join(delimiter) + query_params;
this.hash_list = this.pluck('id')
},
// With optional delimiter
getHash: function() {
return this.hash
},
getHashList: function(delimiter) {
var hash = this.hash_list
delimiter = delimiter || this.metadata('delimiter')
return hash.join(delimiter);
},
redrawMarkers: function(){
// Trigger his on the collection itself to update headers
// The article detail vizs piggy back on this listener to redraw themselves also
this.trigger('resetMetricHeaders');
// Trigger this event so each comparison item can redraw itself
this.models.forEach(function(model){
model.trigger('redrawMarker');
});
}
})
}
collections.article_detailed = {
"instance": null,
"Collection": Backbone.Collection.extend({
model: models.article_detailed.Model,
metadata: helpers.modelsAndCollections.metadata,
url:'/api/_VERSION/content',
set: function() {
// Always remove contents before setting so that we can set an existing model
// Backbone.Collection.prototype.remove.call(this, this.models );
Backbone.Collection.prototype.set.apply(this, arguments);
this.updateHash();
},
updateHash: function() {
// This will just have one, unless we're doing a drawer change set which will empty
if (this.length){
this.hash = this.first().id;
}
},
getHash: function() {
return this.hash;
},
// Add color information for promotions
addLevelColors: function(promotions){
return promotions.map(function(promotion){
var color = pageData.attributeColorLookup[promotion.level];
promotion.color = color;
return promotion;
});
}
})
}
collections.article_detailed_events = {
"Collection": Backbone.Collection.extend({
model: models.event.Model,
metadata: helpers.modelsAndCollections.metadata,
url: 'api/_VERSION/events?facets=tags,categories,levels&status=approved&per_page=10&sous_chefs=!twitter-search-content-item-links-to-event',
parse: function(response){
this.metadata('pagination', response.pagination);
this.metadata('total', response.total);
models.event_tag_facets.set(response.facets);
return response.events;
},
comparator: function(eventItem){
return eventItem.created;
}
})
}
collections.article_detailed_impact_tag_attributes = {
"categories_instance": null,
"levels_instance": null,
"Collection": Backbone.Collection.extend({
model: models.impact_tag.Model,
metadata: helpers.modelsAndCollections.metadata
})
}
// TODO, the url
collections.article_detailed_impact_tags = {
"instance": null,
"Collection": Backbone.Collection.extend({
model: models.impact_tag.Model,
set: function() {
// Always remove contents before setting
Backbone.Collection.prototype.remove.call(this, this.models );
Backbone.Collection.prototype.set.apply(this, arguments);
}
})
}
collections.article_detailed_subject_tags = {
"instance": null,
"Collection": Backbone.Collection.extend({
model: models.subject_tag.Model,
// setUrl: function(id){
// this.url = '/api/content/'+id+'/tag/';
// return this;
// }
// set: function() {
// // Always remove contents before setting
// Backbone.Collection.prototype.remove.call(this, this.models );
// Backbone.Collection.prototype.set.apply(this, arguments);
// }
})
}
collections.article_detailed_timeseries = {
"Collection": Backbone.Collection.extend({
metadata: helpers.modelsAndCollections.metadata,
setUrl: function(articleId){
this.url = 'api/_VERSION/content/'+articleId+'/timeseries?sort=-datetime'
},
parse: function(response){
var metric_selects = ['datetime'].concat(collections.dimensions.instance.metadata('select-timeseries'));
var filtered_response = response.map(function(evt){
return _.pick(evt, metric_selects);
});
return filtered_response;
}
})
}
collections.article_detailed_tweets = {
"Collection": Backbone.Collection.extend({
metadata: helpers.modelsAndCollections.metadata,
setUrl: function(articleId){
this.url = 'api/_VERSION/events?sous_chefs=twitter-search-content-item-links-to-event&per_page=100&content_item_ids=' + articleId
},
parse: function(response){
this.metadata('pagination', response.pagination);
this.metadata('total', response.total);
return response.events;
}
})
}
collections.article_summaries = {
"instance": null,
"Collection": Backbone.Collection.extend({
model: models.article_summary.Model,
metadata: helpers.modelsAndCollections.metadata,
url: 'api/_VERSION/content?facets=subject_tags,impact_tags,categories,levels&incl_body=false',
parse: function(response){
this.metadata('pagination', response.pagination);
this.metadata('total', response.total);
// This will fire a change event and update counts as well as show hide containers
models.tag_facets.set(response.facets);
return response.content_items;
},
})
}
// This is most closely tied to metrics but it also includes information like `title` and `created` date which are just pieces of data
collections.dimensions = {
"instance": null,
"Collection": Backbone.Collection.extend({
metadata: helpers.modelsAndCollections.metadata,
fetchSelects: function(cb){
var self = collections.dimensions.instance
var q = queue()
q.defer(d3.json, '/api/_VERSION/me/settings')
q.defer(d3.json, 'data/selects.json')
q.await(cb)
},
setSelects: function(cb){
var self = collections.dimensions.instance
// Fetch them, see if any are missing and if so, load those from file
self.fetchSelects(function(err, dimensionsSelects, selectsDefaults){
var groups = ['select-dimensions', 'sortable-dimensions', 'select-timeseries']
var settings
if (err){
console.log('Error getting selects', err)
} else {
settings = groups.map(function(group){
var setting_from_api = _.findWhere(dimensionsSelects, {name: group})
var setting
if (!setting_from_api) {
setting = selectsDefaults[group]
} else {
// Set the id of the local model via a naming convention so that when we save back, we will send PATCH and not POST
models['user_' + group.replace(/-/g, '_')].fetch()
setting = setting_from_api.value
}
return setting
})
self.metadata('selects', settings[0]);
self.metadata('sortable-dimensions', settings[1]);
self.metadata('select-timeseries', settings[2]);
cb(null)
}
})
},
cloneMetrics: function(getAll){ // We're lazy so give this a flag if we want to grab all
var metrics = [];
this.metadata('selects').forEach(function(select){
var metric;
if (select.kind == 'metric' || getAll){
metric = _.clone(select); // Beware, we are expecting a non-nested object here
metrics.push(metric);
}
});
return metrics;
},
getSelectDimensions: function(){
var selects_list = this.cloneMetrics(true),
dimension_selects = [],
that = this;
selects_list.forEach(function(selectInfo){
var select_name = selectInfo.name,
dimension_model = that.findWhere({name: select_name}),
dimension_json;
if (dimension_model){
dimension_json = _.clone(dimension_model.toJSON()); // Beware, we are expecting a non-nested object here
_.extend(dimension_json, selectInfo);
dimension_selects.push(dimension_json);
} else {
console.log('ERROR: No dimension model found for', select_name, 'in', that.toJSON())
}
});
return dimension_selects;
},
formatSelectsForIsotope: function(){
var selects = this.cloneMetrics(true),
selects_for_isotope = {};