-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathqueryresultsservice.js
1732 lines (1635 loc) · 57.3 KB
/
queryresultsservice.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
import {G3W_FID, LIST_OF_RELATIONS_TITLE} from 'constant';
import DownloadFormats from './vue/components/actiontools/downloadformats.vue';
import QueryPolygonCsvAttributesComponent from './vue/components/actiontools/querypolygoncsvattributes.vue';
const ApplicationService = require('core/applicationservice');
const {base, inherit, noop, downloadFile, throttle, getUniqueDomId, copyUrl } = require('core/utils/utils');
const DataRouterService = require('core/data/routerservice');
const {getAlphanumericPropertiesFromFeature, createFeatureFromGeometry, createFeatureFromBBOX, createFeatureFromCoordinates} = require('core/utils/geo');
const {t} = require('core/i18n/i18n.service');
const ProjectsRegistry = require('core/project/projectsregistry');
const Layer = require('core/layers/layer');
const GUI = require('gui/gui');
const G3WObject = require('core/g3wobject');
const VectorLayer = require('core/layers/vectorlayer');
const PrintService = require('core/print/printservice');
const CatalogLayersStoresRegistry = require('core/catalog/cataloglayersstoresregistry');
const RelationsPage = require('gui/relations/vue/relationspage');
const PickCoordinatesInteraction = require('g3w-ol/interactions/pickcoordinatesinteraction');
//used to get and set vue reactivity to queryresultservice
const VM = new Vue();
function QueryResultsService() {
this.printService = new PrintService();
this._currentLayerIds = [];
ProjectsRegistry.onafter('setCurrentProject', project => {
this._project = project;
this._setRelations(project);
this._setAtlasActions(project);
this.state.download_data = false;
this.plotLayerIds = [];
});
this.unlistenerlayeractionevents = [];
this._actions = {
'zoomto': QueryResultsService.zoomToElement,
'highlightgeometry': this.highlightGeometry.bind(this),
'clearHighlightGeometry': this.clearHighlightGeometry.bind(this)
};
this._relations = [];
this._atlas = [];
this.plotLayerIds = [];
const project = this._project = ProjectsRegistry.getCurrentProject();
// userful to set right order for query result based on toc order layers
this._projectLayerIds = this._project.getConfigLayers().map(layer => layer.id);
// set reactive state
this.state = {
zoomToResult: true,
components: [],
layers: [],
changed: false,
query: null,
type: 'ows', // or api in case of search
layersactions: {},
actiontools:{}, // addd action tools (for features)
currentactiontools:{}, // current action tools contain component of a specific action (for example download)
currentactionfeaturelayer:{}, // contain current action that expose component vue (it useful to comprare id other action is toggled and expose component)
layeractiontool: {},
layersFeaturesBoxes:{},
layerscustomcomponents:{} // used to show a custom component for a layer
};
this.init = function() {
this.clearState();
};
// Is a vector layer used by query resul to show eventually query resuesta as coordnates, bbox, polygon, etc ..
const color = 'blue';
const stroke = new ol.style.Stroke({
color,
width: 3
});
const fill = new ol.style.Fill({
color
});
this.resultsQueryLayer = new ol.layer.Vector({
style: new ol.style.Style({
stroke,
image: new ol.style.Circle({
fill,
radius: 6
}),
}),
source: new ol.source.Vector()
});
this._vectorLayers = [];
this._addFeaturesLayerResultInteraction = {
id: null, // reference to current layer
interaction: null, // interaction bind to layer,
mapcontrol: null, // add current toggled map control if toggled
toggleeventhandler: null
};
this.setters = {
/**
* Method call when response is handled by Data Provider
* @param queryResponse
* @param options: add is used to know if is a new query request or add/remove query request
*/
setQueryResponse(queryResponse, options={add:false}) {
const {add} = options;
// in case of new request results reset the query otherwise maintain the previous request
if (!add) {
this.clearState();
this.state.query = queryResponse.query;
this.state.type = queryResponse.type;
}
const {data} = queryResponse;
const layers = this._digestFeaturesForLayers(data);
this.setLayersData(layers, options);
},
/**
* method to add layer and feature for response
* @param layers
* @param options
*/
setLayersData(layers, options={add:false}) {
const {add} = options;
if (!add){
// here set the right order of result layers based on toc
this._currentLayerIds = layers.map(layer => layer.id);
this._orderResponseByProjectLayers(layers);
}
layers.forEach(layer => {
// in case of a new request query
if (!add) this.state.layers.push(layer);
//get features from add pick layer
else this.addRemoveFeaturesToLayerResult(layer);
});
this.setActionsForLayers(layers, {add});
this.state.changed = true;
},
/**
* Method
* @param component
*/
addComponent(component) {
this._addComponent(component)
},
/**
*
*/
addActionsForLayers(actions, layers) {},
/**
*
* @param element
*/
postRender(element) {},
/**
*
*/
closeComponent() {},
/**
*
* @param layer
*/
changeLayerResult(layer){
this._changeLayerResult(layer);
},
/**
*
*/
activeMapInteraction(){},
/**
* setter hook to relation table
*/
editFeature({layerId, featureId}={}){},
/**
* Method to listen open/close feature info data content.
* @param open
* @param layer
* @param feature
* @param container
*/
openCloseFeatureResult({open, layer, feature, container}={}){}
};
base(this);
this.addLayersPlotIds = function(layerIds=[]) {
this.plotLayerIds = layerIds;
};
this.getPlotIds = function(){
return this.plotLayerIds;
};
this.findPlotId = function(id){
return this.plotLayerIds.find(plotId => plotId == id);
};
this._setRelations(project);
this._setAtlasActions(project);
this._addVectorLayersDataToQueryResponse();
this._asyncFnc = {
todo: noop,
zoomToLayerFeaturesExtent: {
async: false
},
goToGeometry: {
async: false
}
};
GUI.onbefore('setContent', (options)=>{
const {perc} = options;
this.mapService = this.mapService || ApplicationService.getApplicationService('map');
if (perc === 100 && GUI.isMobile()) {
this._asyncFnc.zoomToLayerFeaturesExtent.async = true;
this._asyncFnc.goToGeometry.async = true;
}
});
}
// Make the public service en Event Emitter
inherit(QueryResultsService, G3WObject);
const proto = QueryResultsService.prototype;
/**
* Method to register for plugin or other component of application to add custom component on result for each layer feature or layer
* @param id unique id identification
* @param layerId Layer id of layer
* @param component custom component
* @param type feature or layer
*/
proto.registerCustomComponent = function({id=getUniqueDomId(), layerId, component, type='feature', position='after'}={}){
if (this.state.layerscustomcomponents[layerId] === undefined)
this.state.layerscustomcomponents[layerId] = {
layer: {
before: [],
after: []
},
feature: {
before: [],
after: []
}
};
this.state.layerscustomcomponents[layerId][type][position].push({
id,
component
});
return id;
};
/**
* To check position
* @param id
* @param layerId
* @param type
*/
proto.unRegisterCustomComponent = function({id, layerId, type, position}){
if (position) this.state.layerscustomcomponents[layerId][type][position] = this.state.layerscustomcomponents[layerId][type][position].filter(({id:componentId}) => componentId !== id);
else Object.keys(this.state.layerscustomcomponents[layerId][type]).forEach(position =>{
this.state.layerscustomcomponents[layerId][type][position] = this.state.layerscustomcomponents[layerId][type][position].filter(({id:componentId}) => componentId !== id);
})
};
/**
* Method to add a feature to current layer result
* @param layer
* @param feature
*/
proto.addFeatureLayerToResult = function(layer, feature){
this.state.layersFeaturesBoxes[this.getBoxId(layer, feature)].collapsed = true;
};
/**
* Method to remove a feature from current layer result
* @param layer
* @param feature
*/
proto.removeFeatureLayerFromResult = function(layer, feature){
const {id, external} = layer;
this.addRemoveFeaturesToLayerResult({
id,
external,
features: [feature]
})
};
/**
* Method wrapper for download
*/
proto.downloadApplicationWrapper = async function(downloadFnc, options={}){
const download_caller_id = ApplicationService.setDownload(true);
GUI.setLoadingContent(true);
try {
await downloadFnc(options);
} catch(err){
GUI.showUserMessage({
type: 'alert',
message: err || 'server_error',
textMessage: err ? true : false
})
}
ApplicationService.setDownload(false, download_caller_id);
GUI.setLoadingContent(false);
};
/**
* Based on layer response check if features layer are to add or remove to current state.layers results
* @param layer
*/
proto.addRemoveFeaturesToLayerResult = function(layer){
//extract features from layer object
let {features=[]} = layer;
// get layer from current state.layers showed on result
const findLayer = this.state.layers.find(_layer => _layer.id === layer.id);
// if get features and find layer
if (findLayer && features.length){
// get id external layer or not (external is a layer added by mapcontrol addexternlayer)
const {external} = findLayer;
// is array of idexes od features that we has to remove from state.layer because is already loaded
const removeFeatureIndexes = [];
// get id of the features
const features_ids = features.map(feature => !external ? feature.attributes[G3W_FID]: feature.id);
// loop nad filter the features that we had to remove)
findLayer.features = findLayer.features.filter(feature => {
const indexFindFeature = features_ids.indexOf(!external ? feature.attributes[G3W_FID]: feature.id);
// check if need to filter or not
const filtered = indexFindFeature === -1;
if (!filtered){
removeFeatureIndexes.push(indexFindFeature);
const featureRemoved = features[indexFindFeature];
this.state.layersFeaturesBoxes[this.getBoxId(layer, feature)].collapsed = true;
setTimeout(()=> delete this.state.layersFeaturesBoxes[this.getBoxId(layer, featureRemoved)]);
} else this.state.layersFeaturesBoxes[this.getBoxId(layer, feature)].collapsed = true;
return filtered;
});
// filter features to add
features = features.filter((feature, index) => removeFeatureIndexes.indexOf(index) === -1);
// check if new feature ha to be added
if (features.length) {
const newlayerfeatures = [...findLayer.features, ...features];
findLayer.features = newlayerfeatures;
}
//in case of removed features
if (findLayer.features.length === 1 && this.state.layersFeaturesBoxes[this.getBoxId(findLayer, findLayer.features[0])])
// used to do all vue reactive thing before update layers
setTimeout(() => this.state.layersFeaturesBoxes[this.getBoxId(findLayer, findLayer.features[0])].collapsed = false);
// in case no more features on layer remove interaction pickcoordinate to get result from map
this.checkIfLayerHasNoFeatures(findLayer);
}
// hightlight new feature
this.state.layers.length === 1 && this.highlightFeaturesPermanently(this.state.layers[0]);
this.changeLayerResult(findLayer);
};
/**
* Method called when layer result features for example is changed
* @param layer
*/
proto._changeLayerResult = function(layer){
const layeractions = this.state.layersactions[layer.id];
// call if present change mthod to action
layeractions.forEach(action => action.change && action.change(layer));
//reset layer current actions tools
this.resetCurrentActionToolsLayer(layer);
};
/**
* Check and do action if layer has no features after delete feature(s
*/
proto.checkIfLayerHasNoFeatures = function(layer){
if (layer.features.length === 0) {
// used to do all vue reactive thing before update layers
setTimeout(() => {
this.state.layers = this.state.layers.filter(_layer => _layer.id !== layer.id);
this.clearHighlightGeometry(layer);
this.removeAddFeaturesLayerResultInteraction({
toggle: true
});
})
}
};
/**
* Method to create boxid identify to query result hmtl
* @param layer
* @param feature
* @param relation_index
* @returns {string}
*/
proto.getBoxId = function(layer, feature, relation_index){
return relation_index !== null && relation_index !== undefined ? `${layer.id}_${feature.id}_${relation_index}` : `${layer.id}_${feature.id}`;
};
proto.setActionsForLayers = function(layers, options={add: false}) {
const {add} = options;
if (!add) {
this.unlistenerlayeractionevents = [];
layers.forEach(layer => {
/**
* set eventually layer action tool and need to be reactive
* @type {{}}
*/
this.state.layeractiontool[layer.id] = Vue.observable({
component: null,
config: null
});
const currentactiontoolslayer = {};
const currentationfeaturelayer = {};
layer.features.forEach((feature, index)=> {
currentactiontoolslayer[index] = null;
currentationfeaturelayer[index] = null;
});
this.state.currentactiontools[layer.id] = Vue.observable(currentactiontoolslayer);
this.state.currentactionfeaturelayer[layer.id] = Vue.observable(currentationfeaturelayer);
const is_external_layer_or_wms = layer.external || (layer.source ? layer.source.type === 'wms' : false);
if (!this.state.layersactions[layer.id]) this.state.layersactions[layer.id] = [];
/**
* An action is an object contains
* {
* id: Unique action Id => required True
download: if is action download or not => required False
class: calss fontawsome to show icon => required True,
state: need to be reactive. Used for example to toggled state of action icon => required False
hint: Tooltip text => required False
init: Method called when action is loaded => required False
clear: Method called before clear the service. Used for example to clear unwatch => require False
change: Method called when feature of layer is changed
cbk: Method called when action is cliccked => required True
}
*
* }
*/
//in case of geometry
if (layer.hasgeometry) {
this.state.layersactions[layer.id].push({
id: 'gotogeometry',
download: false,
mouseover: true,
class: GUI.getFontClass('marker'),
hint: 'sdk.mapcontrols.query.actions.zoom_to_feature.hint',
cbk: throttle(this.goToGeometry.bind(this))
});
}
// in case of relations
if (this._relations) {
const relations = this._relations[layer.id] && this._relations[layer.id].filter(relation =>{
return relation.type === 'MANY';
});
if (relations && relations.length) {
const chartRelationIds = [];
relations.forEach(relation => {
const id = this.plotLayerIds.find(id => id === relation.referencingLayer);
id && chartRelationIds.push(id);
});
this.state.layersactions[layer.id].push({
id: 'show-query-relations',
download: false,
class: GUI.getFontClass('relation'),
hint: 'sdk.mapcontrols.query.actions.relations.hint',
cbk: this.showQueryRelations,
relations,
chartRelationIds
});
const state = this.createActionState({
layer
});
chartRelationIds.length && this.state.layersactions[layer.id].push({
id: 'show-plots-relations',
download: false,
opened: true,
class: GUI.getFontClass('chart'),
state,
hint: 'sdk.mapcontrols.query.actions.relations_charts.hint',
cbk: throttle(this.showRelationsChart.bind(this, chartRelationIds))
});
}
}
/**
*
* Check if layer has atlas
*/
this.getAtlasByLayerId(layer.id).length && this.state.layersactions[layer.id].push({
id: `printatlas`,
download: true,
class: GUI.getFontClass('print'),
hint: `sdk.tooltips.atlas`,
cbk: this.printAtlas.bind(this)
});
const state = this.createActionState({
layer
});
if (layer.downloads.length === 1) {
const [format] = layer.downloads;
const cbk = this.downloadFeatures.bind(this, format);
layer[format] = Vue.observable({
active: false
});
this.state.layersactions[layer.id].push({
id: `download_${format}_feature`,
download: true,
state,
class: GUI.getFontClass('download'),
hint: `sdk.tooltips.download_${format}`,
cbk: (layer, feature, action, index)=>{
action.state.toggled[index] = !action.state.toggled[index];
if (action.state.toggled[index]) cbk(layer, feature, action, index);
else this.setCurrentActionLayerFeatureTool({
index,
action,
layer
})
}
});
} else if (layer.downloads.length > 1 ){
// SET CONSTANT TO AVOID TO CHANGE ALL THINGS
const ACTIONTOOLSDOWNLOADFORMATS = DownloadFormats.name;
const downloads = [];
layer.downloads.forEach(format => {
downloads.push({
id: `download_${format}_feature`,
download: true,
format,
class: GUI.getFontClass(format),
hint: `sdk.tooltips.download_${format}`,
cbk: (layer, feature, action, index)=> {
//used to untoggle downloads action
this.downloadFeatures(format, layer, feature, action, index);
const downloadsaction = this.state.layersactions[layer.id].find(action => action.id === 'downloads');
if (this.state.query.type !== 'polygon') downloadsaction.cbk(layer, feature, downloadsaction, index);
}
});
});
this.state.actiontools[ACTIONTOOLSDOWNLOADFORMATS] = this.state.actiontools[ACTIONTOOLSDOWNLOADFORMATS] || {};
// set config of actionstools
this.state.actiontools[ACTIONTOOLSDOWNLOADFORMATS][layer.id] = {
downloads // ARE DOWNLOAD ACTIONS,
};
// used to
//check if has download actions
this.state.layersactions[layer.id].push({
id: `downloads`,
download: true,
class: GUI.getFontClass('download'),
state,
toggleable: true,
hint: `Downloads`,
change({features}) {
features.forEach((feature, index) =>{
if (this.state.toggled[index] === undefined) VM.$set(this.state.toggled, index, false);
else this.state.toggled[index] = false;
});
},
cbk: (layer, feature, action, index) => {
action.state.toggled[index] = !action.state.toggled[index];
this.setCurrentActionLayerFeatureTool({
layer,
index,
action,
component: action.state.toggled[index] ? DownloadFormats : null
});
}
});
}
/*
Check if si external layer or wms
*/
!is_external_layer_or_wms && this.state.layersactions[layer.id].push({
id: 'removefeaturefromresult',
download: false,
mouseover: true,
class: GUI.getFontClass('minus-square'),
style: {
color: 'red'
},
hint: 'sdk.mapcontrols.query.actions.remove_feature_from_results.hint',
cbk: this.removeFeatureLayerFromResult.bind(this)
});
/**
* check if selection is active
*/
if (layer.selection.active !== undefined) {
// selection action
const state = this.createActionState({
layer
});
this.state.layersactions[layer.id].push({
id: 'selection',
download: false,
class: GUI.getFontClass('success'),
hint: 'sdk.mapcontrols.query.actions.add_selection.hint',
state,
init: ({feature, index, action}={})=>{
layer.selection.active !== void 0 && this.checkFeatureSelection({
layerId: layer.id,
index,
feature,
action
})
},
cbk: throttle(this.addToSelection.bind(this))
});
this.listenClearSelection(layer, 'selection');
//end selection action
}
/*
If not wms of external layer show copy link to feature
*/
!is_external_layer_or_wms && layer.hasgeometry && this.state.layersactions[layer.id].push({
id: 'link_zoom_to_fid',
download: false,
class: GUI.getFontClass('link'),
hint: 'sdk.mapcontrols.query.actions.copy_zoom_to_fid_url.hint',
hint_change: {
hint: 'sdk.mapcontrols.query.actions.copy_zoom_to_fid_url.hint_change',
duration: 1000
},
cbk: this.copyZoomToFidUrl.bind(this)
});
layer.editable && this.state.layersactions[layer.id].push({
id: 'editing',
class: GUI.getFontClass('pencil'),
hint: 'Editing',
cbk: (layer, feature) => {
const layerId = layer.id;
const featureId = feature.attributes[G3W_FID];
feature.geometry && this.mapService.zoomToGeometry(feature.geometry);
setTimeout(()=>{
this.editFeature({
layerId,
featureId
});
}, 300)
}
});
});
this.addActionsForLayers(this.state.layersactions, this.state.layers);
}
};
proto.createActionState = function({layer, dynamicProperties=['toggled']}){
// check number of download formats
const propertiesObject = dynamicProperties.reduce((accumulator, property) =>{
accumulator[property] = {};
return accumulator;
}, {});
layer.features.map((feature, index)=> {
Object.keys(propertiesObject).forEach(property =>{
propertiesObject[property][index] = null;
})
});
return Vue.observable(propertiesObject);
};
/**
* Method to get action referred to layer getting the acion id
* @param layer layer linked to action
* @param id action id
* @returns {*}
*/
proto.getActionLayerById = function({layer, id}={}){
return this.state.layersactions[layer.id].find(action => action.id === id);
};
/**
* Set current layer action tool in feature
* @param layer current layer
* @param index feature index
* @param value component value or null
*/
proto.setCurrentActionLayerFeatureTool = function({layer, action, index, component=null}={}){
if (component){
if (this.state.currentactiontools[layer.id][index] && action.id !== this.state.currentactionfeaturelayer[layer.id][index].id && this.state.currentactionfeaturelayer[layer.id][index].toggleable)
this.state.currentactionfeaturelayer[layer.id][index].state.toggled[index] = false;
this.state.currentactionfeaturelayer[layer.id][index] = action;
} else this.state.currentactionfeaturelayer[layer.id][index] = null;
this.state.currentactiontools[layer.id][index] = component;
};
proto.addCurrentActionToolsLayer = function({id, layer, config={}}){
this.state.actiontools[id] = {};
this.state.actiontools[id][layer.id] = config;
};
/**
* Reset current action tools on layer when feature layer change
* @param layer
*/
proto.resetCurrentActionToolsLayer = function(layer){
layer.features.forEach((feature, index)=>{
if (this.state.currentactiontools[layer.id]) {
if (this.state.currentactiontools[layer.id][index] === undefined) Vue.set(this.state.currentactiontools[layer.id], index, null);
else this.state.currentactiontools[layer.id][index] = null;
this.state.currentactionfeaturelayer[layer.id][index] = null;
}
})
};
/**
*
*/
proto.setLayerActionTool = function({layer, component=null, config=null}={}){
this.state.layeractiontool[layer.id].component = component;
this.state.layeractiontool[layer.id].config = config;
};
/**
* Method copy zoomtofid url
* @param layer
* @param feature
*/
proto.copyZoomToFidUrl = function(layer, feature, action){
const fid = feature.attributes[G3W_FID];
const url = new URL(location.href);
const zoom_to_fid = `${layer.id}|${fid}`;
url.searchParams.set('zoom_to_fid', zoom_to_fid);
copyUrl(url.toString());
action.hint_changed = true;
};
/**
* Clear all
*/
proto.clear = function() {
this.runAsyncTodo();
this.unlistenerEventsActions();
this.mapService.clearHighlightGeometry();
this.resultsQueryLayer.getSource().clear();
this.removeAddFeaturesLayerResultInteraction({
toggle: true
});
this.mapService.getMap().removeLayer(this.resultsQueryLayer);
this._asyncFnc = null;
this._asyncFnc = {
todo: noop,
zoomToLayerFeaturesExtent: {
async: false
},
goToGeometry: {
async: false
}
};
this.clearState();
this.closeComponent();
};
proto.getCurrentLayersIds = function(){
return this._currentLayerIds;
};
proto.runAsyncTodo = function() {
this._asyncFnc.todo();
};
proto._orderResponseByProjectLayers = function(layers) {
layers.sort((layerA, layerB) => {
const aIndex = this._projectLayerIds.indexOf(layerA.id);
const bIndex = this._projectLayerIds.indexOf(layerB.id);
return aIndex > bIndex ? 1 : -1;
});
};
proto.setZoomToResults = function(bool=true) {
this.state.zoomToResult = bool;
};
proto.highlightFeaturesPermanently = function(layer){
const {features} = layer;
this.mapService.highlightFeatures(features, {
duration: Infinity
})
};
/**
* Check if one layer result
* @returns {boolean}
*/
proto.isOneLayerResult = function(){
return this.state.layers.length === 1;
};
/**
*
* @param toggle boolean If true toggle true the mapcontrol
*/
proto.removeAddFeaturesLayerResultInteraction = function({toggle=false}={}){
if (this._addFeaturesLayerResultInteraction.interaction) this.mapService.removeInteraction(this._addFeaturesLayerResultInteraction.interaction);
this._addFeaturesLayerResultInteraction.interaction = null;
this._addFeaturesLayerResultInteraction.id = null;
// check if map control query map is register and if toggled
toggle && this._addFeaturesLayerResultInteraction.mapcontrol && this._addFeaturesLayerResultInteraction.mapcontrol.toggle(true);
this._addFeaturesLayerResultInteraction.mapcontrol = null;
this._addFeaturesLayerResultInteraction.toggleeventhandler && this.mapService.off('mapcontrol:toggled', this._addFeaturesLayerResultInteraction.toggleeventhandler);
this._addFeaturesLayerResultInteraction.toggleeventhandler = null;
};
/**
*
* Adde feature to Features results
* @param layer
*/
proto.addLayerFeaturesToResultsAction = function(layer){
/**
* Check if layer is current layer to add or clear previous
*/
if (this._addFeaturesLayerResultInteraction.id !== null && this._addFeaturesLayerResultInteraction.id !== layer.id){
const layer = this.state.layers.find(layer => layer.id === this._addFeaturesLayerResultInteraction.id);
if (layer) layer.addfeaturesresults.active = false;
//remove previous add result interaction
if (this._addFeaturesLayerResultInteraction.interaction) this.mapService.removeInteraction(this._addFeaturesLayerResultInteraction.interaction);
}
this._addFeaturesLayerResultInteraction.id = layer.id;
layer.addfeaturesresults.active = !layer.addfeaturesresults.active;
if (layer.addfeaturesresults.active) {
this.activeMapInteraction(); // useful o send an event
const {external} = layer;
if (!this._addFeaturesLayerResultInteraction.mapcontrol) this._addFeaturesLayerResultInteraction.mapcontrol = this.mapService.getCurrentToggledMapControl();
this._addFeaturesLayerResultInteraction.interaction = new PickCoordinatesInteraction();
this.mapService.addInteraction(this._addFeaturesLayerResultInteraction.interaction, {
close: false
});
this._addFeaturesLayerResultInteraction.interaction.on('picked', async evt =>{
const {coordinate: coordinates} = evt;
if (!external)
await DataRouterService.getData('query:coordinates',
{
inputs: {
coordinates,
query_point_tolerance: this._project.getQueryPointTolerance(),
layerIds: [layer.id],
multilayers: false,
}, outputs: {
show: {
add: true
}
}
});
else {
const vectorLayer = this._vectorLayers.find(vectorLayer => layer.id === vectorLayer.get('id'));
const responseObject = this.getVectorLayerFeaturesFromQueryRequest(vectorLayer,{
coordinates
});
this.setQueryResponse({
data: [responseObject],
query: {
coordinates
}
}, {add:true});
}
});
const eventHandler = evt => {
if (evt.target.isToggled() && evt.target.isClickMap()) layer.addfeaturesresults.active = false;
};
this._addFeaturesLayerResultInteraction.toggleeventhandler = eventHandler;
this.mapService.once('mapcontrol:toggled', eventHandler);
} else this.removeAddFeaturesLayerResultInteraction({
toggle: true
});
};
proto.deactiveQueryInteractions = function(){
this.state.layers.forEach(layer => { if (layer.addfeaturesresults) layer.addfeaturesresults.active = false});
this.removeAddFeaturesLayerResultInteraction();
};
proto.zoomToLayerFeaturesExtent = function(layer, options={}) {
const {features} = layer;
options.highlight = !this.isOneLayerResult();
if (this._asyncFnc.zoomToLayerFeaturesExtent.async)
this._asyncFnc.todo = this.mapService.zoomToFeatures.bind(this.mapService, features, options);
else this.mapService.zoomToFeatures(features, options);
};
proto.clearState = function(options={}) {
this.state.layers.splice(0);
this.state.query = {};
this.state.querytitle = "";
this.state.changed = false;
// clear action if present
Object.values(this.state.layersactions).forEach(layeractions =>layeractions.forEach(action => action.clear && action.clear()));
this.state.layersactions = {};
this.state.actiontools = {};
this.state.layeractiontool = {};
// current action tools
this.state.currentactiontools = {};
this.state.layersFeaturesBoxes = {};
this.removeAddFeaturesLayerResultInteraction();
};
proto.getState = function() {
return this.state;
};
proto.setState = function(state) {
this.state = state;
};
proto._setRelations = function(project) {
const projectRelations = project.getRelations();
this._relations = projectRelations ? _.groupBy(projectRelations,'referencedLayer'): [];
};
proto.getAtlasByLayerId = function(layerId) {
return this._atlas.filter(atlas => atlas.atlas.qgs_layer_id === layerId);
};
proto._setAtlasActions = function(project){
this._atlas = project.getPrint().filter(printconfig => printconfig.atlas) || [];
};
proto.setTitle = function(querytitle) {
this.state.querytitle = querytitle || "";
};
proto.reset = function() {
this.clearState();
};
/**
* Method that convert response from Data Provider to a Query Result component data structure
* @param featuresForLayers: Array contains for each layer features
* @returns {[]}
* @private
*/
proto._digestFeaturesForLayers = function(featuresForLayers) {
let id = 0;
featuresForLayers = featuresForLayers || [];
const layers = [];
let layerAttributes,
layerRelationsAttributes,
layerTitle,
layerId;
const _handleFeatureFoLayer = featuresForLayer => {
let formStructure;
let sourceType;
let source;
let extractRelations = false;
let external = false;
let editable = false;
const layer = featuresForLayer.layer;
let downloads = [];
let infoformats = [];
let infoformat;
let filter = {};
let selection ={};
if (layer instanceof Layer) {
editable = layer.isEditable();
source = layer.getSource();
infoformats = layer.getInfoFormats(); // add infoformats property
infoformat = layer.getInfoFormat();
// set selection filter and relation if not wms
if ([Layer.SourceTypes.WMS, Layer.SourceTypes.WCS, Layer.SourceTypes.WMST].indexOf(layer.getSourceType()) === -1){
filter = layer.state.filter;
selection = layer.state.selection;
extractRelations = true;
}
downloads = layer.getDownloadableFormats();
try {
sourceType = layer.getSourceType()
} catch(err){}
// sanitize attributes layer only if is ows
layerAttributes = this.state.type === 'ows' ? layer.getAttributes().map(attribute => {
const sanitizeAttribute = {...attribute};
sanitizeAttribute.name = sanitizeAttribute.name.replace(/ /g, '_');
return sanitizeAttribute
}) : layer.getAttributes();
layerRelationsAttributes = [];
layerTitle = layer.getTitle();
layerId = layer.getId();
if (layer.hasFormStructure()) {
const structure = layer.getLayerEditingFormStructure();
if (this._relations && this._relations.length) {
const getRelationFieldsFromFormStructure = node => {
if (!node.nodes) {
node.name ? node.relation = true : null;
} else {
for (const _node of node.nodes) {
getRelationFieldsFromFormStructure(_node);
}
}
};
for (const node of structure) {
getRelationFieldsFromFormStructure(node);
}
}
const fields = layer.getFields().filter(field => field.show); // get features show
formStructure = {
structure,
fields
}
}
} else if (layer instanceof ol.layer.Vector){
layerAttributes = layer.getProperties();
layerRelationsAttributes = [];
layerTitle = layer.get('name');
layerId = layer.get('id');
external = true;
} else if (typeof layer === 'string' || layer instanceof String) {
sourceType = Layer.LayerTypes.VECTOR;
const feature = featuresForLayer.features[0];
layerAttributes = feature ? feature.getProperties() : [];
layerRelationsAttributes = [];
const split_layer_name = layer.split('_');