@quantaroute/checkout 1.3.0 → 1.3.2

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.
@@ -3,13 +3,19 @@ import {
3
3
  View,
4
4
  Text,
5
5
  TouchableOpacity,
6
+ TextInput,
7
+ FlatList,
8
+ ActivityIndicator,
9
+ Keyboard,
10
+ Platform,
6
11
  } from 'react-native';
7
12
  import { OSMView, LocationButton } from 'expo-osm-sdk';
8
13
  import type { OSMViewRef, MarkerConfig } from 'expo-osm-sdk';
9
14
  import * as Location from 'expo-location';
10
- import { getDigiPin, isWithinIndia } from '../core/digipin';
15
+ import { getDigiPin, getLatLngFromDigiPin, isWithinIndia } from '../core/digipin';
16
+ import { autocompleteAddress, looksLikeDigiPin } from '../core/api';
17
+ import type { AutocompleteSuggestion } from '../core/api';
11
18
  import type { MapPinSelectorProps } from '../core/types';
12
- import { resolveMapStyle } from '../core/mapStyles';
13
19
  import { styles, COLORS } from '../styles/checkout.native';
14
20
 
15
21
  // ─── Constants ────────────────────────────────────────────────────────────────
@@ -18,7 +24,12 @@ const INDIA_CENTER = { latitude: 20.5937, longitude: 78.9629 };
18
24
  const OVERVIEW_ZOOM = 5;
19
25
  const STREET_ZOOM = 16;
20
26
 
21
- // Style URL is resolved per-instance from the mapStyle prop (see resolveMapStyle).
27
+ /**
28
+ * Carto Positron vector basemap — same source as the web version.
29
+ * Free, no API key required. Attribution required (shown by OSMView natively).
30
+ */
31
+ const CARTO_STYLE_URL =
32
+ 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json';
22
33
 
