@pro6pp/infer-react 0.0.2-beta.5 → 0.0.2-beta.7
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/README.md +45 -7
- package/dist/index.cjs +511 -6
- package/dist/index.d.cts +13 -11
- package/dist/index.d.ts +13 -11
- package/dist/index.js +500 -4
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -11,13 +11,48 @@ npm install @pro6pp/infer-react
|
|
|
11
11
|
|
|
12
12
|
## Usage
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
The `Pro6PPInfer` component provides a styled address autocomplete input.
|
|
15
15
|
|
|
16
16
|
```tsx
|
|
17
17
|
import React from 'react';
|
|
18
|
-
import {
|
|
18
|
+
import { Pro6PPInfer } from '@pro6pp/infer-react';
|
|
19
19
|
|
|
20
20
|
const AddressForm = () => {
|
|
21
|
+
return (
|
|
22
|
+
<div className="form-group">
|
|
23
|
+
<label>Search Address</label>
|
|
24
|
+
<Pro6PPInfer
|
|
25
|
+
authKey="YOUR_AUTH_KEY"
|
|
26
|
+
country="NL"
|
|
27
|
+
onSelect={(selection) => console.log('Selected:', selection)}
|
|
28
|
+
placeholder="Type a Dutch address..."
|
|
29
|
+
/>
|
|
30
|
+
</div>
|
|
31
|
+
);
|
|
32
|
+
};
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
You can customize the appearance of the component via the following props:
|
|
36
|
+
|
|
37
|
+
| Prop | Description |
|
|
38
|
+
| :--------------------- | :---------------------------------------------------------------------------------------- |
|
|
39
|
+
| `className` | Optional CSS class name for the wrapper `div`. |
|
|
40
|
+
| `disableDefaultStyles` | If `true`, prevents the automatic injection of the default CSS theme. |
|
|
41
|
+
| `placeholder` | Custom placeholder text for the input field. |
|
|
42
|
+
| `noResultsText` | The text to display when no suggestions are found. |
|
|
43
|
+
| `renderItem` | A custom render function for suggestion items, receiving the `item` and `isActive` state. |
|
|
44
|
+
| `renderNoResults` | A custom render function for the empty state, receiving the current `state`. |
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
Alternatively, you can use the headless `useInfer` hook.
|
|
49
|
+
This hook handles all the logic (state, API calls, debouncing, keyboard navigation), but allows you to build your own custom UI.
|
|
50
|
+
|
|
51
|
+
```tsx
|
|
52
|
+
import React from 'react';
|
|
53
|
+
import { useInfer } from '@pro6pp/infer-react';
|
|
54
|
+
|
|
55
|
+
const CustomAddressForm = () => {
|
|
21
56
|
const { state, inputProps, selectItem } = useInfer({
|
|
22
57
|
authKey: 'YOUR_AUTH_KEY',
|
|
23
58
|
country: 'NL',
|
|
@@ -28,19 +63,22 @@ const AddressForm = () => {
|
|
|
28
63
|
<div className="address-autocomplete">
|
|
29
64
|
<label>Address</label>
|
|
30
65
|
|
|
31
|
-
|
|
66
|
+
{/* inputProps contains value, onChange, and onKeyDown */}
|
|
67
|
+
<input {...inputProps} placeholder="Type an address..." className="my-input-class" />
|
|
68
|
+
|
|
69
|
+
{state.isLoading && <div className="spinner">Loading...</div>}
|
|
32
70
|
|
|
33
71
|
{/* render the dropdown */}
|
|
34
72
|
{(state.suggestions.length > 0 || state.cities.length > 0) && (
|
|
35
73
|
<ul className="my-dropdown-class">
|
|
36
|
-
{/* render cities
|
|
74
|
+
{/* render cities */}
|
|
37
75
|
{state.cities.map((city, i) => (
|
|
38
76
|
<li key={`city-${i}`} onClick={() => selectItem(city)}>
|
|
39
77
|
<strong>{city.label}</strong> (City)
|
|
40
78
|
</li>
|
|
41
79
|
))}
|
|
42
80
|
|
|
43
|
-
{/* render streets
|
|
81
|
+
{/* render streets */}
|
|
44
82
|
{state.streets.map((street, i) => (
|
|
45
83
|
<li key={`street-${i}`} onClick={() => selectItem(street)}>
|
|
46
84
|
<strong>{street.label}</strong> (Street)
|
|
@@ -49,14 +87,14 @@ const AddressForm = () => {
|
|
|
49
87
|
|
|
50
88
|
{/* render general suggestions */}
|
|
51
89
|
{state.suggestions.map((item, i) => (
|
|
52
|
-
<li key={`
|
|
90
|
+
<li key={`suggestion-${i}`} onClick={() => selectItem(item)}>
|
|
53
91
|
{item.label}
|
|
54
92
|
</li>
|
|
55
93
|
))}
|
|
56
94
|
</ul>
|
|
57
95
|
)}
|
|
58
96
|
|
|
59
|
-
{state.isValid && <p>Valid address selected
|
|
97
|
+
{state.isValid && <p>Valid address selected.</p>}
|
|
60
98
|
</div>
|
|
61
99
|
);
|
|
62
100
|
};
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
9
|
var __export = (target, all) => {
|
|
7
10
|
for (var name in all)
|
|
8
11
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -15,22 +18,442 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
18
|
}
|
|
16
19
|
return to;
|
|
17
20
|
};
|
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
+
mod
|
|
28
|
+
));
|
|
18
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
19
31
|
|
|
20
|
-
// src/index.
|
|
32
|
+
// src/index.tsx
|
|
21
33
|
var index_exports = {};
|
|
22
34
|
__export(index_exports, {
|
|
35
|
+
Pro6PPInfer: () => Pro6PPInfer,
|
|
23
36
|
useInfer: () => useInfer
|
|
24
37
|
});
|
|
25
38
|
module.exports = __toCommonJS(index_exports);
|
|
26
|
-
var import_react = require("react");
|
|
27
|
-
|
|
39
|
+
var import_react = __toESM(require("react"), 1);
|
|
40
|
+
|
|
41
|
+
// ../core/src/core.ts
|
|
42
|
+
var DEFAULTS = {
|
|
43
|
+
API_URL: "https://api.pro6pp.nl/v2",
|
|
44
|
+
LIMIT: 1e3,
|
|
45
|
+
DEBOUNCE_MS: 300
|
|
46
|
+
};
|
|
47
|
+
var PATTERNS = {
|
|
48
|
+
DIGITS_1_3: /^[0-9]{1,3}$/
|
|
49
|
+
};
|
|
50
|
+
var INITIAL_STATE = {
|
|
51
|
+
query: "",
|
|
52
|
+
stage: null,
|
|
53
|
+
cities: [],
|
|
54
|
+
streets: [],
|
|
55
|
+
suggestions: [],
|
|
56
|
+
isValid: false,
|
|
57
|
+
isError: false,
|
|
58
|
+
isLoading: false,
|
|
59
|
+
selectedSuggestionIndex: -1
|
|
60
|
+
};
|
|
61
|
+
var InferCore = class {
|
|
62
|
+
constructor(config) {
|
|
63
|
+
__publicField(this, "country");
|
|
64
|
+
__publicField(this, "authKey");
|
|
65
|
+
__publicField(this, "apiUrl");
|
|
66
|
+
__publicField(this, "limit");
|
|
67
|
+
__publicField(this, "fetcher");
|
|
68
|
+
__publicField(this, "onStateChange");
|
|
69
|
+
__publicField(this, "onSelect");
|
|
70
|
+
__publicField(this, "state");
|
|
71
|
+
__publicField(this, "abortController", null);
|
|
72
|
+
__publicField(this, "debouncedFetch");
|
|
73
|
+
__publicField(this, "isSelecting", false);
|
|
74
|
+
this.country = config.country;
|
|
75
|
+
this.authKey = config.authKey;
|
|
76
|
+
this.apiUrl = config.apiUrl || DEFAULTS.API_URL;
|
|
77
|
+
this.limit = config.limit || DEFAULTS.LIMIT;
|
|
78
|
+
this.fetcher = config.fetcher || ((url, init) => fetch(url, init));
|
|
79
|
+
this.onStateChange = config.onStateChange || (() => {
|
|
80
|
+
});
|
|
81
|
+
this.onSelect = config.onSelect || (() => {
|
|
82
|
+
});
|
|
83
|
+
this.state = { ...INITIAL_STATE };
|
|
84
|
+
this.debouncedFetch = this.debounce(
|
|
85
|
+
(val) => this.executeFetch(val),
|
|
86
|
+
DEFAULTS.DEBOUNCE_MS
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
handleInput(value) {
|
|
90
|
+
if (this.isSelecting) {
|
|
91
|
+
this.isSelecting = false;
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const isEditingFinal = this.state.stage === "final" && value !== this.state.query;
|
|
95
|
+
this.updateState({
|
|
96
|
+
query: value,
|
|
97
|
+
isValid: false,
|
|
98
|
+
isLoading: !!value.trim(),
|
|
99
|
+
selectedSuggestionIndex: -1
|
|
100
|
+
});
|
|
101
|
+
if (isEditingFinal) {
|
|
102
|
+
this.onSelect(null);
|
|
103
|
+
}
|
|
104
|
+
this.debouncedFetch(value);
|
|
105
|
+
}
|
|
106
|
+
handleKeyDown(event) {
|
|
107
|
+
const target = event.target;
|
|
108
|
+
if (!target) return;
|
|
109
|
+
const totalItems = this.state.cities.length + this.state.streets.length + this.state.suggestions.length;
|
|
110
|
+
if (totalItems > 0) {
|
|
111
|
+
if (event.key === "ArrowDown") {
|
|
112
|
+
event.preventDefault();
|
|
113
|
+
let nextIndex = this.state.selectedSuggestionIndex + 1;
|
|
114
|
+
if (nextIndex >= totalItems) {
|
|
115
|
+
nextIndex = 0;
|
|
116
|
+
}
|
|
117
|
+
this.updateState({ selectedSuggestionIndex: nextIndex });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (event.key === "ArrowUp") {
|
|
121
|
+
event.preventDefault();
|
|
122
|
+
let nextIndex = this.state.selectedSuggestionIndex - 1;
|
|
123
|
+
if (nextIndex < 0) {
|
|
124
|
+
nextIndex = totalItems - 1;
|
|
125
|
+
}
|
|
126
|
+
this.updateState({ selectedSuggestionIndex: nextIndex });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (event.key === "Enter" && this.state.selectedSuggestionIndex >= 0) {
|
|
130
|
+
event.preventDefault();
|
|
131
|
+
const allItems = [...this.state.cities, ...this.state.streets, ...this.state.suggestions];
|
|
132
|
+
const item = allItems[this.state.selectedSuggestionIndex];
|
|
133
|
+
if (item) {
|
|
134
|
+
this.selectItem(item);
|
|
135
|
+
this.updateState({ selectedSuggestionIndex: -1 });
|
|
136
|
+
}
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const val = target.value;
|
|
141
|
+
if (event.key === " " && this.shouldAutoInsertComma(val)) {
|
|
142
|
+
event.preventDefault();
|
|
143
|
+
const next = `${val.trim()}, `;
|
|
144
|
+
this.updateQueryAndFetch(next);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
selectItem(item) {
|
|
148
|
+
this.debouncedFetch.cancel();
|
|
149
|
+
if (this.abortController) {
|
|
150
|
+
this.abortController.abort();
|
|
151
|
+
}
|
|
152
|
+
const label = typeof item === "string" ? item : item.label;
|
|
153
|
+
let logicValue = label;
|
|
154
|
+
if (typeof item !== "string" && typeof item.value === "string") {
|
|
155
|
+
logicValue = item.value;
|
|
156
|
+
}
|
|
157
|
+
const valueObj = typeof item !== "string" && typeof item.value === "object" ? item.value : void 0;
|
|
158
|
+
const isFullResult = !!valueObj && Object.keys(valueObj).length > 0;
|
|
159
|
+
this.isSelecting = true;
|
|
160
|
+
if (this.state.stage === "final" || isFullResult) {
|
|
161
|
+
let finalQuery = label;
|
|
162
|
+
if (valueObj && Object.keys(valueObj).length > 0) {
|
|
163
|
+
const { street, street_number, house_number, city } = valueObj;
|
|
164
|
+
const number = street_number || house_number;
|
|
165
|
+
if (street && number && city) {
|
|
166
|
+
finalQuery = `${street} ${number}, ${city}`;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
this.finishSelection(finalQuery, valueObj);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const subtitle = typeof item !== "string" ? item.subtitle : null;
|
|
173
|
+
this.processSelection(logicValue, subtitle);
|
|
174
|
+
}
|
|
175
|
+
shouldAutoInsertComma(currentVal) {
|
|
176
|
+
const isStartOfSegmentAndNumeric = !currentVal.includes(",") && PATTERNS.DIGITS_1_3.test(currentVal.trim());
|
|
177
|
+
if (isStartOfSegmentAndNumeric) return true;
|
|
178
|
+
if (this.state.stage === "house_number") {
|
|
179
|
+
const currentFragment = this.getCurrentFragment(currentVal);
|
|
180
|
+
return PATTERNS.DIGITS_1_3.test(currentFragment);
|
|
181
|
+
}
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
finishSelection(label, value) {
|
|
185
|
+
this.updateState({
|
|
186
|
+
query: label,
|
|
187
|
+
suggestions: [],
|
|
188
|
+
cities: [],
|
|
189
|
+
streets: [],
|
|
190
|
+
isValid: true,
|
|
191
|
+
stage: "final"
|
|
192
|
+
});
|
|
193
|
+
this.onSelect(value || label);
|
|
194
|
+
setTimeout(() => {
|
|
195
|
+
this.isSelecting = false;
|
|
196
|
+
}, 0);
|
|
197
|
+
}
|
|
198
|
+
processSelection(text, subtitle) {
|
|
199
|
+
const { stage, query } = this.state;
|
|
200
|
+
let nextQuery = query;
|
|
201
|
+
const isContextualSelection = subtitle && (stage === "city" || stage === "street" || stage === "mixed");
|
|
202
|
+
if (isContextualSelection) {
|
|
203
|
+
if (stage === "city") {
|
|
204
|
+
nextQuery = `${subtitle}, ${text}, `;
|
|
205
|
+
} else {
|
|
206
|
+
const prefix = this.getQueryPrefix(query);
|
|
207
|
+
nextQuery = prefix ? `${prefix} ${text}, ${subtitle}, ` : `${text}, ${subtitle}, `;
|
|
208
|
+
}
|
|
209
|
+
this.updateQueryAndFetch(nextQuery);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (stage === "direct" || stage === "addition") {
|
|
213
|
+
this.finishSelection(text);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const hasComma = query.includes(",");
|
|
217
|
+
const isFirstSegment = !hasComma && (stage === "city" || stage === "street" || stage === "house_number_first");
|
|
218
|
+
if (isFirstSegment) {
|
|
219
|
+
nextQuery = `${text}, `;
|
|
220
|
+
} else {
|
|
221
|
+
nextQuery = this.replaceLastSegment(query, text);
|
|
222
|
+
if (stage !== "house_number") {
|
|
223
|
+
nextQuery += ", ";
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
this.updateQueryAndFetch(nextQuery);
|
|
227
|
+
}
|
|
228
|
+
executeFetch(val) {
|
|
229
|
+
const text = (val || "").toString();
|
|
230
|
+
if (!text.trim()) {
|
|
231
|
+
this.abortController?.abort();
|
|
232
|
+
this.resetState();
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
this.updateState({ isError: false });
|
|
236
|
+
if (this.abortController) this.abortController.abort();
|
|
237
|
+
this.abortController = new AbortController();
|
|
238
|
+
const url = new URL(`${this.apiUrl}/infer/${this.country.toLowerCase()}`);
|
|
239
|
+
const params = {
|
|
240
|
+
authKey: this.authKey,
|
|
241
|
+
query: text,
|
|
242
|
+
limit: this.limit.toString()
|
|
243
|
+
};
|
|
244
|
+
url.search = new URLSearchParams(params).toString();
|
|
245
|
+
this.fetcher(url.toString(), { signal: this.abortController.signal }).then((res) => {
|
|
246
|
+
if (!res.ok) throw new Error("Network error");
|
|
247
|
+
return res.json();
|
|
248
|
+
}).then((data) => this.mapResponseToState(data)).catch((e) => {
|
|
249
|
+
if (e.name !== "AbortError") {
|
|
250
|
+
this.updateState({ isError: true, isLoading: false });
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
mapResponseToState(data) {
|
|
255
|
+
const newState = {
|
|
256
|
+
stage: data.stage,
|
|
257
|
+
isLoading: false
|
|
258
|
+
};
|
|
259
|
+
let autoSelect = false;
|
|
260
|
+
let autoSelectItem = null;
|
|
261
|
+
const rawSuggestions = data.suggestions || [];
|
|
262
|
+
const uniqueSuggestions = [];
|
|
263
|
+
const seen = /* @__PURE__ */ new Set();
|
|
264
|
+
for (const item of rawSuggestions) {
|
|
265
|
+
const key = `${item.label}|${item.subtitle || ""}|${JSON.stringify(item.value || {})}`;
|
|
266
|
+
if (!seen.has(key)) {
|
|
267
|
+
seen.add(key);
|
|
268
|
+
uniqueSuggestions.push(item);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (data.stage === "mixed") {
|
|
272
|
+
newState.cities = data.cities || [];
|
|
273
|
+
newState.streets = data.streets || [];
|
|
274
|
+
newState.suggestions = [];
|
|
275
|
+
} else {
|
|
276
|
+
newState.suggestions = uniqueSuggestions;
|
|
277
|
+
newState.cities = [];
|
|
278
|
+
newState.streets = [];
|
|
279
|
+
if (data.stage === "final" && uniqueSuggestions.length === 1) {
|
|
280
|
+
autoSelect = true;
|
|
281
|
+
autoSelectItem = uniqueSuggestions[0];
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
newState.isValid = data.stage === "final";
|
|
285
|
+
if (autoSelect && autoSelectItem) {
|
|
286
|
+
newState.query = autoSelectItem.label;
|
|
287
|
+
newState.suggestions = [];
|
|
288
|
+
newState.cities = [];
|
|
289
|
+
newState.streets = [];
|
|
290
|
+
newState.isValid = true;
|
|
291
|
+
this.updateState(newState);
|
|
292
|
+
const val = typeof autoSelectItem.value === "object" ? autoSelectItem.value : autoSelectItem.label;
|
|
293
|
+
this.onSelect(val);
|
|
294
|
+
} else {
|
|
295
|
+
this.updateState(newState);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
updateQueryAndFetch(nextQuery) {
|
|
299
|
+
this.updateState({ query: nextQuery, suggestions: [], cities: [], streets: [] });
|
|
300
|
+
this.updateState({ isLoading: true, isValid: false });
|
|
301
|
+
this.debouncedFetch(nextQuery);
|
|
302
|
+
setTimeout(() => {
|
|
303
|
+
this.isSelecting = false;
|
|
304
|
+
}, 0);
|
|
305
|
+
}
|
|
306
|
+
replaceLastSegment(fullText, newSegment) {
|
|
307
|
+
const lastCommaIndex = fullText.lastIndexOf(",");
|
|
308
|
+
if (lastCommaIndex === -1) return newSegment;
|
|
309
|
+
return `${fullText.slice(0, lastCommaIndex + 1)} ${newSegment}`.trim();
|
|
310
|
+
}
|
|
311
|
+
getQueryPrefix(q) {
|
|
312
|
+
const lastComma = q.lastIndexOf(",");
|
|
313
|
+
return lastComma === -1 ? "" : q.slice(0, lastComma + 1).trimEnd();
|
|
314
|
+
}
|
|
315
|
+
getCurrentFragment(q) {
|
|
316
|
+
return (q.split(",").slice(-1)[0] ?? "").trim();
|
|
317
|
+
}
|
|
318
|
+
resetState() {
|
|
319
|
+
this.updateState({ ...INITIAL_STATE, query: this.state.query });
|
|
320
|
+
}
|
|
321
|
+
updateState(updates) {
|
|
322
|
+
this.state = { ...this.state, ...updates };
|
|
323
|
+
this.onStateChange(this.state);
|
|
324
|
+
}
|
|
325
|
+
debounce(func, wait) {
|
|
326
|
+
let timeout;
|
|
327
|
+
const debounced = (...args) => {
|
|
328
|
+
if (timeout) clearTimeout(timeout);
|
|
329
|
+
timeout = setTimeout(() => func.apply(this, args), wait);
|
|
330
|
+
};
|
|
331
|
+
debounced.cancel = () => {
|
|
332
|
+
if (timeout) {
|
|
333
|
+
clearTimeout(timeout);
|
|
334
|
+
timeout = void 0;
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
return debounced;
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// ../core/src/default-styles.ts
|
|
342
|
+
var DEFAULT_STYLES = `
|
|
343
|
+
.pro6pp-wrapper {
|
|
344
|
+
position: relative;
|
|
345
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
346
|
+
box-sizing: border-box;
|
|
347
|
+
width: 100%;
|
|
348
|
+
}
|
|
349
|
+
.pro6pp-wrapper * {
|
|
350
|
+
box-sizing: border-box;
|
|
351
|
+
}
|
|
352
|
+
.pro6pp-input {
|
|
353
|
+
width: 100%;
|
|
354
|
+
padding: 10px 12px;
|
|
355
|
+
border: 1px solid #e0e0e0;
|
|
356
|
+
border-radius: 4px;
|
|
357
|
+
font-size: 16px;
|
|
358
|
+
line-height: 1.5;
|
|
359
|
+
transition: border-color 0.2s, box-shadow 0.2s;
|
|
360
|
+
}
|
|
361
|
+
.pro6pp-input:focus {
|
|
362
|
+
outline: none;
|
|
363
|
+
border-color: #3b82f6;
|
|
364
|
+
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
|
365
|
+
}
|
|
366
|
+
.pro6pp-dropdown {
|
|
367
|
+
position: absolute;
|
|
368
|
+
top: 100%;
|
|
369
|
+
left: 0;
|
|
370
|
+
right: 0;
|
|
371
|
+
z-index: 9999;
|
|
372
|
+
margin-top: 4px;
|
|
373
|
+
background: white;
|
|
374
|
+
border: 1px solid #e0e0e0;
|
|
375
|
+
border-radius: 4px;
|
|
376
|
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
|
|
377
|
+
max-height: 300px;
|
|
378
|
+
overflow-y: auto;
|
|
379
|
+
list-style: none !important;
|
|
380
|
+
padding: 0 !important;
|
|
381
|
+
margin: 0 !important;
|
|
382
|
+
overflow: hidden;
|
|
383
|
+
}
|
|
384
|
+
.pro6pp-item {
|
|
385
|
+
padding: 12px 12px 9px 12px;
|
|
386
|
+
cursor: pointer;
|
|
387
|
+
display: flex;
|
|
388
|
+
flex-direction: row;
|
|
389
|
+
align-items: center;
|
|
390
|
+
color: #000000;
|
|
391
|
+
font-size: 14px;
|
|
392
|
+
line-height: 1;
|
|
393
|
+
white-space: nowrap;
|
|
394
|
+
overflow: hidden;
|
|
395
|
+
border-radius: 0 !important;
|
|
396
|
+
margin: 0 !important;
|
|
397
|
+
}
|
|
398
|
+
.pro6pp-item:hover, .pro6pp-item--active {
|
|
399
|
+
background-color: #f5f5f5;
|
|
400
|
+
}
|
|
401
|
+
.pro6pp-item__label {
|
|
402
|
+
font-weight: 500;
|
|
403
|
+
flex-shrink: 0;
|
|
404
|
+
}
|
|
405
|
+
.pro6pp-item__subtitle {
|
|
406
|
+
font-size: 14px;
|
|
407
|
+
color: #404040;
|
|
408
|
+
overflow: hidden;
|
|
409
|
+
text-overflow: ellipsis;
|
|
410
|
+
flex-shrink: 1;
|
|
411
|
+
}
|
|
412
|
+
.pro6pp-item__chevron {
|
|
413
|
+
margin-left: auto;
|
|
414
|
+
display: flex;
|
|
415
|
+
align-items: center;
|
|
416
|
+
color: #a3a3a3;
|
|
417
|
+
padding-left: 8px;
|
|
418
|
+
}
|
|
419
|
+
.pro6pp-no-results {
|
|
420
|
+
padding: 12px;
|
|
421
|
+
color: #555555;
|
|
422
|
+
font-size: 14px;
|
|
423
|
+
text-align: center;
|
|
424
|
+
user-select: none;
|
|
425
|
+
pointer-events: none;
|
|
426
|
+
}
|
|
427
|
+
.pro6pp-loader {
|
|
428
|
+
position: absolute;
|
|
429
|
+
right: 12px;
|
|
430
|
+
top: 50%;
|
|
431
|
+
transform: translateY(-50%);
|
|
432
|
+
width: 16px;
|
|
433
|
+
height: 16px;
|
|
434
|
+
border: 2px solid #e0e0e0;
|
|
435
|
+
border-top-color: #404040;
|
|
436
|
+
border-radius: 50%;
|
|
437
|
+
animation: pro6pp-spin 0.6s linear infinite;
|
|
438
|
+
pointer-events: none;
|
|
439
|
+
}
|
|
440
|
+
@keyframes pro6pp-spin {
|
|
441
|
+
to { transform: translateY(-50%) rotate(360deg); }
|
|
442
|
+
}
|
|
443
|
+
`;
|
|
444
|
+
|
|
445
|
+
// src/index.tsx
|
|
28
446
|
function useInfer(config) {
|
|
29
|
-
const [state, setState] = (0, import_react.useState)(
|
|
447
|
+
const [state, setState] = (0, import_react.useState)(INITIAL_STATE);
|
|
30
448
|
const core = (0, import_react.useMemo)(() => {
|
|
31
|
-
return new
|
|
449
|
+
return new InferCore({
|
|
32
450
|
...config,
|
|
33
|
-
onStateChange: (newState) =>
|
|
451
|
+
onStateChange: (newState) => {
|
|
452
|
+
setState({ ...newState });
|
|
453
|
+
if (config.onStateChange) {
|
|
454
|
+
config.onStateChange(newState);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
34
457
|
});
|
|
35
458
|
}, [config.country, config.authKey, config.limit]);
|
|
36
459
|
return {
|
|
@@ -44,7 +467,89 @@ function useInfer(config) {
|
|
|
44
467
|
selectItem: (item) => core.selectItem(item)
|
|
45
468
|
};
|
|
46
469
|
}
|
|
470
|
+
var Pro6PPInfer = ({
|
|
471
|
+
className,
|
|
472
|
+
style,
|
|
473
|
+
inputProps,
|
|
474
|
+
placeholder = "Start typing an address...",
|
|
475
|
+
renderItem,
|
|
476
|
+
disableDefaultStyles = false,
|
|
477
|
+
noResultsText = "No results found",
|
|
478
|
+
renderNoResults,
|
|
479
|
+
...config
|
|
480
|
+
}) => {
|
|
481
|
+
const { state, selectItem, inputProps: coreInputProps } = useInfer(config);
|
|
482
|
+
const inputRef = (0, import_react.useRef)(null);
|
|
483
|
+
(0, import_react.useEffect)(() => {
|
|
484
|
+
if (disableDefaultStyles) return;
|
|
485
|
+
const styleId = "pro6pp-styles";
|
|
486
|
+
if (!document.getElementById(styleId)) {
|
|
487
|
+
const styleEl = document.createElement("style");
|
|
488
|
+
styleEl.id = styleId;
|
|
489
|
+
styleEl.textContent = DEFAULT_STYLES;
|
|
490
|
+
document.head.appendChild(styleEl);
|
|
491
|
+
}
|
|
492
|
+
}, [disableDefaultStyles]);
|
|
493
|
+
const items = (0, import_react.useMemo)(() => {
|
|
494
|
+
return [
|
|
495
|
+
...state.cities.map((c) => ({ ...c, type: "city" })),
|
|
496
|
+
...state.streets.map((s) => ({ ...s, type: "street" })),
|
|
497
|
+
...state.suggestions.map((s) => ({ ...s, type: "suggestion" }))
|
|
498
|
+
];
|
|
499
|
+
}, [state.cities, state.streets, state.suggestions]);
|
|
500
|
+
const handleSelect = (item) => {
|
|
501
|
+
selectItem(item);
|
|
502
|
+
if (!state.isValid && inputRef.current) {
|
|
503
|
+
inputRef.current.focus();
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
const hasResults = items.length > 0;
|
|
507
|
+
const showNoResults = !state.isLoading && !state.isError && state.query.length > 0 && !hasResults && !state.isValid;
|
|
508
|
+
const showDropdown = hasResults || showNoResults;
|
|
509
|
+
return /* @__PURE__ */ import_react.default.createElement("div", { className: `pro6pp-wrapper ${className || ""}`, style }, /* @__PURE__ */ import_react.default.createElement("div", { style: { position: "relative" } }, /* @__PURE__ */ import_react.default.createElement(
|
|
510
|
+
"input",
|
|
511
|
+
{
|
|
512
|
+
ref: inputRef,
|
|
513
|
+
type: "text",
|
|
514
|
+
className: "pro6pp-input",
|
|
515
|
+
placeholder,
|
|
516
|
+
autoComplete: "off",
|
|
517
|
+
...inputProps,
|
|
518
|
+
...coreInputProps
|
|
519
|
+
}
|
|
520
|
+
), state.isLoading && /* @__PURE__ */ import_react.default.createElement("div", { className: "pro6pp-loader" })), showDropdown && /* @__PURE__ */ import_react.default.createElement("ul", { className: "pro6pp-dropdown", role: "listbox" }, hasResults ? items.map((item, index) => {
|
|
521
|
+
const isActive = index === state.selectedSuggestionIndex;
|
|
522
|
+
const secondaryText = item.subtitle || item.count;
|
|
523
|
+
const showChevron = item.value === void 0 || item.value === null;
|
|
524
|
+
return /* @__PURE__ */ import_react.default.createElement(
|
|
525
|
+
"li",
|
|
526
|
+
{
|
|
527
|
+
key: `${item.label}-${index}`,
|
|
528
|
+
role: "option",
|
|
529
|
+
"aria-selected": isActive,
|
|
530
|
+
className: `pro6pp-item ${isActive ? "pro6pp-item--active" : ""}`,
|
|
531
|
+
onMouseDown: (e) => e.preventDefault(),
|
|
532
|
+
onClick: () => handleSelect(item)
|
|
533
|
+
},
|
|
534
|
+
renderItem ? renderItem(item, isActive) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("span", { className: "pro6pp-item__label" }, item.label), secondaryText && /* @__PURE__ */ import_react.default.createElement("span", { className: "pro6pp-item__subtitle" }, ", ", secondaryText), showChevron && /* @__PURE__ */ import_react.default.createElement("div", { className: "pro6pp-item__chevron" }, /* @__PURE__ */ import_react.default.createElement(
|
|
535
|
+
"svg",
|
|
536
|
+
{
|
|
537
|
+
width: "16",
|
|
538
|
+
height: "16",
|
|
539
|
+
viewBox: "0 0 24 24",
|
|
540
|
+
fill: "none",
|
|
541
|
+
stroke: "currentColor",
|
|
542
|
+
strokeWidth: "2",
|
|
543
|
+
strokeLinecap: "round",
|
|
544
|
+
strokeLinejoin: "round"
|
|
545
|
+
},
|
|
546
|
+
/* @__PURE__ */ import_react.default.createElement("polyline", { points: "9 18 15 12 9 6" })
|
|
547
|
+
)))
|
|
548
|
+
);
|
|
549
|
+
}) : /* @__PURE__ */ import_react.default.createElement("li", { className: "pro6pp-no-results" }, renderNoResults ? renderNoResults(state) : noResultsText)));
|
|
550
|
+
};
|
|
47
551
|
// Annotate the CommonJS export names for ESM import in node:
|
|
48
552
|
0 && (module.exports = {
|
|
553
|
+
Pro6PPInfer,
|
|
49
554
|
useInfer
|
|
50
555
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,16 +1,7 @@
|
|
|
1
|
+
import React from 'react';
|
|
1
2
|
import { InferConfig, InferState, InferCore, InferResult } from '@pro6pp/infer-core';
|
|
2
3
|
export { AddressValue, CountryCode, Fetcher, InferConfig, InferResult, InferState, Stage } from '@pro6pp/infer-core';
|
|
3
4
|
|
|
4
|
-
/**
|
|
5
|
-
* Hook for the Pro6PP Infer API.
|
|
6
|
-
* @param config - The API configuration.
|
|
7
|
-
* @returns An object containing the current state, input helpers, and selection handler.
|
|
8
|
-
* @example
|
|
9
|
-
* const { state, inputProps, selectItem } = useInfer({
|
|
10
|
-
* authKey: 'YOUR_KEY',
|
|
11
|
-
* country: 'NL'
|
|
12
|
-
* });
|
|
13
|
-
*/
|
|
14
5
|
declare function useInfer(config: InferConfig): {
|
|
15
6
|
state: InferState;
|
|
16
7
|
core: InferCore;
|
|
@@ -21,5 +12,16 @@ declare function useInfer(config: InferConfig): {
|
|
|
21
12
|
};
|
|
22
13
|
selectItem: (item: InferResult | string) => void;
|
|
23
14
|
};
|
|
15
|
+
interface Pro6PPInferProps extends InferConfig {
|
|
16
|
+
className?: string;
|
|
17
|
+
style?: React.CSSProperties;
|
|
18
|
+
inputProps?: React.InputHTMLAttributes<HTMLInputElement>;
|
|
19
|
+
placeholder?: string;
|
|
20
|
+
renderItem?: (item: InferResult, isActive: boolean) => React.ReactNode;
|
|
21
|
+
disableDefaultStyles?: boolean;
|
|
22
|
+
noResultsText?: string;
|
|
23
|
+
renderNoResults?: (state: InferState) => React.ReactNode;
|
|
24
|
+
}
|
|
25
|
+
declare const Pro6PPInfer: React.FC<Pro6PPInferProps>;
|
|
24
26
|
|
|
25
|
-
export { useInfer };
|
|
27
|
+
export { Pro6PPInfer, type Pro6PPInferProps, useInfer };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,16 +1,7 @@
|
|
|
1
|
+
import React from 'react';
|
|
1
2
|
import { InferConfig, InferState, InferCore, InferResult } from '@pro6pp/infer-core';
|
|
2
3
|
export { AddressValue, CountryCode, Fetcher, InferConfig, InferResult, InferState, Stage } from '@pro6pp/infer-core';
|
|
3
4
|
|
|
4
|
-
/**
|
|
5
|
-
* Hook for the Pro6PP Infer API.
|
|
6
|
-
* @param config - The API configuration.
|
|
7
|
-
* @returns An object containing the current state, input helpers, and selection handler.
|
|
8
|
-
* @example
|
|
9
|
-
* const { state, inputProps, selectItem } = useInfer({
|
|
10
|
-
* authKey: 'YOUR_KEY',
|
|
11
|
-
* country: 'NL'
|
|
12
|
-
* });
|
|
13
|
-
*/
|
|
14
5
|
declare function useInfer(config: InferConfig): {
|
|
15
6
|
state: InferState;
|
|
16
7
|
core: InferCore;
|
|
@@ -21,5 +12,16 @@ declare function useInfer(config: InferConfig): {
|
|
|
21
12
|
};
|
|
22
13
|
selectItem: (item: InferResult | string) => void;
|
|
23
14
|
};
|
|
15
|
+
interface Pro6PPInferProps extends InferConfig {
|
|
16
|
+
className?: string;
|
|
17
|
+
style?: React.CSSProperties;
|
|
18
|
+
inputProps?: React.InputHTMLAttributes<HTMLInputElement>;
|
|
19
|
+
placeholder?: string;
|
|
20
|
+
renderItem?: (item: InferResult, isActive: boolean) => React.ReactNode;
|
|
21
|
+
disableDefaultStyles?: boolean;
|
|
22
|
+
noResultsText?: string;
|
|
23
|
+
renderNoResults?: (state: InferState) => React.ReactNode;
|
|
24
|
+
}
|
|
25
|
+
declare const Pro6PPInfer: React.FC<Pro6PPInferProps>;
|
|
24
26
|
|
|
25
|
-
export { useInfer };
|
|
27
|
+
export { Pro6PPInfer, type Pro6PPInferProps, useInfer };
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,426 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
+
|
|
5
|
+
// src/index.tsx
|
|
6
|
+
import React, { useState, useMemo, useEffect, useRef } from "react";
|
|
7
|
+
|
|
8
|
+
// ../core/src/core.ts
|
|
9
|
+
var DEFAULTS = {
|
|
10
|
+
API_URL: "https://api.pro6pp.nl/v2",
|
|
11
|
+
LIMIT: 1e3,
|
|
12
|
+
DEBOUNCE_MS: 300
|
|
13
|
+
};
|
|
14
|
+
var PATTERNS = {
|
|
15
|
+
DIGITS_1_3: /^[0-9]{1,3}$/
|
|
16
|
+
};
|
|
17
|
+
var INITIAL_STATE = {
|
|
18
|
+
query: "",
|
|
19
|
+
stage: null,
|
|
20
|
+
cities: [],
|
|
21
|
+
streets: [],
|
|
22
|
+
suggestions: [],
|
|
23
|
+
isValid: false,
|
|
24
|
+
isError: false,
|
|
25
|
+
isLoading: false,
|
|
26
|
+
selectedSuggestionIndex: -1
|
|
27
|
+
};
|
|
28
|
+
var InferCore = class {
|
|
29
|
+
constructor(config) {
|
|
30
|
+
__publicField(this, "country");
|
|
31
|
+
__publicField(this, "authKey");
|
|
32
|
+
__publicField(this, "apiUrl");
|
|
33
|
+
__publicField(this, "limit");
|
|
34
|
+
__publicField(this, "fetcher");
|
|
35
|
+
__publicField(this, "onStateChange");
|
|
36
|
+
__publicField(this, "onSelect");
|
|
37
|
+
__publicField(this, "state");
|
|
38
|
+
__publicField(this, "abortController", null);
|
|
39
|
+
__publicField(this, "debouncedFetch");
|
|
40
|
+
__publicField(this, "isSelecting", false);
|
|
41
|
+
this.country = config.country;
|
|
42
|
+
this.authKey = config.authKey;
|
|
43
|
+
this.apiUrl = config.apiUrl || DEFAULTS.API_URL;
|
|
44
|
+
this.limit = config.limit || DEFAULTS.LIMIT;
|
|
45
|
+
this.fetcher = config.fetcher || ((url, init) => fetch(url, init));
|
|
46
|
+
this.onStateChange = config.onStateChange || (() => {
|
|
47
|
+
});
|
|
48
|
+
this.onSelect = config.onSelect || (() => {
|
|
49
|
+
});
|
|
50
|
+
this.state = { ...INITIAL_STATE };
|
|
51
|
+
this.debouncedFetch = this.debounce(
|
|
52
|
+
(val) => this.executeFetch(val),
|
|
53
|
+
DEFAULTS.DEBOUNCE_MS
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
handleInput(value) {
|
|
57
|
+
if (this.isSelecting) {
|
|
58
|
+
this.isSelecting = false;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const isEditingFinal = this.state.stage === "final" && value !== this.state.query;
|
|
62
|
+
this.updateState({
|
|
63
|
+
query: value,
|
|
64
|
+
isValid: false,
|
|
65
|
+
isLoading: !!value.trim(),
|
|
66
|
+
selectedSuggestionIndex: -1
|
|
67
|
+
});
|
|
68
|
+
if (isEditingFinal) {
|
|
69
|
+
this.onSelect(null);
|
|
70
|
+
}
|
|
71
|
+
this.debouncedFetch(value);
|
|
72
|
+
}
|
|
73
|
+
handleKeyDown(event) {
|
|
74
|
+
const target = event.target;
|
|
75
|
+
if (!target) return;
|
|
76
|
+
const totalItems = this.state.cities.length + this.state.streets.length + this.state.suggestions.length;
|
|
77
|
+
if (totalItems > 0) {
|
|
78
|
+
if (event.key === "ArrowDown") {
|
|
79
|
+
event.preventDefault();
|
|
80
|
+
let nextIndex = this.state.selectedSuggestionIndex + 1;
|
|
81
|
+
if (nextIndex >= totalItems) {
|
|
82
|
+
nextIndex = 0;
|
|
83
|
+
}
|
|
84
|
+
this.updateState({ selectedSuggestionIndex: nextIndex });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (event.key === "ArrowUp") {
|
|
88
|
+
event.preventDefault();
|
|
89
|
+
let nextIndex = this.state.selectedSuggestionIndex - 1;
|
|
90
|
+
if (nextIndex < 0) {
|
|
91
|
+
nextIndex = totalItems - 1;
|
|
92
|
+
}
|
|
93
|
+
this.updateState({ selectedSuggestionIndex: nextIndex });
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (event.key === "Enter" && this.state.selectedSuggestionIndex >= 0) {
|
|
97
|
+
event.preventDefault();
|
|
98
|
+
const allItems = [...this.state.cities, ...this.state.streets, ...this.state.suggestions];
|
|
99
|
+
const item = allItems[this.state.selectedSuggestionIndex];
|
|
100
|
+
if (item) {
|
|
101
|
+
this.selectItem(item);
|
|
102
|
+
this.updateState({ selectedSuggestionIndex: -1 });
|
|
103
|
+
}
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const val = target.value;
|
|
108
|
+
if (event.key === " " && this.shouldAutoInsertComma(val)) {
|
|
109
|
+
event.preventDefault();
|
|
110
|
+
const next = `${val.trim()}, `;
|
|
111
|
+
this.updateQueryAndFetch(next);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
selectItem(item) {
|
|
115
|
+
this.debouncedFetch.cancel();
|
|
116
|
+
if (this.abortController) {
|
|
117
|
+
this.abortController.abort();
|
|
118
|
+
}
|
|
119
|
+
const label = typeof item === "string" ? item : item.label;
|
|
120
|
+
let logicValue = label;
|
|
121
|
+
if (typeof item !== "string" && typeof item.value === "string") {
|
|
122
|
+
logicValue = item.value;
|
|
123
|
+
}
|
|
124
|
+
const valueObj = typeof item !== "string" && typeof item.value === "object" ? item.value : void 0;
|
|
125
|
+
const isFullResult = !!valueObj && Object.keys(valueObj).length > 0;
|
|
126
|
+
this.isSelecting = true;
|
|
127
|
+
if (this.state.stage === "final" || isFullResult) {
|
|
128
|
+
let finalQuery = label;
|
|
129
|
+
if (valueObj && Object.keys(valueObj).length > 0) {
|
|
130
|
+
const { street, street_number, house_number, city } = valueObj;
|
|
131
|
+
const number = street_number || house_number;
|
|
132
|
+
if (street && number && city) {
|
|
133
|
+
finalQuery = `${street} ${number}, ${city}`;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
this.finishSelection(finalQuery, valueObj);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const subtitle = typeof item !== "string" ? item.subtitle : null;
|
|
140
|
+
this.processSelection(logicValue, subtitle);
|
|
141
|
+
}
|
|
142
|
+
shouldAutoInsertComma(currentVal) {
|
|
143
|
+
const isStartOfSegmentAndNumeric = !currentVal.includes(",") && PATTERNS.DIGITS_1_3.test(currentVal.trim());
|
|
144
|
+
if (isStartOfSegmentAndNumeric) return true;
|
|
145
|
+
if (this.state.stage === "house_number") {
|
|
146
|
+
const currentFragment = this.getCurrentFragment(currentVal);
|
|
147
|
+
return PATTERNS.DIGITS_1_3.test(currentFragment);
|
|
148
|
+
}
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
finishSelection(label, value) {
|
|
152
|
+
this.updateState({
|
|
153
|
+
query: label,
|
|
154
|
+
suggestions: [],
|
|
155
|
+
cities: [],
|
|
156
|
+
streets: [],
|
|
157
|
+
isValid: true,
|
|
158
|
+
stage: "final"
|
|
159
|
+
});
|
|
160
|
+
this.onSelect(value || label);
|
|
161
|
+
setTimeout(() => {
|
|
162
|
+
this.isSelecting = false;
|
|
163
|
+
}, 0);
|
|
164
|
+
}
|
|
165
|
+
processSelection(text, subtitle) {
|
|
166
|
+
const { stage, query } = this.state;
|
|
167
|
+
let nextQuery = query;
|
|
168
|
+
const isContextualSelection = subtitle && (stage === "city" || stage === "street" || stage === "mixed");
|
|
169
|
+
if (isContextualSelection) {
|
|
170
|
+
if (stage === "city") {
|
|
171
|
+
nextQuery = `${subtitle}, ${text}, `;
|
|
172
|
+
} else {
|
|
173
|
+
const prefix = this.getQueryPrefix(query);
|
|
174
|
+
nextQuery = prefix ? `${prefix} ${text}, ${subtitle}, ` : `${text}, ${subtitle}, `;
|
|
175
|
+
}
|
|
176
|
+
this.updateQueryAndFetch(nextQuery);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (stage === "direct" || stage === "addition") {
|
|
180
|
+
this.finishSelection(text);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const hasComma = query.includes(",");
|
|
184
|
+
const isFirstSegment = !hasComma && (stage === "city" || stage === "street" || stage === "house_number_first");
|
|
185
|
+
if (isFirstSegment) {
|
|
186
|
+
nextQuery = `${text}, `;
|
|
187
|
+
} else {
|
|
188
|
+
nextQuery = this.replaceLastSegment(query, text);
|
|
189
|
+
if (stage !== "house_number") {
|
|
190
|
+
nextQuery += ", ";
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
this.updateQueryAndFetch(nextQuery);
|
|
194
|
+
}
|
|
195
|
+
executeFetch(val) {
|
|
196
|
+
const text = (val || "").toString();
|
|
197
|
+
if (!text.trim()) {
|
|
198
|
+
this.abortController?.abort();
|
|
199
|
+
this.resetState();
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
this.updateState({ isError: false });
|
|
203
|
+
if (this.abortController) this.abortController.abort();
|
|
204
|
+
this.abortController = new AbortController();
|
|
205
|
+
const url = new URL(`${this.apiUrl}/infer/${this.country.toLowerCase()}`);
|
|
206
|
+
const params = {
|
|
207
|
+
authKey: this.authKey,
|
|
208
|
+
query: text,
|
|
209
|
+
limit: this.limit.toString()
|
|
210
|
+
};
|
|
211
|
+
url.search = new URLSearchParams(params).toString();
|
|
212
|
+
this.fetcher(url.toString(), { signal: this.abortController.signal }).then((res) => {
|
|
213
|
+
if (!res.ok) throw new Error("Network error");
|
|
214
|
+
return res.json();
|
|
215
|
+
}).then((data) => this.mapResponseToState(data)).catch((e) => {
|
|
216
|
+
if (e.name !== "AbortError") {
|
|
217
|
+
this.updateState({ isError: true, isLoading: false });
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
mapResponseToState(data) {
|
|
222
|
+
const newState = {
|
|
223
|
+
stage: data.stage,
|
|
224
|
+
isLoading: false
|
|
225
|
+
};
|
|
226
|
+
let autoSelect = false;
|
|
227
|
+
let autoSelectItem = null;
|
|
228
|
+
const rawSuggestions = data.suggestions || [];
|
|
229
|
+
const uniqueSuggestions = [];
|
|
230
|
+
const seen = /* @__PURE__ */ new Set();
|
|
231
|
+
for (const item of rawSuggestions) {
|
|
232
|
+
const key = `${item.label}|${item.subtitle || ""}|${JSON.stringify(item.value || {})}`;
|
|
233
|
+
if (!seen.has(key)) {
|
|
234
|
+
seen.add(key);
|
|
235
|
+
uniqueSuggestions.push(item);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (data.stage === "mixed") {
|
|
239
|
+
newState.cities = data.cities || [];
|
|
240
|
+
newState.streets = data.streets || [];
|
|
241
|
+
newState.suggestions = [];
|
|
242
|
+
} else {
|
|
243
|
+
newState.suggestions = uniqueSuggestions;
|
|
244
|
+
newState.cities = [];
|
|
245
|
+
newState.streets = [];
|
|
246
|
+
if (data.stage === "final" && uniqueSuggestions.length === 1) {
|
|
247
|
+
autoSelect = true;
|
|
248
|
+
autoSelectItem = uniqueSuggestions[0];
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
newState.isValid = data.stage === "final";
|
|
252
|
+
if (autoSelect && autoSelectItem) {
|
|
253
|
+
newState.query = autoSelectItem.label;
|
|
254
|
+
newState.suggestions = [];
|
|
255
|
+
newState.cities = [];
|
|
256
|
+
newState.streets = [];
|
|
257
|
+
newState.isValid = true;
|
|
258
|
+
this.updateState(newState);
|
|
259
|
+
const val = typeof autoSelectItem.value === "object" ? autoSelectItem.value : autoSelectItem.label;
|
|
260
|
+
this.onSelect(val);
|
|
261
|
+
} else {
|
|
262
|
+
this.updateState(newState);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
updateQueryAndFetch(nextQuery) {
|
|
266
|
+
this.updateState({ query: nextQuery, suggestions: [], cities: [], streets: [] });
|
|
267
|
+
this.updateState({ isLoading: true, isValid: false });
|
|
268
|
+
this.debouncedFetch(nextQuery);
|
|
269
|
+
setTimeout(() => {
|
|
270
|
+
this.isSelecting = false;
|
|
271
|
+
}, 0);
|
|
272
|
+
}
|
|
273
|
+
replaceLastSegment(fullText, newSegment) {
|
|
274
|
+
const lastCommaIndex = fullText.lastIndexOf(",");
|
|
275
|
+
if (lastCommaIndex === -1) return newSegment;
|
|
276
|
+
return `${fullText.slice(0, lastCommaIndex + 1)} ${newSegment}`.trim();
|
|
277
|
+
}
|
|
278
|
+
getQueryPrefix(q) {
|
|
279
|
+
const lastComma = q.lastIndexOf(",");
|
|
280
|
+
return lastComma === -1 ? "" : q.slice(0, lastComma + 1).trimEnd();
|
|
281
|
+
}
|
|
282
|
+
getCurrentFragment(q) {
|
|
283
|
+
return (q.split(",").slice(-1)[0] ?? "").trim();
|
|
284
|
+
}
|
|
285
|
+
resetState() {
|
|
286
|
+
this.updateState({ ...INITIAL_STATE, query: this.state.query });
|
|
287
|
+
}
|
|
288
|
+
updateState(updates) {
|
|
289
|
+
this.state = { ...this.state, ...updates };
|
|
290
|
+
this.onStateChange(this.state);
|
|
291
|
+
}
|
|
292
|
+
debounce(func, wait) {
|
|
293
|
+
let timeout;
|
|
294
|
+
const debounced = (...args) => {
|
|
295
|
+
if (timeout) clearTimeout(timeout);
|
|
296
|
+
timeout = setTimeout(() => func.apply(this, args), wait);
|
|
297
|
+
};
|
|
298
|
+
debounced.cancel = () => {
|
|
299
|
+
if (timeout) {
|
|
300
|
+
clearTimeout(timeout);
|
|
301
|
+
timeout = void 0;
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
return debounced;
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
// ../core/src/default-styles.ts
|
|
309
|
+
var DEFAULT_STYLES = `
|
|
310
|
+
.pro6pp-wrapper {
|
|
311
|
+
position: relative;
|
|
312
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
313
|
+
box-sizing: border-box;
|
|
314
|
+
width: 100%;
|
|
315
|
+
}
|
|
316
|
+
.pro6pp-wrapper * {
|
|
317
|
+
box-sizing: border-box;
|
|
318
|
+
}
|
|
319
|
+
.pro6pp-input {
|
|
320
|
+
width: 100%;
|
|
321
|
+
padding: 10px 12px;
|
|
322
|
+
border: 1px solid #e0e0e0;
|
|
323
|
+
border-radius: 4px;
|
|
324
|
+
font-size: 16px;
|
|
325
|
+
line-height: 1.5;
|
|
326
|
+
transition: border-color 0.2s, box-shadow 0.2s;
|
|
327
|
+
}
|
|
328
|
+
.pro6pp-input:focus {
|
|
329
|
+
outline: none;
|
|
330
|
+
border-color: #3b82f6;
|
|
331
|
+
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
|
332
|
+
}
|
|
333
|
+
.pro6pp-dropdown {
|
|
334
|
+
position: absolute;
|
|
335
|
+
top: 100%;
|
|
336
|
+
left: 0;
|
|
337
|
+
right: 0;
|
|
338
|
+
z-index: 9999;
|
|
339
|
+
margin-top: 4px;
|
|
340
|
+
background: white;
|
|
341
|
+
border: 1px solid #e0e0e0;
|
|
342
|
+
border-radius: 4px;
|
|
343
|
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
|
|
344
|
+
max-height: 300px;
|
|
345
|
+
overflow-y: auto;
|
|
346
|
+
list-style: none !important;
|
|
347
|
+
padding: 0 !important;
|
|
348
|
+
margin: 0 !important;
|
|
349
|
+
overflow: hidden;
|
|
350
|
+
}
|
|
351
|
+
.pro6pp-item {
|
|
352
|
+
padding: 12px 12px 9px 12px;
|
|
353
|
+
cursor: pointer;
|
|
354
|
+
display: flex;
|
|
355
|
+
flex-direction: row;
|
|
356
|
+
align-items: center;
|
|
357
|
+
color: #000000;
|
|
358
|
+
font-size: 14px;
|
|
359
|
+
line-height: 1;
|
|
360
|
+
white-space: nowrap;
|
|
361
|
+
overflow: hidden;
|
|
362
|
+
border-radius: 0 !important;
|
|
363
|
+
margin: 0 !important;
|
|
364
|
+
}
|
|
365
|
+
.pro6pp-item:hover, .pro6pp-item--active {
|
|
366
|
+
background-color: #f5f5f5;
|
|
367
|
+
}
|
|
368
|
+
.pro6pp-item__label {
|
|
369
|
+
font-weight: 500;
|
|
370
|
+
flex-shrink: 0;
|
|
371
|
+
}
|
|
372
|
+
.pro6pp-item__subtitle {
|
|
373
|
+
font-size: 14px;
|
|
374
|
+
color: #404040;
|
|
375
|
+
overflow: hidden;
|
|
376
|
+
text-overflow: ellipsis;
|
|
377
|
+
flex-shrink: 1;
|
|
378
|
+
}
|
|
379
|
+
.pro6pp-item__chevron {
|
|
380
|
+
margin-left: auto;
|
|
381
|
+
display: flex;
|
|
382
|
+
align-items: center;
|
|
383
|
+
color: #a3a3a3;
|
|
384
|
+
padding-left: 8px;
|
|
385
|
+
}
|
|
386
|
+
.pro6pp-no-results {
|
|
387
|
+
padding: 12px;
|
|
388
|
+
color: #555555;
|
|
389
|
+
font-size: 14px;
|
|
390
|
+
text-align: center;
|
|
391
|
+
user-select: none;
|
|
392
|
+
pointer-events: none;
|
|
393
|
+
}
|
|
394
|
+
.pro6pp-loader {
|
|
395
|
+
position: absolute;
|
|
396
|
+
right: 12px;
|
|
397
|
+
top: 50%;
|
|
398
|
+
transform: translateY(-50%);
|
|
399
|
+
width: 16px;
|
|
400
|
+
height: 16px;
|
|
401
|
+
border: 2px solid #e0e0e0;
|
|
402
|
+
border-top-color: #404040;
|
|
403
|
+
border-radius: 50%;
|
|
404
|
+
animation: pro6pp-spin 0.6s linear infinite;
|
|
405
|
+
pointer-events: none;
|
|
406
|
+
}
|
|
407
|
+
@keyframes pro6pp-spin {
|
|
408
|
+
to { transform: translateY(-50%) rotate(360deg); }
|
|
409
|
+
}
|
|
410
|
+
`;
|
|
411
|
+
|
|
412
|
+
// src/index.tsx
|
|
4
413
|
function useInfer(config) {
|
|
5
414
|
const [state, setState] = useState(INITIAL_STATE);
|
|
6
415
|
const core = useMemo(() => {
|
|
7
416
|
return new InferCore({
|
|
8
417
|
...config,
|
|
9
|
-
onStateChange: (newState) =>
|
|
418
|
+
onStateChange: (newState) => {
|
|
419
|
+
setState({ ...newState });
|
|
420
|
+
if (config.onStateChange) {
|
|
421
|
+
config.onStateChange(newState);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
10
424
|
});
|
|
11
425
|
}, [config.country, config.authKey, config.limit]);
|
|
12
426
|
return {
|
|
@@ -20,6 +434,88 @@ function useInfer(config) {
|
|
|
20
434
|
selectItem: (item) => core.selectItem(item)
|
|
21
435
|
};
|
|
22
436
|
}
|
|
437
|
+
var Pro6PPInfer = ({
|
|
438
|
+
className,
|
|
439
|
+
style,
|
|
440
|
+
inputProps,
|
|
441
|
+
placeholder = "Start typing an address...",
|
|
442
|
+
renderItem,
|
|
443
|
+
disableDefaultStyles = false,
|
|
444
|
+
noResultsText = "No results found",
|
|
445
|
+
renderNoResults,
|
|
446
|
+
...config
|
|
447
|
+
}) => {
|
|
448
|
+
const { state, selectItem, inputProps: coreInputProps } = useInfer(config);
|
|
449
|
+
const inputRef = useRef(null);
|
|
450
|
+
useEffect(() => {
|
|
451
|
+
if (disableDefaultStyles) return;
|
|
452
|
+
const styleId = "pro6pp-styles";
|
|
453
|
+
if (!document.getElementById(styleId)) {
|
|
454
|
+
const styleEl = document.createElement("style");
|
|
455
|
+
styleEl.id = styleId;
|
|
456
|
+
styleEl.textContent = DEFAULT_STYLES;
|
|
457
|
+
document.head.appendChild(styleEl);
|
|
458
|
+
}
|
|
459
|
+
}, [disableDefaultStyles]);
|
|
460
|
+
const items = useMemo(() => {
|
|
461
|
+
return [
|
|
462
|
+
...state.cities.map((c) => ({ ...c, type: "city" })),
|
|
463
|
+
...state.streets.map((s) => ({ ...s, type: "street" })),
|
|
464
|
+
...state.suggestions.map((s) => ({ ...s, type: "suggestion" }))
|
|
465
|
+
];
|
|
466
|
+
}, [state.cities, state.streets, state.suggestions]);
|
|
467
|
+
const handleSelect = (item) => {
|
|
468
|
+
selectItem(item);
|
|
469
|
+
if (!state.isValid && inputRef.current) {
|
|
470
|
+
inputRef.current.focus();
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
const hasResults = items.length > 0;
|
|
474
|
+
const showNoResults = !state.isLoading && !state.isError && state.query.length > 0 && !hasResults && !state.isValid;
|
|
475
|
+
const showDropdown = hasResults || showNoResults;
|
|
476
|
+
return /* @__PURE__ */ React.createElement("div", { className: `pro6pp-wrapper ${className || ""}`, style }, /* @__PURE__ */ React.createElement("div", { style: { position: "relative" } }, /* @__PURE__ */ React.createElement(
|
|
477
|
+
"input",
|
|
478
|
+
{
|
|
479
|
+
ref: inputRef,
|
|
480
|
+
type: "text",
|
|
481
|
+
className: "pro6pp-input",
|
|
482
|
+
placeholder,
|
|
483
|
+
autoComplete: "off",
|
|
484
|
+
...inputProps,
|
|
485
|
+
...coreInputProps
|
|
486
|
+
}
|
|
487
|
+
), state.isLoading && /* @__PURE__ */ React.createElement("div", { className: "pro6pp-loader" })), showDropdown && /* @__PURE__ */ React.createElement("ul", { className: "pro6pp-dropdown", role: "listbox" }, hasResults ? items.map((item, index) => {
|
|
488
|
+
const isActive = index === state.selectedSuggestionIndex;
|
|
489
|
+
const secondaryText = item.subtitle || item.count;
|
|
490
|
+
const showChevron = item.value === void 0 || item.value === null;
|
|
491
|
+
return /* @__PURE__ */ React.createElement(
|
|
492
|
+
"li",
|
|
493
|
+
{
|
|
494
|
+
key: `${item.label}-${index}`,
|
|
495
|
+
role: "option",
|
|
496
|
+
"aria-selected": isActive,
|
|
497
|
+
className: `pro6pp-item ${isActive ? "pro6pp-item--active" : ""}`,
|
|
498
|
+
onMouseDown: (e) => e.preventDefault(),
|
|
499
|
+
onClick: () => handleSelect(item)
|
|
500
|
+
},
|
|
501
|
+
renderItem ? renderItem(item, isActive) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("span", { className: "pro6pp-item__label" }, item.label), secondaryText && /* @__PURE__ */ React.createElement("span", { className: "pro6pp-item__subtitle" }, ", ", secondaryText), showChevron && /* @__PURE__ */ React.createElement("div", { className: "pro6pp-item__chevron" }, /* @__PURE__ */ React.createElement(
|
|
502
|
+
"svg",
|
|
503
|
+
{
|
|
504
|
+
width: "16",
|
|
505
|
+
height: "16",
|
|
506
|
+
viewBox: "0 0 24 24",
|
|
507
|
+
fill: "none",
|
|
508
|
+
stroke: "currentColor",
|
|
509
|
+
strokeWidth: "2",
|
|
510
|
+
strokeLinecap: "round",
|
|
511
|
+
strokeLinejoin: "round"
|
|
512
|
+
},
|
|
513
|
+
/* @__PURE__ */ React.createElement("polyline", { points: "9 18 15 12 9 6" })
|
|
514
|
+
)))
|
|
515
|
+
);
|
|
516
|
+
}) : /* @__PURE__ */ React.createElement("li", { className: "pro6pp-no-results" }, renderNoResults ? renderNoResults(state) : noResultsText)));
|
|
517
|
+
};
|
|
23
518
|
export {
|
|
519
|
+
Pro6PPInfer,
|
|
24
520
|
useInfer
|
|
25
521
|
};
|
package/package.json
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"url": "https://github.com/pro6pp/infer-sdk/issues"
|
|
21
21
|
},
|
|
22
22
|
"sideEffects": false,
|
|
23
|
-
"version": "0.0.2-beta.
|
|
23
|
+
"version": "0.0.2-beta.7",
|
|
24
24
|
"main": "./dist/index.cjs",
|
|
25
25
|
"module": "./dist/index.js",
|
|
26
26
|
"types": "./dist/index.d.ts",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"react": ">=16"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@pro6pp/infer-core": "0.0.2-beta.
|
|
49
|
+
"@pro6pp/infer-core": "0.0.2-beta.5"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@testing-library/dom": "^10.4.1",
|