@pro6pp/infer-react 0.0.2-beta.5 → 0.0.2-beta.6

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.cjs CHANGED
@@ -3,6 +3,7 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
7
  var __export = (target, all) => {
7
8
  for (var name in all)
8
9
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -16,6 +17,7 @@ var __copyProps = (to, from, except, desc) => {
16
17
  return to;
17
18
  };
18
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
19
21
 
20
22
  // src/index.ts
21
23
  var index_exports = {};
@@ -24,11 +26,240 @@ __export(index_exports, {
24
26
  });
25
27
  module.exports = __toCommonJS(index_exports);
26
28
  var import_react = require("react");
27
- var import_infer_core = require("@pro6pp/infer-core");
29
+
30
+ // ../core/src/core.ts
31
+ var DEFAULTS = {
32
+ API_URL: "https://api.pro6pp.nl/v2",
33
+ LIMIT: 1e3,
34
+ DEBOUNCE_MS: 300
35
+ };
36
+ var PATTERNS = {
37
+ DIGITS_1_3: /^[0-9]{1,3}$/
38
+ };
39
+ var INITIAL_STATE = {
40
+ query: "",
41
+ stage: null,
42
+ cities: [],
43
+ streets: [],
44
+ suggestions: [],
45
+ isValid: false,
46
+ isError: false,
47
+ isLoading: false,
48
+ selectedSuggestionIndex: -1
49
+ };
50
+ var InferCore = class {
51
+ constructor(config) {
52
+ __publicField(this, "country");
53
+ __publicField(this, "authKey");
54
+ __publicField(this, "apiUrl");
55
+ __publicField(this, "limit");
56
+ __publicField(this, "fetcher");
57
+ __publicField(this, "onStateChange");
58
+ __publicField(this, "onSelect");
59
+ __publicField(this, "state");
60
+ __publicField(this, "abortController", null);
61
+ __publicField(this, "debouncedFetch");
62
+ this.country = config.country;
63
+ this.authKey = config.authKey;
64
+ this.apiUrl = config.apiUrl || DEFAULTS.API_URL;
65
+ this.limit = config.limit || DEFAULTS.LIMIT;
66
+ this.fetcher = config.fetcher || ((url, init) => fetch(url, init));
67
+ this.onStateChange = config.onStateChange || (() => {
68
+ });
69
+ this.onSelect = config.onSelect || (() => {
70
+ });
71
+ this.state = { ...INITIAL_STATE };
72
+ this.debouncedFetch = this.debounce(
73
+ (val) => this.executeFetch(val),
74
+ DEFAULTS.DEBOUNCE_MS
75
+ );
76
+ }
77
+ handleInput(value) {
78
+ this.updateState({
79
+ query: value,
80
+ isValid: false,
81
+ isLoading: !!value.trim(),
82
+ selectedSuggestionIndex: -1
83
+ });
84
+ if (this.state.stage === "final") {
85
+ this.onSelect(null);
86
+ }
87
+ this.debouncedFetch(value);
88
+ }
89
+ handleKeyDown(event) {
90
+ const target = event.target;
91
+ if (!target) return;
92
+ const totalItems = this.state.cities.length + this.state.streets.length + this.state.suggestions.length;
93
+ if (totalItems > 0) {
94
+ if (event.key === "ArrowDown") {
95
+ event.preventDefault();
96
+ let nextIndex = this.state.selectedSuggestionIndex + 1;
97
+ if (nextIndex >= totalItems) {
98
+ nextIndex = 0;
99
+ }
100
+ this.updateState({ selectedSuggestionIndex: nextIndex });
101
+ return;
102
+ }
103
+ if (event.key === "ArrowUp") {
104
+ event.preventDefault();
105
+ let nextIndex = this.state.selectedSuggestionIndex - 1;
106
+ if (nextIndex < 0) {
107
+ nextIndex = totalItems - 1;
108
+ }
109
+ this.updateState({ selectedSuggestionIndex: nextIndex });
110
+ return;
111
+ }
112
+ if (event.key === "Enter" && this.state.selectedSuggestionIndex >= 0) {
113
+ event.preventDefault();
114
+ const allItems = [...this.state.cities, ...this.state.streets, ...this.state.suggestions];
115
+ const item = allItems[this.state.selectedSuggestionIndex];
116
+ if (item) {
117
+ this.selectItem(item);
118
+ this.updateState({ selectedSuggestionIndex: -1 });
119
+ }
120
+ return;
121
+ }
122
+ }
123
+ const val = target.value;
124
+ if (event.key === " " && this.shouldAutoInsertComma(val)) {
125
+ event.preventDefault();
126
+ const next = `${val.trim()}, `;
127
+ this.updateQueryAndFetch(next);
128
+ }
129
+ }
130
+ selectItem(item) {
131
+ const label = typeof item === "string" ? item : item.label;
132
+ const value = typeof item !== "string" ? item.value : void 0;
133
+ const subtitle = typeof item !== "string" ? item.subtitle : null;
134
+ if (this.state.stage === "final") {
135
+ this.finishSelection(label, value);
136
+ return;
137
+ }
138
+ this.processSelection(label, subtitle);
139
+ }
140
+ shouldAutoInsertComma(currentVal) {
141
+ const isStartOfSegmentAndNumeric = !currentVal.includes(",") && PATTERNS.DIGITS_1_3.test(currentVal.trim());
142
+ if (isStartOfSegmentAndNumeric) return true;
143
+ if (this.state.stage === "house_number") {
144
+ const currentFragment = this.getCurrentFragment(currentVal);
145
+ return PATTERNS.DIGITS_1_3.test(currentFragment);
146
+ }
147
+ return false;
148
+ }
149
+ finishSelection(label, value) {
150
+ this.updateState({ query: label, suggestions: [], cities: [], streets: [], isValid: true });
151
+ this.onSelect(value || label);
152
+ }
153
+ processSelection(label, subtitle) {
154
+ const { stage, query } = this.state;
155
+ let nextQuery = query;
156
+ const isContextualSelection = subtitle && (stage === "city" || stage === "street" || stage === "mixed");
157
+ if (isContextualSelection) {
158
+ if (stage === "city") {
159
+ nextQuery = `${subtitle}, ${label}, `;
160
+ } else {
161
+ const prefix = this.getQueryPrefix(query);
162
+ nextQuery = prefix ? `${prefix} ${label}, ${subtitle}, ` : `${label}, ${subtitle}, `;
163
+ }
164
+ this.updateQueryAndFetch(nextQuery);
165
+ return;
166
+ }
167
+ if (stage === "direct" || stage === "addition") {
168
+ this.finishSelection(label);
169
+ return;
170
+ }
171
+ const hasComma = query.includes(",");
172
+ const isFirstSegment = !hasComma && (stage === "city" || stage === "street" || stage === "house_number_first");
173
+ if (isFirstSegment) {
174
+ nextQuery = `${label}, `;
175
+ } else {
176
+ nextQuery = this.replaceLastSegment(query, label);
177
+ if (stage !== "house_number") {
178
+ nextQuery += ", ";
179
+ }
180
+ }
181
+ this.updateQueryAndFetch(nextQuery);
182
+ }
183
+ executeFetch(val) {
184
+ const text = (val || "").toString();
185
+ if (!text.trim()) {
186
+ this.abortController?.abort();
187
+ this.resetState();
188
+ return;
189
+ }
190
+ this.updateState({ isError: false });
191
+ if (this.abortController) this.abortController.abort();
192
+ this.abortController = new AbortController();
193
+ const url = new URL(`${this.apiUrl}/infer/${this.country.toLowerCase()}`);
194
+ const params = {
195
+ authKey: this.authKey,
196
+ query: text,
197
+ limit: this.limit.toString()
198
+ };
199
+ url.search = new URLSearchParams(params).toString();
200
+ this.fetcher(url.toString(), { signal: this.abortController.signal }).then((res) => {
201
+ if (!res.ok) throw new Error("Network error");
202
+ return res.json();
203
+ }).then((data) => this.mapResponseToState(data)).catch((e) => {
204
+ if (e.name !== "AbortError") {
205
+ this.updateState({ isError: true, isLoading: false });
206
+ }
207
+ });
208
+ }
209
+ mapResponseToState(data) {
210
+ const newState = {
211
+ stage: data.stage,
212
+ isLoading: false
213
+ };
214
+ if (data.stage === "mixed") {
215
+ newState.cities = data.cities || [];
216
+ newState.streets = data.streets || [];
217
+ newState.suggestions = [];
218
+ } else {
219
+ newState.suggestions = data.suggestions || [];
220
+ newState.cities = [];
221
+ newState.streets = [];
222
+ }
223
+ newState.isValid = data.stage === "final";
224
+ this.updateState(newState);
225
+ }
226
+ updateQueryAndFetch(nextQuery) {
227
+ this.updateState({ query: nextQuery, suggestions: [], cities: [], streets: [] });
228
+ this.handleInput(nextQuery);
229
+ }
230
+ replaceLastSegment(fullText, newSegment) {
231
+ const lastCommaIndex = fullText.lastIndexOf(",");
232
+ if (lastCommaIndex === -1) return newSegment;
233
+ return `${fullText.slice(0, lastCommaIndex + 1)} ${newSegment}`.trim();
234
+ }
235
+ getQueryPrefix(q) {
236
+ const lastComma = q.lastIndexOf(",");
237
+ return lastComma === -1 ? "" : q.slice(0, lastComma + 1).trimEnd();
238
+ }
239
+ getCurrentFragment(q) {
240
+ return (q.split(",").slice(-1)[0] ?? "").trim();
241
+ }
242
+ resetState() {
243
+ this.updateState({ ...INITIAL_STATE, query: this.state.query });
244
+ }
245
+ updateState(updates) {
246
+ this.state = { ...this.state, ...updates };
247
+ this.onStateChange(this.state);
248
+ }
249
+ debounce(func, wait) {
250
+ let timeout;
251
+ return (...args) => {
252
+ if (timeout) clearTimeout(timeout);
253
+ timeout = setTimeout(() => func.apply(this, args), wait);
254
+ };
255
+ }
256
+ };
257
+
258
+ // src/index.ts
28
259
  function useInfer(config) {
29
- const [state, setState] = (0, import_react.useState)(import_infer_core.INITIAL_STATE);
260
+ const [state, setState] = (0, import_react.useState)(INITIAL_STATE);
30
261
  const core = (0, import_react.useMemo)(() => {
31
- return new import_infer_core.InferCore({
262
+ return new InferCore({
32
263
  ...config,
33
264
  onStateChange: (newState) => setState({ ...newState })
34
265
  });
package/dist/index.js CHANGED
@@ -1,6 +1,239 @@
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
+
1
5
  // src/index.ts
2
6
  import { useState, useMemo } from "react";
3
- import { InferCore, INITIAL_STATE } from "@pro6pp/infer-core";
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
+ this.country = config.country;
41
+ this.authKey = config.authKey;
42
+ this.apiUrl = config.apiUrl || DEFAULTS.API_URL;
43
+ this.limit = config.limit || DEFAULTS.LIMIT;
44
+ this.fetcher = config.fetcher || ((url, init) => fetch(url, init));
45
+ this.onStateChange = config.onStateChange || (() => {
46
+ });
47
+ this.onSelect = config.onSelect || (() => {
48
+ });
49
+ this.state = { ...INITIAL_STATE };
50
+ this.debouncedFetch = this.debounce(
51
+ (val) => this.executeFetch(val),
52
+ DEFAULTS.DEBOUNCE_MS
53
+ );
54
+ }
55
+ handleInput(value) {
56
+ this.updateState({
57
+ query: value,
58
+ isValid: false,
59
+ isLoading: !!value.trim(),
60
+ selectedSuggestionIndex: -1
61
+ });
62
+ if (this.state.stage === "final") {
63
+ this.onSelect(null);
64
+ }
65
+ this.debouncedFetch(value);
66
+ }
67
+ handleKeyDown(event) {
68
+ const target = event.target;
69
+ if (!target) return;
70
+ const totalItems = this.state.cities.length + this.state.streets.length + this.state.suggestions.length;
71
+ if (totalItems > 0) {
72
+ if (event.key === "ArrowDown") {
73
+ event.preventDefault();
74
+ let nextIndex = this.state.selectedSuggestionIndex + 1;
75
+ if (nextIndex >= totalItems) {
76
+ nextIndex = 0;
77
+ }
78
+ this.updateState({ selectedSuggestionIndex: nextIndex });
79
+ return;
80
+ }
81
+ if (event.key === "ArrowUp") {
82
+ event.preventDefault();
83
+ let nextIndex = this.state.selectedSuggestionIndex - 1;
84
+ if (nextIndex < 0) {
85
+ nextIndex = totalItems - 1;
86
+ }
87
+ this.updateState({ selectedSuggestionIndex: nextIndex });
88
+ return;
89
+ }
90
+ if (event.key === "Enter" && this.state.selectedSuggestionIndex >= 0) {
91
+ event.preventDefault();
92
+ const allItems = [...this.state.cities, ...this.state.streets, ...this.state.suggestions];
93
+ const item = allItems[this.state.selectedSuggestionIndex];
94
+ if (item) {
95
+ this.selectItem(item);
96
+ this.updateState({ selectedSuggestionIndex: -1 });
97
+ }
98
+ return;
99
+ }
100
+ }
101
+ const val = target.value;
102
+ if (event.key === " " && this.shouldAutoInsertComma(val)) {
103
+ event.preventDefault();
104
+ const next = `${val.trim()}, `;
105
+ this.updateQueryAndFetch(next);
106
+ }
107
+ }
108
+ selectItem(item) {
109
+ const label = typeof item === "string" ? item : item.label;
110
+ const value = typeof item !== "string" ? item.value : void 0;
111
+ const subtitle = typeof item !== "string" ? item.subtitle : null;
112
+ if (this.state.stage === "final") {
113
+ this.finishSelection(label, value);
114
+ return;
115
+ }
116
+ this.processSelection(label, subtitle);
117
+ }
118
+ shouldAutoInsertComma(currentVal) {
119
+ const isStartOfSegmentAndNumeric = !currentVal.includes(",") && PATTERNS.DIGITS_1_3.test(currentVal.trim());
120
+ if (isStartOfSegmentAndNumeric) return true;
121
+ if (this.state.stage === "house_number") {
122
+ const currentFragment = this.getCurrentFragment(currentVal);
123
+ return PATTERNS.DIGITS_1_3.test(currentFragment);
124
+ }
125
+ return false;
126
+ }
127
+ finishSelection(label, value) {
128
+ this.updateState({ query: label, suggestions: [], cities: [], streets: [], isValid: true });
129
+ this.onSelect(value || label);
130
+ }
131
+ processSelection(label, subtitle) {
132
+ const { stage, query } = this.state;
133
+ let nextQuery = query;
134
+ const isContextualSelection = subtitle && (stage === "city" || stage === "street" || stage === "mixed");
135
+ if (isContextualSelection) {
136
+ if (stage === "city") {
137
+ nextQuery = `${subtitle}, ${label}, `;
138
+ } else {
139
+ const prefix = this.getQueryPrefix(query);
140
+ nextQuery = prefix ? `${prefix} ${label}, ${subtitle}, ` : `${label}, ${subtitle}, `;
141
+ }
142
+ this.updateQueryAndFetch(nextQuery);
143
+ return;
144
+ }
145
+ if (stage === "direct" || stage === "addition") {
146
+ this.finishSelection(label);
147
+ return;
148
+ }
149
+ const hasComma = query.includes(",");
150
+ const isFirstSegment = !hasComma && (stage === "city" || stage === "street" || stage === "house_number_first");
151
+ if (isFirstSegment) {
152
+ nextQuery = `${label}, `;
153
+ } else {
154
+ nextQuery = this.replaceLastSegment(query, label);
155
+ if (stage !== "house_number") {
156
+ nextQuery += ", ";
157
+ }
158
+ }
159
+ this.updateQueryAndFetch(nextQuery);
160
+ }
161
+ executeFetch(val) {
162
+ const text = (val || "").toString();
163
+ if (!text.trim()) {
164
+ this.abortController?.abort();
165
+ this.resetState();
166
+ return;
167
+ }
168
+ this.updateState({ isError: false });
169
+ if (this.abortController) this.abortController.abort();
170
+ this.abortController = new AbortController();
171
+ const url = new URL(`${this.apiUrl}/infer/${this.country.toLowerCase()}`);
172
+ const params = {
173
+ authKey: this.authKey,
174
+ query: text,
175
+ limit: this.limit.toString()
176
+ };
177
+ url.search = new URLSearchParams(params).toString();
178
+ this.fetcher(url.toString(), { signal: this.abortController.signal }).then((res) => {
179
+ if (!res.ok) throw new Error("Network error");
180
+ return res.json();
181
+ }).then((data) => this.mapResponseToState(data)).catch((e) => {
182
+ if (e.name !== "AbortError") {
183
+ this.updateState({ isError: true, isLoading: false });
184
+ }
185
+ });
186
+ }
187
+ mapResponseToState(data) {
188
+ const newState = {
189
+ stage: data.stage,
190
+ isLoading: false
191
+ };
192
+ if (data.stage === "mixed") {
193
+ newState.cities = data.cities || [];
194
+ newState.streets = data.streets || [];
195
+ newState.suggestions = [];
196
+ } else {
197
+ newState.suggestions = data.suggestions || [];
198
+ newState.cities = [];
199
+ newState.streets = [];
200
+ }
201
+ newState.isValid = data.stage === "final";
202
+ this.updateState(newState);
203
+ }
204
+ updateQueryAndFetch(nextQuery) {
205
+ this.updateState({ query: nextQuery, suggestions: [], cities: [], streets: [] });
206
+ this.handleInput(nextQuery);
207
+ }
208
+ replaceLastSegment(fullText, newSegment) {
209
+ const lastCommaIndex = fullText.lastIndexOf(",");
210
+ if (lastCommaIndex === -1) return newSegment;
211
+ return `${fullText.slice(0, lastCommaIndex + 1)} ${newSegment}`.trim();
212
+ }
213
+ getQueryPrefix(q) {
214
+ const lastComma = q.lastIndexOf(",");
215
+ return lastComma === -1 ? "" : q.slice(0, lastComma + 1).trimEnd();
216
+ }
217
+ getCurrentFragment(q) {
218
+ return (q.split(",").slice(-1)[0] ?? "").trim();
219
+ }
220
+ resetState() {
221
+ this.updateState({ ...INITIAL_STATE, query: this.state.query });
222
+ }
223
+ updateState(updates) {
224
+ this.state = { ...this.state, ...updates };
225
+ this.onStateChange(this.state);
226
+ }
227
+ debounce(func, wait) {
228
+ let timeout;
229
+ return (...args) => {
230
+ if (timeout) clearTimeout(timeout);
231
+ timeout = setTimeout(() => func.apply(this, args), wait);
232
+ };
233
+ }
234
+ };
235
+
236
+ // src/index.ts
4
237
  function useInfer(config) {
5
238
  const [state, setState] = useState(INITIAL_STATE);
6
239
  const core = useMemo(() => {
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.5",
23
+ "version": "0.0.2-beta.6",
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.3"
49
+ "@pro6pp/infer-core": "0.0.2-beta.4"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@testing-library/dom": "^10.4.1",