23
34
  /**
24
35
  * Custom pin SVG as a data URI — matches the web pin colour (#0ea5e9).
@@ -58,7 +69,9 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
58
69
  defaultLng,
59
70
  mapHeight = 380,
60
71
  theme = 'light',
61
- mapStyle,
72
+ enableSearch = true,
73
+ apiKey,
74
+ apiBaseUrl,
62
75
  }) => {
63
76
  const mapRef = useRef<OSMViewRef>(null);
64
77
 
@@ -73,14 +86,19 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
73
86
  const [mapReady, setMapReady] = useState(false);
74
87
  const [locateError, setLocateError] = useState<string | null>(null);
75
88
 
89
+ // ── Search state ──────────────────────────────────────────────────────────
90
+ const [searchQuery, setSearchQuery] = useState('');
91
+ const [suggestions, setSuggestions] = useState<AutocompleteSuggestion[]>([]);
92
+ const [searchLoading, setSearchLoading] = useState(false);
93
+ const [searchError, setSearchError] = useState<string | null>(null);
94
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
95
+
76
96
  const isDark = theme === 'dark';
77
- const { url: styleUrl } = resolveMapStyle(mapStyle);
78
97
 
79
98
  // Resolve numeric height: web passes '380px', native should pass 380 or a number
80
99
  const mapHeightNum =
81
100
  typeof mapHeight === 'string' ? parseInt(mapHeight, 10) || 380 : mapHeight;
82
101
 
83
- // ── Coordinate update (pin drag or tap) ─────────────────────────────────────
84
102
  const handleCoordChange = useCallback(
85
103
  (latitude: number, longitude: number) => {
86
104
  setCoord({ latitude, longitude });
@@ -89,6 +107,71 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
89
107
  []
90
108
  );
91
109
 
110
+ // ── Fly map + move pin ────────────────────────────────────────────────────
111
+ const flyToCoord = useCallback((latitude: number, longitude: number) => {
112
+ handleCoordChange(latitude, longitude);
113
+ void mapRef.current?.animateToLocation(latitude, longitude, STREET_ZOOM);
114
+ }, [handleCoordChange]);
115
+
116
+ // ── Search input change ───────────────────────────────────────────────────
117
+ const handleSearchChange = useCallback((value: string) => {
118
+ setSearchQuery(value);
119
+ setSearchError(null);
120
+ if (debounceRef.current) clearTimeout(debounceRef.current);
121
+
122
+ const trimmed = value.trim();
123
+
124
+ if (!trimmed) {
125
+ setSuggestions([]);
126
+ setSearchLoading(false);
127
+ return;
128
+ }
129
+
130
+ // DigiPin — offline, instant
131
+ // Keep the text visible in the input; just close the keyboard and dropdown.
132
+ if (looksLikeDigiPin(trimmed)) {
133
+ try {
134
+ const coords = getLatLngFromDigiPin(trimmed.toUpperCase());
135
+ flyToCoord(parseFloat(coords.latitude), parseFloat(coords.longitude));
136
+ setSuggestions([]);
137
+ setSearchQuery(trimmed.toUpperCase());
138
+ Keyboard.dismiss();
139
+ } catch {
140
+ setSearchError('Invalid DigiPin code');
141
+ }
142
+ return;
143
+ }
144
+
145
+ if (trimmed.length < 3) {
146
+ setSuggestions([]);
147
+ return;
148
+ }
149
+
150
+ setSearchLoading(true);
151
+ debounceRef.current = setTimeout(async () => {
152
+ try {
153
+ // Forward current pin position so the API can bias/bound results nearby
154
+ const results = await autocompleteAddress(
155
+ trimmed, apiKey ?? '', apiBaseUrl, 5,
156
+ coord.latitude, coord.longitude,
157
+ );
158
+ setSuggestions(results);
159
+ } catch (err) {
160
+ setSearchError(err instanceof Error ? err.message : 'Search failed');
161
+ setSuggestions([]);
162
+ } finally {
163
+ setSearchLoading(false);
164
+ }
165
+ }, 400);
166
+ }, [apiKey, apiBaseUrl, flyToCoord]);
167
+
168
+ const handleSuggestionSelect = useCallback((s: AutocompleteSuggestion) => {
169
+ flyToCoord(s.coordinates.latitude, s.coordinates.longitude);
170
+ setSearchQuery('');
171
+ setSuggestions([]);
172
+ Keyboard.dismiss();
173
+ }, [flyToCoord]);
174
+
92
175
  // ── Marker config (draggable checkout pin) ──────────────────────────────────
93
176
  const pinMarkers: MarkerConfig[] = [
94
177
  {
@@ -144,6 +227,72 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
144
227
  </View>
145
228
  </View>
146
229
 
230
+ {/* ── Search bar ── */}
231
+ {enableSearch && (
232
+ <View style={[styles.searchBar, isDark && styles.searchBarDark]}>
233
+ <View style={[styles.searchInputWrap, isDark && styles.searchInputWrapDark]}>
234
+ <TextInput
235
+ style={[styles.searchInput, isDark && styles.searchInputDark]}
236
+ placeholder="Search address, 'pharmacy near me', or DigiPin…"
237
+ placeholderTextColor={isDark ? COLORS.textFaint : COLORS.textMuted}
238
+ value={searchQuery}
239
+ onChangeText={handleSearchChange}
240
+ autoCapitalize="characters"
241
+ autoCorrect={false}
242
+ returnKeyType="search"
243
+ clearButtonMode={Platform.OS === 'ios' ? 'while-editing' : 'never'}
244
+ />
245
+ {searchLoading && (
246
+ <ActivityIndicator
247
+ size="small"
248
+ color={COLORS.primary}
249
+ style={styles.searchSpinner}
250
+ />
251
+ )}
252
+ </View>
253
+
254
+ {searchError ? (
255
+ <Text style={styles.searchError}>{searchError}</Text>
256
+ ) : null}
257
+
258
+ {suggestions.length > 0 ? (
259
+ <FlatList
260
+ data={suggestions}
261
+ keyExtractor={(_, i) => String(i)}
262
+ style={[styles.searchDropdown, isDark && styles.searchDropdownDark]}
263
+ keyboardShouldPersistTaps="handled"
264
+ renderItem={({ item }) => (
265
+ <TouchableOpacity
266
+ style={[styles.searchSuggestion, isDark && styles.searchSuggestionDark]}
267
+ onPress={() => handleSuggestionSelect(item)}
268
+ activeOpacity={0.7}
269
+ >
270
+ <Text
271
+ style={[styles.searchSuggestionName, isDark && styles.textLight]}
272
+ numberOfLines={1}
273
+ >
274
+ {item.displayName}
275
+ </Text>
276
+ {item.address && item.address !== item.displayName ? (
277
+ <Text
278
+ style={[styles.searchSuggestionSub, isDark && styles.textMutedStyle]}
279
+ numberOfLines={1}
280
+ >
281
+ {item.address}
282
+ </Text>
283
+ ) : null}
284
+ </TouchableOpacity>
285
+ )}
286
+ />
287
+ ) : null}
288
+
289
+ <Text style={[styles.searchHint, isDark && styles.textMutedStyle]}>
290
+ <Text style={styles.searchHintChip}>DigiPin </Text>
291
+ Type your DigiPin for instant offline lookup
292
+ </Text>
293
+ </View>
294
+ )}
295
+
147
296
  {/* ── Map area ── */}
