Subversion Repositories eFlore/Applications.cel

Rev

Rev 3866 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 3866 Rev 3867
1
import {debounce} from "../lib/debounce.js";
1
import {debounce} from "../lib/debounce.js";
2
 
2
 
3
export const NOMINATIM_OSM_URL = 'https://nominatim.openstreetmap.org/';
3
export const NOMINATIM_OSM_URL = 'https://nominatim.openstreetmap.org/';
4
const NOMINATIM_OSM_DEFAULT_PARAMS = {
4
const NOMINATIM_OSM_DEFAULT_PARAMS = {
5
    'format': 'json',
5
    'format': 'json',
6
    'countrycodes': 'fr',
6
    'countrycodes': 'fr',
7
    'addressdetails': 1,
7
    'addressdetails': 1,
8
    'limit': 10
8
    'limit': 10
9
};
9
};
10
const ESC_KEY_STRING = /^Esc(ape)?/;
10
const ESC_KEY_STRING = /^Esc(ape)?/;
11
 
11
 
12
export function TbPlaces(clientCallback) {
12
export function TbPlaces(clientCallback) {
13
 
13
 
14
    /**
14
    /**
15
     * used in this.onSuggestionSelected()
15
     * used in this.onSuggestionSelected()
16
     *
16
     *
17
     * @callback clientCallback
17
     * @callback clientCallback
18
     * @param {String} locality
18
     * @param {String} locality
19
     * @param {{lat: number, lng: number }} coordinates
19
     * @param {{lat: number, lng: number }} coordinates
20
     */
20
     */
21
    this.clientCallback = clientCallback;
21
    this.clientCallback = clientCallback;
22
    this.searchResults = [];
22
    this.searchResults = [];
23
}
23
}
24
 
24
 
25
TbPlaces.prototype.init = function() {
25
TbPlaces.prototype.init = function() {
26
    this.initForm();
26
    this.initForm();
27
    this.initEvts();
27
    this.initEvts();
28
};
28
};
29
 
29
 
30
TbPlaces.prototype.initForm = function() {
30
TbPlaces.prototype.initForm = function() {
31
    this.places = $('#tb-places');
31
    this.places = $('#tb-places');
32
    this.placeLabel = this.places.siblings('label');
32
    this.placeLabel = this.places.siblings('label');
33
    this.placesResults = $('.tb-places-results');
33
    this.placesResults = $('.tb-places-results');
34
    this.placesResultsContainer = $('.tb-places-results-container');
34
    this.placesResultsContainer = $('.tb-places-results-container');
35
    this.placesCloseButton = $('.tb-places-close');
35
    this.placesCloseButton = $('.tb-places-close');
36
};
36
};
37
 
37
 
38
TbPlaces.prototype.initEvts = function() {
38
TbPlaces.prototype.initEvts = function() {
39
    if (0 < this.places.length) {
39
    if (0 < this.places.length) {
40
 
40
 
41
        this.toggleCloseButton(false);
41
        this.toggleCloseButton(false);
42
        this.places.off('input').on('input', debounce(this.launchSearch.bind(this), 500));
42
        this.places.off('input').on('input', debounce(this.launchSearch.bind(this), 500));
43
        this.places.off('keydown').on('keydown', debounce(this.handlePlacesKeydown.bind(this), 500));
43
        this.places.off('keydown').on('keydown', debounce(this.handlePlacesKeydown.bind(this), 500));
44
    }
44
    }
45
};
45
};
46
 
46
 
47
TbPlaces.prototype.handlePlacesKeydown = function(evt) {
47
TbPlaces.prototype.handlePlacesKeydown = function(evt) {
48
    const suggestionEl = $('.tb-places-suggestion'),
48
    const suggestionEl = $('.tb-places-suggestion'),
49
        isEscape = 27 === evt.keyCode || ESC_KEY_STRING.test(evt.key),
49
        isEscape = 27 === evt.keyCode || ESC_KEY_STRING.test(evt.key),
50
        isArrowDown = 40 === evt.keyCode || 'ArrowDown' === evt.key,
50
        isArrowDown = 40 === evt.keyCode || 'ArrowDown' === evt.key,
51
        isEnter = 13 === evt.keyCode || 'Enter' === evt.key;
51
        isEnter = 13 === evt.keyCode || 'Enter' === evt.key;
52
 
52
 
53
    if (isEscape || isArrowDown || isEnter) {
53
    if (isEscape || isArrowDown || isEnter) {
54
        evt.preventDefault();
54
        evt.preventDefault();
55
 
55
 
56
        if (isEscape) {
56
        if (isEscape) {
57
            this.placesCloseButton.trigger('click');
57
            this.placesCloseButton.trigger('click');
58
            this.places.focus();
58
            this.places.focus();
59
        } else if(isArrowDown || isEnter) {
59
        } else if(isArrowDown || isEnter) {
60
            if ( 0 <  suggestionEl.length) {
60
            if ( 0 <  suggestionEl.length) {
61
                suggestionEl.first().focus();
61
                suggestionEl.first().focus();
62
            } else {
62
            } else {
63
                this.launchSearch();
63
                this.launchSearch();
64
            }
64
            }
65
        }
65
        }
66
    }
66
    }
67
};
67
};
68
 
