-
Notifications
You must be signed in to change notification settings - Fork 88
/
component.js
1048 lines (961 loc) · 33.5 KB
/
component.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
// The MIT License (MIT)
//
// Copyright (c) 2015-2022 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import angular from 'angular';
import {COORDINATES_LAYER_NAME} from 'gmf/index.js';
import {gmfBackgroundlayerStatus} from 'gmf/backgroundlayerselector/status.js';
import gmfLayertreeTreeManager from 'gmf/layertree/TreeManager.js';
import gmfSearchFulltextSearch from 'gmf/search/FulltextSearch.js';
import gmfThemeThemes, {findThemeByName} from 'gmf/theme/Themes.js';
import ngeoMapFeatureOverlayMgr from 'ngeo/map/FeatureOverlayMgr.js';
import ngeoMiscAutoProjection from 'ngeo/misc/AutoProjection.js';
import ngeoMiscColorpickerComponent from 'ngeo/misc/colorpickerComponent.js';
import ngeoMessagePopoverComponent from 'ngeo/message/popoverComponent.js';
import ngeoSearchModule from 'ngeo/search/module.js';
import olFeature from 'ol/Feature.js';
import {asArray as asColorArray} from 'ol/color.js';
import olGeomPoint from 'ol/geom/Point.js';
import olFormatGeoJSON from 'ol/format/GeoJSON.js';
import * as olProj from 'ol/proj.js';
import {appendParams as olUriAppendParams} from 'ol/uri.js';
import SimpleGeometry from 'ol/geom/SimpleGeometry.js';
import {buildStyle} from 'ngeo/options.js';
/**
* @type {angular.IModule}
* @hidden
*/
const myModule = angular.module('gmfSearch', [
gmfLayertreeTreeManager.name,
gmfSearchFulltextSearch.name,
gmfThemeThemes.name,
ngeoMiscAutoProjection.name,
ngeoMiscColorpickerComponent.name,
ngeoSearchModule.name,
ngeoMapFeatureOverlayMgr.name,
ngeoMessagePopoverComponent.name,
]);
/**
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @return {string} Template URL.
* @private
* @hidden
*/
function gmfSearchTemplateUrl_(element, attrs) {
const templateUrl = attrs.gmfSearchTemplateurl;
return templateUrl !== undefined ? templateUrl : 'gmf/search';
}
myModule.run(
/**
* @ngInject
* @param {angular.ITemplateCacheService} $templateCache
*/
($templateCache) => {
// @ts-ignore: webpack
$templateCache.put('gmf/search', require('./component.html'));
}
);
/**
* @param {JQuery} $element Element.
* @param {angular.IAttributes} $attrs Attributes.
* @param {function(JQuery, angular.IAttributes): string} gmfSearchTemplateUrl Template function.
* @return {string} Template URL.
* @ngInject
* @private
* @hidden
*/
function gmfSearchTemplateUrl($element, $attrs, gmfSearchTemplateUrl) {
return gmfSearchTemplateUrl($element, $attrs);
}
/**
* A component that allows to search and recenter on a selected
* result's feature.
* It can search in multiple GeoJSON datasources.
* It can filter and group results by a feature's property.
*
* This component uses the {@link import("ngeo/map/FeatureOverlayMgr.js").FeatureOverlayMgr} to create a
* feature overlay for drawing features on the map. The application
* is responsible to initialize the {@link import("ngeo/map/FeatureOverlayMgr.js").FeatureOverlayMgr}
* with the map.
*
* Example:
*
* <gmf-search gmf-search-map="::ctrl.map"
* gmf-search-options="::ctrl.searchOptions">
* </gmf-search>
*
* The 'fulltextsearchUrl' value in the examples above set three "_query" parameters: "limit",
* "partitionlimit" and "ranksystem". For this last one "ts_rank_cd" is the only effective value. It's used to
* order your search results with the "ts_rank_cd" ranking system from PostgreSQL module pg_trgm. Without
* this value, the PostgreSQL function "similarity" (module pg_trgm) is used for the ranking. Read the
* full-text search c2cgeoportal documentation to know more.
* You can also add these parameters to the "url" variable of one (or more) of the
* SearchDirectiveDatasource given to this component. That
* allows you to have multiples configurations on one search component.
*
* @htmlAttribute {string} gmf-search-input-value The input value (read only).
* @htmlAttribute {import("ol/Map.js").default} gmf-search-map The map.
* @htmlAttribute {Twitter.Typeahead.Options|undefined} gmf-search-options Addition Twitter.Typeahead.
* options.
* @htmlAttribute {SearchComponentListeners} gmf-search-listeners The listeners.
* @htmlAttribute {function=} gmf-search-on-init Optional function called when the component is initialized.
* @htmlAttribute {function=} gmf-search-action Optional function called when no default action is defined.
* @htmlAttribute {string} gmf-search-options-name Optional options name when multiple search component are defined.
* @ngdoc component
* @ngname gmfSearch
*/
const searchComponent = {
bindings: {
'inputValue': '=?gmfSearchInputValue',
'map': '<gmfSearchMap',
'typeaheadOptions': '<?gmfSearchOptions',
'additionalListeners': '<gmfSearchListeners',
'onInitCallback': '<?gmfSearchOnInit',
'searchActionCallback': '&?gmfSearchAction',
'optionsName': '<?gmfSearchOptionsName',
},
controller: 'gmfSearchController',
templateUrl: gmfSearchTemplateUrl,
};
myModule.value('gmfSearchTemplateUrl', gmfSearchTemplateUrl_);
// Register the controller in the module
myModule.component('gmfSearch', searchComponent);
/**
* @hidden
*/
export class SearchController {
/**
* @param {JQuery} $element Element.
* @param {angular.IScope} $scope The component's scope.
* @param {angular.ICompileService} $compile Angular compile service.
* @param {angular.ITimeoutService} $timeout Angular timeout service.
* @param {angular.auto.IInjectorService} $injector Angular injector service.
* @param {angular.gettext.gettextCatalog} gettextCatalog Gettext catalog.
* @param {import("ngeo/misc/AutoProjection.js").AutoProjectionService} ngeoAutoProjection The ngeo
* coordinates service.
* @param {function} ngeoSearchCreateGeoJSONBloodhound
* The ngeo create GeoJSON Bloodhound service.
* @param {import("ngeo/map/FeatureOverlayMgr.js").FeatureOverlayMgr} ngeoFeatureOverlayMgr The ngeo feature
* overlay manager service.
* @param {import("gmf/theme/Themes.js").ThemesService} gmfThemes gmf Themes service.
* @param {import("gmf/layertree/TreeManager.js").LayertreeTreeManager} gmfTreeManager gmf Tree Manager
* service.
* @param {import("gmf/search/FulltextSearch.js").FulltextSearchService} gmfSearchFulltextSearch
* gmf Full text search service.
* @param {import("ngeo/statemanager/Location.js").StatemanagerLocation} ngeoLocation The location service.
* @param {import('gmf/options.js').gmfSearchOptions} gmfSearchOptions The options.
* @param {import('gmf/options.js').gmfSearchGroups} gmfSearchGroups The groups.
* @param {string} fulltextsearchUrl The service URL.
* @ngInject
* @ngdoc controller
* @ngname GmfSearchController
*/
constructor(
$element,
$scope,
$compile,
$timeout,
$injector,
gettextCatalog,
ngeoAutoProjection,
ngeoSearchCreateGeoJSONBloodhound,
ngeoFeatureOverlayMgr,
gmfThemes,
gmfTreeManager,
gmfSearchFulltextSearch,
ngeoLocation,
gmfSearchOptions,
gmfSearchGroups,
fulltextsearchUrl
) {
this.options = gmfSearchOptions;
this.groups = gmfSearchGroups;
this.fulltextsearchUrl = fulltextsearchUrl;
/**
* @type {JQuery}
* @private
*/
this.element_ = $element;
/**
* @type {angular.IScope}
* @private
*/
this.scope_ = $scope;
/**
* @type {angular.ICompileService}
* @private
*/
this.compile_ = $compile;
/**
* @type {angular.ITimeoutService}
* @private
*/
this.timeout_ = $timeout;
/**
* @type {angular.auto.IInjectorService}
*/
this.injector_ = $injector;
/**
* @type {angular.gettext.gettextCatalog}
* @private
*/
this.gettextCatalog_ = gettextCatalog;
/**
* @type {import("gmf/theme/Themes.js").ThemesService}
* @private
*/
this.gmfThemes_ = gmfThemes;
/**
* @type {import("gmf/layertree/TreeManager.js").LayertreeTreeManager}
* @private
*/
this.gmfTreeManager_ = gmfTreeManager;
/**
* @type {import("gmf/search/FulltextSearch.js").FulltextSearchService}
* @private
*/
this.fullTextSearch_ = gmfSearchFulltextSearch;
/**
* @type {function}
* @private
*/
this.ngeoSearchCreateGeoJSONBloodhound_ = ngeoSearchCreateGeoJSONBloodhound;
/**
* @type {import("ngeo/map/FeatureOverlayMgr.js").FeatureOverlayMgr}
* @private
*/
this.ngeoFeatureOverlayMgr = ngeoFeatureOverlayMgr;
/**
* @type {import("ngeo/statemanager/Location.js").StatemanagerLocation|undefined}
* @private
*/
this.ngeoLocation_ = ngeoLocation;
/**
* @type {import("ngeo/misc/AutoProjection.js").AutoProjectionService}
* @private
*/
this.ngeoAutoProjection_ = ngeoAutoProjection;
/**
* @type {?import("ol/Map.js").default}
*/
this.map = null;
/**
* @type {?function(): void}
*/
this.onInitCallback = null;
/**
* @type {function(unknown): void}
*/
this.searchActionCallback;
/**
* Supported projections for coordinates search.
* @type {import('ol/proj/Projection.js').default[]}
* @private
*/
this.coordinatesProjectionsInstances_ = [];
/**
* @type {import("ngeo/map/FeatureOverlay.js").FeatureOverlay}
* @private
*/
this.featureOverlay_ = ngeoFeatureOverlayMgr.getFeatureOverlay();
/**
* @type {Twitter.Typeahead.Options}
*/
this.typeaheadOptions = /** @type {Twitter.Typeahead.Options} */ ({
highlight: true,
});
/**
* @type {(Twitter.Typeahead.Dataset<olFeature<import('ol/geom/Geometry.js').default>>|Twitter.Typeahead.Dataset<CoordinateSuggestion>)[]}
*/
this.datasets = [];
/**
* @type {string}
*/
this.inputValue = '';
/**
* @type {string}
*/
this.color = '';
/**
* @type {boolean}
*/
this.displayColorPicker = false;
/**
* @type {?import('ngeo/search/searchDirective.js').SearchDirectiveListeners<olFeature<import('ol/geom/Geometry.js').default>>}
*/
this.listeners = null;
/**
* @type {import('ngeo/search/searchDirective.js').SearchDirectiveListeners<olFeature<import('ol/geom/Geometry.js').default>>}
*/
this.additionalListeners = {};
/**
* @type {boolean}
*/
this.clearButton = this.options.clearButton !== false;
/**
* @type {string}
*/
this.optionsName = null;
if (!this.clearButton) {
// Empty the search field on focus and blur.
this.element_.find('input').on('focus blur', () => {
this.clear();
});
}
this.featureOverlay_.setStyle(this.getSearchStyle_.bind(this));
this.scope_.$watch(() => this.color, this.setStyleColor.bind(this));
if (this.ngeoLocation_) {
const searchQuery = this.ngeoLocation_.getParam('search');
if (searchQuery) {
let resultIndex = 1;
if (this.ngeoLocation_.getParam('search-select-index')) {
resultIndex = parseInt(this.ngeoLocation_.getParam('search-select-index') || '', 10);
}
let mapZoom;
if (this.ngeoLocation_.getParam('search-maxzoom')) {
mapZoom = parseInt(this.ngeoLocation_.getParam('search-maxzoom') || '', 10);
} else if (this.ngeoLocation_.getParam('map_zoom')) {
mapZoom = parseInt(this.ngeoLocation_.getParam('map_zoom') || '', 10);
}
this.fulltextsearch_(searchQuery, resultIndex, mapZoom);
}
}
}
/**
* Called on initialization of the controller.
*/
$onInit() {
const config = this.optionsName || 'gmfSearchOptions';
const gettextCatalog = this.gettextCatalog_;
/**
* FIXME: dynamic typing when the config key is different
* @type {import('gmf/options.js').gmfSearchOptions}
*/
this.options = this.injector_.get(config);
this.placeholder = this.options.placeholder || 'Search…';
gettextCatalog.getString('Search…');
this.coordinatesProjectionsInstances_ =
this.options.coordinatesProjections === undefined
? [this.map.getView().getProjection()]
: this.ngeoAutoProjection_.getProjectionList(this.options.coordinatesProjections);
// Merge typeahead options from the controller options with the constant options
if (this.typeaheadOptions) {
Object.assign(this.options, this.typeaheadOptions);
}
this.initDatasets_();
this.listeners = this.mergeListeners_(this.additionalListeners, {
select: this.select_.bind(this),
change: this.handleChange_.bind(this),
close: this.close_.bind(this),
datasetsempty: this.datasetsempty_.bind(this),
});
if (this.onInitCallback) {
this.onInitCallback();
}
}
/**
* Merges the custom listeners received via the component attributes and the
* listeners that are needed for this controller to function (close and select).
* @param {import('ngeo/search/searchDirective.js').SearchDirectiveListeners<olFeature<import('ol/geom/Geometry.js').default>>} additionalListeners
* Custom provided listeners.
* @param {import('ngeo/search/searchDirective.js').SearchDirectiveListeners<olFeature<import('ol/geom/Geometry.js').default>>} listeners Default listeners.
* @return {import('ngeo/search/searchDirective.js').SearchDirectiveListeners<olFeature<import('ol/geom/Geometry.js').default>>} Merged listeners.
* @private
*/
mergeListeners_(additionalListeners, listeners) {
if (additionalListeners === undefined) {
return listeners;
}
return {
open: additionalListeners.open,
close:
additionalListeners.close === undefined
? listeners.close
: function () {
listeners.close();
additionalListeners.close();
},
change: additionalListeners.change,
cursorchange: additionalListeners.cursorchange,
datasetsempty: additionalListeners.datasetsempty,
select:
additionalListeners.select === undefined
? listeners.select
: function (evt, obj, dataset) {
listeners.select(evt, obj, dataset);
additionalListeners.select(evt, obj, dataset);
},
autocomplete: additionalListeners.autocomplete,
};
}
/**
* Initialize datasets for the search
* @private
*/
initDatasets_() {
const gettextCatalog = this.gettextCatalog_;
for (const datasource of this.options.datasources || []) {
/** @type {string[]} */
const groupValues = datasource.groupValues !== undefined ? datasource.groupValues : this.groups;
/** @type {import('gmf/options.js').SearchAction[]} */
const groupActions = datasource.groupActions || [];
/** @type {{title: string, filter: function(import("geojson").Feature): boolean}[]} */
const filters = [];
if (groupValues.length === 0) {
filters.push({
'title': '',
'filter': this.filterLayername_(),
});
} else {
groupValues.forEach((layerName) => {
filters.push({
'title': layerName,
'filter': this.filterLayername_(layerName),
});
});
}
groupActions.forEach((action) => {
filters.push({
'title': gettextCatalog.getString(action.title),
'filter': this.filterAction_(action.action),
});
});
filters.forEach((filter) => {
this.datasets.push(
this.createDataset_(
{
bloodhoundOptions: datasource.bloodhoundOptions,
datasetTitle: filter.title,
labelKey: datasource.labelKey,
projection: datasource.projection,
typeaheadDatasetOptions: datasource.typeaheadDatasetOptions,
url: datasource.url || this.fulltextsearchUrl,
},
filter.filter
)
);
});
}
// For searching coordinates
this.datasets.push({
source: this.createSearchCoordinates_(this.map.getView()),
name: 'coordinates',
display: 'label',
templates: {
header: () => {
const header = gettextCatalog.getString('Recenter to');
return `<div class="gmf-search-header" translate>${header}</div>`;
},
/**
* @param {CoordinateSuggestion} suggestion
*/
suggestion: (suggestion) => {
const coordinates = suggestion.label;
let html = `<p class="gmf-search-label">${coordinates}</p>`;
html = `<div class="gmf-search-datum">${html}</div>`;
return html;
},
},
});
}
/**
* @param {import('gmf/options.js').SearchComponentDatasource} config The config of the dataset.
* @param {(function(import("geojson").Feature): boolean)=} opt_filter A filter function
* based on a GeoJSONFeaturesCollection's array.
* @return {Twitter.Typeahead.Dataset<olFeature<import('ol/geom/Geometry.js').default>>} A typeahead dataset.
* @private
*/
createDataset_(config, opt_filter) {
const gettextCatalog = this.gettextCatalog_;
const componentScope = this.scope_;
const compile = this.compile_;
const bloodhoundEngine = this.createAndInitBloodhound_(config, opt_filter);
/** @type {Twitter.Typeahead.Dataset<olFeature<import('ol/geom/Geometry.js').default>>} */
const typeaheadDataset = {
limit: Infinity,
source: bloodhoundEngine.ttAdapter(),
display: (suggestion) => {
return suggestion.get(config.labelKey);
},
templates: {
header: () => {
if (!config.datasetTitle) {
return '';
} else {
const header = gettextCatalog.getString(config.datasetTitle);
return `<div class="gmf-search-header">${header}</div>`;
}
},
suggestion: (suggestion) => {
const scope = componentScope.$new(true);
// @ts-ignore: scope ...
scope.feature = suggestion;
let html = `<p class="gmf-search-label" translate>${suggestion.get(config.labelKey)}</p>`;
html += `<p class="gmf-search-group" translate>${
suggestion.get('layer_name') || config.datasetTitle
}</p>`;
html = `<div class="gmf-search-datum">${html}</div>`;
return compile(html)(scope).html();
},
},
};
if (config.typeaheadDatasetOptions) {
Object.assign(typeaheadDataset, config.typeaheadDatasetOptions);
}
return typeaheadDataset;
}
/**
* @param {string} action The action to keep.
* @return {(function(import("geojson").Feature): boolean)} A filter function based on a
* GeoJSONFeaturesCollection's array.
* @private
*/
filterAction_(action) {
return (
/**
* @param {import("geojson").Feature} feature
* @return {boolean}
*/
function (feature) {
const properties = feature.properties || {};
if (properties.actions) {
// result is an action (add_theme, add_group, ...)
// add it to the corresponding group
return (
!properties.layer_name &&
/** @type {import('gmf/options.js').SearchAction[]} */ (properties.actions).some(
(act) => act.action === action
)
);
} else {
return false;
}
}
);
}
/**
* @param {string=} opt_layerName The layerName to keep. If null, keep all layers
* (In all cases, except actions layers).
* @return {function(import("geojson").Feature): boolean} A filter function based on a
* GeoJSONFeaturesCollection's array.
* @private
*/
filterLayername_(opt_layerName) {
return (
/**
* @param {import("geojson").Feature} feature
* @return {boolean}
*/
function (feature) {
const featureLayerName = (feature.properties || {}).layer_name;
// Keep only layers with layer_name (don't keep action layers).
if (featureLayerName === undefined) {
return false;
}
if (opt_layerName === undefined) {
return true;
}
return featureLayerName === opt_layerName;
}
);
}
/**
* @param {import('gmf/options.js').SearchComponentDatasource} config The config of the dataset.
* @param {(function(import("geojson").Feature): boolean)=} opt_filter Afilter function
* based on a GeoJSONFeaturesCollection's array.
* @return {Bloodhound<olFeature<import('ol/geom/Geometry.js').default>[]>} The bloodhound engine.
* @private
*/
createAndInitBloodhound_(config, opt_filter) {
if (!this.map) {
throw new Error('Missing map');
}
const mapProjectionCode = this.map.getView().getProjection().getCode();
const remoteOptions = this.getBloodhoudRemoteOptions_();
const bloodhound = this.ngeoSearchCreateGeoJSONBloodhound_(
config.url,
opt_filter,
olProj.get(mapProjectionCode),
olProj.get(config.projection),
config.bloodhoundOptions,
remoteOptions
);
bloodhound.initialize();
return bloodhound;
}
/**
* @return {Bloodhound.RemoteOptions<GeoJSON.FeatureCollection>} Options.
* @private
*/
getBloodhoudRemoteOptions_() {
const gettextCatalog = this.gettextCatalog_;
return /** @type {Bloodhound.RemoteOptions<GeoJSON.FeatureCollection>} */ ({
rateLimitWait: this.options.delay == undefined ? 50 : this.options.delay,
prepare: (query, settings) => {
const url = settings.url;
if (!url) {
throw new Error('Missing URL');
}
const lang = gettextCatalog.getCurrentLanguage();
settings.xhrFields = {
withCredentials: true,
};
settings.url = olUriAppendParams(url, {
query: query,
lang: lang,
});
return settings;
},
});
}
/**
* @typedef {Object} CoordinateSuggestion
* @property {string} label
* @property {number[]} position
* @property {string} tt_source
*/
/**
* @param {import("ol/View.js").default} view View.
* @return {function(string, function(CoordinateSuggestion[]))} function defining parameters for the search
* suggestions.
* @private
*/
createSearchCoordinates_(view) {
const viewProjection = view.getProjection();
const extent = viewProjection.getExtent();
return (query, callback) => {
const suggestions = [];
const coordinates = this.ngeoAutoProjection_.stringToCoordinates(query);
if (coordinates === null) {
return;
}
const position = this.ngeoAutoProjection_.tryProjectionsWithInversion(
coordinates,
extent,
viewProjection,
this.coordinatesProjectionsInstances_.map((proj) => proj.getCode())
);
if (position === null) {
return;
}
suggestions.push({
label: coordinates.join(' '),
position: position,
tt_source: 'coordinates',
});
callback(suggestions);
};
}
/**
* Style for search results.
* @param {null|olFeature<import('ol/geom/Geometry.js').default>|import("ol/render/Feature.js").default} feature
* The searched feature.
* @param {number} resolution The current resolution of the map.
* @return {import("ol/style/Style.js").default} A style for this kind of features.
* @private
*/
getSearchStyle_(feature, resolution) {
if (!feature) {
throw new Error('Missing feature');
}
const style = buildStyle(
this.options.styles[feature.get('layer_name')] || this.options.styles['default']
);
const trueStyle = /** @type {import('ol/style/Style.js').default} */ (style);
if (this.color) {
const color = asColorArray(this.color);
const strokeStyle = trueStyle.getStroke();
const prevStrokeColor = /** @type {number[]} */ (strokeStyle.getColor());
const strokeColor = color.slice();
strokeColor[3] = prevStrokeColor[3];
if (strokeStyle) {
strokeStyle.setColor(strokeColor);
}
const fillStyle = trueStyle.getFill();
const prevFillColor = /** @type {number[]} */ (fillStyle.getColor());
const fillColor = color.slice();
fillColor[3] = prevFillColor[3];
if (fillStyle) {
fillStyle.setColor(fillColor);
}
let imageStyle = trueStyle.getImage();
if (imageStyle) {
const circleStyle = /** @type {import('ol/style/Circle.js').default} */ (imageStyle);
const imageStrokeStyle = circleStyle.getStroke();
if (imageStrokeStyle) {
imageStrokeStyle.setColor(strokeColor);
}
const imageFillStyle = circleStyle.getFill();
if (imageFillStyle) {
imageFillStyle.setColor(fillColor);
}
// clone the image as only new ones are rerendered
imageStyle = imageStyle.clone();
trueStyle.setImage(imageStyle);
}
}
return trueStyle;
}
/**
* Set a new color for the search feature style.
* @param {string} color The color to set.
*/
setStyleColor(color) {
if (color) {
this.color = color;
this.ngeoFeatureOverlayMgr.getLayer().changed();
}
}
/**
* @private
*/
setTTDropdownVisibility_() {
if (this.clearButton) {
const ttDropdown = this.element_.find('.twitter-typeahead .tt-menu');
this.inputValue ? ttDropdown.show() : ttDropdown.hide();
}
}
/**
*/
onClearButton() {
this.featureOverlay_.clear();
this.clear();
this.displayColorPicker = false;
}
/**
*/
clear() {
const typeahead = this.element_.find('.twitter-typeahead');
const ttmenu = typeahead.children('.tt-menu');
const inputs = typeahead.children('input');
// clear model value, the 'real' input value and tt's suggestions
this.inputValue = '';
$(inputs[1]).typeahead('val', '');
ttmenu.children('.tt-dataset').empty();
this.setTTDropdownVisibility_();
}
/**
*/
blur() {
const typeahead = this.element_.find('.twitter-typeahead');
const inputs = typeahead.children('input');
// Blur as soon as possible in digest loops
this.timeout_(() => {
$(inputs[1]).blur();
});
}
/**
* @param {JQueryEventObject} event Event.
* @param {olFeature<import('ol/geom/Geometry.js').default>|CoordinateSuggestion} suggestion Suggestion.
* @param {Twitter.Typeahead.Dataset<olFeature<import('ol/geom/Geometry.js').default>>} dataset Dataset.
* @private
*/
select_(event, suggestion, dataset) {
if (!this.map) {
throw new Error('Missing map');
}
// @ts-ignore: extra parameter
if (suggestion.tt_source === 'coordinates') {
const coordinateSuggestion = /** @type {CoordinateSuggestion} */ (suggestion);
const geom = new olGeomPoint(coordinateSuggestion.position);
this.featureOverlay_.clear();
this.featureOverlay_.addFeature(
new olFeature({
geometry: geom,
'layer_name': COORDINATES_LAYER_NAME,
})
);
this.map.getView().setCenter(coordinateSuggestion.position);
this.leaveSearch_();
} else {
if (!(suggestion instanceof olFeature)) {
throw new Error('Wrong suggestion type');
}
this.selectFromGMF_(event, suggestion, dataset);
}
}
/**
* @param {JQueryEventObject} event Event.
* @param {olFeature<import('ol/geom/Geometry.js').default>} feature Feature.
* @param {Twitter.Typeahead.Dataset<olFeature<import('ol/geom/Geometry.js').default>>} dataset Dataset.
* @private
*/
selectFromGMF_(event, feature, dataset) {
if (!this.map) {
throw new Error('Missing map');
}
const actions = feature.get('actions');
const featureGeometry = feature.getGeometry();
if (actions) {
for (let i = 0, ii = actions.length; i < ii; i++) {
const action = actions[i];
const actionName = action.action;
const actionData = action.data;
if (actionName == 'add_theme') {
this.gmfThemes_.getThemesObject().then((themes) => {
const theme = findThemeByName(themes, actionData);
if (theme) {
gmfBackgroundlayerStatus.touchedByUser = true;
this.gmfTreeManager_.addFirstLevelGroups(theme.children);
}
});
} else if (actionName == 'add_group') {
this.gmfTreeManager_.addGroupByName(actionData, true);
} else if (actionName == 'add_layer') {
const groupActions = /** @type {import('gmf/options.js').SearchAction[]} */ (this.options
.datasources[0].groupActions);
let datasourcesActionsHaveAddLayer;
groupActions.forEach((groupAction) => {
if (groupAction.action === 'add_layer') {
datasourcesActionsHaveAddLayer = true;
return true;
}
});
if (datasourcesActionsHaveAddLayer) {
const silent = !!featureGeometry;
this.gmfTreeManager_.addGroupByLayerName(actionData, true, silent);
}
} else {
if (this.searchActionCallback) {
this.searchActionCallback(action);
}
}
}
}
const size = this.map.getSize();
if (featureGeometry instanceof SimpleGeometry && size) {
const view = this.map.getView();
this.featureOverlay_.clear();
this.featureOverlay_.addFeature(feature);
this.displayColorPicker = true;
const fitArray =
featureGeometry.getType() === 'GeometryCollection' ? featureGeometry.getExtent() : featureGeometry;
view.fit(fitArray, {
size: size,
maxZoom: this.options.maxZoom || 16,
});
}
this.leaveSearch_();
}
/**
* @private
*/
leaveSearch_() {
if (!this.clearButton) {
this.clear();
}
this.blur();
}
/**
* @private
*/
close_() {
if (!this.clearButton) {
this.setTTDropdownVisibility_();
}
}
/**
* @param {JQueryEventObject} event Event.
* @param {string} query Query.
* @param {boolean} empty Empty.
* @private
*/
datasetsempty_(event, query, empty) {
// workaround to display a 'no result found' in the search result when all of
// the datasets are empty.
// based on https://github.com/twitter/typeahead.js/issues/780#issuecomment-251554452
// FIXME: remove this workaround when https://github.com/corejavascript/typeahead.js/issues/60 is fixed
// If there is no clear button clean the map and colorpicker.
if (!this.clearButton) {
this.featureOverlay_.clear();
this.displayColorPicker = false;
}
const menu = this.element_.find('.twitter-typeahead .tt-menu');
const message = menu.children('.gmf-search-no-results');
if (message.length == 0) {
const gettextCatalog = this.gettextCatalog_;
const innerHTML = gettextCatalog.getString('No result found');
const div = $(`<div class="gmf-search-no-results" translate>${innerHTML}</div>`);
menu.append(div);
}
if (empty) {
message.show();
menu.addClass('gmf-search-no-results');
} else {
menu.removeClass('gmf-search-no-results');
message.hide();
}
}
/**
* Performs a full-text search and centers the map on the first search result.
* @param {string} query Search query.
* @param {number} resultIndex Return nth result instead.
* @param {number=} opt_zoom Optional zoom level.
* @private
*/
fulltextsearch_(query, resultIndex, opt_zoom) {
if (resultIndex < 1) {
// can't be lower than one
resultIndex = 1;
}