Subversion Repositories eFlore/Applications.cel

Rev

Rev 3857 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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