-
Notifications
You must be signed in to change notification settings - Fork 79
/
MainStage.js
1233 lines (1050 loc) · 37.4 KB
/
MainStage.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
define(["lib-build/tpl!./MainMediaContainerMap",
"lib-build/tpl!./MainMediaContainerImage",
"lib-build/tpl!./MainMediaContainerEmbed",
"lib-build/css!./MainStage",
"../core/WebApplicationData",
"../core/Helper",
"dojo/has",
"esri/arcgis/utils",
"esri/renderers/UniqueValueRenderer",
"esri/geometry/Point",
"esri/geometry/Extent",
"esri/config",
"esri/geometry/webMercatorUtils",
"esri/symbols/SimpleMarkerSymbol",
//"esri/dijit/PopupMobile",
"esri/tasks/query",
"esri/tasks/QueryTask",
"dojo/topic",
"dojo/on",
"dojo/aspect",
"dojo/_base/lang"
],
function(
mainMediaContainerMapTpl,
mainMediaContainerImageTpl,
mainMediaContainerEmbedTpl,
viewCss,
WebApplicationData,
Helper,
has,
arcgisUtils,
UniqueValueRenderer,
Point,
Extent,
esriConfig,
webMercatorUtils,
SimpleMarkerSymbol,
//PopupMobile,
Query,
QueryTask,
topic,
on,
aspect,
lang
){
return function MainStage(container, isInBuilder, mainView)
{
var _this = this;
//
// Media containers
//
function addTemporaryMainMediaContainer(webmap)
{
$("#mainStagePanel .medias").append(
mainMediaContainerMapTpl({
webmapid: webmap,
isTemporary: true,
altText: '',
focusToPanel: i18n.viewer.a11y.focusContent
})
);
}
this.updateMainMediaContainers = function()
{
var webmaps = app.data.getWebmapObjects(),
images = app.data.getImageObjects(),
embeds = app.data.getEmbeds();
//
// Map
//
// Add new container
$.each(webmaps, function(i, webmap){
var mapContainer = $('.mapContainer[data-webmapid="' + webmap.id + '"]');
if ( ! mapContainer.length )
$("#mainStagePanel .medias").append(
mainMediaContainerMapTpl({
webmapid: webmap.id,
altText: webmap.altText || '',
isTemporary: false,
focusToPanel: i18n.viewer.a11y.focusContent
})
);
});
// Remove unused container
$('.mapContainer').each(function() {
var id = $(this).data('webmapid');
var found = _.some(webmaps, function(wm) {
return id === wm.id;
});
if (!found) {
$(this).parent().remove();
}
});
//
// Image
//
// Add new container
$.each(images, function(i, img){
var imageContainer = $('.imgContainer[data-src="' + img.url + '"]');
if ( ! imageContainer.length )
$("#mainStagePanel .medias").append(
mainMediaContainerImageTpl({
url: img.url,
altText: img.altText,
focusToPanel: i18n.viewer.a11y.focusContent
})
);
});
// Remove unused containers
$('.imgContainer').each(function(){
var src = $(this).data('src');
var found = _.some(images, function(img) {
return src === img.url;
});
if (!found) {
$(this).parent().remove();
}
});
//
// Embed (video and webpage)
//
// Add new container
$.each(embeds, function(i, embedInfo) {
// TODO this has to be reviewed to not allow content to be loaded too early? or give the same option for url?
var embedUrl = embedInfo.url,
embedhash = "";
if ( embedUrl.lastIndexOf('#') > 0 ) {
embedUrl = embedUrl.substring(0, embedUrl.lastIndexOf('#'));
embedhash = embedInfo.url.substring(embedInfo.url.lastIndexOf('#') + 1);
embedInfo.hash = embedhash;
}
if (useParentOriginUrl(embedInfo, embedUrl)) {
embedUrl = getParentOriginUrl(embedUrl);
}
var embedContainer = $('.embedContainer[data-src="' + (embedUrl || embedInfo.ts) + '"]');
if ( ! embedContainer.length ) {
//
// Frametag are added straight to the dom without any container
// a class and a data attribute are added below
// Ideally there should be a container so that it's possible to do more funny stuff like adding
// multiple iframe but these makes it difficult to center the frame(s)
//
$("#mainStagePanel .medias").append(
mainMediaContainerEmbedTpl({
url: embedUrl,
frameTag: embedInfo.frameTag,
altText: embedInfo.altText,
// Introduced in V1.1
unload: !!(embedInfo.unload === undefined || embedInfo.unload),
focusToPanel: i18n.viewer.a11y.focusContent
})
);
// If it's a frame tag
if ( !! embedInfo.frameTag ) {
// Find the Iframe
var frameTag = $("#mainStagePanel .medias .mainMediaContainer").last().find('iframe').first();
// Transform the src attribute into a data-src and Add the timestamp
frameTag.addClass('embedContainer')
.attr('data-src', frameTag.attr('src'))
.removeAttr('src')
.attr('data-ts', embedInfo.ts)
// Introduced in V1.1
.attr('data-unload', !!(embedInfo.unload === undefined || embedInfo.unload));
}
}
});
// Remove unused containers
$('.embedContainer').each(function() {
var embedSRC = $(this).data('ts') || $(this).data('src');
var embedInUse = $.grep(embeds, function (embed) {
var embedUrl = embed.url;
if (embedUrl.lastIndexOf('#') > 0) {
embedUrl = embedUrl.substring(0, embedUrl.lastIndexOf('#'));
}
// replace embedUrl test variable with parentOriginUrl
if (useParentOriginUrl(embed, embedUrl)) {
embedUrl = getParentOriginUrl(embedUrl);
}
return embedSRC == embedUrl || embedSRC == embed.ts;
}).length > 0;
if ( ! embedInUse ) {
$(this).parent().remove();
}
});
container.find('.mainMediaContainer').on('focus.generic', function() {
onMainstageFocus();
});
container.find('.return-to-content').on('click', function() {
somehowLeaveMainstage();
});
setMapControlsColor();
};
function useParentOriginUrl(embedInfo, embedUrl) {
return embedInfo && embedInfo.useParentOrigin && window.location.origin.match(/arcgis\.com/) &&
embedUrl && embedUrl.match && embedUrl.match(/arcgis\.com/);
}
function getParentOriginUrl(storedUrl) {
var urlAsURL = new window.URL(storedUrl);
return window.location.origin + urlAsURL.pathname + urlAsURL.search;
}
//
// Management of Main Stage: all media
//
this.beforeMainMediaUpdate = function(index)
{
var section = app.data.getStoryByIndex(index);
if ( section && section.media && section.media.type == 'webmap' ) {
var webmapId = section.media.webmap.id;
if (app.maps[webmapId]) {
var map = app.maps[webmapId].response.map;
var locLayer = map.getLayer("MJActionsLocate");
if (locLayer) {
map.removeLayer(locLayer);
}
}
}
};
this.updateMainMediaWithStoryMainMedia = function(index)
{
var section = app.data.getStoryByIndex(index);
if ( section && section.media )
updateMainMedia(section.media, section, index);
topic.publish("story-load-section", index);
};
this.updateMainMediaWithStoryAction = function(media)
{
updateMainMedia(media, app.data.getCurrentSection(), null);
};
function updateMainMedia(media, section, index)
{
// Refresh any iframe that would be the current Main Stage Media
// If it's a video player this will stop current video playback
var activeFrame = $(".mainMediaContainer.active > iframe[data-unload=true]");
if ( activeFrame.length ) {
activeFrame.attr('src', '');
}
// Fade out active container
$(".mainMediaContainer.active").fadeOut();
// Stop loading Indicator if running
// From now only the Map has a loading indicator
stopMainStageLoadingIndicator();
if ( media.type == "webmap" )
updateMainMediaMaps(media.webmap.id, section, index, media);
else if ( media.type == "image" )
updateMainMediaPicture(media.image);
else if ( media.type == "video" )
updateMainMediaEmbed(media.video.url, media.video);
else if ( media.type == "webpage" ){
var embedUrl = media.webpage.url;
if ( embedUrl.lastIndexOf('#') > 0 )
embedUrl = embedUrl.substring(0, embedUrl.lastIndexOf('#'));
updateMainMediaEmbed(embedUrl || media.webpage.ts, media.webpage);
}
}
function startMainStageLoadingIndicator()
{
$('#mainStageLoadingIndicator').fadeIn();
}
function stopMainStageLoadingIndicator()
{
$('#mainStageLoadingIndicator').fadeOut();
}
//
// Layout
//
this.updateMainStageWithLayoutSettings = function()
{
var appLayout = WebApplicationData.getLayoutId(),
appColors = app.data.getWebAppData().getColors(),
layoutCfg = WebApplicationData.getLayoutCfg(),
bodyWidth = $("body").width();
// Resize embed that are have display fit
styleMainStageEmbed();
container.css("background-color", appColors.media);
setMapControlsColor();
if ( appLayout == "float" ) {
var mapWidth = $("#contentPanel").width(),
panelPos = $("#floatingPanel").position(),
panelWidth = $("#floatingPanel").width(),
isLeft = layoutCfg.position == "left",
mapArea = isLeft ? mapWidth - (panelPos.left + panelWidth) : panelPos.left;
// Attribution
if ( isLeft )
$(".mainMediaContainer.active .esriControlsBR").css({
left: panelPos.left + panelWidth + 5,
right: 'inherit'
});
else
$(".mainMediaContainer.active .esriControlsBR").css({
left: 'inherit',
right: mapWidth - panelPos.left + 5
});
// Map configuration, loading indicator and error
if ( isLeft )
$(".mapConfigOverlay.position, .mapConfigOverlay.popup, #mainStageLoadingIndicator, .mainStageErrorContainer").css("left", panelPos.left + panelWidth + mapArea / 2);
else
$(".mapConfigOverlay.position, .mapConfigOverlay.popup, #mainStageLoadingIndicator, .mainStageErrorContainer").css("left", mapArea / 2);
if ( $("body").hasClass("mobile-view") )
$("#mainStageLoadingIndicator, .mainStageErrorContainer").css("left", "50%");
//
// Center some components on the Main Stage space at the left or right of the panel
//
var panelIsRight = $("body").hasClass("layout-float-right"),
paddingDir = panelIsRight ? "padding-right" : "padding-left",
posDir = panelIsRight ? "right" : "left",
val = $("#floatingPanel").position().left;
if ( panelIsRight )
val = bodyWidth - val;
else
val += $("#floatingPanel").width();
// Help, builder landing"es
$(".centerAlignOnFloat").addClass('is-floating')
.css({ paddingRight: '', paddingLeft: '' })
.css(paddingDir, val);
// Back button
$(".mediaBackContainer")
.css({ left: 'inherit', right: 'inherit' })
.css(posDir, val + mapArea / 2);
// Help goes over the floating panel when screen too small
if ( bodyWidth <= 1067 )
$("#builderHelp").css(paddingDir, 0);
// Main Stage Images that are centered
$(".mainMediaContainer .imgContainer.center")
.css({ left: 0, right: 0 })
.css(posDir, val);
// Main Stage video&embed that are centered
$(".mainMediaContainer .embedContainer.center")
.css({ left: 0, right: 0 })
.css(posDir, val);
// Main Stage video&embed that are custom
$(".mainMediaContainer .embedContainer.custom")
.css({ left: 0, right: 0 })
.css(posDir, val);
// Autoplay
$("#autoplay")
.css({ left: 'inherit', right: 'inherit' })
.css(posDir, val + mapArea / 2);
}
// Side Panel
else {
// Attribution
$(".mainMediaContainer.active .esriControlsBR").css({
left: "",
right: ""
});
// Map configuration, loading indicator and error
$(".mapConfigOverlay.position, .mapConfigOverlay.popup, #mainStageLoadingIndicator, .mainStageErrorContainer").css("left", "50%");
// Reset centering that may have been done if user has changed layouts
$(".centerAlignOnFloat").removeClass('is-floating').css({ paddingRight: '', paddingLeft: '' });
$('.mediaBackContainer').css({left: '50%', right: 'inherit'});
$(".mainMediaContainer .imgContainer.center").css({ left: 0, right: 0 });
$(".mainMediaContainer .embedContainer.center").css({ left: 0, right: 0 });
$(".mainMediaContainer .embedContainer.custom").css({ left: 0, right: 0 });
$("#autoplay").css({ left: '50%', right: 'inherit' });
}
};
//
// Management of Main Stage: map
//
// TODO params of the next two function has to be cleanedup
function updateMainMediaMaps(newWebmapId, section, index, media)
{
//var currentWebmapId = $('.mapContainer:visible').data('webmapid');
var mapContainer = $('.mapContainer[data-webmapid="' + newWebmapId + '"]');
// If map is already loading - let's wait
if ( mapContainer.hasClass('isLoading') ) {
return;
}
$('.mainMediaContainer').removeClass("active has-error");
mapContainer.parent().addClass("active");
if ( newWebmapId ) {
// The map has already been loaded
if ( mapContainer.hasClass('map') ) {
var extentBeforeUpdate = app.map ? app.map.extent : null;
app.map = app.maps[newWebmapId].response.map;
app.mapItem = app.maps[newWebmapId].response.itemInfo;
app.mapConfig = app.maps[newWebmapId];
updateMainMediaMapsStep2(
mapContainer,
section,
extentBeforeUpdate,
index,
media,
true
);
}
// Need to load the map
else {
mapContainer.addClass('isLoading');
startMainStageLoadingIndicator();
// Get the extent to be used to load the webmap
var extent = media && media.webmap ? media.webmap.extent : null;
if ( extent ) {
try {
extent = new Extent(extent);
} catch (e) {
extent = null;
}
}
mainView.loadWebmap(newWebmapId, mapContainer[0], extent).then(
lang.hitch(_this, function(response){
var extentBeforeUpdate = app.map ? app.map.extent : null;
app.maps[newWebmapId] = mainView.getMapConfig(response, mapContainer);
app.map = response.map;
app.mapItem = app.maps[newWebmapId].response.itemInfo;
app.mapConfig = app.maps[newWebmapId];
// Popup
if ( app.map.infoWindow ) {
$(app.map.infoWindow.domNode).addClass("light");
app.map.infoWindow.markerSymbol = new SimpleMarkerSymbol().setSize(0);
}
updateMainMediaMapsStep2(
mapContainer,
section,
extentBeforeUpdate,
index,
media,
false
);
//
// Register events for the builder
// because we need to know for Map Configuration what is the intended extent
// before the zoom when there is lods (the resulting extent will always be different)
//
if ( isInBuilder ) {
// can't use update-end as it's not correct value for setExtent when lods
app.ignoreNextEvent = false;
aspect.before(app.map, "setExtent", function(extent) {
console.log("Set extent:", extent);
if ( ! app.ignoreNextEvent ) {
app.lastExtentSet = extent;
// A pan or zoom will also be triggered
app.ignoreNextEvent = true;
}
});
var handle = app.map.on("update-end", function(){
handle.remove();
app.lastExtentSet = app.map.extent;
// store the initial extent in a new property
// TODO is that necessary? to not mess with browser resize and init map extent?
//app.map._params.extent = app.map.extent;
app.map.mapJournalInitExtent = app.map.extent;
app.ignoreNextEvent = true;
});
var onPanOrZoomEnd = function(e)
{
if ( ! app.ignoreNextEvent )
app.lastExtentSet = e.extent;
else
app.ignoreNextEvent = false;
};
app.map.on("zoom-end", onPanOrZoomEnd);
app.map.on("pan-end", onPanOrZoomEnd);
}
/*
var handle = app.map.on("update-end", function(){
handle.remove();
stopMainStageLoadingIndicator();
});
*/
setTimeout(function(){
stopMainStageLoadingIndicator();
}, 50);
mapContainer.removeClass('isLoading');
mapContainer.parent().removeClass("has-error");
}),
lang.hitch(_this, function(){
stopMainStageLoadingIndicator();
mapContainer.removeClass('isLoading');
mapContainer.parent().addClass("has-error");
mapContainer.parent().find('.error').html(i18n.viewer.errors.mapLoadingFail);
topic.publish("story-loaded-map", {
id: newWebmapId,
index: index
});
topic.publish("ADDEDIT_LOAD_WEBMAP_FAIL");
})
);
// Publish an early loaded after two second in case the map is slow to load
setTimeout(function(){
topic.publish("story-section-map-timeout");
}, 2000);
}
}
}
function updateMainMediaMapsStep2(mapContainer, section, oldExtent, index, media, notFirstLoad)
{
_this.updateMainStageWithLayoutSettings();
setMapControlsColor();
var mainStage = mapContainer.parent();
if (mainStage[0] === document.activeElement) {
onMapMainstageFocus();
} else {
mainStage.off('focus.map').on('focus.map', onMapMainstageFocus);
}
//app.data.debug();
// if( WebApplicationData.getLayoutId() == "float" )
// app.map.disableKeyboardNavigation();
// else
// app.map.enableKeyboardNavigation();
try {
app.map.resize();
app.map.reposition();
} catch(e) { }
// If this is a story section
if ( section || media ) {
//
// Layers
//
// - Array of {id:'', visible:''} for the overrided layers (compared to the webmap initial state)
// - Only overrided layers are present there to allow the webmap to evolve outside of the app
// - If default visibility of layers are changed outside of the app, all view that didn't override the value will see the change
// - if the webmap evolve the array may reference deleted layers. That's cleaned anytime user open the Configure map View and Save
var layerCfg = media && media.webmap ? media.webmap.layers : null,
mapDefault = app.maps[media.webmap.id].response.itemInfo.itemData.operationalLayers;
// Loop through webmap layers and set the visibility
// The visibility is set to the section definition when defined or to the webmap initial visibility
$.each(mapDefault, function(i, layer){
var override;
if ( layer.layerObject) {
override = $(layerCfg).filter(function(i, l){ return l.id == layer.layerObject.id; });
// necessary because 4x mapviewer doesn't return parent layer visibility by default :/
var layerViz = layer.visibility === undefined ? true : layer.visibility;
var updateVisibility = function()
{
layer.layerObject.setVisibility(override.length ? override[0].visibility : layerViz);
};
if ( layer.layerObject.loaded )
updateVisibility();
else {
layer.layerObject.on("load", updateVisibility);
}
}
else if ( layer.featureCollection && layer.featureCollection.layers ) {
$.each(layer.featureCollection.layers, function(i, fcLayer){
override = $(layerCfg).filter(function(i, l){
// Because the configuration store the map layerObject id like "mapNotes_914_0" instead of "mapNotes_914"
// Should change that and keep V1.0 compatibility
return l.id.split('_').slice(0,-1).join('_') == fcLayer.layerObject.id.split('_').slice(0,-1).join('_');
});
var fcLayerViz = fcLayer.visibility === undefined ? true : fcLayer.visibility;
fcLayer.layerObject.setVisibility(override.length ? override[0].visibility : fcLayerViz);
});
}
});
//
// Extent
//
var extent = media && media.webmap ? media.webmap.extent : null;
if ( extent ) {
try {
extent = new Extent(extent);
} catch (e){
//
}
}
// Get back to the home section and section is configured to web map default
if ( ! extent && notFirstLoad && index === 0 ) {
extent = app.map._params.extent;
}
if ( extent ) {
var currentMap = app.maps[media.webmap.id];
if (currentMap && currentMap.mapCommand) {
currentMap.mapCommand.currentHomeExtent = extent;
}
app.map.setExtent(extent/*, true*/).then(function(){
applyPopupConfiguration(media.webmap.popup, index);
topic.publish("story-loaded-map", {
id: media.webmap.id,
index: index
});
}); // TODO has at least to use _core.setExtent
}
else
topic.publish("story-loaded-map", {
id: media.webmap.id,
index: index
});
/*
// Reuse the current extent
else if( oldExtent )
app.map.setExtent(oldExtent);
*/
//
// Map Controls
//
var overviewSettings = media.webmap.overview || {},
legendSettings = media.webmap.legend || {},
geocoderSettings = media.webmap.geocoder || {};
// If it's a Main Stage Action, look to use the section Main Stage media
// configuration IF it's a webmap
if ( index === null && section.media && section.media.webmap ) {
overviewSettings = section.media.webmap.overview || {},
legendSettings = section.media.webmap.legend || {};
}
if ( overviewSettings.enable !== undefined ) {
app.maps[media.webmap.id].overview.toggle(overviewSettings.enable, WebApplicationData.getColors());
app.maps[media.webmap.id].overview.toggleExpanded(overviewSettings.openByDefault);
app.maps[media.webmap.id].overview.setSettings(overviewSettings);
}
if ( legendSettings.enable !== undefined ) {
app.maps[media.webmap.id].legend.toggle(legendSettings.enable);
app.maps[media.webmap.id].legend.toggleExpanded(legendSettings.openByDefault);
app.maps[media.webmap.id].legend.setSettings(legendSettings);
}
if ( geocoderSettings.enable !== undefined ) {
app.maps[media.webmap.id].geocoder.toggle(geocoderSettings.enable);
}
/* */
//
// Popup
//
if ( ! extent ) {
applyPopupConfiguration(media.webmap.popup, index);
// Otherwise called through extent change callback
}
/* alt text
* needs to change dynamically because we reuse map containers
*/
var altText = media && media.webmap ? media.webmap.altText : null;
if (altText && mainStage) {
mainStage.attr('aria-label', altText);
}
}
else {
topic.publish("ADDEDIT_WEBMAP_DONE");
}
}
function applyPopupConfiguration(popupCfg, index)
{
// When an action is performed the popup will be closed
// But features aren't cleared so it can be restored
app.map.infoWindow.hide();
if ( popupCfg ) {
var layer = app.map.getLayer(popupCfg.layerId),
// TODO some MapService layer seems to require this
// need to investigate more to make sure there is no other way
// also if the popup contains multiple features, only the first feature will be displayed
serviceId = popupCfg.layerId ? popupCfg.layerId.split('_').slice(0, -1).join('_') : '',
layer2 = app.map.getLayer(serviceId);
app.map.infoWindow.clearFeatures();
if ( layer ) {
if (layer.updating) {
var eventListener = layer.on('update-end', function() {
eventListener.remove();
applyPopupConfigurationStep2(popupCfg, index);
});
} else {
applyPopupConfigurationStep2(popupCfg, index);
}
}
// TODO
else if ( layer2 ) {
var layerIdx = popupCfg.layerId.split('_').slice(-1).join('_'),
layerUrl = layer2.url + '/' + layerIdx;
var w; // walker
if ((w = layer2) && (w = w.infoTemplates) && (w = w[layerIdx]) && (w = w.layerUrl)) {
layerUrl = w;
}
applyPopupConfigurationStep2Alt(popupCfg, index, serviceId, layerIdx, layerUrl);
}
// On FS the layer will be null until loaded...
else
var handle = app.map.on("update-end", function(){
applyPopupConfiguration(popupCfg, index);
handle.remove();
});
}
}
function applyPopupConfigurationStep2(popupCfg, index)
{
var query = new Query(),
layer = app.map.getLayer(popupCfg.layerId);
if ( ! layer )
return;
query.objectIds = [popupCfg.fieldValue];
// Feature Service
if (!layer._collection) {
query.returnGeometry = true;
query.outFields = ["*"]; // popupCfg.fieldName ?
query.outSpatialReference = app.map.spatialReference;
}
// TODO: Image Services
if ( ! layer.queryFeatures ) {
return;
}
layer.queryFeatures(query).then(function(featureSet) {
applyPopupConfigurationStep3(popupCfg, featureSet.features, index);
});
}
// TODO
function applyPopupConfigurationStep2Alt(popupCfg, index, serviceId, layerIdx, layerUrl)
{
var queryTask = new QueryTask(layerUrl),
query = new Query(),
layer = app.map.getLayer(serviceId);
if ( ! layer )
return;
query.objectIds = [popupCfg.fieldValue];
query.returnGeometry = true;
query.outFields = ["*"]; // popupCfg.fieldName ?
query.outSpatialReference = app.map.spatialReference;
queryTask.execute(query, function(featureSet) {
applyPopupConfigurationStep3(popupCfg, featureSet.features, index, serviceId, layerIdx);
});
}
function applyPopupConfigurationStep3(popupCfg, features, index, serviceId, layerIdx)
{
if ( ! features || ! features.length )
return;
var geom = features[0].geometry,
center = null;
if ( popupCfg.anchorPoint )
center = new Point(popupCfg.anchorPoint);
else
center = geom.getExtent() ? geom.getExtent().getCenter() : geom;
// TODO
if ( serviceId ) {
features[0].infoTemplate = app.map.getLayer(serviceId).infoTemplates[layerIdx].infoTemplate;
app.map.infoWindow.setContent(features[0].getContent());
}
else {
app.map.infoWindow.setFeatures(features);
}
app.map.infoWindow.show(center);
// Center the map is the geometry isn't visible
if ( ! app.map.extent.contains(center) ) {
app.map.centerAt(center);
/*
// Show back btn only if it's a Main Stage action
if ( index === null ) {
$('.mediaBackContainer')
.show()
.css("marginLeft", - $(".mediaBackContainer .backButton").outerWidth() / 2)
.css("marginRight", - $(".mediaBackContainer .backButton").outerWidth() / 2);
}
*/
}
/*
else if ( index === null ) {
$('.mediaBackContainer')
.show()
.css("marginLeft", - $(".mediaBackContainer .backButton").outerWidth() / 2)
.css("marginRight", - $(".mediaBackContainer .backButton").outerWidth() / 2);
}
*/
}
function setMapControlsColor()
{
if ( app.mapConfig ) {
var appColors = app.data.getWebAppData().getColors();
app.mapConfig.overview.setColors(appColors);
app.mapConfig.legend.setColors(appColors);
}
}
// Builder events
this.showWebmapById = function(webmapId)
{
updateMainMediaMaps(webmapId, null, null, null);
};
this.reloadCurrentWebmap = function()
{
var currentSection = app.data.getCurrentSection();
if ( currentSection && currentSection.media && currentSection.media.webmap ) {
var webmapId = currentSection.media.webmap.id,
mapContainer = $('.mapContainer[data-webmapid="' + webmapId + '"]');
mapContainer.parent().remove();
if ( app.maps[webmapId] ) {
app.maps[webmapId].response.map.destroy();
delete app.maps[webmapId];
}
$("#mainStagePanel .medias").append(
mainMediaContainerMapTpl({
webmapid: webmapId,
isTemporary: false,
altText: currentSection.media.webmap.altText || '',
focusToPanel: i18n.viewer.a11y.focusContent
})
);
topic.publish("story-navigate-section", app.data.getCurrentSectionIndex());
}
};
this.loadTmpWebmap = function(webmapId)
{
if ( ! $('.mapContainer[data-webmapid="' + webmapId + '"]').length )
addTemporaryMainMediaContainer(webmapId);
updateMainMediaMaps(webmapId, null, null, null);
};
//
// Management of Main Stage: picture
//
function updateMainMediaPicture(image)
{
$('.mainMediaContainer').removeClass('active');
var pictureContainer = $('.imgContainer[data-src="' + image.url + '"]');
if ( pictureContainer.length ) {
// If image hasn't been loaded, display loading indicator
if ( pictureContainer.css('background-image') == 'none' ) {
startMainStageLoadingIndicator();
}
var sizedUrl = image.url;
if (image.sizes) {
var sorted = _.sortBy(image.sizes, 'width').reverse();
sizedUrl = sorted[0].url;
if (sorted.length > 1) {
var compareWidth = image.display && image.display === 'fit' ? $('#mainStagePanel').width() : $('body').width();
_.some(sorted, function(fileObj) {
if (fileObj.width && fileObj.width < compareWidth) {
return true;
}
sizedUrl = fileObj.url;
return false;
});
}
}
pictureContainer.parent().addClass('active')
.attr('aria-label', image.altText);
var tokenizedUrl = Helper.possiblyAddToken(sizedUrl);
// Load a hidden image in JS
var tmpImg = new Image();
tmpImg.src = tokenizedUrl;
tmpImg.onload = function() {
// Display the image through CSS background, thanks to browser cache no reload is needed
pictureContainer
.removeClass("center fit fill stretch")
.addClass(image.display)
.css({
left: 0,
right: 0
})
.css('background-image', 'url("' + tokenizedUrl + '")');
_this.updateMainStageWithLayoutSettings();
// If the section is still active, stop the loading indicator
// after a little delay to accomodate heavy image that takes a while to display
if ( pictureContainer.parent().hasClass('active') ) {
setTimeout(stopMainStageLoadingIndicator(), 100);
}
};
}
}
//
// Management of Main Stage: embed (video and webpage)
//
function updateMainMediaEmbed(url, cfg)
{
if (useParentOriginUrl(cfg, url)) {