148
297
  <View style={{ height: mapHeightNum, position: 'relative' }}>
149
298
  <OSMView
@@ -151,7 +300,7 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
151
300
  style={{ flex: 1 }}
152
301
  initialCenter={{ latitude: initLat, longitude: initLng }}
153
302
  initialZoom={hasDefault ? STREET_ZOOM : OVERVIEW_ZOOM}
154
- styleUrl={styleUrl}
303
+ styleUrl={CARTO_STYLE_URL}
155
304
  markers={pinMarkers}
156
305
  showUserLocation={false}
157
306
  scrollEnabled
@@ -1,10 +1,11 @@
1
- import React, { useEffect, useRef, useState, useCallback } from 'react';
1
+ import React, { useEffect, useRef, useState, useCallback, useId } from 'react';
2
2
  import maplibregl from 'maplibre-gl';
3
3
  import 'maplibre-gl/dist/maplibre-gl.css';
4
- import { getDigiPin, isWithinIndia } from '../core/digipin';
4
+ import { getDigiPin, getLatLngFromDigiPin, isWithinIndia } from '../core/digipin';
5
+ import { autocompleteAddress, looksLikeDigiPin } from '../core/api';
6
+ import type { AutocompleteSuggestion } from '../core/api';
5
7
  import { useGeolocation } from '../hooks/useGeolocation';
6
8
  import type { MapPinSelectorProps } from '../core/types';
7
- import { resolveMapStyle } from '../core/mapStyles';
8
9
 
9
10
  // ─── Constants ───────────────────────────────────────────────────────────────
10
11
 
@@ -14,7 +15,13 @@ const MIN_ZOOM = 6; // users cannot zoom out beyond a useful India-level v
14
15
  const OVERVIEW_ZOOM = 9;
15
16
  const STREET_ZOOM = 18;
16
17
 
17
- // Style URL is resolved per-instance from the mapStyle prop (see resolveMapStyle).
18
+ /**
19
+ * Carto Positron – free vector basemap, no API key required.
20
+ * Attribution: © OpenStreetMap contributors © CARTO
21
+ * Terms: https://carto.com/legal/
22
+ */
23
+ const CARTO_STYLE_URL =
24
+ 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json';
18
25
 
19
26
  // ─── Pin dimensions ───────────────────────────────────────────────────────────
20
27
  // MUST match the SVG width/height exactly.
@@ -97,34 +104,132 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
97
104
  defaultLat,
98
105
  defaultLng,
99
106
  mapHeight = '380px',
100
- theme: _theme = 'light', // kept for future dark-mode pin tint; unused for now
101
- mapStyle,
107
+ theme: _theme = 'light',
102
108
  indiaBoundaryUrl,
