-
Notifications
You must be signed in to change notification settings - Fork 383
/
search.js
254 lines (236 loc) · 12.2 KB
/
search.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
/*
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as Rx from 'rxjs';
import toBbox from 'turf-bbox';
import pointOnSurface from '@turf/point-on-surface';
import assign from 'object-assign';
import { sortBy, isNil } from 'lodash';
import { queryableLayersSelector, getLayerFromName } from '../selectors/layers';
import { updateAdditionalLayer } from '../actions/additionallayers';
import { showMapinfoMarker, featureInfoClick} from '../actions/mapInfo';
import { zoomToExtent, zoomToPoint} from '../actions/map';
import {
SEARCH_LAYER_WITH_FILTER,
TEXT_SEARCH_STARTED,
TEXT_SEARCH_RESULTS_PURGE,
TEXT_SEARCH_RESET,
TEXT_SEARCH_ITEM_SELECTED,
ZOOM_ADD_POINT,
addMarker,
nonQueriableLayerError,
serverError,
resultsPurge,
searchTextLoading,
searchResultLoaded,
searchResultError,
selectNestedService,
searchTextChanged
} from '../actions/search';
import CoordinatesUtils from '../utils/CoordinatesUtils';
import {defaultIconStyle} from '../utils/SearchUtils';
import {generateTemplateString} from '../utils/TemplateUtils';
import {API} from '../api/searchText';
import {getFeatureSimple} from '../api/WFS';
/**
* Gets every `TEXT_SEARCH_STARTED` event.
* Dispatches the request to all the services in the action, postprocess them
* and updates every tume the results
* @param {external:Observable} action$ manages `TEXT_SEARCH_STARTED` and `TEXT_SEARCH_RESULTS_PURGE`, `TEXT_SEARCH_RESET`, `TEXT_SEARCH_ITEM_SELECTED` for cancellation
* @memberof epics.search
* @return {external:Observable}
*/
export const searchEpic = action$ =>
action$.ofType(TEXT_SEARCH_STARTED)
.debounceTime(250)
.switchMap( action =>
// create a stream of streams from array
Rx.Observable.from(
(action.services || [ {type: "nominatim", priority: 5} ])
// Create an stream for each Service
.map((service) => {
const serviceInstance = API.Utils.getService(service.type);
if (!serviceInstance) {
const err = new Error("Service Missing");
err.msgId = "search.service_missing";
err.serviceType = service.type;
return Rx.Observable.of(err).do((e) => {throw e; });
}
return Rx.Observable.defer(() =>
serviceInstance(action.searchText, service.options)
.then( (response = []) => response.map(result => ({...result, __SERVICE__: service, __PRIORITY__: service.priority || 0}))
))
.retryWhen(errors => errors.delay(200).scan((count, err) => {
if ( count >= 2) {
throw err;
}
return count + 1;
}, 0));
}) // map
)// from
// merge all results from the streams
.mergeAll()
.scan((oldRes, newRes) => sortBy([...oldRes, ...newRes], ["__PRIORITY__"]))
// limit the number of results returned from all services to maxResults
.map((results) => searchResultLoaded(results.slice(0, action.maxResults || 15), false))
.startWith(searchTextLoading(true))
.takeUntil(action$.ofType( TEXT_SEARCH_RESULTS_PURGE, TEXT_SEARCH_RESET, TEXT_SEARCH_ITEM_SELECTED))
.concat([searchTextLoading(false)])
.catch(e => {
const err = {msgId: "search.generic_error", ...e, message: e.message, stack: e.stack};
return Rx.Observable.from([searchResultError(err), searchTextLoading(false)]);
})
);
/**
* Gets every `TEXT_SEARCH_ITEM_SELECTED` event.
* on item selections zooms to the selected item, adds the marker to the marker layer and clear
* search results.
* If the selected item has a `__SERVICE__.then` entry, configures the search tool
* to manage the nested services.
* If the searvice has a search text template, it configures the searchText with
* using the template.
* @param {Observable} action$ stream of actions. Manages `TEXT_SEARCH_ITEM_SELECTED`
* @memberof epics.search
* @return {Observable}
*/
export const searchItemSelected = action$ =>
action$.ofType(TEXT_SEARCH_ITEM_SELECTED)
.switchMap(action => {
// itemSelectionStream --> emits actions for zoom and marker add
let itemSelectionStream = Rx.Observable.of(action.item)
.concatMap((item) => {
if (item && item.__SERVICE__ && item.__SERVICE__.geomService) {
let staticFilter = generateTemplateString(item.__SERVICE__.geomService.options.staticFilter || "")(item);
// retrieve geometry from geomService or pass the item directly
return Rx.Observable.fromPromise(
API.Utils.getService(item.__SERVICE__.geomService.type)("", assign({}, item.__SERVICE__.geomService.options, { staticFilter }))
.then(res => assign({}, item, { geometry: CoordinatesUtils.mergeToPolyGeom(res) }))
);
}
return Rx.Observable.of(action.item);
}).concatMap((item) => {
// check if the service has been configured to start a GetFeatureInfo request based on the item selected
// if so, then do it with a point inside the geometry
let bbox = item.bbox || item.properties.bbox || toBbox(item);
let actions = [
zoomToExtent([bbox[0], bbox[1], bbox[2], bbox[3]], "EPSG:4326", 21),
addMarker(item)
];
if (item.__SERVICE__ && !isNil(item.__SERVICE__.launchInfoPanel) && item.__SERVICE__.options && item.__SERVICE__.options.typeName) {
let coord = pointOnSurface(item).geometry.coordinates;
const latlng = { lng: coord[0], lat: coord[1] };
const typeName = item.__SERVICE__.options.typeName;
if (coord) {
let itemId = null;
let filterNameList = [];
let overrideParams = {};
if (item.__SERVICE__.launchInfoPanel === "single_layer") {
/* take info from the item selected and restrict feature info to this layer
* and force info_format to application/json for allowing
* filtering results later on (identify epic) */
filterNameList = [typeName];
itemId = item.id;
overrideParams = { [item.__SERVICE__.options.typeName]: { info_format: "application/json" } };
}
return [
featureInfoClick({ latlng }, typeName, filterNameList, overrideParams, itemId),
showMapinfoMarker(),
...actions
];
}
}
return actions;
});
const item = action.item;
let nestedServices = item && item.__SERVICE__ && item.__SERVICE__.then;
// if a nested service is present, select the item and the nested service
let nestedServicesStream = nestedServices ? Rx.Observable.of(selectNestedService(
nestedServices.map((nestedService) => ({
...nestedService,
options: {
item,
...nestedService.options
}
})), {
text: generateTemplateString(item.__SERVICE__.displayName || "")(item),
placeholder: item.__SERVICE__.nestedPlaceholder && generateTemplateString(item.__SERVICE__.nestedPlaceholder || "")(item),
placeholderMsgId: item.__SERVICE__.nestedPlaceholderMsgId && generateTemplateString(item.__SERVICE__.nestedPlaceholderMsgId || "")(item)
},
generateTemplateString(item.__SERVICE__.searchTextTemplate || "")(item)
)) : Rx.Observable.empty();
// if the service has a searchTextTemplate, use it to modify the search text to display
let searchTextTemplate = item.__SERVICE__ && item.__SERVICE__.searchTextTemplate;
let searchTextStream = searchTextTemplate ? Rx.Observable.of(searchTextChanged(generateTemplateString(searchTextTemplate)(item))) : Rx.Observable.empty();
return Rx.Observable.of(resultsPurge()).concat(itemSelectionStream, nestedServicesStream, searchTextStream);
});
/**
* Gets every `ZOOM_ADD_POINT` event.
* it creates/updates an additional layer for showing a marker for a given point
*
*/
export const zoomAndAddPointEpic = (action$, store) =>
action$.ofType(ZOOM_ADD_POINT)
.switchMap(action => {
const feature = {
type: "Feature",
geometry: {
type: "Point",
coordinates: [action.pos.x, action.pos.y]
}
};
const state = store.getState();
return Rx.Observable.from([
updateAdditionalLayer("search", "search", 'overlay', {
features: [feature],
type: "vector",
name: "searchPoints",
id: "searchPoints",
visibility: true,
style: state.search && state.search.style || defaultIconStyle
}),
zoomToPoint(action.pos, action.zoom, action.crs)
]);
});
/**
* Gets every `SEARCH_WITH_FILTER` event.
* Triggers a GetFeature with a subsequent getFeatureInfo with a point taken from geometry of first feature retrieved
*/
export const searchOnStartEpic = (action$, store) =>
action$.ofType(SEARCH_LAYER_WITH_FILTER)
.switchMap(({layer: name, "cql_filter": cqlFilter}) => {
const state = store.getState();
// if layer is NOT queriable and visible then show error notification
if (queryableLayersSelector(state).filter(l => l.name === name ).length === 0) {
return Rx.Observable.of(nonQueriableLayerError());
}
const layer = getLayerFromName(state, name);
if (layer && cqlFilter) {
return Rx.Observable.defer(() =>
// take geoserver url from layer
getFeatureSimple(layer.url, {
maxFeatures: 1,
typeName: name,
srsName: "EPSG:4326",
outputFormat: "application/json",
// create a filter like : `(ATTR ilike '%word1%') AND (ATTR ilike '%word2%')`
cql_filter: cqlFilter
})
.then( (response = {}) => response.features && response.features.length && {...response.features[0], typeName: name})
)
.switchMap(({ type, geometry, typeName }) => {
let coord = pointOnSurface({ type, geometry }).geometry.coordinates;
const latlng = {lng: coord[0], lat: coord[1] };
if (coord) { // trigger get feature info
return Rx.Observable.of(featureInfoClick({latlng}, typeName, [typeName], {[typeName]: {cql_filter: cqlFilter}}), showMapinfoMarker());
}
return Rx.Observable.empty();
}).catch(() => {
return Rx.Observable.of(serverError());
});
}
return Rx.Observable.empty();
});