/
Geosuggest.jsx
340 lines (289 loc) · 7.79 KB
/
Geosuggest.jsx
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
/* global window */
import React from 'react';
import classnames from 'classnames';
import defaults from './defaults';
import filterInputAttributes from './filter-input-attributes';
import Input from './input';
import SuggestList from './suggest-list';
// Escapes special characters in user input for regex
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/**
* Entry point for the Geosuggest component
*/
class Geosuggest extends React.Component {
/**
* The constructor. Sets the initial state.
* @param {Object} props The properties object.
*/
constructor(props) {
super(props);
this.state = {
isSuggestsHidden: true,
userInput: this.props.initialValue,
activeSuggest: null,
suggests: [],
timer: null
};
}
/**
* Change inputValue if prop changes
* @param {Object} props The new props
*/
componentWillReceiveProps(props) {
if (this.props.initialValue !== props.initialValue) {
this.setState({userInput: props.initialValue});
}
}
/**
* Called on the client side after component is mounted.
* Google api sdk object will be obtained and cached as a instance property.
* Necessary objects of google api will also be determined and saved.
*/
componentDidMount() {
this.setState({userInput: this.props.initialValue});
var googleMaps = this.props.googleMaps ||
(window.google && // eslint-disable-line no-extra-parens
window.google.maps) ||
this.googleMaps;
if (!googleMaps) {
console.error(// eslint-disable-line no-console
'Google map api was not found in the page.');
return;
}
this.googleMaps = googleMaps;
this.autocompleteService = new googleMaps.places.AutocompleteService();
this.geocoder = new googleMaps.Geocoder();
}
/**
* When the component will unmount
*/
componentWillUnmount() {
clearTimeout(this.state.timer);
}
/**
* When the input got changed
* @param {String} userInput The input value of the user
*/
onInputChange(userInput) {
this.setState({userInput}, () => {
this.showSuggests();
this.props.onChange(userInput);
});
}
/**
* When the input gets focused
*/
onInputFocus() {
this.props.onFocus();
this.showSuggests();
}
/**
* When the input gets blurred
*/
onInputBlur() {
if (!this.state.ignoreBlur) {
this.hideSuggests();
}
}
/**
* Focus the input
*/
focus() {
this.refs.input.focus();
}
/**
* Update the value of the user input
* @param {String} userInput the new value of the user input
*/
update(userInput) {
this.setState({userInput});
this.props.onChange(userInput);
}
/*
* Clear the input and close the suggestion pane
*/
clear() {
this.setState({userInput: ''}, () => this.hideSuggests());
}
/**
* Search for new suggests
*/
searchSuggests() {
if (!this.state.userInput) {
this.updateSuggests();
return;
}
const options = {
input: this.state.userInput
};
['location', 'radius', 'bounds', 'types'].forEach(option => {
if (this.props[option]) {
options[option] = this.props[option];
}
});
if (this.props.country) {
options.componentRestrictions = {
country: this.props.country
};
}
this.autocompleteService.getPlacePredictions(
options,
suggestsGoogle => {
this.updateSuggests(suggestsGoogle || []); // can be null
if (this.props.autoActivateFirstSuggest) {
this.activateSuggest('next');
}
}
);
}
/**
* Update the suggests
* @param {Array} suggestsGoogle The new google suggests
*/
updateSuggests(suggestsGoogle = []) {
var suggests = [],
regex = new RegExp(escapeRegExp(this.state.userInput), 'gim'),
skipSuggest = this.props.skipSuggest;
this.props.fixtures.forEach(suggest => {
if (!skipSuggest(suggest) && suggest.label.match(regex)) {
suggest.placeId = suggest.label;
suggests.push(suggest);
}
});
suggestsGoogle.forEach(suggest => {
if (!skipSuggest(suggest)) {
suggests.push({
label: this.props.getSuggestLabel(suggest),
placeId: suggest.place_id
});
}
});
this.setState({suggests});
}
/**
* Show the suggestions
*/
showSuggests() {
this.searchSuggests();
this.setState({isSuggestsHidden: false});
}
/**
* Hide the suggestions
*/
hideSuggests() {
this.props.onBlur();
const timer = setTimeout(() => {
this.setState({isSuggestsHidden: true});
}, 100);
this.setState({timer});
}
/**
* Activate a new suggest
* @param {String} direction The direction in which to activate new suggest
*/
activateSuggest(direction) { // eslint-disable-line complexity
if (this.state.isSuggestsHidden) {
this.showSuggests();
return;
}
const suggestsCount = this.state.suggests.length - 1,
next = direction === 'next';
let newActiveSuggest = null,
newIndex = 0,
i = 0;
for (i; i <= suggestsCount; i++) {
if (this.state.suggests[i] === this.state.activeSuggest) {
newIndex = next ? i + 1 : i - 1;
}
}
if (!this.state.activeSuggest) {
newIndex = next ? 0 : suggestsCount;
}
if (newIndex >= 0 && newIndex <= suggestsCount) {
newActiveSuggest = this.state.suggests[newIndex];
}
this.setState({activeSuggest: newActiveSuggest});
}
/**
* When an item got selected
* @param {GeosuggestItem} suggest The selected suggest item
*/
selectSuggest(suggest) {
if (!suggest) {
suggest = {
label: this.state.userInput
};
}
this.setState({
isSuggestsHidden: true,
userInput: suggest.label
});
if (suggest.location) {
this.setState({ignoreBlur: false});
this.props.onSuggestSelect(suggest);
return;
}
this.geocodeSuggest(suggest);
}
/**
* Geocode a suggest
* @param {Object} suggest The suggest
*/
geocodeSuggest(suggest) {
this.geocoder.geocode(
suggest.placeId ? {placeId: suggest.placeId} : {address: suggest.label},
(results, status) => {
if (status !== this.googleMaps.GeocoderStatus.OK) {
return;
}
var gmaps = results[0],
location = gmaps.geometry.location;
suggest.gmaps = gmaps;
suggest.location = {
lat: location.lat(),
lng: location.lng()
};
this.props.onSuggestSelect(suggest);
}
);
}
/**
* Render the view
* @return {Function} The React element to render
*/
render() {
const attributes = filterInputAttributes(this.props),
classes = classnames(
'geosuggest',
this.props.className
);
return <div className={classes}>
<Input className={this.props.inputClassName}
ref='input'
value={this.state.userInput}
onChange={this.onInputChange.bind(this)}
onFocus={this.onInputFocus.bind(this)}
onBlur={this.onInputBlur.bind(this)}
onNext={() => this.activateSuggest('next')}
onPrev={() => this.activateSuggest('prev')}
onSelect={() => this.selectSuggest(this.state.activeSuggest)}
onEscape={this.hideSuggests.bind(this)}
{...attributes} />
<SuggestList
isHidden={this.state.isSuggestsHidden}
suggests={this.state.suggests}
activeSuggest={this.state.activeSuggest}
onSuggestMouseDown={() => this.setState({ignoreBlur: true})}
onSuggestMouseOut={() => this.setState({ignoreBlur: false})}
onSuggestSelect={this.selectSuggest.bind(this)}/>
</div>;
}
}
/**
* Default values for the properties
* @type {Object}
*/
Geosuggest.defaultProps = defaults;
export default Geosuggest;