68
 
69
TbPlaces.prototype.launchSearch = function () {
69
TbPlaces.prototype.launchSearch = function () {
70
    if (!!this.places.val()) {
70
    if (!!this.places.val()) {
71
        const url = NOMINATIM_OSM_URL+'search',
71
        const url = NOMINATIM_OSM_URL+'search',
72
            params = {
72
            params = {
73
                'q': this.places.val(),
73
                'q': this.places.val(),
74
                'format': 'json',
74
                'format': 'json',
75
                'polygon_geojson': 1,
75
                'polygon_geojson': 1,
76
                'zoom': 17
76
                'zoom': 17
77
            };
77
            };
78
 
78
 
79
        this.placeLabel.addClass('loading');
79
        this.placeLabel.addClass('loading');
80
        $.ajax({
80
        $.ajax({
81
            method: "GET",
81
            method: "GET",
82
            url: url,
82
            url: url,
83
            data: {...NOMINATIM_OSM_DEFAULT_PARAMS, ...params},
83
            data: {...NOMINATIM_OSM_DEFAULT_PARAMS, ...params},
84
            success: this.nominatimOsmResponseCallback.bind(this),
84
            success: this.nominatimOsmResponseCallback.bind(this),
85
            error: () => {
85
            error: () => {
86
                this.placeLabel.removeClass('loading');
86
                this.placeLabel.removeClass('loading');
87
                this.handleSearchError();
87
                this.handleSearchError();
88
            }
88
            }
89
        });
89
        });
90
    }
90
    }
91
};
91
};
92
 
92
 
93
TbPlaces.prototype.nominatimOsmResponseCallback = function(data) {
93
TbPlaces.prototype.nominatimOsmResponseCallback = function(data) {
94
    this.places.siblings('label').removeClass('loading');
94
    this.places.siblings('label').removeClass('loading');
95
    if (0 < data.length) {
95
    if (0 < data.length) {
96
        this.searchResults = data;
96
        this.searchResults = data;
97
        this.setSuggestions();
97
        this.setSuggestions();
98
        this.toggleCloseButton();
98
        this.toggleCloseButton();
99
        this.resetOnClick();
99
        this.resetOnClick();
100
        this.onSuggestionSelected();
100
        this.onSuggestionSelected();
101
    } else {
101
    } else {
102
        this.handleSearchError();
102
        this.handleSearchError();
103
    }
103
    }
104
};
104
};
105
 
105
 
106
TbPlaces.prototype.setSuggestions = function() {
106
TbPlaces.prototype.setSuggestions = function() {
107
    const lthis = this,
107
    const lthis = this,
108
        acceptedSuggestions = [];
108
        acceptedSuggestions = [];
109
 
109
 
110
    this.placesResults.empty();
110
    this.placesResults.empty();
111
    this.searchResults.forEach(suggestion => {
111
    this.searchResults.forEach(suggestion => {
112
        if(lthis.validateSuggestionData(suggestion)) {
112
        if(lthis.validateSuggestionData(suggestion)) {
113
            const locality = suggestion['display_name'];
113
            const locality = suggestion['display_name'];
114
 
114
 
115
            if (locality && !acceptedSuggestions.includes(locality)) {
115
            if (locality && !acceptedSuggestions.includes(locality)) {
116
                acceptedSuggestions.push(locality);
116
                acceptedSuggestions.push(locality);
117
                lthis.placesResults.append(
117
                lthis.placesResults.append(
118
                    '<li class="tb-places-suggestion" data-place-id="'+suggestion['place_id']+'" tabindex="-1">' +
118
                    '<li class="tb-places-suggestion" data-place-id="'+suggestion['place_id']+'" tabindex="-1">' +
119
                        locality +
119
                        locality +
120
                    '</li>'
120
                    '</li>'
121
                );
121
                );
122
            }
122
            }
123
        }
123
        }
124
    });
124
    });
125
    if(0 < acceptedSuggestions.length) {
125
    if(0 < acceptedSuggestions.length) {
126
        this.placesResultsContainer.removeClass('hidden');
126
        this.placesResultsContainer.removeClass('hidden');
127
    } else {
127
    } else {
128
        this.resetPlacesSearch();
128
        this.resetPlacesSearch();
129
    }
129
    }
130
};
130
};
131
 