109
+ enableSearch = true,
110
+ apiKey,
111
+ apiBaseUrl,
103
112
  }) => {
104
113
  const containerRef = useRef<HTMLDivElement>(null);
105
114
  const mapRef = useRef<maplibregl.Map | null>(null);
106
115
  const markerRef = useRef<maplibregl.Marker | null>(null);
107
116
 
108
- // Compute once here so both state init and the useEffect use the same values.
109
117
  const initLat = defaultLat ?? INDIA_CENTER.lat;
110
118
  const initLng = defaultLng ?? INDIA_CENTER.lng;
111
119
  const hasDefault = defaultLat !== undefined && defaultLng !== undefined;
112
120
 
113
121
  const [lat, setLat] = useState(initLat);
114
122
  const [lng, setLng] = useState(initLng);
115
- // Compute DigiPin eagerly (offline, ~0.1 ms) so the badge shows immediately.
116
123
  const [digipin, setDigipin] = useState<string | null>(() =>
117
124
  computeDigiPinSafe(initLat, initLng)
118
125
  );
119
126
  const [mapLoaded, setMapLoaded] = useState(false);
120
127
 
128
+ // ── Search state ─────────────────────────────────────────────────────────
129
+ const [searchQuery, setSearchQuery] = useState('');
130
+ const [suggestions, setSuggestions] = useState<AutocompleteSuggestion[]>([]);
131
+ const [searchLoading, setSearchLoading] = useState(false);
132
+ const [searchError, setSearchError] = useState<string | null>(null);
133
+ const [dropdownOpen, setDropdownOpen] = useState(false);
134
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
135
+ const searchInputRef = useRef<HTMLInputElement>(null);
136
+ const listboxId = useId();
137
+
121
138
  const { loading: geoLoading, error: geoError, locate, clearError } = useGeolocation();
122
139
 
123
- // Update DigiPin badge (offline, instant)
124
140
  const refreshDigipin = useCallback((la: number, lo: number) => {
125
141
  setDigipin(computeDigiPinSafe(la, lo));
126
142
  }, []);
127
143
 
144
+ // ── Fly map + move pin to a coord ────────────────────────────────────────
145
+ const flyToCoord = useCallback((la: number, lo: number) => {
146
+ setLat(la);
147
+ setLng(lo);
148
+ refreshDigipin(la, lo);
149
+ if (mapRef.current) {
150
+ mapRef.current.flyTo({ center: [lo, la], zoom: STREET_ZOOM, duration: 900, essential: true });
151
+ }
152
+ markerRef.current?.setLngLat([lo, la]);
153
+ }, [refreshDigipin]);
154
+
155
+ // ── Search input change handler ──────────────────────────────────────────
156
+ const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
157
+ const value = e.target.value;
158
+ setSearchQuery(value);
159
+ setSearchError(null);
160
+
161
+ if (debounceRef.current) clearTimeout(debounceRef.current);
162
+
163
+ const trimmed = value.trim();
164
+
165
+ // Empty — close dropdown
166
+ if (!trimmed) {
167
+ setSuggestions([]);
168
+ setDropdownOpen(false);
169
+ setSearchLoading(false);
170
+ return;
171
+ }
172
+
173
+ // DigiPin input — resolve 100% offline, instant, zero API cost
174
+ // Keep the text in the input so the user can see what resolved.
175
+ if (looksLikeDigiPin(trimmed)) {
176
+ try {
177
+ const coords = getLatLngFromDigiPin(trimmed.toUpperCase());
178
+ const la = parseFloat(coords.latitude);
179
+ const lo = parseFloat(coords.longitude);
180
+ flyToCoord(la, lo);
181
+ setSuggestions([]);
182
+ setDropdownOpen(false);
183
+ // normalise to canonical XX-XXX-XXXX format in case user typed without dashes
184
+ setSearchQuery(trimmed.toUpperCase());
185
+ } catch {
186
+ setSearchError('Invalid DigiPin code');
187
+ }
188
+ return;
189
+ }
190
+
191
+ // Address search — debounce 400 ms, need ≥ 3 chars
192
+ if (trimmed.length < 3) {
193
+ setSuggestions([]);
194
+ setDropdownOpen(false);
195
+ return;
196
+ }
197
+
198
+ setSearchLoading(true);
199
+ debounceRef.current = setTimeout(async () => {
200
+ try {
201
+ const key = apiKey ?? '';
202
+ // Forward current pin position so the API can bias/bound results nearby
203
+ const results = await autocompleteAddress(trimmed, key, apiBaseUrl, 5, lat, lng);
204
+ setSuggestions(results);
205
+ setDropdownOpen(results.length > 0);
206
+ } catch (err) {
207
+ setSearchError(err instanceof Error ? err.message : 'Search failed');
208
+ setSuggestions([]);
209
+ setDropdownOpen(false);
210
+ } finally {
211
+ setSearchLoading(false);
212
+ }
213
+ }, 400);
214
+ }, [apiKey, apiBaseUrl, flyToCoord]);
215
+
216
+ // ── Pick a suggestion from the dropdown ──────────────────────────────────
217
+ const handleSuggestionSelect = useCallback((s: AutocompleteSuggestion) => {
218
+ flyToCoord(s.coordinates.latitude, s.coordinates.longitude);
219
+ setSearchQuery('');
220
+ setSuggestions([]);
221
+ setDropdownOpen(false);
222
+ searchInputRef.current?.blur();
223
+ }, [flyToCoord]);
224
+
225
+ const handleSearchKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
226
+ if (e.key === 'Escape') {
227
+ setSuggestions([]);
228
+ setDropdownOpen(false);
229
+ setSearchQuery('');
230
+ }
231
+ }, []);
232
+
128
233
  // ── Map initialization (runs once) ────────────────────────────────────────
