forked from mviewer/mviewerstudio
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmviewerstudio.js
1444 lines (1336 loc) · 47 KB
/
mviewerstudio.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 _conf;
var API = {};
var mviewer = {};
$(document).ready(function () {
//Get URL Parameters
if (window.location.search) {
$.extend(
API,
$.parseJSON(
'{"' +
decodeURIComponent(
window.location.search.substring(1).replace(/&/g, '","').replace(/=/g, '":"')
) +
'"}'
)
);
}
fetch("apps/config.json", {
method: "GET",
header: {
contentType: "application/json",
},
})
.then((r) => r.json())
.then((data) => {
//Mviewer Studio version
// console.groupCollapsed("init app from config");
_conf = data.app_conf;
const VERSION = _conf.mviewerstudio_version;
document.querySelector("#creditInfo").innerHTML =
`MviewerStudio | Licence GPL-3.0 | Version ${VERSION}`;
let mvCompliantInfo = document.querySelector("#mviewerCompliantInfo");
mvCompliantInfo.innerHTML = `${mvCompliantInfo.innerHTML} ${_conf.mviewer_version}`;
if (_conf.logout_url) {
$("#menu_user_logout a").attr("href", _conf.logout_url);
}
// Update web page title and title in the brand navbar
document.title = _conf.studio_title;
$("#studio-title").text(_conf.studio_title);
// Base layers
mv.showBaseLayers(_conf.baselayers, "default-bl");
// Sélection par défaut des 2 1er baselayers
$("#frm-bl .bl input").slice(0, 2).prop("checked", true).trigger("change");
$("#frm-bl-visible").val($("#frm-bl-visible option:not(:disabled)").first().val());
// Map extent
map2.getView().setCenter(_conf.map.center);
map2.getView().setZoom(_conf.map.zoom);
// Form placeholders
$("#opt-title").attr("placeholder", _conf.app_form_placeholders.app_title);
$("#opt-logo").attr("placeholder", _conf.app_form_placeholders.logo_url);
$("#opt-help").attr("placeholder", _conf.app_form_placeholders.help_file);
// translate
_initTranslate();
var csw_providers = [];
var wms_providers = [];
if (
_conf.external_themes &&
_conf.external_themes.used &&
_conf.external_themes.url
) {
$.ajax({
type: "GET",
url: _conf.external_themes.url,
success: function (csv) {
_conf.external_themes.data = Papa.parse(csv, {
header: true,
}).data;
mv.getThemeTable(_conf.external_themes.data);
},
});
} else {
$("#btn-importTheme").remove();
}
nb_providers = 0;
if (_conf.data_providers && _conf.data_providers.csw) {
_conf.data_providers.csw.forEach(function (provider, id) {
var cls = "active";
if (nb_providers > 0) {
cls = "";
}
csw_provider_html = '<li class="' + cls + '">';
csw_provider_html +=
'<a onclick="setActiveProvider(this);" href="#" class="dropdown-item"';
csw_provider_html +=
' data-providertype="csw" data-provider="' + provider.url + '"';
if (provider.baseref) {
csw_provider_html += ' data-metadata-app="' + provider.baseref + '"';
}
csw_provider_html += ">" + provider.title + "</a></li>";
csw_providers.push(csw_provider_html);
nb_providers++;
});
$("#providers_list").append(csw_providers.join(" "));
if (_conf.data_providers.csw.length > 0) {
$("#providers_list").append('<li role="separator" class="divider"></li>');
}
}
if (_conf.data_providers && _conf.data_providers.wms) {
_conf.data_providers.wms.forEach(function (provider, id) {
var cls = "active";
if (nb_providers > 0) {
cls = "";
}
wms_providers.push(
'<li class="' +
cls +
'">' +
'<a onclick="setActiveProvider(this);" data-providertype="wms" class="dropdown-item"' +
' data-provider="' +
provider.url +
'" href="#">' +
provider.title +
"</a></li>"
);
nb_providers++;
});
$("#providers_list").append(wms_providers.join(" "));
if (_conf.data_providers.wms.length > 0) {
$("#providers_list").append('<li role="separator" class="divider"></li>');
}
}
if (API.xml) {
loadApplicationParametersFromRemoteFile(API.xml);
} else if (API.wmc) {
loadApplicationParametersFromWMC(API.wmc);
} else {
newConfiguration();
}
updateProviderSearchButtonState();
// Default params for layers
if (_conf.default_params && _conf.default_params.layer) {
mv.setDefaultLayerProperties(_conf.default_params.layer);
}
// Get user info
getUser();
})
.catch((err) => {
console.log(err);
alertCustom(mviewer.tr("msg.config_load_error"), "danger");
});
});
//EPSG:2154
proj4.defs(
"EPSG:2154",
"+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
);
ol.proj.proj4.register(proj4);
//Map
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
],
target: "map",
});
var savedParameters;
//Map_filter
var draw;
var source = new ol.source.Vector({ wrapX: false });
var vector = new ol.layer.Vector({
source: source,
});
var map2 = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
vector,
],
target: "map_filter",
});
var config;
const getUser = () => {
if (!_conf.user_info) return;
fetch(_conf.user_info, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((r) => (r.ok ? r.json() : Promise.reject(r)))
.then((data) => {
var userGroupFullName = "";
var userGroupSlugName = "";
var selectGroupPopup = false;
if (data) {
if (data.organisation && data.organisation.legal_name) {
userGroupFullName = data.organisation.legal_name;
} else if (data && data.user_groups) {
if (data.user_groups.length > 1) {
selectGroupPopup = true;
} else {
userGroupFullName = data.user_groups[0].full_name;
userGroupSlugName = data.user_groups[0].slug_name;
}
}
if (selectGroupPopup) {
mv.updateUserGroupList(data);
$("#mod-groupselection").modal({
backdrop: "static",
keyboard: false,
});
} else {
mv.updateUserInfo({
userName: data.user_name,
name: `${data.first_name} ${data.last_name}`,
groupSlugName: userGroupSlugName || data.normalize_name,
groupFullName: userGroupFullName,
});
}
if (_conf.user_info_visible && data.user_name != "anonymous") {
let connectText = `Connecté en tant que ${data.first_name} ${data.last_name} (${userGroupFullName})`;
$("#user_connected").text(connectText);
document.querySelector("#user_connected").classList.remove("d-none");
document.querySelector("#menu_user_logout").classList.remove("d-none");
}
}
})
.catch((err) => alertCustom(mviewer.tr("msg.user_info_retrieval_error"), "danger"));
};
var newConfiguration = function (infos) {
[
"opt-title",
"opt-logo",
"optProxyUrl",
"opt-favicon",
"opt-help",
"opt-home",
"theme-edit-icon",
"theme-edit-title",
].forEach(function (param, id) {
$("#" + param).val("");
});
$("#optProxyUrl").val(_conf?.proxy);
// default checked state
[
"opt-exportpng",
"opt-zoomtools",
"opt-geoloc",
"opt-mouseposition",
"opt-studio",
"opt-measuretools",
"opt-initialextenttool",
"opt-mini",
"opt-showhelp",
"opt-coordinates",
"opt-togglealllayersfromtheme",
"SwitchCustomBackground",
"SwitchAdvanced",
].forEach((id) => {
document.querySelector(`#${id}`).checked = false;
});
["opt-zoomtools", "opt-measuretools", "opt-initialextenttool"].forEach((id) => {
document.querySelector(`#${id}`).checked = true;
});
$("#opt-style").val("css/themes/default.css").trigger("change");
$("#frm-searchlocalities").val("ban").trigger("change");
$("#FadvElasticBlock form").trigger("reset");
// Icon help
var icon = "fas fa-home";
$("#opt-iconhelp").val(icon);
$("#opt-iconhelp").siblings(".selected-icon").attr("class", "selected-icon");
$("#opt-iconhelp").siblings(".selected-icon").addClass(icon);
map.getView().setCenter(_conf.map.center);
map.getView().setZoom(_conf.map.zoom);
const newDate = moment();
config = {
application: { title: "", logo: "" },
themes: {},
date: infos?.date || newDate.toISOString(),
temp: { layers: {} },
id: infos?.id || mv.uuid(),
description: infos?.description || newDate.format("DD-MM-YYYY-HH-mm-ss"),
isFile: !!infos?.id,
relation: infos?.relation,
};
//Store des parametres non gérés
savedParameters = { application: [], baselayers: {} };
$("#themes-list, #liste_applications, #distinct_values")
.find(".list-group-item")
.remove();
$("#frm-bl .custom-bl").remove();
$("#nameAppBlock").empty();
// Gestion des accordéons
["collapseHomePage", "collapseFondPlan", "collapseElasticSearch"].forEach(
function (param) {
$("#" + param).collapse("hide");
}
);
// Gestion des fonds de plan
$("#frm-bl .bl input").prop("checked", false).trigger("change");
$("#frm-bl .bl input").slice(0, 2).prop("checked", true).trigger("change");
$("#frm-bl-mode").val("default").trigger("change");
$("#frm-bl-visible").val($("#frm-bl-visible option:not(:disabled)").first().val());
//Init advanced options
$(".advanced").css("display", "none");
// Init du wizard
$("#stepStudio").find(".nav-item a:first").tab("show");
$("#navWizFadv").css("display", "none");
};
var loadLayers = function (themeid) {
var theme = config.themes[themeid];
if (theme) {
$.each(theme.layers, function (index, layer) {
addLayer(layer.title, layer.id, layer.index);
});
}
};
var deleteThemeItem = function (btn) {
var el = $(btn).closest(".list-group-item")[0];
var themeid = $(el).attr("data-themeid");
deleteTheme(themeid);
el && el.parentNode.removeChild(el);
};
var deleteLayerItem = function (btn, themeid) {
var el = $(btn).closest(".layers-list-item")[0];
deleteLayer(el.getAttribute("data-layerid"), themeid);
el && el.parentNode.removeChild(el);
};
var sortableThemeList = Sortable.create(document.getElementById("themes-list"), {
handle: ".moveList",
animation: 150,
ghostClass: "ghost",
onEnd: function (evt) {
sortThemes();
},
});
sortThemes = function () {
var orderedThemes = {};
$(".themes-list-item").each(function (i, item) {
var id = $(this).attr("data-themeid");
orderedThemes[id] = config.themes[id];
});
config.themes = orderedThemes;
};
setConf = (key, value) => {
_conf[key] = value;
};
getConf = (key) => _conf[key];
sortLayers = function (fromIndex, toIndex) {
var themeid = mv.getCurrentThemeId();
var arr = config.themes[themeid].layers;
var element = arr[fromIndex];
arr.splice(fromIndex, 1);
arr.splice(toIndex, 0, element);
};
$("input[type=file]").change(function () {
loadApplicationParametersFromFile();
});
var addLayer = function (title, layerid, themeid) {
// test if theme is saved
if (!config.themes[themeid]) {
saveThemes();
}
var item = $(`#themeLayers-${themeid}`).append(`
<div class="list-group-item layers-list-item" data-layerid="${layerid}">
<span class="layer-name moveList">${title}</span>
<div class="layer-options-btn" style="display:inline-flex; justify-content: end;">
<button class="btn btn-sm btn-secondary" onclick={mv.setCurrentThemeId("${themeid}");}><span class="layer-move moveList" i18n="move" title="Déplacer"><i class="bi bi-arrows-move"></i></span></button>
<button class="btn btn-sm btn-secondary deleteLayerButton" onclick="deleteLayerItem(this, '${themeid}');"><span class="layer-remove" i18n="delete" title="Supprimer"><i class="bi bi-x-circle"></i></span></button>
<button class="btn btn-sm btn-info" onclick="editLayer(this, '${themeid}', '${layerid}');"><span class="layer-edit" i18n="edit_layer" title="Editer cette couche"><i class="bi bi-gear-fill"></i></span></button>
</div>
</div>`);
};
var editLayer = function (item, themeid, layerid) {
mv.setCurrentThemeId(themeid);
mv.setCurrentLayerId(layerid);
var element = $(item).parent().parent();
var layerid = element.attr("data-layerid");
element.addClass("active");
if (layerid != "undefined") {
$("#mod-layerOptions").modal("show");
mv.showLayerOptions(element, themeid, layerid);
} else {
$("#input-ogc-filter").val("");
$("#csw-results .csw-result").remove();
$("#mod-layerNew").modal("show");
}
};
var importThemes = function () {
console.groupCollapsed("importThemes");
//console.log("external theme to import", _conf.external_themes.data);
$("#tableThemaExt .selected").each(function (id, item) {
var url = $(item).attr("data-url");
var id = $(item).attr("data-theme-id");
var label = $(item).attr("data-theme-label");
addTheme(label, true, id, false, url, "default");
});
$("#mod-themesview").modal("hide");
};
var sortableElement = function (targetId, callback) {
Sortable.create(document.getElementById(targetId), {
handle: ".moveList",
animation: 150,
ghostClass: "ghost",
onEnd: function (evt) {
callback(evt);
},
});
};
sortableElement("themes-list", sortThemes);
var addTheme = function (title, collapsed, themeid, icon, url, layersvisibility) {
if (url) {
//external theme
$("#themes-list").append(`
<div class="list-group-item list-group-item themes-list-item" data-theme-url="${url}" data-theme="${title}" data-themeid="${themeid}" data-theme-collapsed="${collapsed}" data-theme-icon="${icon}" data-theme-layersvisibility="${layersvisibility}">
<div class="theme-infos">
<span class="theme-name moveList" contentEditable="true">${title}</span><span class="theme-infos-layer">Ext.</span>
</div>
<div class="theme-options-btn">
<button class="btn btn-sm btn-secondary" ><span class="theme-move moveList" id18="move" title="Déplacer"><i class="bi bi-arrows-move"></i></span></button>
<button class="btn btn-sm btn-secondary" onclick="deleteThemeItem(this);" ><span class="theme-remove" id18="delete" title="Supprimer"><i class="bi bi-x-circle"></i></span></button>
<button class="btn btn-sm btn-info" onclick="editThemeExt(this);"><span class="theme-edit" id18="edit_layer" title="Editer ce thème"><i class="bi bi-gear-fill"></i></span></button>
</div>
</div>`);
} else {
$("#themes-list").append(
`<div class="list-group-item themes-list-item" id="${themeid}" data-theme="${title}" data-themeid="${themeid}" data-theme-collapsed="${collapsed}" data-theme-icon="${icon}">
<div class="theme-infos ">
<span type="button" class="selected-icon ${icon} picker-button" data-bs-target="#iconPicker" data-bs-toggle="modal"></span>
<input type="text" class="theme-name" value="${title}" aria-label="title">
<span class="theme-infos-layer">0</span>
<div class="custom-control custom-switch m-2">
<input type="checkbox" class="custom-control-input" id="${themeid}-theme-edit-collapsed" ${collapsed === "false" ? "checked" : ""}>
<label class="custom-control-label" for="${themeid}-theme-edit-collapsed"><span i18n="modal.theme.paramspanel.opt_unfolded">Déroulée par défaut</span></label>
</div>
</div>
<div class="theme-options-btn text-right">
<button onclick={mv.setCurrentThemeId("${themeid}");} class="btn btn-sm btn-outline-info" id="btn-addLayer-${themeid}" data-bs-target="#mod-layerNew" data-themeid="${themeid}" data-bs-toggle="modal"><i class="bi bi-plus-lg"></i> Ajouter une donnée</button>
<button class="btn btn-sm btn-secondary"><span class="theme-move moveList" title="Déplacer"><i class="bi bi-arrows-move"></i></span></button>
<button class="btn btn-sm btn-secondary" onclick="deleteThemeItem(this);" ><span class="theme-remove" title="Supprimer"><i class="bi bi-x-circle"></i></span></button>
</div>
<div id="themeLayers-${themeid}" class="theme-layer-list list-group mt-3 mb-2"></div>
</div>`
);
sortableElement("themeLayers-" + themeid, sortLayers);
}
config.themes[themeid] = {
title: title,
id: themeid,
icon: icon,
collapsed: collapsed,
layersvisibility: layersvisibility,
url: url,
layers: [],
};
};
// Only one checkbox "collapsed" checked
$("#themes-list").on("change", ".custom-control-input", function () {
if ($(this).is(":checked")) {
$("#themes-list .custom-control-input").not(this).prop("checked", false);
}
});
document
.getElementById("mod-layerNew")
.addEventListener("show.bs.modal", function (event) {
// `event.relatedTarget` est l'élément déclencheur (le bouton)
const button = event.relatedTarget;
const themeId = button.getAttribute("data-themeid");
const selectLayersButton = document.getElementById("selectLayersButton");
selectLayersButton.setAttribute("data-themeid", themeId);
});
// Update layers counter
$("#mod-layerNew").on("click", "#selectLayersButton", function () {
const themeId = mv.getCurrentThemeId();
const th = $(`div[data-themeid="${themeId}"]`);
var nb_layers = $(`#${themeId} .theme-layer-list`).children(".list-group-item").length;
th.find(".theme-infos-layer").text(nb_layers);
});
// New save function to override old one to edit and save all the themes at the same time now.
var saveThemes = function () {
const themes = $(".themes-list-item");
for (i = 0; i < themes.length; i++) {
const theme = themes[i];
const themeid = theme.getAttribute("data-themeid");
const th = $(`div[data-themeid="${themeid}"]`);
const title = th.attr("data-theme-url")
? theme.getAttribute("data-theme")
: th.find(".theme-name").val();
const icon = th.attr("data-theme-icon");
const collapsed = !$(`#${themeid}-theme-edit-collapsed`).prop("checked");
config.themes[themeid].title = title;
config.themes[themeid].id = themeid;
config.themes[themeid].collapsed = collapsed;
config.themes[themeid].icon = icon;
}
};
var editThemeExt = function (item) {
$("#themes-list .list-group-item").removeClass("active");
$(item).parent().parent().addClass("active");
var themeid = $(item).parent().parent().attr("data-themeid");
$("#themeExt-edit").attr("data-themeid", themeid);
document.getElementById("nameThemeExt").innerHTML = "";
var title = $(item).parent().parent().attr("data-theme");
var titleBlock = document.getElementById("nameThemeExt");
titleBlock.append(title);
var layersvisibility = $(item).parent().parent().attr("data-theme-layersvisibility");
$("#themeext-layersvisibility").val(layersvisibility);
$("#mod-themeExtOptions").modal("show");
};
var saveThemeExt = function () {
//get active item in left panel
var theme = $("#themes-list .active");
//get edited values
var themeid = $("#themeExt-edit").attr("data-themeid");
var layersvisibility = $("#themeext-layersvisibility").val();
theme.attr("data-theme-layersvisibility", layersvisibility);
//save theme locally
config.themes[themeid].layersvisibility = layersvisibility;
//deactivate theme edition
$("#themes-list .list-group-item").removeClass("active");
$("#mod-themeExtOptions").modal("hide");
};
var deleteTheme = function (themeid) {
delete config.themes[themeid];
};
var deleteLayer = function (layerid, themeid) {
var index = config.themes[themeid].layers.findIndex(function (l) {
return l.id === layerid;
});
config.themes[themeid].layers.splice(index, 1);
};
var createId = function (obj) {
var d = new Date();
var df =
d.getFullYear() +
("0" + (d.getMonth() + 1)).slice(-2) +
("0" + d.getDate()).slice(-2) +
("0" + d.getHours()).slice(-2) +
("0" + d.getMinutes()).slice(-2) +
("0" + d.getSeconds()).slice(-2);
return obj + "-" + df;
};
var createBaseLayerDef = function (bsl) {
var parameters = "";
$.each(bsl, function (param, value) {
if (param === "attribution") {
value = mv.escapeXml(value);
}
parameters += param + '="' + value + '" ';
});
return parameters;
};
var deleteMyApplications = function () {
if (!_conf?.php?.delete_service) {
return alert(mviewer.tr("msg.config_error"));
}
$.ajax({
type: "GET",
url: _conf.php.delete_service,
success: function (data) {
alert(data.deleted_files + mviewer.tr("msg.deleted_apps"));
mv.getListeApplications();
},
error: function (xhr, ajaxOptions, thrownError) {
console.error("map files deletion failed", {
xhr: xhr,
ajaxOptions: ajaxOptions,
thrownError: thrownError,
});
alert(mviewer.tr("msg.delete_req_error"));
},
});
};
var deleteApplication = (id) => {
return fetch(`${_conf.api}/${id}`, {
method: "DELETE",
})
.then((r) => (r.ok ? r.json() : Promise.reject(r)))
.then((r) => r.success && showHome())
.then(alertCustom("Application supprimée avec succès !", "info"))
.catch((err) => alertCustom("Suppression impossible.", "danger"));
};
var showAlertDelApp = (id) => {
genericModalContent.innerHTML = "";
genericModalContent.innerHTML = `
<div class="modal-header">
<h5 class="modal-title" i18n="modal.exit.title">Attention</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p i18n="confirm.delete_app">
Êtes-vous sûr de vouloir supprimer votre application définitivement ?
</p>
<a class="cardsClose save-close zoomCard" data-bs-dismiss="modal" onclick="deleteApplication('${id}');">
<i class="ri-delete-bin-2-line"></i>
<span i18n="btn.delete_go_home">Supprimer mon application et retourner à l'accueil</span>
</a>
<a class="cardsClose notsave-close zoomCard" class="close" data-bs-dismiss="modal" aria-label="Close">
<i class="ri-arrow-go-back-line"></i>
<span i18n="cancel">Annuler</span>
</a>
<a class="returnConf-close" class="close" data-bs-dismiss="modal" aria-label="Close"><i class="ri-arrow-left-line"></i> <span i18n="modal.exit.previous">${mviewer.tr(
"delete.request.back"
)}</span></a>
</div>
`;
$("#genericModal").modal("show");
};
var showAlertDelAppFromList = (id) => {
genericModalContent.innerHTML = "";
genericModalContent.innerHTML = `
<div class="modal-header">
<h5 class="modal-title" i18n="modal.exit.title">${mviewer.tr(
"delete.request.warning"
)}</h5>
<button type="button" class="close" data-bs-toggle="modal" data-bs-target="#mod-importfile" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p i18n="confirm.delete_app">
${mviewer.tr("delete.request.title")}
</p>
<a class="cardsClose save-close zoomCard" data-bs-toggle="modal" data-bs-target="#mod-importfile" onclick="deleteAppFromList('${id}');">
<i class="ri-delete-bin-2-line"></i>
<span i18n="btn.delete">${mviewer.tr("delete.request.delete")}</span>
</a>
<a class="cardsClose notsave-close zoomCard" class="close" data-bs-toggle="modal" data-bs-target="#mod-importfile" aria-label="Close">
<i class="ri-arrow-go-back-line"></i>
<span i18n="cancel">${mviewer.tr("delete.request.cancel")}</span>
</a>
<a class="returnConf-close" class="close" data-bs-toggle="modal" data-bs-target="#mod-importfile" aria-label="Close"><i class="ri-arrow-left-line"></i> <span i18n="modal.exit.previous">Retour</span></a>
</div>
`;
$("#genericModal").modal("show");
};
var deleteAppFromList = (id) => {
deleteApplication(id).then((r) => {
document.getElementById("liste_applications").innerHTML = "";
mv.getListeApplications();
});
};
var getConfig = () => {
var padding = function (n) {
return "\r\n" + " ".repeat(n);
};
var savedProxy = "";
var olscompletion = "";
var elasticsearch = "";
// Url du studio
var studioUrl = "";
if ($("#opt-studio").prop("checked")) {
let readURL = new URL(window.location.href);
studioUrl = `${readURL.origin}${readURL.pathname}?xml=`;
}
var application = [
"<application",
'title="' + $("#opt-title").val() + '"',
'logo="' + $("#opt-logo").val() + '"',
'favicon="' + $("#opt-favicon").val() + '"',
'help="' + $("#opt-help").val() + '"',
'titlehelp="' + $("#opt-titlehelp").val() + '"',
'iconhelp="' + $("#opt-iconhelp").val() + '"',
'home="' + $("#opt-home").val() + '"',
'style="' + $("#opt-style").val() + '"',
'zoomtools="' + ($("#opt-zoomtools").prop("checked") === true) + '"',
'initialextenttool="' + ($("#opt-initialextenttool").prop("checked") === true) + '"',
'exportpng="' + ($("#opt-exportpng").prop("checked") === true) + '"',
'showhelp="' + ($("#opt-showhelp").prop("checked") === true) + '"',
'coordinates="' + ($("#opt-coordinates").prop("checked") === true) + '"',
'measuretools="' + ($("#opt-measuretools").prop("checked") === true) + '"',
'mouseposition="' + ($("#opt-mouseposition").prop("checked") === true) + '"',
'geoloc="' + ($("#opt-geoloc").prop("checked") === true) + '"',
'studio="' + studioUrl + '"',
'togglealllayersfromtheme="' +
($("#opt-togglealllayersfromtheme").prop("checked") === true) +
'"',
];
config.title = $("#opt-title").val();
if (config.title == "") {
$("#opt-title").addClass("is-invalid");
alertCustom(mviewer.tr("msg.alert_app_name"), "danger");
}
savedParameters.application.forEach(function (parameter, id) {
$.each(parameter, function (prop, val) {
application.push(prop + '="' + val + '"');
});
});
application = application.join(padding(4)) + ">" + padding(0) + "</application>";
savedProxy = `${padding(0)}<proxy url=""/>`;
if ($("#optProxyUrl").val() && _conf.proxy) {
savedProxy = `${padding(0)}<proxy url="${$("#optProxyUrl").val() || _conf.proxy}"/>`;
}
var search_params = { bbox: false, localities: false, features: false, static: false };
if ($("#SwitchAdressSearch").is(":checked")) {
olscompletion = [
padding(0) + '<olscompletion type="' + $("#frm-searchlocalities").val() + '"',
'url="' + $("#opt-searchlocalities-url").val() + '"',
'attribution="' + $("#opt-searchlocalities-attribution").val() + '" />',
].join(" ");
search_params.localities = true;
}
if (
$("#frm-globalsearch").val() === "elasticsearch" &&
$("#opt-elasticsearch-url").val()
) {
elasticsearch = [
padding(0) + '<elasticsearch url="' + $("#opt-elasticsearch-url").val() + '"',
'geometryfield="' + $("#opt-elasticsearch-geometryfield").val() + '"',
'linkid="' + $("#opt-elasticsearch-linkid").val() + '"',
'doctypes="' + $("#opt-elasticsearch-doctypes").val() + '"',
'mode="' + ($("#opt-elasticsearch-mode").val() || "match") + '"',
'version="' + $("#opt-elasticsearch-version").val() + '" />',
].join(" ");
if ($("#opt-elasticsearch-doctypes").val().length >= 0) {
search_params.static = "true";
}
if ($("#opt-elasticsearch-bbox").prop("checked")) {
search_params.bbox = "true";
}
}
if ($("#opt-searchfeatures").prop("checked")) {
search_params.features = true;
}
searchparameters =
padding(0) +
'<searchparameters bbox="' +
search_params.bbox +
'" localities="' +
search_params.localities +
'" features="' +
search_params.features +
'" static="' +
search_params.static +
'"/>';
var maxextentStr = "";
if ($("#opt-maxextent").prop("checked")) {
maxextent = map.getView().calculateExtent();
maxextentStr = `maxextent="${maxextent}"`;
}
var extentStr = "";
extent = map.getView().calculateExtent();
extentStr = `extent="${extent}"`;
var center = map.getView().getCenter().join(",");
var zoom = map.getView().getZoom();
var mapoptions =
padding(0) +
'<mapoptions projection="EPSG:3857" center="' +
center +
'" maxzoom="' +
$("#opt-maxzoom").val() +
'" zoom="' +
zoom +
'" ' +
extentStr +
" " +
maxextentStr +
"/>";
var baseLayersMode = $("#frm-bl-mode").val();
var visibleBaselayer = $("#frm-bl-visible").val();
var baseLayers = [padding(0) + '<baselayers style="' + baseLayersMode + '">'];
$(".bl input:checked").each(function (i, b) {
// set first bl visible
const baseLayerId = $(b).parent().parent().attr("data-layerid");
var baseLayer =
_conf.baselayers[baseLayerId] ||
savedParameters.baselayers[baseLayerId] ||
getConf("customBaseLayers")[baseLayerId];
var definition = [
'<baselayer visible="false" ',
createBaseLayerDef(baseLayer),
" ></baselayer>",
].join("");
if (baseLayer.id === visibleBaselayer) {
definition = definition.replace('visible="false"', 'visible="true"');
}
baseLayers.push(padding(4) + definition);
});
baseLayers.push(padding(0) + "</baselayers>");
var themes = [
padding(0) + '<themes mini="' + ($("#opt-mini").prop("checked") === true) + '">',
];
// Respect theme order
$(".themes-list-item").each(function (id, theme) {
saveThemes();
var themeid = $(theme).attr("data-themeid");
if (config.themes[themeid]) {
var t = config.themes[themeid];
var theme = [];
if (t.url) {
theme = [
padding(4) +
'<theme id="' +
t.id +
'" url="' +
t.url +
'" name="' +
t.title +
'" collapsed="' +
t.collapsed +
'" icon="' +
t.icon +
'" layersvisibility="' +
t.layersvisibility +
'">',
];
} else {
theme = [
padding(4) +
'<theme id="' +
t.id +
'" name="' +
t.title +
'" collapsed="' +
t.collapsed +
'" icon="' +
t.icon +
'">',
];
}
$(t.layers).each(function (i, l) {
var layer = mv.writeLayerNode(l);
theme.push(layer);
});
themes.push(theme.join(" "));
themes.push(padding(4) + "</theme>");
}
});
themes.push(padding(0) + "</themes>");
const mviewerVersion = _conf?.mviewer_version || "";
var conf = [
'<?xml version="1.0" encoding="UTF-8"?>\r\n<config mviewerversion="' +
mviewerVersion +
'" mviewerstudioversion="' +
_conf?.mviewerstudio_version +
'">\r\n',
"<metadata>\r\n" + mv.createDublinCore(config) + "\r\n</metadata>\r\n",
application,
mapoptions,
savedProxy,
olscompletion,
elasticsearch,
searchparameters,
baseLayers.join(" "),
themes.join(" "),
padding(0) + "</config>",
];
return conf;
};
let previewWithPhp = (conf) => {
if (!_conf?.php?.upload_service) {
alertCustom(mviewer.tr("msg.alert_wrong_config"), "error");
}
// Save the map serverside
$.ajax({
type: "POST",
url: _conf.php.upload_service,
data: conf.join(""),
dataType: "json",
contentType: "text/xml",
success: function (data) {
// Preview the map
var url = "";
if (data.success && data.filepath) {
// Build a short and readable URL for the map
let url = mv.produceUrl(data.filepath);
window.open(url, "mvs_vizualize");
alertCustom(mviewer.tr("msg.download_success"), "success");
}
},
});
};
let previewAppsWithoutSave = (id, showPublish) => {
if (config.relation && _conf.publish_url && showPublish) {
const filePath = `${mv.getAuthentUserInfos("groupSlugName")}/${config.relation}`;
const previewUrl = mv.produceUrl(filePath, true);
return window.open(previewUrl, "mvs_vizualize");
}
const confXml = getConfig();
if (!confXml || (confXml && !mv.validateXML(confXml.join("")))) {
return alertCustom("XML invalide !", "danger");
}
if (_conf.is_php) {
return previewWithPhp(confXml);
}
if (!id || !config.isFile) {
return alertCustom(mviewer.tr("msg.preview_no_save"), "danger");
}
return fetch(`${_conf.api}/${id}/preview`, {
method: "POST",
headers: {
"Content-Type": "text/xml",
},
body: confXml.join(""),
})
.then((r) => (r.ok ? r.json() : Promise.reject(r)))
.then((data) => {
const url = mv.produceUrl(data.file, config.relation && config.showPublish);
const prevWindow = window.open(url, "mvs_vizualize");
if (prevWindow) {
prevWindow.focus();
prevWindow.location.reload();
}
})
.catch((err) => alertCustom(mviewer.tr("msg.xml_doc_invalid"), "error"));
};
const downloadXML = () => {
if (_conf.is_php) {
return downloadXML4PHP();
}
fetch(`api/download/${config.id}`)
.then((r) => r.json())
.then((r) => {
let link = document.createElement("a");
link.download = r.name;
link.href = _conf.mviewer_instance + r.url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
});
};
const downloadXML4PHP = () => {
const conf = getConfig();
if (mv.validateXML(conf.join(""))) {
var element = document.createElement("a");
element.setAttribute(
"href",
"data:text/xml;charset=utf-8," + encodeURIComponent(conf.join(""))