131
 
132
TbPlaces.prototype.validateSuggestionData = function(suggestion) {
132
TbPlaces.prototype.validateSuggestionData = function(suggestion) {
133
    const validGeometry = undefined !== suggestion.lat && undefined !== suggestion.lon,
133
    const validGeometry = undefined !== suggestion.lat && undefined !== suggestion.lon,
134
        typeLocalisation = this.places.data('typeLocalisation') || '',
134
        typeLocalisation = this.places.data('typeLocalisation') || '',
135
        validGeometryType = 'rue' === typeLocalisation ? 'LineString' === suggestion?.geojson.type : true,
135
        validGeometryType = 'rue' === typeLocalisation ? 'LineString' === suggestion?.geojson.type : true,
136
        validAddressData = undefined !== suggestion.address,
136
        validAddressData = undefined !== suggestion.address,
137
        validDisplayName = undefined !== suggestion['display_name'];
137
        validDisplayName = undefined !== suggestion['display_name'];
138
 
138
 
139
    return (validGeometry && validGeometryType && validAddressData && validDisplayName);
139
    return (validGeometry && validGeometryType && validAddressData && validDisplayName);
140
};
140
};
141
 
141
 
142
TbPlaces.prototype.onSuggestionSelected = function() {
142
TbPlaces.prototype.onSuggestionSelected = function() {
143
    const lthis = this;
143
    const lthis = this;
144
 
144
 
145
    $('.tb-places-suggestion').off('click').on('click', function (evt) {
145
    $('.tb-places-suggestion').off('click').on('click', function (evt) {
146
        const $thisSuggestion = $(this),
146
        const $thisSuggestion = $(this),
147
            suggestion = lthis.searchResults.find(suggestion => suggestion['place_id'] === $thisSuggestion.data('placeId'));
147
            suggestion = lthis.searchResults.find(suggestion => suggestion['place_id'] === $thisSuggestion.data('placeId'));
148
 
148
 
149
        evt.preventDefault();
149
        evt.preventDefault();
150
 
150
 
151
        lthis.places.val($thisSuggestion.text());
151
        lthis.places.val($thisSuggestion.text());
152
 
-
 
153
        suggestion.geojson.coordinates = lthis.formatCoordinatesArray(suggestion.geojson);
-
 
154
        lthis.clientCallback(suggestion);
152
        lthis.clientCallback(suggestion);
155
        lthis.placesCloseButton.trigger('click');
153
        lthis.placesCloseButton.trigger('click');
156
 
154
 
157
    }).off('keydown').on('keydown', function (evt) {
155
    }).off('keydown').on('keydown', function (evt) {
158
        evt.preventDefault();
156
        evt.preventDefault();
159
 
157
 
160
        const $thisSuggestion = $(this);
158
        const $thisSuggestion = $(this);
161
 
159
 
162
        if (13 === evt.keyCode || 'Enter' === evt.key) {
160
        if (13 === evt.keyCode || 'Enter' === evt.key) {
163
            $thisSuggestion.trigger('click');
161
            $thisSuggestion.trigger('click');
164
        } else if (38 === evt.keyCode || 'ArrowUp'=== evt.key) {
162
        } else if (38 === evt.keyCode || 'ArrowUp'=== evt.key) {
165
            if(0 < $thisSuggestion.prev().length) {
163
            if(0 < $thisSuggestion.prev().length) {
166
                $thisSuggestion.prev().focus();
164
                $thisSuggestion.prev().focus();
167
            } else {
165
            } else {
168
                lthis.places.focus();
166
                lthis.places.focus();
169
            }
167
            }
170
        } else if((40 === evt.keyCode || 'ArrowDown' === evt.key) && 0 < $thisSuggestion.next().length) {
168
        } else if((40 === evt.keyCode || 'ArrowDown' === evt.key) && 0 < $thisSuggestion.next().length) {
171
            $thisSuggestion.next().focus();
169
            $thisSuggestion.next().focus();
172
        } else if (27 === evt.keyCode || ESC_KEY_STRING.test(evt.key)) {
170
        } else if (27 === evt.keyCode || ESC_KEY_STRING.test(evt.key)) {
173
            lthis.placesCloseButton.trigger('click');
171
            lthis.placesCloseButton.trigger('click');
174
            lthis.places.focus();
172
            lthis.places.focus();
175
        }
173
        }
176
    });
174
    });
177
};
175
};
178
 
