leaflet-geosearch
Version:
Adds support for address lookup (a.k.a. geocoding / geosearching) to Leaflet.
76 lines • 2.65 kB
JavaScript
import { createElement, addClassName, removeClassName, cx, stopPropagation, replaceClassName, } from './domUtils';
import { ESCAPE_KEY, ENTER_KEY } from './constants';
export default class SearchElement {
container;
form;
input;
handleSubmit;
hasError = false;
constructor({ handleSubmit, searchLabel, classNames = {}, }) {
this.container = createElement('div', cx('geosearch', classNames.container));
this.form = createElement('form', cx('', classNames.form), this.container, {
autocomplete: 'none',
onClick: stopPropagation,
onDblClick: stopPropagation,
touchStart: stopPropagation,
touchEnd: stopPropagation,
});
this.input = createElement('input', cx('glass', classNames.input), this.form, {
type: 'text',
placeholder: searchLabel || 'search',
name: 'geosearch',
onInput: this.onInput,
onKeyUp: (e) => this.onKeyUp(e),
onKeyPress: (e) => this.onKeyPress(e),
onFocus: this.onFocus,
onBlur: this.onBlur,
// For some reason, leaflet is blocking the 'touchstart', manually give
// focus to the input onClick
// > Ignored attempt to cancel a touchstart event with cancelable=false,
// > for example because scrolling is in progress and cannot be interrupted.
onClick: () => {
this.input.focus();
this.input.dispatchEvent(new Event('focus'));
},
});
this.handleSubmit = handleSubmit;
}
onFocus() {
addClassName(this.form, 'active');
}
onBlur() {
removeClassName(this.form, 'active');
}
async onSubmit(event) {
stopPropagation(event);
replaceClassName(this.container, 'error', 'pending');
await this.handleSubmit({ query: this.input.value });
removeClassName(this.container, 'pending');
}
onInput() {
if (!this.hasError) {
return;
}
removeClassName(this.container, 'error');
this.hasError = false;
}
onKeyUp(event) {
if (event.keyCode !== ESCAPE_KEY) {
return;
}
removeClassName(this.container, ['pending', 'active']);
this.input.value = '';
document.body.focus();
document.body.blur();
}
onKeyPress(event) {
if (event.keyCode !== ENTER_KEY) {
return;
}
this.onSubmit(event);
}
setQuery(query) {
this.input.value = query;
}
}
//# sourceMappingURL=SearchElement.js.map