@ta-interaktiv/react-municipality-search 2.2.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,7 +5,6 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var React = require('react');
6
6
  var styled = require('styled-components');
7
7
  var web = require('@react-spring/web');
8
- var Cookies = require('js-cookie');
9
8
 
10
9
  /******************************************************************************
11
10
  Copyright (c) Microsoft Corporation.
@@ -38,6 +37,56 @@ function __extends(d, b) {
38
37
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
39
38
  }
40
39
 
40
+ function __awaiter(thisArg, _arguments, P, generator) {
41
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
42
+ return new (P || (P = Promise))(function (resolve, reject) {
43
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
44
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
45
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
46
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
47
+ });
48
+ }
49
+
50
+ function __generator(thisArg, body) {
51
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
52
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
53
+ function verb(n) { return function (v) { return step([n, v]); }; }
54
+ function step(op) {
55
+ if (f) throw new TypeError("Generator is already executing.");
56
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
57
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
58
+ if (y = 0, t) op = [op[0] & 2, t.value];
59
+ switch (op[0]) {
60
+ case 0: case 1: t = op; break;
61
+ case 4: _.label++; return { value: op[1], done: false };
62
+ case 5: _.label++; y = op[1]; op = [0]; continue;
63
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
64
+ default:
65
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
66
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
67
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
68
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
69
+ if (t[2]) _.ops.pop();
70
+ _.trys.pop(); continue;
71
+ }
72
+ op = body.call(thisArg, _);
73
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
74
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
75
+ }
76
+ }
77
+
78
+ function __values(o) {
79
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
80
+ if (m) return m.call(o);
81
+ if (o && typeof o.length === "number") return {
82
+ next: function () {
83
+ if (o && i >= o.length) o = void 0;
84
+ return { value: o && o[i++], done: !o };
85
+ }
86
+ };
87
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
88
+ }
89
+
41
90
  function __read(o, n) {
42
91
  var m = typeof Symbol === "function" && o[Symbol.iterator];
43
92
  if (!m) return o;
@@ -107,27 +156,11 @@ data.list;
107
156
  data.results;
108
157
 
109
158
  var MESSAGES = { de: data$1, fr: data };
110
- var localStorageItemName = 'selectedMunicipalities';
111
- var translationServiceFactory = function (messageList, locale) {
112
- return function (key) {
113
- if (key == null) {
114
- return '';
115
- }
116
- return (key
117
- .split('.')
118
- .reduce(function (messages, prop) { return messages[prop]; }, messageList[locale]) || 'TRANSLATED STRING NOT FOUND');
119
- };
120
- };
121
- function getDomain() {
122
- var url = window.location.hostname;
123
- url = url.replace(/(https?:\/\/)?(www.)?/i, '');
124
- var urlArray = url.split('.');
125
- url = urlArray.slice(urlArray.length - 2).join('.');
126
- if (url.indexOf('/') !== -1) {
127
- return url.split('/')[0];
128
- }
129
- return url;
130
- }
159
+ var STARTS_WITH_NUMBER = /^\d/;
160
+ var CONTAINS_ONLY_LETTERS = /^\D+$/;
161
+ var CONTAINS_FOUR_DIGITS = /\d{4}/;
162
+ var API_URL = 'https://tamedia-discovery-municipalities.s3.eu-central-1.amazonaws.com/';
163
+ var LEGACY_API_URL = 'https://interaktiv.tagesanzeiger.ch/static/gemeindesuche/';
131
164
  var MunicipalityDownloadError = (function (_super) {
132
165
  __extends(MunicipalityDownloadError, _super);
133
166
  function MunicipalityDownloadError() {
@@ -135,385 +168,234 @@ var MunicipalityDownloadError = (function (_super) {
135
168
  }
136
169
  return MunicipalityDownloadError;
137
170
  }(Error));
138
- var startsWithNumber = /^\d/;
139
- var containsOnlyLetters = /^\D+$/;
140
- var containsFourDigits = /\d{4}/;
141
- function showResults(results) {
142
- return results.length > 0;
143
- }
144
- var MunicipalitySearch = (function (_super) {
145
- __extends(MunicipalitySearch, _super);
146
- function MunicipalitySearch() {
147
- var _this = _super !== null && _super.apply(this, arguments) || this;
148
- _this.state = {
149
- isLoading: true,
150
- results: [],
151
- value: '',
152
- error: null,
153
- municipalities: [],
154
- };
155
- _this.resetComponent = function () {
156
- _this.setState({
157
- isLoading: false,
158
- results: [],
159
- value: '',
160
- });
161
- };
162
- _this.filterList = function (searchTerm) {
163
- var results = [];
164
- searchTerm = searchTerm.trim();
165
- if (searchTerm.length > 1 && _this.state.municipalities !== null) {
166
- var digitsResultsArray = containsFourDigits.exec(searchTerm);
167
- var municipalities = _this.state.municipalities;
168
- if (digitsResultsArray) {
169
- var digits_1 = digitsResultsArray[0];
170
- results = municipalities.filter(function (municipality) { var _a; return ((_a = municipality.PLZ4) !== null && _a !== void 0 ? _a : '').toString() === digits_1; });
171
- if (results.length < 1) {
172
- _this.setState({ error: 'error.noResultsByZip' });
173
- }
174
- }
175
- else if (startsWithNumber.test(searchTerm)) {
176
- results = municipalities.filter(function (municipality) { var _a; return RegExp("^".concat(searchTerm)).test(((_a = municipality.PLZ4) !== null && _a !== void 0 ? _a : '').toString()); });
177
- if (results.length < 1) {
178
- _this.setState({ error: 'error.noResultsByZip' });
179
- }
180
- }
181
- else if (containsOnlyLetters.test(searchTerm)) {
182
- var sanitizedSearchTerm = searchTerm.replace('.', '\\.');
183
- var r_1 = RegExp(sanitizedSearchTerm, 'i');
184
- var exactWordRegex_1 = RegExp("\\b".concat(sanitizedSearchTerm, "\\b"), 'i');
185
- var rankResults = function (searchTerm, arrayToSort) {
186
- return arrayToSort.sort(function (a, b) {
187
- var _a, _b;
188
- var aScore = scoreResult_1(searchTerm.toLowerCase(), a[(_a = _this.props.propertyToSearch) !== null && _a !== void 0 ? _a : MunicipalitySearch.defaultProps.propertyToSearch].toLowerCase());
189
- var bScore = scoreResult_1(searchTerm.toLowerCase(), b[(_b = _this.props.propertyToSearch) !== null && _b !== void 0 ? _b : MunicipalitySearch.defaultProps.propertyToSearch].toLowerCase());
190
- return bScore - aScore;
191
- });
192
- };
193
- var scoreResult_1 = function (searchTerm, stringToCompare) {
194
- if (stringToCompare === searchTerm) {
195
- return 2;
196
- }
197
- else if (exactWordRegex_1.test(stringToCompare)) {
198
- return 1;
199
- }
200
- else {
201
- return 0;
202
- }
203
- };
204
- var notExactMatches = municipalities.filter(function (municipality) { var _a; return r_1.test(municipality[(_a = _this.props.propertyToSearch) !== null && _a !== void 0 ? _a : MunicipalitySearch.defaultProps.propertyToSearch]); });
205
- results = rankResults(sanitizedSearchTerm, notExactMatches).slice(0, _this.props.maxResults);
206
- if (results.length < 1) {
207
- _this.setState({ error: 'error.noResultsByName' });
171
+ var translate = function (messageList, locale, key) {
172
+ if (key == null)
173
+ return '';
174
+ return (key
175
+ .split('.')
176
+ .reduce(function (messages, prop) { return messages[prop]; }, messageList[locale]) || 'TRANSLATED STRING NOT FOUND');
177
+ };
178
+ var muniToString = function (muni) { var _a, _b; return "".concat(muni.GDENR).concat((_a = muni.ORTNAME) !== null && _a !== void 0 ? _a : '').concat((_b = muni.PLZ4) !== null && _b !== void 0 ? _b : ''); };
179
+ var MunicipalitySearch = function (_a) {
180
+ var _b;
181
+ var _c = _a.municipalityData, municipalityData = _c === void 0 ? '2021v3' : _c, _d = _a.locale, locale = _d === void 0 ? 'de' : _d, _e = _a.resultBackgroundColor, resultBackgroundColor = _e === void 0 ? 'var(--site-background)' : _e, _f = _a.inputBackgroundColor, inputBackgroundColor = _f === void 0 ? 'var(--site-background)' : _f, _g = _a.maxResults, maxResults = _g === void 0 ? 10 : _g, _h = _a.propertyToSearch, propertyToSearch = _h === void 0 ? 'NORMGEMEINDE' : _h, _j = _a.dedupe, dedupe = _j === void 0 ? false : _j, _k = _a.resetOnSelect, resetOnSelect = _k === void 0 ? false : _k, onSelectionHandler = _a.onSelectionHandler, placeholder = _a.placeholder, iconOnRightSide = _a.iconOnRightSide, customMunicipalities = _a.customMunicipalities, selectedMunicipality = _a.selectedMunicipality, selectedMunicipalityId = _a.selectedMunicipalityId, onCloseHandler = _a.onCloseHandler;
182
+ var _l = __read(React.useState([]), 2), results = _l[0], setResults = _l[1];
183
+ var _m = __read(React.useState(''), 2), value = _m[0], setValue = _m[1];
184
+ var _o = __read(React.useState(null), 2), error = _o[0], setError = _o[1];
185
+ var _p = __read(React.useState([]), 2), municipalities = _p[0], setMunicipalities = _p[1];
186
+ var t = React.useCallback(function (key) { return translate(MESSAGES, locale, key); }, [locale]);
187
+ React.useEffect(function () {
188
+ setResults([]);
189
+ setValue('');
190
+ setError(null);
191
+ if (customMunicipalities) {
192
+ setMunicipalities(customMunicipalities);
193
+ return;
194
+ }
195
+ var cancelled = false;
196
+ var fetchData = function (useLegacy) {
197
+ if (useLegacy === void 0) { useLegacy = false; }
198
+ return __awaiter(void 0, void 0, void 0, function () {
199
+ var baseUrl, res, data, err_1;
200
+ return __generator(this, function (_a) {
201
+ switch (_a.label) {
202
+ case 0:
203
+ baseUrl = useLegacy ? LEGACY_API_URL : API_URL;
204
+ _a.label = 1;
205
+ case 1:
206
+ _a.trys.push([1, 4, , 5]);
207
+ return [4, fetch("".concat(baseUrl).concat(municipalityData, ".json"))];
208
+ case 2:
209
+ res = _a.sent();
210
+ if (!res.ok) {
211
+ throw new MunicipalityDownloadError("Download error: ".concat(res.status, ": ").concat(res.statusText, "."));
212
+ }
213
+ return [4, res.json()];
214
+ case 3:
215
+ data = _a.sent();
216
+ if (!cancelled)
217
+ setMunicipalities(data);
218
+ return [3, 5];
219
+ case 4:
220
+ err_1 = _a.sent();
221
+ if (cancelled)
222
+ return [2];
223
+ if (!useLegacy)
224
+ return [2, fetchData(true)];
225
+ if (err_1 instanceof MunicipalityDownloadError) {
226
+ console.error(err_1);
227
+ console.info('Make sure that you have the municipality and zip code data for the required year uploaded to the Interaktiv server.');
228
+ setError('error.municipalitiesNotDownloaded');
229
+ }
230
+ else {
231
+ throw err_1;
232
+ }
233
+ return [3, 5];
234
+ case 5: return [2];
208
235
  }
209
- }
210
- window.dataLayer = window.dataLayer || [];
211
- window.dataLayer.push({
212
- event: 'Interactions',
213
- event_action: 'input',
214
- event_label: "search:for_".concat(searchTerm, ":results_").concat(results.length),
215
236
  });
216
- }
217
- return _this.removeDuplicates(results, searchTerm);
218
- };
219
- _this.handleSearchChange = function (e) {
220
- var value = e.currentTarget.value;
221
- _this.setState({ isLoading: true, value: value });
222
- if (value.length < 1) {
223
- return _this.resetComponent();
224
- }
225
- var results = _this.filterList(value);
226
- if (results.length > 0) {
227
- _this.setState({ error: null, isLoading: false, results: results });
228
- }
229
- _this.setState({ results: results, isLoading: false });
230
- };
231
- _this.sendToDataPipeline = function (plz4) {
232
- var BASE_URL = 'https://w.tda.io/b/votation';
233
- var ZIP = '?zip=' + plz4;
234
- var url = BASE_URL + ZIP;
235
- return window
236
- .fetch(url, {
237
- method: 'GET',
238
- mode: 'no-cors',
239
- credentials: 'include',
240
- })
241
- .then(function (response) {
242
- console.log(response);
243
- })
244
- .catch(function (error) {
245
- console.log(error);
246
237
  });
247
238
  };
248
- _this.getStoredMunicipalities = function () {
249
- var _a, _b;
250
- var munisFromLocalStorage = [];
251
- var munisFromCookies = [];
252
- try {
253
- var munisFromLocalStorageString = (_a = localStorage.getItem('selectedMunicipalities')) !== null && _a !== void 0 ? _a : '[]';
254
- munisFromLocalStorage = JSON.parse(munisFromLocalStorageString);
255
- }
256
- catch (e) {
257
- console.log(e);
258
- console.warn('🗄 localStorage of selectedMunicipalities is not available');
239
+ fetchData();
240
+ return function () {
241
+ cancelled = true;
242
+ };
243
+ }, [municipalityData, customMunicipalities]);
244
+ var removeDuplicates = function (arr, searchTerm) {
245
+ var e_1, _a, e_2, _b;
246
+ var _c, _d, _e, _f, _g;
247
+ var map = new Map();
248
+ try {
249
+ for (var arr_1 = __values(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) {
250
+ var v = arr_1_1.value;
251
+ var key = dedupe
252
+ ? "".concat((_c = v.ORTNAME) !== null && _c !== void 0 ? _c : '').concat(v.GDENR)
253
+ : "".concat((_d = v.PLZ4) !== null && _d !== void 0 ? _d : '').concat((_e = v.ORTNAME) !== null && _e !== void 0 ? _e : '').concat(v.GDENR);
254
+ map.set(key, v);
259
255
  }
256
+ }
257
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
258
+ finally {
260
259
  try {
261
- var munisFromCookiesString = (_b = Cookies.get('selectedMunicipalities')) !== null && _b !== void 0 ? _b : '[]';
262
- munisFromCookies = JSON.parse(munisFromCookiesString);
263
- }
264
- catch (e) {
265
- console.log(e);
266
- console.warn('🍪 cookies of selectedMunicipalities is not available');
260
+ if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1);
267
261
  }
268
- var ordered = __spreadArray(__spreadArray([], __read(munisFromLocalStorage), false), __read(munisFromCookies), false).sort(function (a, b) {
269
- if (b.timestamp && a.timestamp) {
270
- return b.timestamp - a.timestamp;
271
- }
272
- if (b.timestamp) {
273
- return 1;
262
+ finally { if (e_1) throw e_1.error; }
263
+ }
264
+ var exact = [];
265
+ var rest = [];
266
+ var lower = searchTerm.toLowerCase();
267
+ try {
268
+ for (var _h = __values(map.values()), _j = _h.next(); !_j.done; _j = _h.next()) {
269
+ var m = _j.value;
270
+ if (((_f = m.GDENAMK) === null || _f === void 0 ? void 0 : _f.toLowerCase()) === lower ||
271
+ ((_g = m.ORTNAME) === null || _g === void 0 ? void 0 : _g.toLowerCase()) === lower) {
272
+ exact.push(m);
274
273
  }
275
- if (a.timestamp) {
276
- return -1;
274
+ else {
275
+ rest.push(m);
277
276
  }
278
- return 0;
279
- });
280
- return _this.deduplicateMunicipalityArray(ordered);
281
- };
282
- _this.saveToSelectedMunicipalities = function (newMuni) {
283
- var prevSelectedMunicipalities = _this.getStoredMunicipalities();
284
- var slicedArray = prevSelectedMunicipalities.slice(0, 15);
285
- newMuni.timestamp = Date.now();
286
- slicedArray.unshift(newMuni);
287
- console.log('domain:', getDomain());
288
- try {
289
- var newMuniArray = JSON.stringify(_this.deduplicateMunicipalityArray(slicedArray));
290
- localStorage.setItem(localStorageItemName, newMuniArray);
291
- Cookies.set(localStorageItemName, newMuniArray, {
292
- expires: 365,
293
- domain: getDomain(),
294
- });
295
277
  }
296
- catch (_a) {
297
- console.warn('🗄 localStorage is not writeable');
278
+ }
279
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
280
+ finally {
281
+ try {
282
+ if (_j && !_j.done && (_b = _h.return)) _b.call(_h);
298
283
  }
299
- };
300
- _this.deduplicateMunicipalityArray = function (munis) {
301
- return __spreadArray([], __read(new Map(munis
302
- .slice()
303
- .reverse()
304
- .map(function (muni) {
305
- var _a;
306
- return [
307
- ((_a = muni.ORTNAME) !== null && _a !== void 0 ? _a : '') +
308
- muni.GDENR +
309
- (_this.props.dedupe ? '' : muni.PLZ4),
310
- muni,
311
- ];
312
- })).values()), false).reverse()
313
- .sort(function (a, b) {
314
- if (b.timestamp && a.timestamp) {
315
- return b.timestamp - a.timestamp;
316
- }
317
- if (b.timestamp) {
284
+ finally { if (e_2) throw e_2.error; }
285
+ }
286
+ return __spreadArray(__spreadArray([], __read(exact), false), __read(rest), false);
287
+ };
288
+ var filterList = function (searchTerm) {
289
+ searchTerm = searchTerm.trim();
290
+ if (searchTerm.length <= 1 || municipalities.length === 0) {
291
+ return [];
292
+ }
293
+ var filtered = [];
294
+ var fourDigitMatch = CONTAINS_FOUR_DIGITS.exec(searchTerm);
295
+ if (fourDigitMatch) {
296
+ filtered = municipalities.filter(function (m) { var _a; return ((_a = m.PLZ4) !== null && _a !== void 0 ? _a : '').toString() === fourDigitMatch[0]; });
297
+ }
298
+ else if (STARTS_WITH_NUMBER.test(searchTerm)) {
299
+ filtered = municipalities.filter(function (m) { var _a; return RegExp("^".concat(searchTerm)).test(((_a = m.PLZ4) !== null && _a !== void 0 ? _a : '').toString()); });
300
+ }
301
+ else if (CONTAINS_ONLY_LETTERS.test(searchTerm)) {
302
+ var sanitized = searchTerm.replace('.', '\\.');
303
+ var regex_1 = RegExp(sanitized, 'i');
304
+ var exactWordRegex_1 = RegExp("\\b".concat(sanitized, "\\b"), 'i');
305
+ var scoreResult_1 = function (term, compare) {
306
+ if (compare === term)
307
+ return 2;
308
+ if (exactWordRegex_1.test(compare))
318
309
  return 1;
319
- }
320
- if (a.timestamp) {
321
- return -1;
322
- }
323
310
  return 0;
324
- });
325
- };
326
- _this.getMunicipalitiesData = function (useLegacy) {
327
- if (_this.props.customMunicipalities) {
328
- _this.setState({
329
- isLoading: false,
330
- municipalities: _this.props.customMunicipalities,
331
- });
332
- return Promise.resolve(_this.props.customMunicipalities);
333
- }
334
- _this.setState({
335
- isLoading: true,
336
- });
337
- useLegacy && console.log('Municipality search: using legacy endpoint 👴');
338
- var API_BASE_URL = useLegacy
339
- ? 'https://interaktiv.tagesanzeiger.ch/static/gemeindesuche/'
340
- : 'https://tamedia-discovery-municipalities.s3.eu-central-1.amazonaws.com/';
341
- return fetch(API_BASE_URL + "".concat(_this.props.municipalityData, ".json"))
342
- .then(function (res) {
343
- if (!res.ok) {
344
- throw new MunicipalityDownloadError("Download error: ".concat(res.status, ": ").concat(res.statusText, "."));
345
- }
346
- return res.json();
347
- })
348
- .then(function (data) {
349
- _this.setState({
350
- isLoading: false,
351
- municipalities: data,
352
- });
353
- return Promise.resolve(data);
311
+ };
312
+ filtered = municipalities
313
+ .filter(function (m) { return regex_1.test(m[propertyToSearch]); })
314
+ .sort(function (a, b) {
315
+ var aScore = scoreResult_1(searchTerm.toLowerCase(), a[propertyToSearch].toLowerCase());
316
+ var bScore = scoreResult_1(searchTerm.toLowerCase(), b[propertyToSearch].toLowerCase());
317
+ return bScore - aScore;
354
318
  })
355
- .catch(function (error) {
356
- if (!useLegacy)
357
- return _this.getMunicipalitiesData(true);
358
- if (error instanceof MunicipalityDownloadError) {
359
- console.log(error);
360
- console.info('Make sure that you have the municipality and zip code data for the required year uploaded to the Interaktiv server.');
361
- console.info('Read more about the data generation in the "data" directory in the project repository for the MunicipalitySearch React component.');
362
- _this.setState({
363
- isLoading: false,
364
- error: 'error.municipalitiesNotDownloaded',
365
- });
366
- }
367
- else {
368
- throw error;
369
- }
370
- });
371
- };
372
- return _this;
373
- }
374
- MunicipalitySearch.prototype.removeDuplicates = function (arr, searchTerm) {
375
- var _this = this;
376
- var map = new Map();
377
- arr.forEach(function (v) {
378
- var _a, _b, _c;
379
- if (_this.props.dedupe) {
380
- map.set(((_a = v.ORTNAME) !== null && _a !== void 0 ? _a : '') + v.GDENR, v);
381
- }
382
- else {
383
- map.set(((_b = v.PLZ4) !== null && _b !== void 0 ? _b : '') + ((_c = v.ORTNAME) !== null && _c !== void 0 ? _c : '') + v.GDENR, v);
384
- }
319
+ .slice(0, maxResults);
320
+ }
321
+ window.dataLayer = window.dataLayer || [];
322
+ window.dataLayer.push({
323
+ event: 'Interactions',
324
+ event_action: 'input',
325
+ event_label: "search:for_".concat(searchTerm, ":results_").concat(filtered.length),
385
326
  });
386
- var result = __spreadArray([], __read(map.values()), false).reduce(function (acc, cur) {
387
- var _a, _b;
388
- if (((_a = cur.GDENAMK) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === searchTerm.toLowerCase() ||
389
- ((_b = cur.ORTNAME) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === searchTerm.toLowerCase()) {
390
- acc[0].push(cur);
391
- }
392
- else {
393
- acc[1].push(cur);
394
- }
395
- return acc;
396
- }, [[], []])
397
- .flat();
398
- return result;
327
+ return removeDuplicates(filtered, searchTerm);
399
328
  };
400
- MunicipalitySearch.prototype.componentDidUpdate = function (prevProps) {
401
- if (prevProps.municipalityData !== this.props.municipalityData) {
402
- this.resetComponent();
403
- this.getMunicipalitiesData();
404
- }
329
+ var resetComponent = function () {
330
+ setResults([]);
331
+ setValue('');
405
332
  };
406
- MunicipalitySearch.prototype.muniToString = function (muni) {
407
- var _a, _b;
408
- return muni.GDENR + ((_a = muni.ORTNAME) !== null && _a !== void 0 ? _a : '') + ((_b = muni.PLZ4) !== null && _b !== void 0 ? _b : '');
333
+ var handleSearchChange = function (e) {
334
+ var inputValue = e.currentTarget.value;
335
+ setValue(inputValue);
336
+ if (inputValue.length < 1) {
337
+ return resetComponent();
338
+ }
339
+ setResults(filterList(inputValue));
409
340
  };
410
- MunicipalitySearch.prototype.componentDidMount = function () {
411
- var _this = this;
412
- this.getMunicipalitiesData().then(function (data) {
413
- var prevSelectedMunicipalities = _this.getStoredMunicipalities();
414
- if (_this.props.showLastSelectedMunicipalities &&
415
- prevSelectedMunicipalities.length > 0) {
416
- var allBfsIdsAndNames_1 = prevSelectedMunicipalities.map(function (muni) { return _this.muniToString(muni); });
417
- var filteredFromFetchedData = data.filter(function (muni) {
418
- return allBfsIdsAndNames_1.includes(_this.muniToString(muni));
419
- });
420
- filteredFromFetchedData.sort(function (a, b) {
421
- return (allBfsIdsAndNames_1.indexOf(_this.muniToString(a)) -
422
- allBfsIdsAndNames_1.indexOf(_this.muniToString(b)));
423
- });
424
- var dedupedData = _this.deduplicateMunicipalityArray(filteredFromFetchedData);
425
- dedupedData.sort(function (a, b) {
426
- return (allBfsIdsAndNames_1.indexOf(_this.muniToString(a)) -
427
- allBfsIdsAndNames_1.indexOf(_this.muniToString(b)));
428
- });
429
- var muniCount = _this.props.numberOfLastSelectedMunicipalities;
430
- _this.setState({
431
- results: dedupedData.slice(0, muniCount),
432
- });
433
- }
434
- });
341
+ var handleSelect = function (municipality) {
342
+ onSelectionHandler(municipality);
343
+ if (resetOnSelect)
344
+ resetComponent();
435
345
  };
436
- MunicipalitySearch.prototype.render = function () {
437
- var _this = this;
438
- var _a, _b, _c;
439
- var _d = this.state; _d.isLoading; var value = _d.value, results = _d.results;
440
- var t = translationServiceFactory(MESSAGES, this.props.locale);
441
- var preSelectedMunicipality = (_a = this.props.selectedMunicipality) !== null && _a !== void 0 ? _a : this.state.municipalities.find(function (muni) {
442
- return muni.GDENR === _this.props.selectedMunicipalityId;
443
- });
444
- return (React.createElement(MunicipalitySearchContainer, { className: 'municipality-search' },
445
- React.createElement(InputRow, { className: 'inputRow' },
446
- React.createElement(FlexInput, { type: 'text', "$lessPaddingLeft": !!preSelectedMunicipality || this.props.iconOnRightSide, placeholder: this.props.placeholder || t('placeholder'), value: (_b = preSelectedMunicipality === null || preSelectedMunicipality === void 0 ? void 0 : preSelectedMunicipality.NORMGEMEINDE) !== null && _b !== void 0 ? _b : value, disabled: this.state.error === 'error.municipalitiesNotDownloaded' ||
447
- !!preSelectedMunicipality, onChange: this.handleSearchChange, "$backgroundColor": this.props.inputBackgroundColor }),
448
- preSelectedMunicipality ? (React.createElement(Icon, { onClick: function () { var _a, _b; return (_b = (_a = _this.props).onCloseHandler) === null || _b === void 0 ? void 0 : _b.call(_a); }, "$isClickable": true, id: 'search-closing-icon', "$isRight": true },
449
- React.createElement("svg", { width: '20', height: '21', viewBox: '0 0 24 25', xmlns: 'http://www.w3.org/2000/svg', fill: 'currentColor', strokeWidth: '2' },
450
- React.createElement("path", { d: 'M3.9 22L2 20.1L9.6 12.5L2 4.9L3.9 3L11.5 10.6L19.1 3L21 4.9L13.4 12.5L21 20.1L19.1 22L11.5 14.4L3.9 22Z', fill: 'currentColor' })))) : (React.createElement(Icon, { "$isRight": (_c = this.props) === null || _c === void 0 ? void 0 : _c.iconOnRightSide },
451
- React.createElement("svg", { width: '18', height: '18', viewBox: '0 0 18 18', fill: 'none', xmlns: 'http://www.w3.org/2000/svg', stroke: 'currentColor', strokeWidth: '2' },
452
- React.createElement("circle", { cx: '7.5', cy: '7.5', r: '6' }),
453
- React.createElement("line", { x1: '11', y1: '11', x2: '17', y2: '17' }))))),
454
- showResults(results) && (React.createElement(Results, { className: 'results', "$backgroundColor": this.props.resultBackgroundColor }, showResults(results) && (React.createElement(web.Transition, { native: true, items: results, keys: function (result) { return _this.muniToString(result); }, from: { transform: 'translate(0,-20px)', opacity: 0 }, enter: { transform: 'translate(0,0px)', opacity: 1 }, config: web.config.gentle }, function (values, result) {
346
+ var preSelectedMunicipality = selectedMunicipality !== null && selectedMunicipality !== void 0 ? selectedMunicipality : municipalities.find(function (m) { return m.GDENR === selectedMunicipalityId; });
347
+ var hasResults = results.length > 0;
348
+ return (React.createElement(MunicipalitySearchContainer, { className: 'municipality-search' },
349
+ React.createElement(InputRow, { className: 'inputRow' },
350
+ React.createElement(FlexInput, { type: 'text', "$lessPaddingLeft": !!preSelectedMunicipality || iconOnRightSide, placeholder: placeholder || t('placeholder'), value: (_b = preSelectedMunicipality === null || preSelectedMunicipality === void 0 ? void 0 : preSelectedMunicipality.NORMGEMEINDE) !== null && _b !== void 0 ? _b : value, disabled: error === 'error.municipalitiesNotDownloaded' ||
351
+ !!preSelectedMunicipality, onChange: handleSearchChange, "$backgroundColor": inputBackgroundColor }),
352
+ preSelectedMunicipality ? (React.createElement(Icon, { onClick: function () { return onCloseHandler === null || onCloseHandler === void 0 ? void 0 : onCloseHandler(); }, "$isClickable": true, id: 'search-closing-icon', "$isRight": true },
353
+ React.createElement("svg", { width: '20', height: '21', viewBox: '0 0 24 25', xmlns: 'http://www.w3.org/2000/svg', fill: 'currentColor', strokeWidth: '2' },
354
+ React.createElement("path", { d: 'M3.9 22L2 20.1L9.6 12.5L2 4.9L3.9 3L11.5 10.6L19.1 3L21 4.9L13.4 12.5L21 20.1L19.1 22L11.5 14.4L3.9 22Z', fill: 'currentColor' })))) : (React.createElement(Icon, { "$isRight": iconOnRightSide },
355
+ React.createElement("svg", { width: '18', height: '18', viewBox: '0 0 18 18', fill: 'none', xmlns: 'http://www.w3.org/2000/svg', stroke: 'currentColor', strokeWidth: '2' },
356
+ React.createElement("circle", { cx: '7.5', cy: '7.5', r: '6' }),
357
+ React.createElement("line", { x1: '11', y1: '11', x2: '17', y2: '17' }))))),
358
+ hasResults && (React.createElement(Results, { className: 'results', "$backgroundColor": resultBackgroundColor },
359
+ React.createElement(web.Transition, { items: results, keys: muniToString, from: { transform: 'translate(0,-20px)', opacity: 0 }, enter: { transform: 'translate(0,0px)', opacity: 1 }, config: web.config.gentle }, function (style, result) {
455
360
  var _a;
456
- return (React.createElement(web.animated.div, { onClick: function () {
457
- _this.props.onSelectionHandler(result);
458
- if (_this.props.showLastSelectedMunicipalities) {
459
- _this.saveToSelectedMunicipalities(result);
460
- }
461
- if (_this.props.resetOnSelect) {
462
- _this.resetComponent();
463
- }
464
- }, onKeyUp: function (e) {
361
+ return (React.createElement(web.animated.div, { onClick: function () { return handleSelect(result); }, onKeyUp: function (e) {
465
362
  if (e.key === 'Enter' || e.key === 'Space') {
466
- _this.props.onSelectionHandler(result);
467
- if (_this.props.resetOnSelect) {
468
- _this.resetComponent();
469
- }
363
+ handleSelect(result);
470
364
  }
471
- }, className: 'result', style: values, tabIndex: 0 },
365
+ }, className: 'result', style: style, tabIndex: 0 },
472
366
  React.createElement(ResultHeader, { className: 'resultHeader' },
473
367
  React.createElement(ResultPlz, { className: 'resultPlz' }, result.PLZ4),
474
368
  ' ',
475
369
  result.ORTNAME),
476
370
  React.createElement(ResultMeta, { className: 'resultMeta' },
477
- React.createElement(React.Fragment, null,
478
- result.ORTNAME ? t('list.municipalityPrefix') : '',
479
- ' ',
480
- React.createElement("b", null, (_a = result.GDENAMK) !== null && _a !== void 0 ? _a : result.NORMGEMEINDE +
481
- ((results.find(function (muni) {
482
- return muni !== result &&
483
- muni.NORMGEMEINDE === result.NORMGEMEINDE;
484
- }) && result.KTKZ)
485
- ? ' (' + result.KTKZ + ')'
486
- : ''))))));
487
- }))))));
488
- };
489
- MunicipalitySearch.defaultProps = {
490
- municipalityData: '2021v3',
491
- locale: 'de',
492
- numberOfLastSelectedMunicipalities: 1,
493
- resultBackgroundColor: 'var(--site-background)',
494
- inputBackgroundColor: 'var(--site-background)',
495
- maxResults: 10,
496
- propertyToSearch: "NORMGEMEINDE"
497
- };
498
- return MunicipalitySearch;
499
- }(React.Component));
371
+ result.ORTNAME ? t('list.municipalityPrefix') : '',
372
+ ' ',
373
+ React.createElement("b", null, (_a = result.GDENAMK) !== null && _a !== void 0 ? _a : result.NORMGEMEINDE +
374
+ (results.find(function (m) {
375
+ return m !== result &&
376
+ m.NORMGEMEINDE === result.NORMGEMEINDE;
377
+ }) && result.KTKZ
378
+ ? " (".concat(result.KTKZ, ")")
379
+ : '')))));
380
+ })))));
381
+ };
500
382
  var Icon = styled.i(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n cursor: ", ";\n position: absolute;\n top: 50%;\n ", "\n padding-left: 0.8em;\n transform: translateY(-50%);\n display: flex;\n opacity: 0.5;\n transition: opacity 0.5s ease-in-out;\n animation: fromLeft 0.3s ease-in-out;\n @keyframes fromLeft {\n 0% {\n transform: translateY(-50%) translateX(-10px);\n opacity: 0;\n }\n 100% {\n transform: translateY(-50%) translateX(0);\n }\n }\n &#search-closing-icon {\n &:hover {\n opacity: 1;\n }\n animation: fromRight 0.3s ease-in-out;\n @keyframes fromRight {\n 0% {\n transform: translateY(-50%) translateX(10px);\n opacity: 0;\n }\n 100% {\n transform: translateY(-50%) translateX(0);\n }\n }\n }\n"], ["\n cursor: ", ";\n position: absolute;\n top: 50%;\n ", "\n padding-left: 0.8em;\n transform: translateY(-50%);\n display: flex;\n opacity: 0.5;\n transition: opacity 0.5s ease-in-out;\n animation: fromLeft 0.3s ease-in-out;\n @keyframes fromLeft {\n 0% {\n transform: translateY(-50%) translateX(-10px);\n opacity: 0;\n }\n 100% {\n transform: translateY(-50%) translateX(0);\n }\n }\n &#search-closing-icon {\n &:hover {\n opacity: 1;\n }\n animation: fromRight 0.3s ease-in-out;\n @keyframes fromRight {\n 0% {\n transform: translateY(-50%) translateX(10px);\n opacity: 0;\n }\n 100% {\n transform: translateY(-50%) translateX(0);\n }\n }\n }\n"])), function (props) { return (props.$isClickable ? 'pointer' : 'default'); }, function (props) { return (props.$isRight ? 'right: 0; padding-right: 0.8em;' : ''); });
501
- var MunicipalitySearchContainer = styled.div(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n --border-radius: 0.3em;\n font-size: 18px;\n font-family: var(--font-plex);\n @media screen and (max-width: 599px) {\n max-width: 100%;\n }\n max-width: 300px;\n width: 100%;\n color: inherit;\n position: relative;\n"], ["\n --border-radius: 0.3em;\n font-size: 18px;\n font-family: var(--font-plex);\n @media screen and (max-width: 599px) {\n max-width: 100%;\n }\n max-width: 300px;\n width: 100%;\n color: inherit;\n position: relative;\n"])));
502
- var InputRow = styled.div(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n position: relative;\n display: flex;\n flex-direction: row;\n align-items: center;\n input:focus ~ i {\n opacity: 1;\n }\n .ui.input {\n width: 100%;\n max-width: 100%;\n transition: all 0.5s ease-in-out;\n }\n"], ["\n position: relative;\n display: flex;\n flex-direction: row;\n align-items: center;\n input:focus ~ i {\n opacity: 1;\n }\n .ui.input {\n width: 100%;\n max-width: 100%;\n transition: all 0.5s ease-in-out;\n }\n"])));
503
- var FlexInput = styled.input(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n // reset the default input styles\n color: inherit;\n background-color: ", ";\n border: solid 1px #7e7e7e7e;\n border-radius: var(--border-radius);\n box-shadow: none;\n font-size: 1em;\n outline: none;\n transition: all 0.3s ease-in-out;\n padding: 0.5em;\n padding-left: ", ";\n margin: 0;\n width: 100%;\n display: flex;\n &:disabled {\n opacity: 0.5;\n }\n &::placeholder {\n color: inherit;\n opacity: 0.5;\n }\n"], ["\n // reset the default input styles\n color: inherit;\n background-color: ", ";\n border: solid 1px #7e7e7e7e;\n border-radius: var(--border-radius);\n box-shadow: none;\n font-size: 1em;\n outline: none;\n transition: all 0.3s ease-in-out;\n padding: 0.5em;\n padding-left: ", ";\n margin: 0;\n width: 100%;\n display: flex;\n &:disabled {\n opacity: 0.5;\n }\n &::placeholder {\n color: inherit;\n opacity: 0.5;\n }\n"])), function (_a) {
504
- var backgroundColor = _a.$backgroundColor;
505
- return backgroundColor;
383
+ var MunicipalitySearchContainer = styled.div(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n --border-radius: 0.3em;\n font-size: 18px;\n font-family: var(--font-plex);\n max-width: 300px;\n width: 100%;\n color: inherit;\n position: relative;\n\n @media screen and (max-width: 599px) {\n max-width: 100%;\n }\n"], ["\n --border-radius: 0.3em;\n font-size: 18px;\n font-family: var(--font-plex);\n max-width: 300px;\n width: 100%;\n color: inherit;\n position: relative;\n\n @media screen and (max-width: 599px) {\n max-width: 100%;\n }\n"])));
384
+ var InputRow = styled.div(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n position: relative;\n display: flex;\n flex-direction: row;\n align-items: center;\n\n input:focus ~ i {\n opacity: 1;\n }\n"], ["\n position: relative;\n display: flex;\n flex-direction: row;\n align-items: center;\n\n input:focus ~ i {\n opacity: 1;\n }\n"])));
385
+ var FlexInput = styled.input(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n color: inherit;\n background-color: ", ";\n border: solid 1px #7e7e7e7e;\n border-radius: var(--border-radius);\n box-shadow: none;\n font-size: 1em;\n outline: none;\n transition: all 0.3s ease-in-out;\n padding: 0.5em;\n padding-left: ", ";\n margin: 0;\n width: 100%;\n display: flex;\n\n &:disabled {\n opacity: 0.5;\n }\n\n &::placeholder {\n color: inherit;\n opacity: 0.5;\n }\n"], ["\n color: inherit;\n background-color: ", ";\n border: solid 1px #7e7e7e7e;\n border-radius: var(--border-radius);\n box-shadow: none;\n font-size: 1em;\n outline: none;\n transition: all 0.3s ease-in-out;\n padding: 0.5em;\n padding-left: ", ";\n margin: 0;\n width: 100%;\n display: flex;\n\n &:disabled {\n opacity: 0.5;\n }\n\n &::placeholder {\n color: inherit;\n opacity: 0.5;\n }\n"])), function (_a) {
386
+ var $backgroundColor = _a.$backgroundColor;
387
+ return $backgroundColor;
506
388
  }, function (_a) {
507
- var lessPaddingLeft = _a.$lessPaddingLeft;
508
- return lessPaddingLeft ? '1em' : '2.4em';
389
+ var $lessPaddingLeft = _a.$lessPaddingLeft;
390
+ return $lessPaddingLeft ? '1em' : '2.4em';
509
391
  });
510
- var Results = styled.div(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n margin-top: 0.25em;\n display: grid;\n grid-template-columns: 1fr;\n grid-gap: 0;\n font-family: var(--font-plex);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n pointer-events: auto;\n position: absolute;\n background-color: ", ";\n width: 100%;\n border-radius: var(--border-radius);\n @media screen and (min-width: 599px) {\n max-width: 300px;\n }\n .result {\n max-width: 100%;\n color: currentColor;\n padding: calc(11 / 16 * 1em) calc(14 / 16 * 1em);\n border-radius: var(--border-radius);\n box-shadow: 0 0 0 rgba(0, 0, 0, 0.3);\n //border: 1px solid #007abf;\n color: inherit;\n line-height: 1.1em;\n cursor: pointer;\n transition: box-shadow 200ms ease-in-out;\n &:hover,\n &:focus {\n box-shadow:\n 0 0 0.5ex rgba(0, 0, 0, 0.2),\n 0 0 0 1px #007abf inset;\n }\n }\n"], ["\n margin-top: 0.25em;\n display: grid;\n grid-template-columns: 1fr;\n grid-gap: 0;\n font-family: var(--font-plex);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n pointer-events: auto;\n position: absolute;\n background-color: ", ";\n width: 100%;\n border-radius: var(--border-radius);\n @media screen and (min-width: 599px) {\n max-width: 300px;\n }\n .result {\n max-width: 100%;\n color: currentColor;\n padding: calc(11 / 16 * 1em) calc(14 / 16 * 1em);\n border-radius: var(--border-radius);\n box-shadow: 0 0 0 rgba(0, 0, 0, 0.3);\n //border: 1px solid #007abf;\n color: inherit;\n line-height: 1.1em;\n cursor: pointer;\n transition: box-shadow 200ms ease-in-out;\n &:hover,\n &:focus {\n box-shadow:\n 0 0 0.5ex rgba(0, 0, 0, 0.2),\n 0 0 0 1px #007abf inset;\n }\n }\n"])), function (_a) {
511
- var backgroundColor = _a.$backgroundColor;
512
- return backgroundColor;
392
+ var Results = styled.div(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n margin-top: 0.25em;\n font-family: var(--font-plex);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n pointer-events: auto;\n position: absolute;\n background-color: ", ";\n width: 100%;\n border-radius: var(--border-radius);\n\n @media screen and (min-width: 599px) {\n max-width: 300px;\n }\n\n .result {\n max-width: 100%;\n color: inherit;\n padding: calc(11 / 16 * 1em) calc(14 / 16 * 1em);\n border-radius: var(--border-radius);\n box-shadow: 0 0 0 rgba(0, 0, 0, 0.3);\n line-height: 1.1em;\n cursor: pointer;\n transition: box-shadow 200ms ease-in-out;\n\n &:hover,\n &:focus {\n box-shadow:\n 0 0 0.5ex rgba(0, 0, 0, 0.2),\n 0 0 0 1px #007abf inset;\n }\n }\n"], ["\n margin-top: 0.25em;\n font-family: var(--font-plex);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n pointer-events: auto;\n position: absolute;\n background-color: ", ";\n width: 100%;\n border-radius: var(--border-radius);\n\n @media screen and (min-width: 599px) {\n max-width: 300px;\n }\n\n .result {\n max-width: 100%;\n color: inherit;\n padding: calc(11 / 16 * 1em) calc(14 / 16 * 1em);\n border-radius: var(--border-radius);\n box-shadow: 0 0 0 rgba(0, 0, 0, 0.3);\n line-height: 1.1em;\n cursor: pointer;\n transition: box-shadow 200ms ease-in-out;\n\n &:hover,\n &:focus {\n box-shadow:\n 0 0 0.5ex rgba(0, 0, 0, 0.2),\n 0 0 0 1px #007abf inset;\n }\n }\n"])), function (_a) {
393
+ var $backgroundColor = _a.$backgroundColor;
394
+ return $backgroundColor;
513
395
  });
514
- var ResultHeader = styled.div(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n /* font-weight: 700; */\n"], ["\n /* font-weight: 700; */\n"])));
515
- var ResultPlz = styled.span(templateObject_7 || (templateObject_7 = __makeTemplateObject(["\n /* opacity: 0.5; */\n font-weight: 400;\n"], ["\n /* opacity: 0.5; */\n font-weight: 400;\n"])));
516
- var ResultMeta = styled.div(templateObject_8 || (templateObject_8 = __makeTemplateObject(["\n /* opacity: 0.66; */\n font-size: 0.9em;\n"], ["\n /* opacity: 0.66; */\n font-size: 0.9em;\n"])));
396
+ var ResultHeader = styled.div(templateObject_6 || (templateObject_6 = __makeTemplateObject([""], [""])));
397
+ var ResultPlz = styled.span(templateObject_7 || (templateObject_7 = __makeTemplateObject(["\n font-weight: 400;\n"], ["\n font-weight: 400;\n"])));
398
+ var ResultMeta = styled.div(templateObject_8 || (templateObject_8 = __makeTemplateObject(["\n font-size: 0.9em;\n"], ["\n font-size: 0.9em;\n"])));
517
399
  var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7, templateObject_8;
518
400
 
519
401
  exports.MunicipalitySearch = MunicipalitySearch;