This repository has been archived by the owner on Jun 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
sleek.js
993 lines (869 loc) · 29.7 KB
/
sleek.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
/**
* @fileoverview Main template logic, code shared by all platforms supported
* by the template.
*
* The code is extended in sleek.[platform].js to add platform-specific logic.
* To ease maintenance, the goal is to share as much code as possible between
* versions.
*/
/*global define, Joshfire, document*/
define([
'joshlib!collection',
'joshlib!ui/dynamiccontainer',
'joshlib!ui/item',
'joshlib!ui/list',
'joshlib!ui/cardpanel',
'joshlib!ui/fadeinpanel',
'joshlib!ui/factorymedia',
'joshlib!ui/imageloader',
'joshlib!ui/imagesloader',
'joshlib!router',
'joshlib!vendor/backbone',
'joshlib!vendor/underscore',
'joshlib!utils/dollar',
'joshlib!utils/i18n',
'ui/imagegallery'],
function (Collection, DynamicContainer, Item, List, CardPanel, FadeInPanel, FactoryMedia, ImageLoader, ImagesLoader, Router, Backbone, _, $, Localizer, ImageGallery) {
var Sleek = function() {
_.bindAll(this, 'initialize', 'setColor', 'slugify');
};
Sleek.extend = Backbone.View.extend;
_.extend(Sleek.prototype, Backbone.Events);
_.extend(Sleek.prototype, {
/**
* Device family that identifies the platform handled by a more specific class.
* Override this property in derivated class as appropriate. For instance, set
* the property to 'phone' in sleek.phone.js.
*
* The property is typically used to target platform-specific CSS files and
* properties.
*/
deviceFamily: 'all',
/**
* Client width available in CSS pixels
*
* Note the value is merely used as an indication to pick up a thumbnail
* image for listing views. It is not correct in that it does not follow
* orientation changes, but that's normally not a big deal.
*
* IMPORTANT: that value used to be computed in getThumbnail but, on iPad
* at least, accessing document.body.clientWidth forces a refresh of the
* screen which, in turn, means the screen will flicker for half a second,
* hence the need to store it once and for all here.
*/
clientWidth: document.body.clientWidth,
/**
* Initialization flag. The flag is set once the application is ready
* to process its first route.
*/
initialized: false,
/**
* The following flag is used to determine whether the router needs to
* trigger the "loaded" hook when the main view is done rendering or
* not.
*
* The flag is set once the hook has been triggered. Once set, this
* flag is never reset while the application is running.
*/
loadedHookTriggered: false,
/**
* Selector where fastNavigate() will be activated
* False to disable
*/
fastNavigateSelector: false,
/**
* Converts a schema.org type into an internal type of items
*/
convertItemType: function(type) {
var outputType = null;
switch (type) {
case 'Article/Status':
outputType = 'status';
break;
case 'NewsArticle':
case 'BlogPosting':
case 'Article':
case 'CreativeWork':
outputType = 'news';
break;
case 'Event':
outputType = 'event';
break;
case 'ImageObject':
outputType = 'photo';
break;
case 'VideoObject':
outputType = 'video';
break;
case 'MusicRecording':
outputType = 'sound';
break;
case 'Product':
outputType = 'product';
break;
default:
outputType = 'other';
break;
}
return outputType;
},
/**
* Initialization of the application.
* The function is automatically called by the framework when the application
* is loaded.
*
* @function
*/
initialize: function() {
var self = this;
this.localizer = Localizer;
this.title = Joshfire.factory.config.app.name;
this.tabs = Joshfire.factory.config.template.options.tabs || [];
this.tabicons = Joshfire.factory.config.template.options.tabicons || [];
this.backgroundURL = Joshfire.factory.config.template.options.backgroundimage ? Joshfire.factory.config.template.options.backgroundimage.url : Joshfire.factory.config.template.options.backgroundurl;
this.logoURL = Joshfire.factory.config.app.logo ?
Joshfire.factory.config.app.logo.contentURL : null;
// Set the document's title to the application title
document.title = this.title;
// Sets the locale and loads the corresponding dictionnary.
// It is then defined in the html templates's scope.
this.localizer.setLocale({
locale: Joshfire.factory.config.template.options.language || 'auto'
}, function() {
// Includes the correct dictionnary which is required by
// moment.js's i18n native solution.
self.setMomentLanguage();
// Set the template color based on the option selected by the user
// (this loads the CSS)
self.setColor(Joshfire.factory.config.template.options.color || 'gray', function () {
//
// Sections: one section per datasource
//
// (The way the list of datasources is retrieved actually depends
// on whether the code is used in Sleek or in Spot)
var datasources = self.getDatasources();
var sections = new Array(datasources.length);
var loaded = 0;
// Prepare sections
_.forEach(datasources, _.bind(function(datasource, index) {
var name = this.tabs[index] || datasource.name || '';
var icon = this.tabicons[index];
var slug = index + '--' + this.slugify(name.toLowerCase());
var collection = this.createCollection(datasource);
// Main section type depends on the type of content returned by the
// datasource. Datasources that return mixed content typically fall
// in the "other" category.
var outputType = datasource.getOutputType();
sections[index] = {
name: name,
slug: slug,
icon: icon || self.convertItemType(outputType),
outputType: self.convertItemType(outputType),
collection: collection,
index: index
};
// if this datasource is registered to server side event,
if(datasource.config.sse) {
self.listenToSSE(sections[index], datasource.config.sse.url);
}
}, self));
// Create the views once all sections have been initialized
var views = self.createViews(sections);
// Initialize the router and start the application
var controllers = self.createRoutes(sections, views);
self.router = Router(controllers);
self.setupFastNavigate();
self.init();
self.initialized = true;
// The "loaded" hook is triggered once when the router handles
// the first route and when the view is rendered. The hook will
// typically hide a possibly installed splashscreen
var loaded = function() {
if (!self.loadedHookTriggered && self.initialized) {
self.loadedHookTriggered = true;
Joshfire.factory.getAddOns('loaded').run();
}
};
views.bind('load', loaded);
//failsafe if first tab fails to load for some reason
setTimeout(loaded, 20*1000);
views.render();
self.router.historyStart();
});
});
},
createCollection: function(datasource) {
return new Collection([], {
dataSource: datasource,
dataSourceQuery: {}
});
},
setupFastNavigate:function() {
if (!this.fastNavigateSelector) return;
var self = this;
var fastNavigate = function(evt) {
var href = $(evt.currentTarget).attr("href");
if (href.substring(0,1)=="#") {
self.router.navigate(href.substring(1),true);
evt.preventDefault();
evt.stopPropagation();
return false;
}
};
$(this.fastNavigateSelector).live("touchstart mousedown",fastNavigate);
},
/**
* Overload this to get custom initializations for devices
*/
init:function() {},
/**
* Returns the list of datasources entered by the user, in the
* right order.
*
* @function
* @return {Array(Object)} The list of datasources, an empty
* array when no datasources are defined.
*/
getDatasources: function() {
var mainDatasource = Joshfire.factory.getDataSource('main');
var datasources = [];
if (mainDatasource && mainDatasource.children &&
(mainDatasource.children.length > 0)) {
datasources = datasources.concat(mainDatasource.children);
}
return datasources;
},
/**
* Sets the template color
*
* @function
* @param {string} color The color to set (value must be one of the supported
* colors, e.g. "gray", "blue", etc.)
* @param {function} callback Callback function run when CSS is done loading
*/
setColor: function(color, callback) {
$('#color').remove();
window.Sid.css('css/' + this.deviceFamily + '.' + color + '.css', callback, 'afterfirststyle');
},
/**
* Sets the main title
*
* @function
* @param {string} value The title to set.
* The string is interpreted as HTML markup.
*/
setTitle: function(value) {
$('#title').html(value);
},
/**
* Retrieves the classname(s) to use to flag an item in a list
* or the detail element that represents the item.
*
* Override this method in derivated classes as needed.
*
* @function
* @param {string} itemType itemType The section's output type
*/
getClassName: function (itemType, context) {
if (context === 'list') {
switch (itemType) {
case 'status':
case 'event':
return 'content hashed-list';
case 'photo':
return 'content mosaic-list';
default:
return 'content simple-list';
}
}
else if(context === 'single') {
return 'single content detail';
}
else {
return 'content detail';
}
},
/**
* Initializes and renders the application toolbar
*
* @function
* @param {Array(Object)} sections The list of sections to include
* in the toolbar
* @return {UIElement} The created toolbar element
*/
createToolbar: function(sections) {
var sectionCollection = new Backbone.Collection();
var section = null;
for(var i = 0; i < sections.length; i++) {
section = sections[i];
sectionCollection.add({
name: section.name,
icon: section.icon,
linkURL: '#' + section.slug,
outputType: section.outputType,
slug: section.slug
});
}
var toolbar = this.createToolbarElement();
toolbar.setCollection(sectionCollection);
toolbar.render();
return toolbar;
},
/**
* Initializes views created from the given list of sections.
*
* @function
* @param {Array(Object)} sections The list of sections
* (see "initialize" for format)
* @return {Object} Views created identified by their ID
*/
createViews: function(sections) {
var views = {};
var sectionsView = null;
// Create additional views and overlays
// (hook for derivated classes to add more logic)
this.createAdditionalViews(views);
if (!sections || (sections.length === 0)) {
sectionsView = new Item({
el: '#cards',
model: new Backbone.Model(),
templateEl: '#template-nodata'
});
return sectionsView;
}
// Create the toolbar
// (not very clean to set it in "this", but TV version needs
// to put the toolbar in a horizontal layout)
this.toolbarView = this.createToolbar(sections);
// Parse sections and build corresponding views
_.forEach(sections, _.bind(function(section) {
var sectionView = this.createSectionView(section);
views[section.slug] = sectionView;
}, this));
sectionsView = new FadeInPanel({
el: '#cards',
children: views
});
return sectionsView;
},
/**
* Creates additional views.
*
* This function is an empty hook that derivated classes may use to add
* additional views logic.
*
* @function
* @param {Object} views Views of the application, to complete with
* additional views created by the function (keys are views IDs)
*/
createAdditionalViews: function(views) {
},
/**
* Creates the toolbar UI element. Default implementation is a Toolbar,
* but you may want to override this in derivated classes.
*
* @function
* @return {UIElement} The toolbar UI element to use
*/
createToolbarElement: function() {
return new List({
el: '#toolbar',
templateEl: '#template-toolbar',
itemTemplateEl: '#toolbar-item'
});
},
/**
* Section is a dynamic container so that we can automatically
* switch to detail view when the collection contains only one
* item
*/
createSectionView: function(section) {
var view = new DynamicContainer({
collection: section.collection,
viewFactory: this.viewFactory(section)
});
section.view = view;
return view;
},
viewFactory: function(section) {
return _.bind(function(params) {
var collection = params.collection;
if (section.outputType === 'photo') {
return this.createListElement(section);
}
if(collection.length === 1) {
return this.createDetailContainer(section, true);
}
var list = this.createListElement(section);
var detail = this.createDetailContainer(section);
var view = this.createListAndDetailView(list, detail);
return view;
}, this);
},
createListAndDetailView: function(list, detail) {
},
/**
* Refreshes a section list by forcing a fetch from server
*
* @function
* @param {Object} the list section
* @parma {Backbone.View} the section container
*/
refreshList: function(section, container) {
section.collection.fetch({
dataSourceQuery: {
nocache: true
},
success: _.bind(function() {
this.showList(section, container);
}, this)
});
},
/**
* Updates a section list (uses cache if present)
*
* @function
* @param {Object} the list section
* @parma {Backbone.View} the section container
*/
updateList: function(section, container) {
section.collection.fetch({
success: _.bind(function() {
this.showList(section, container);
}, this)
});
},
/**
* Make this section listen to Server Side Event (SSE)
*
* @function
* @param section: the section that should listen to SSE
* @param streamURL: utl of the SSE stream
*/
listenToSSE: function(section, streamURL) {
var source = new EventSource(streamURL);
var self = this;
source.addEventListener('message', function(e) {
console.log(e.data);
var data = JSON.parse(e.data);
section.collection.add(data);
}, false);
source.addEventListener('open', function(e) {
console.log("SSE opened");
}, false);
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log("SSE lost");
}
}, false);
},
/**
* Displays a section list
* (assuming the section is already active).
*
* @function
* @param {Object} the list section
* @parma {Backbone.View} the section container
*/
showList: function(section, container) {
if(container.view.children && container.view.children.list) {
container.view.showChild('list', 'left');
} else if(section.collection.length) {
container.setModel(section.collection.at(0));
container.render();
}
},
/**
* Moves focus to the list view
* (for views that have separate list and a detail sub-views)
*
* @function
* @param {Backbone.View} the section container
*/
moveToList: function(container) {
if (container.view.children && container.view.children.list) {
container.view.showChild('list', 'left');
}
},
/**
* Updates a section item detail.
*
* @function
* @param {Object} the detail section
* @parma {Backbone.View} the section container
*/
updateDetail: function(section, container, offset) {
section.collection.fetch({
success: _.bind(function() {
this.showDetail(section, container, offset);
}, this)
});
},
/**
* Displays a section item detail.
*
* @function
* @param {Object} the detail section
* @parma {Backbone.View} the section container
*/
showDetail: function(section, container, offset) {
if(container.view.children && container.view.children.detail) {
var detail = container.view.children.detail;
if(section.collection.length > offset) {
detail.setModel(section.collection.at(offset));
detail.render();
}
container.view.showChild('detail', 'right');
}
},
/**
* Creates the element to use to represent a list of items
* for the given section.
*
* Default implement creates a List linked to the
* template-list-view template.
*
* Override this function in derivated classes to add
* specific logic.
*
* @function
* @param {Object} section Section to render
* @return {UIElement} The element to use. May include a detailed view.
*/
createListElement: function(section) {
if (section.outputType === 'photo') {
var isSingle = (section.collection.length > 1) ? '' : 'single';
var tEl = isSingle ? '#template-single-photo' : '#template-list-view';
return new ImageGallery({
templateEl: tEl,
scroller: true,
itemFactory: this.itemFactory(section),
collection: section.collection,
className: isSingle + ' ' + section.outputType + ' ' + this.getClassName(section.outputType, 'list'),
dataLoadingClass: 'dataloading',
loadingClass: 'loading'
});
}
else {
return new List({
templateEl: '#template-list-view',
scroller: true,
itemFactory: this.itemFactory(section),
collection: section.collection,
className: section.outputType + ' ' +
this.getClassName(section.outputType, 'list')
});
}
},
/**
* Creates the container element for the detail view of the given section.
*
* Default implementation creates a DynamicContainer that uses
* createDetailElement to select the right UI element to create
* for the item to render. No detail view for 'photo' streams.
*
* Override this function in derivated class as necessary.
*
* @function
* @param {Object} section Section to render
* @param {bool} whether this is a detail view for a single page
* @return {UIElement} The container element to use.
* Null when section does not have any associated detail view
* (or when the detail view is managed by dedicated code)
*/
createDetailContainer: function(section, isSingle) {
var self = this;
return new DynamicContainer({
viewFactory: function (options) {
// Delegate the creation to createDetailElement
_.extend(options, { slug: section.slug });
return self.createDetailElement(options, isSingle);
},
className: self.getClassName(section, isSingle ? 'single' : 'detail')
});
},
/**
* Creates the element to use to represent an item for the given section.
*
* Default implement creates a List linked to the
* template-list-view template.
*
* Override this function in derivated classes to add
* specific logic.
*
* @function
* @param {Object} options Rendering options
* @return {UIElement} The element to use.
*/
createDetailElement: function(options) {
if(!options.model) {
return new Item({});
}
var itemType = this.convertItemType(options.model.get('@type'));
var self = this;
switch (itemType) {
case 'video':
return new FactoryMedia({
templateEl: '#template-' + itemType,
scroller: true,
scrollerSelector: '.wrapper',
width: self.getContentWidth(),
height: self.getContentHeight(),
mediaOptions: {
strategy: 'html5',
width: '100%',
height: '80%',
adjustSize: true
}
});
case 'sound':
return new FactoryMedia({
templateEl: '#template-' + itemType,
mediaOptions: {
strategy: 'html5'
}
});
case 'status':
return new ImageLoader({
templateEl: '#template-' + itemType,
scroller: true,
getImageUrl: function () {
return self.getAuthorThumbnail(options.model.toJSON());
}
});
case 'photo':
case 'product':
case 'other':
return new ImageLoader({
templateEl: '#template-' + itemType,
scroller: true,
getImageUrl: function () {
return self.getThumbnail(options.model.toJSON());
}
});
default:
return new ImagesLoader({
templateEl: '#template-' + itemType,
scroller: true,
imageClass: 'fadein',
processImageEl: function (el) {
// Prepare image container and spinner
var loader = document.createElement('div');
loader.setAttribute('class', 'loader inv');
var container = document.createElement('div');
container.setAttribute('class', 'figure');
container.appendChild(loader);
// Constrain container width to the width of the image if known
// so that the loader appears correctly centered on screen.
// (it would always appear at the center of the screen otherwise)
if (el.getAttribute('width')) {
container.setAttribute('style',
'width:' + el.getAttribute('width') + 'px;max-width:100%');
}
else {
container.setAttribute('style',
'width:' + el.getAttribute('width') + 'px;max-width:100%');
}
// Wrap the image in its container and return the container
el.parentNode.replaceChild(container, el);
container.appendChild(el);
return container;
}
});
}
},
//
// Creates a list item view based on the type of the item.
//
itemFactory: function(section) {
var self = this;
return function(model, offset) {
var item = model.toJSON();
var type = section.outputType || self.convertItemType(item['@type']);
var templateEl = '#template-' + type + '-item';
var options = {
data: { section: section },
model: model,
offset: offset,
templateEl: templateEl
};
switch(type) {
case 'photo':
case 'video':
case 'product':
case 'news':
options.getImageUrl = function () {
return self.getThumbnail(item, offset, 0.2);
};
options.imageContainer = '.figure';
return new ImageLoader(options);
case 'status':
options.getImageUrl = function () {
return self.getAuthorThumbnail(item, offset);
};
options.imageContainer = '.figure';
return new ImageLoader(options);
default:
return new Item(options);
}
};
},
/**
* Create routes for all created views.
*
* Function stub that only handles the home page.
* Override this function in derivated classes.
*
* @function
* @param {Array(Object)} sections The list of sections that compose the app
* @param {Object} Created views identified by their ID
* @return {Object} Route controllers
*/
createRoutes: function(sections, views) {
return {
routes: {
'': 'home'
},
home: function() {
if (sections.length) {
window.location = '#' + sections[0].slug;
}
else {
$('#title').html('No data');
document.body.id = 'nodata';
$('#refresh').hide();
}
}
};
},
/**
* Returns the width that is available for detailed views.
*
* The function is used in particular to tell the media factory the
* maximum width it may use.
*
* @function
* @return {integer} The width available in CSS pixels
*/
getContentWidth: function() {
// Note the app contains more than one slide panel, but only
// one that should be displayed at a given time
var panels = $('.slide-panel').get();
var activePanel = _.max(panels, function (panel) {
return $(panel).width();
});
// Slide panels take twice the width available
// (since they contain two panels)
return Math.floor($(activePanel).width());
},
/**
* Returns the height that is available for detailed views.
*
* The function is used in particular to tell the media factory the
* maximum width it may use.
*
* @function
* @return {integer} The width available in CSS pixels
*/
getContentHeight: function() {
// Note the app contains more than one slide panel, but only
// one that should be displayed at a given time
var panels = $('.slide-panel').get();
var activePanel = _.max(panels, function (panel) {
return $(panel).height();
});
return $(activePanel).height();
},
/**
* Returns the URL of the thumbnail of an object
*
* @function
* @param {object} item schema.org friendly object to parse
* @param {Integer} offset The offset position (only used in TV version)
* @param {Number} widthRatio The fraction of screen width available
* for the image, e.g. 0.4 for a thumbnail that is to occupy 40% of the
* screen width
* @return {string} Thumbnail URL that best match the viewport size
*/
getThumbnail: function(item, offset, widthRatio) {
if (!item) return '';
widthRatio = widthRatio || 0.2;
var neededWidth = this.clientWidth * widthRatio;
var thumbnailWidth = 0;
var bestWidth = 0;
// Check the full list of thumbnails to start with
var thumbnails = item.thumbnail;
var thumbnailUrl = null;
var thumbnail = null;
var best = null;
if (thumbnails && (thumbnails.length > 0)) {
best = thumbnails[0];
bestWidth = best.width || 0;
for (var i=0; i < thumbnails.length; i++) {
thumbnail = thumbnails[i];
thumbnailWidth = thumbnail.width || 0;
if (((thumbnailWidth >= neededWidth) &&
((thumbnailWidth < bestWidth) || (bestWidth < neededWidth))) ||
((bestWidth < neededWidth) && (thumbnailWidth > bestWidth))) {
best = thumbnails[i];
}
}
thumbnailUrl = best.contentURL;
}
if (!thumbnailUrl) {
// No thumbnail URL found yet, return the value of the image property
// of the object if set. If not and if image, return its content
if (item.image && item.image.contentURL) {
thumbnailUrl = item.image.contentURL;
} else if ((item['@type'] === 'ImageObject') && item.contentURL) {
thumbnailUrl = item.contentURL;
}
}
if (!thumbnailUrl) {
thumbnailUrl = '';
}
return thumbnailUrl;
},
/**
* Sets the global language of the app.
*
* @function
* @param {string} locale || auto ; should be sent by the factory
* @return {null}
*/
setMomentLanguage: function() {
// en is the default lang here, move along
if(this.localizer.getLocale() === 'en') return;
window.Sid.js('lang/moment/'+this.localizer.getLocale()+'.js', _.bind(function() {
moment.lang(this.localizer.getLocale());
}, this));
},
/**
* Returns the URL of a thumbnail of the item's author.
*
* @function
* @param {object} item schema.org friendly object to parse
* @return {string} Thumbnail URL that best matches the viewport size
*/
getAuthorThumbnail: function(item, offset) {
if (!item) return '';
var thumbnailUrl = '';
if (item.author && item.author[0]) {
thumbnailUrl = this.getThumbnail(item.author[0], offset, 0.2);
}
if (!thumbnailUrl) {
// Fallback to "usual" thumbnail
thumbnailUrl = this.getThumbnail(item, offset, 0.2);
}
return thumbnailUrl;
},
slugify: function(text) {
text = text.replace(/[^\-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
text = text.replace(/&/gi, "-");
return text;
}
});
return Sleek;
});