129
234
  useEffect(() => {
130
235
  if (!containerRef.current) return;
@@ -140,11 +245,10 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
140
245
  : Promise.resolve(null);
141
246
 
142
247
  const initZoom = hasDefault ? STREET_ZOOM : OVERVIEW_ZOOM;
143
- const { url: styleUrl, attributionHtml } = resolveMapStyle(mapStyle);
144
248
 
145
249
  const map = new maplibregl.Map({
146
250
  container: containerRef.current,
147
- style: styleUrl,
251
+ style: CARTO_STYLE_URL,
148
252
  center: [initLng, initLat],
149
253
  zoom: initZoom,
150
254
  minZoom: MIN_ZOOM, // lock: cannot zoom out past level 7
@@ -153,11 +257,12 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
153
257
  touchZoomRotate: true,
154
258
  });
155
259
 
156
- // Attribution (required by OSM + each basemap provider's terms)
260
+ // Attribution (required by Carto & OSM terms)
157
261
  map.addControl(
158
262
  new maplibregl.AttributionControl({
159
263
  compact: true,
160
- customAttribution: attributionHtml,
264
+ customAttribution:
265
+ '© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors &nbsp;© <a href="https://carto.com/attributions" target="_blank" rel="noopener">CARTO</a>',
161
266
  }),
162
267
  'bottom-right'
163
268
  );
@@ -291,6 +396,118 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
291
396
  </div>
292
397
  </div>
293
398
 
399
+ {/* ── Search bar ── */}
400
+ {enableSearch && (
401
+ <div className="qr-search-bar" role="search">
402
+ <div className="qr-search-bar__input-wrap">
403
+ {/* Search icon */}
404
+ <svg
405
+ className="qr-search-bar__icon"
406
+ aria-hidden="true"
407
+ viewBox="0 0 24 24"
408
+ fill="none"
409
+ stroke="currentColor"
410
+ strokeWidth="2"
411
+ strokeLinecap="round"
412
+ strokeLinejoin="round"
413
+ >
414
+ <circle cx="11" cy="11" r="8" />
415
+ <path d="M21 21l-4.35-4.35" />
416
+ </svg>
417
+
418
+ <input
419
+ ref={searchInputRef}
420
+ type="search"
421
+ className="qr-search-bar__input"
422
+ placeholder="Search address, 'pharmacy near me', or DigiPin…"
423
+ value={searchQuery}
424
+ onChange={handleSearchChange}
425
+ onKeyDown={handleSearchKeyDown}
426
+ autoComplete="off"
427
+ autoCorrect="off"
428
+ autoCapitalize="characters"
429
+ spellCheck={false}
430
+ aria-label="Search address or DigiPin"
431
+ aria-autocomplete="list"
432
+ aria-controls={dropdownOpen ? listboxId : undefined}
433
+ aria-expanded={dropdownOpen}
434
+ />
435
+
436
+ {/* Inline loading spinner */}
437
+ {searchLoading && (
438
+ <span className="qr-search-bar__spinner qr-spinner qr-spinner--sm" aria-hidden="true" />
439
+ )}
440
+
441
+ {/* Clear button */}
442
+ {searchQuery && !searchLoading && (
443
+ <button
444
+ type="button"
445
+ className="qr-search-bar__clear"
446
+ onClick={() => { setSearchQuery(''); setSuggestions([]); setDropdownOpen(false); setSearchError(null); }}
447
+ aria-label="Clear search"
448
+ tabIndex={-1}
449
+ >
450
+ ×
451
+ </button>
452
+ )}
453
+ </div>
454
+
455
+ {/* Inline error */}
456
+ {searchError && (
457
+ <p className="qr-search-bar__error" role="alert">{searchError}</p>
458
+ )}
459
+
460
+ {/* Suggestions dropdown */}
461
+ {dropdownOpen && suggestions.length > 0 && (
462
+ <ul
463
+ id={listboxId}
464
+ className="qr-search-bar__dropdown"
465
+ role="listbox"
466
+ aria-label="Address suggestions"
467
+ >
468
+ {suggestions.map((s, i) => (
469
+ <li
470
+ key={i}
471
+ className="qr-search-bar__suggestion"
472
+ role="option"
473
+ aria-selected="false"
474
+ onMouseDown={(e) => {
475
+ e.preventDefault(); // keep input focus until after click
476
+ handleSuggestionSelect(s);
477
+ }}
478
+ >
479
+ <svg
480
+ className="qr-search-bar__suggestion-icon"
481
+ aria-hidden="true"
482
+ viewBox="0 0 24 24"
483
+ fill="none"
484
+ stroke="currentColor"
485
+ strokeWidth="1.8"
486
+ strokeLinecap="round"
487
+ strokeLinejoin="round"
488
+ >
489
+ <path d="M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z" />
490
+ <circle cx="12" cy="9" r="2.5" />
491
+ </svg>
492
+ <div className="qr-search-bar__suggestion-text">
493
+ <span className="qr-search-bar__suggestion-name">{s.displayName}</span>
494
+ {s.address && s.address !== s.displayName && (
495
+ <span className="qr-search-bar__suggestion-sub">{s.address}</span>
496
+ )}
497
+ </div>
498
+ </li>
499
+ ))}
500
+ </ul>
501
+ )}
502
+
503
+ {/* DigiPin hint chip */}
504
+ <p className="qr-search-bar__hint">
505
+ <span className="qr-search-bar__hint-chip">DigiPin</span>
506
+ Type your DigiPin code for instant offline lookup — no API call
507
+ </p>
508
+ </div>
509
+ )}
510
+
294
511
  {/* ── Map area ── */}
295
512
  <div className="qr-map-outer" style={{ height: mapHeight }}>
296
513
  {/* MapLibre GL container */}
package/src/core/api.ts CHANGED
@@ -2,6 +2,10 @@ import type { LocationLookupResponse } from './types';
2
2
 
3
3
  const DEFAULT_BASE_URL = 'https://api.quantaroute.com';
4
4
 
5
+ // ─── DigiPin regex (matches "XXX-XXX-XXXX" with valid characters) ─────────────
6
+ // Valid chars: F C 9 8 J 3 2 7 K 4 5 6 L M P T (from the 4×4 DIGIPIN_GRID)
7
+ const DIGIPIN_PATTERN = /^[FC98J327K456LMPT]{3}-[FC98J327K456LMPT]{3}-[FC98J327K456LMPT]{4}$/i;
8
+
5
9
  /**
6
10
  * Cross-platform timeout signal.
7
11
  * AbortSignal.timeout() is not available in React Native / Hermes — fall back
@@ -112,6 +116,94 @@ export async function lookupLocation(
112
116
  return data;
113
117
  }
114
118
 
119
+ // ─── Autocomplete ─────────────────────────────────────────────────────────────
120
+
121
+ /** One address suggestion from /v1/digipin/autocomplete */
122
+ export interface AutocompleteSuggestion {
123
+ displayName: string;
124
+ address: string;
125
+ coordinates: { latitude: number; longitude: number };
126
+ confidence: number;
127
+ addressComponents: {
128
+ house_number?: string;
129
+ road?: string;
130
+ neighbourhood?: string;
131
+ suburb?: string;
132
+ city?: string;
133
+ state?: string;
134
+ postcode?: string;
135
+ country?: string;
136
+ [key: string]: string | undefined;
137
+ };
138
+ }
139
+
140
+ export interface AutocompleteResponse {
141
+ success: boolean;
142
+ data: AutocompleteSuggestion[];
143
+ error?: string;
144
+ message?: string;
145
+ }
146
+
147
+ /**
148
+ * Returns true if the trimmed input looks like a complete DigiPin code.
149
+ * Used to skip the API call and resolve offline instead.
150
+ */
151
+ export function looksLikeDigiPin(input: string): boolean {
152
+ return DIGIPIN_PATTERN.test(input.trim().toUpperCase());
153
+ }
154
+
155
+ /**
156
+ * Call QuantaRoute's autocomplete API.
157
+ * Minimum 3 characters required; max 10 suggestions.
158
+ *
159
+ * Pass userLat / userLng (the map pin's current position) to unlock:
160
+ * – Location-biased results (~50 km soft radius around the pin)
161
+ * – "Near me" / "nearby" keyword support with a tight ~10 km hard radius
162
+ */
163
+ export async function autocompleteAddress(
164
+ query: string,
165
+ apiKey: string,
166
+ baseUrl: string = DEFAULT_BASE_URL,
167
+ limit = 5,
168
+ userLat?: number,
169
+ userLng?: number,
170
+ ): Promise<AutocompleteSuggestion[]> {
171
+ let url =
172
+ `${baseUrl.replace(/\/$/, '')}/v1/digipin/autocomplete` +
173
+ `?q=${encodeURIComponent(query.trim())}&limit=${Math.min(limit, 10)}`;
174
+
175
+ if (typeof userLat === 'number' && typeof userLng === 'number') {
176
+ url += `&lat=${userLat.toFixed(6)}&lng=${userLng.toFixed(6)}`;
177
+ }
178
+
179
+ let res: Response;
180
+ try {
181
+ res = await fetch(url, {
182
+ method: 'GET',
183
+ headers: { 'x-api-key': apiKey },
184
+ signal: makeTimeoutSignal(8_000),
185
+ });
186
+ } catch (err) {
187
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
188
+ throw new Error('Autocomplete request timed out.');
189
+ }
190
+ throw new Error(`Network error: ${err instanceof Error ? err.message : String(err)}`);
191
+ }
192
+
193
+ if (!res.ok) {
194
+ if (res.status === 401 || res.status === 403) {
195
+ throw new Error('Invalid API key.');
196
+ }
197
+ if (res.status === 429) {
198
+ throw new Error('Rate limit exceeded.');
199
+ }
200
+ return []; // silently return empty on other errors
201
+ }
202
+
203
+ const data = (await res.json()) as AutocompleteResponse;
204
+ return data.success ? (data.data ?? []) : [];
205
+ }
206
+
115
207
  /**
116
208
  * Call QuantaRoute's Reverse Geocoding API.
117
209
  * Converts DigiPin → address components from Nominatim/OpenStreetMap.