-
 
179
TbPlaces.prototype.formatCoordinatesArray = function(geojson) {
-
 
180
    const coordinatesArray = geojson.coordinates,
-
 
181
        geojsonType = geojson.type,
-
 
182
        coordinatesArrayLength = coordinatesArray.length;
-
 
183
 
-
 
184
    if ('Point' === geojsonType) {
-
 
185
        coordinatesArray.reverse();
-
 
186
    } else if (0 > coordinatesArrayLength) {
-
 
187
        for (let i = 0; i <= coordinatesArrayLength; i++) {
-
 
188
            coordinatesArray[i].reverse();
-
 
189
        }
-
 
190
    }
-
 
191
 
-
 
192
    return coordinatesArray;
-
 
193
}
-
 
194
 
176
 
195
TbPlaces.prototype.resetOnClick = function () {
177
TbPlaces.prototype.resetOnClick = function () {
196
    const lthis = this;
178
    const lthis = this;
197
 
179
 
198
    this.placesCloseButton.off('click').on('click', function (event) {
180
    this.placesCloseButton.off('click').on('click', function (event) {
199
        event.preventDefault();
181
        event.preventDefault();
200
        lthis.resetPlacesSearch();
182
        lthis.resetPlacesSearch();
201
    });
183
    });
202
};
184
};
203
 
185
 
204
TbPlaces.prototype.toggleCloseButton = function(isShow = true) {
186
TbPlaces.prototype.toggleCloseButton = function(isShow = true) {
205
    this.placesCloseButton.toggleClass('hidden', !isShow);
187
    this.placesCloseButton.toggleClass('hidden', !isShow);
206
    $('.tb-places-search-icon').toggleClass('hidden', isShow);
188
    $('.tb-places-search-icon').toggleClass('hidden', isShow);
207
};
189
};
208
 
190
 
209
TbPlaces.prototype.handleSearchError = function() {
191
TbPlaces.prototype.handleSearchError = function() {
210
    this.resetPlacesSearch();
192
    this.resetPlacesSearch();
211
    if (0 === $('#tb-places-error').length) {
193
    if (0 === $('#tb-places-error').length) {
212
        this.places.closest('#tb-places-zone').after(
194
        this.places.closest('#tb-places-zone').after(
213
            `<span id="tb-places-error" class="error mb-3 mt-3">
195
            `<span id="tb-places-error" class="error mb-3 mt-3">
214
                Votre recherche n’a pas donné de résultat pour le moment.<br>Vous pouvez soit poursuivre ou modifier votre recherche,<br>soit rechercher votre station directement sur la carte.
196
                Votre recherche n’a pas donné de résultat pour le moment.<br>Vous pouvez soit poursuivre ou modifier votre recherche,<br>soit rechercher votre station directement sur la carte.
215
            </span>`
197
            </span>`
216
        );
198
        );
217
        setTimeout(function() {
199
        setTimeout(function() {
218
            $('#tb-places-error').remove();
200
            $('#tb-places-error').remove();
219
        }, 10000);
201
        }, 10000);
220
    }
202
    }
221
};
203
};
222
 
204
 
223
TbPlaces.prototype.resetPlacesSearch = function() {
205
TbPlaces.prototype.resetPlacesSearch = function() {
224
    this.toggleCloseButton(false);
206
    this.toggleCloseButton(false);
225
    this.placesResultsContainer.addClass('hidden');
207
    this.placesResultsContainer.addClass('hidden');
226
    this.placesResults.empty();
208
    this.placesResults.empty();
227
};
209
};
228
 
210