@quantaroute/checkout 1.3.0 → 1.3.1

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,70 @@ 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
+ if (looksLikeDigiPin(trimmed)) {
132
+ try {
133
+ const coords = getLatLngFromDigiPin(trimmed.toUpperCase());
134
+ flyToCoord(parseFloat(coords.latitude), parseFloat(coords.longitude));
135
+ setSuggestions([]);
136
+ setSearchQuery('');
137
+ Keyboard.dismiss();
138
+ } catch {
139
+ setSearchError('Invalid DigiPin code');
140
+ }
141
+ return;
142
+ }
143
+
144
+ if (trimmed.length < 3) {
145
+ setSuggestions([]);
146
+ return;
147
+ }
148
+
149
+ setSearchLoading(true);
150
+ debounceRef.current = setTimeout(async () => {
151
+ try {
152
+ // Forward current pin position so the API can bias/bound results nearby
153
+ const results = await autocompleteAddress(
154
+ trimmed, apiKey ?? '', apiBaseUrl, 5,
155
+ coord.latitude, coord.longitude,
156
+ );
157
+ setSuggestions(results);
158
+ } catch (err) {
159
+ setSearchError(err instanceof Error ? err.message : 'Search failed');
160
+ setSuggestions([]);
161
+ } finally {
162
+ setSearchLoading(false);
163
+ }
164
+ }, 400);
165
+ }, [apiKey, apiBaseUrl, flyToCoord]);
166
+
167
+ const handleSuggestionSelect = useCallback((s: AutocompleteSuggestion) => {
168
+ flyToCoord(s.coordinates.latitude, s.coordinates.longitude);
169
+ setSearchQuery('');
170
+ setSuggestions([]);
171
+ Keyboard.dismiss();
172
+ }, [flyToCoord]);
173
+
92
174
  // ── Marker config (draggable checkout pin) ──────────────────────────────────
93
175
  const pinMarkers: MarkerConfig[] = [
94
176
  {
@@ -144,6 +226,72 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
144
226
  </View>
145
227
  </View>
146
228
 
229
+ {/* ── Search bar ── */}
230
+ {enableSearch && (
231
+ <View style={[styles.searchBar, isDark && styles.searchBarDark]}>
232
+ <View style={[styles.searchInputWrap, isDark && styles.searchInputWrapDark]}>
233
+ <TextInput
234
+ style={[styles.searchInput, isDark && styles.searchInputDark]}
235
+ placeholder="Search address, 'pharmacy near me', or DigiPin…"
236
+ placeholderTextColor={isDark ? COLORS.textFaint : COLORS.textMuted}
237
+ value={searchQuery}
238
+ onChangeText={handleSearchChange}
239
+ autoCapitalize="characters"
240
+ autoCorrect={false}
241
+ returnKeyType="search"
242
+ clearButtonMode={Platform.OS === 'ios' ? 'while-editing' : 'never'}
243
+ />
244
+ {searchLoading && (
245
+ <ActivityIndicator
246
+ size="small"
247
+ color={COLORS.primary}
248
+ style={styles.searchSpinner}
249
+ />
250
+ )}
251
+ </View>
252
+
253
+ {searchError ? (
254
+ <Text style={styles.searchError}>{searchError}</Text>
255
+ ) : null}
256
+
257
+ {suggestions.length > 0 ? (
258
+ <FlatList
259
+ data={suggestions}
260
+ keyExtractor={(_, i) => String(i)}
261
+ style={[styles.searchDropdown, isDark && styles.searchDropdownDark]}
262
+ keyboardShouldPersistTaps="handled"
263
+ renderItem={({ item }) => (
264
+ <TouchableOpacity
265
+ style={[styles.searchSuggestion, isDark && styles.searchSuggestionDark]}
266
+ onPress={() => handleSuggestionSelect(item)}
267
+ activeOpacity={0.7}
268
+ >
269
+ <Text
270
+ style={[styles.searchSuggestionName, isDark && styles.textLight]}
271
+ numberOfLines={1}
272
+ >
273
+ {item.displayName}
274
+ </Text>
275
+ {item.address && item.address !== item.displayName ? (
276
+ <Text
277
+ style={[styles.searchSuggestionSub, isDark && styles.textMutedStyle]}
278
+ numberOfLines={1}
279
+ >
280
+ {item.address}
281
+ </Text>
282
+ ) : null}
283
+ </TouchableOpacity>
284
+ )}
285
+ />
286
+ ) : null}
287
+
288
+ <Text style={[styles.searchHint, isDark && styles.textMutedStyle]}>
289
+ <Text style={styles.searchHintChip}>DigiPin </Text>
290
+ Type your DigiPin for instant offline lookup
291
+ </Text>
292
+ </View>
293
+ )}
294
+
147
295
  {/* ── Map area ── */}
148
296
  <View style={{ height: mapHeightNum, position: 'relative' }}>
149
297
  <OSMView
@@ -151,7 +299,7 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
151
299
  style={{ flex: 1 }}
152
300
  initialCenter={{ latitude: initLat, longitude: initLng }}
153
301
  initialZoom={hasDefault ? STREET_ZOOM : OVERVIEW_ZOOM}
154
- styleUrl={styleUrl}
302
+ styleUrl={CARTO_STYLE_URL}
155
303
  markers={pinMarkers}
156
304
  showUserLocation={false}
157
305
  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,130 @@ 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
+ if (looksLikeDigiPin(trimmed)) {
175
+ try {
176
+ const coords = getLatLngFromDigiPin(trimmed.toUpperCase());
177
+ const la = parseFloat(coords.latitude);
178
+ const lo = parseFloat(coords.longitude);
179
+ flyToCoord(la, lo);
180
+ setSuggestions([]);
181
+ setDropdownOpen(false);
182
+ setSearchQuery('');
183
+ } catch {
184
+ setSearchError('Invalid DigiPin code');
185
+ }
186
+ return;
187
+ }
188
+
189
+ // Address search — debounce 400 ms, need ≥ 3 chars
190
+ if (trimmed.length < 3) {
191
+ setSuggestions([]);
192
+ setDropdownOpen(false);
193
+ return;
194
+ }
195
+
196
+ setSearchLoading(true);
197
+ debounceRef.current = setTimeout(async () => {
198
+ try {
199
+ const key = apiKey ?? '';
200
+ // Forward current pin position so the API can bias/bound results nearby
201
+ const results = await autocompleteAddress(trimmed, key, apiBaseUrl, 5, lat, lng);
202
+ setSuggestions(results);
203
+ setDropdownOpen(results.length > 0);
204
+ } catch (err) {
205
+ setSearchError(err instanceof Error ? err.message : 'Search failed');
206
+ setSuggestions([]);
207
+ setDropdownOpen(false);
208
+ } finally {
209
+ setSearchLoading(false);
210
+ }
211
+ }, 400);
212
+ }, [apiKey, apiBaseUrl, flyToCoord]);
213
+
214
+ // ── Pick a suggestion from the dropdown ──────────────────────────────────
215
+ const handleSuggestionSelect = useCallback((s: AutocompleteSuggestion) => {
216
+ flyToCoord(s.coordinates.latitude, s.coordinates.longitude);
217
+ setSearchQuery('');
218
+ setSuggestions([]);
219
+ setDropdownOpen(false);
220
+ searchInputRef.current?.blur();
221
+ }, [flyToCoord]);
222
+
223
+ const handleSearchKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
224
+ if (e.key === 'Escape') {
225
+ setSuggestions([]);
226
+ setDropdownOpen(false);
227
+ setSearchQuery('');
228
+ }
229
+ }, []);
230
+
128
231
  // ── Map initialization (runs once) ────────────────────────────────────────
129
232
  useEffect(() => {
130
233
  if (!containerRef.current) return;
@@ -140,11 +243,10 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
140
243
  : Promise.resolve(null);
141
244
 
142
245
  const initZoom = hasDefault ? STREET_ZOOM : OVERVIEW_ZOOM;
143
- const { url: styleUrl, attributionHtml } = resolveMapStyle(mapStyle);
144
246
 
145
247
  const map = new maplibregl.Map({
146
248
  container: containerRef.current,
147
- style: styleUrl,
249
+ style: CARTO_STYLE_URL,
148
250
  center: [initLng, initLat],
149
251
  zoom: initZoom,
150
252
  minZoom: MIN_ZOOM, // lock: cannot zoom out past level 7
@@ -153,11 +255,12 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
153
255
  touchZoomRotate: true,
154
256
  });
155
257
 
156
- // Attribution (required by OSM + each basemap provider's terms)
258
+ // Attribution (required by Carto & OSM terms)
157
259
  map.addControl(
158
260
  new maplibregl.AttributionControl({
159
261
  compact: true,
160
- customAttribution: attributionHtml,
262
+ customAttribution:
263
+ '© <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
264
  }),
162
265
  'bottom-right'
163
266
  );
@@ -291,6 +394,118 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
291
394
  </div>
292
395
  </div>
293
396
 
397
+ {/* ── Search bar ── */}
398
+ {enableSearch && (
399
+ <div className="qr-search-bar" role="search">
400
+ <div className="qr-search-bar__input-wrap">
401
+ {/* Search icon */}
402
+ <svg
403
+ className="qr-search-bar__icon"
404
+ aria-hidden="true"
405
+ viewBox="0 0 24 24"
406
+ fill="none"
407
+ stroke="currentColor"
408
+ strokeWidth="2"
409
+ strokeLinecap="round"
410
+ strokeLinejoin="round"
411
+ >
412
+ <circle cx="11" cy="11" r="8" />
413
+ <path d="M21 21l-4.35-4.35" />
414
+ </svg>
415
+
416
+ <input
417
+ ref={searchInputRef}
418
+ type="search"
419
+ className="qr-search-bar__input"
420
+ placeholder="Search address, 'pharmacy near me', or DigiPin…"
421
+ value={searchQuery}
422
+ onChange={handleSearchChange}
423
+ onKeyDown={handleSearchKeyDown}
424
+ autoComplete="off"
425
+ autoCorrect="off"
426
+ autoCapitalize="characters"
427
+ spellCheck={false}
428
+ aria-label="Search address or DigiPin"
429
+ aria-autocomplete="list"
430
+ aria-controls={dropdownOpen ? listboxId : undefined}
431
+ aria-expanded={dropdownOpen}
432
+ />
433
+
434
+ {/* Inline loading spinner */}
435
+ {searchLoading && (
436
+ <span className="qr-search-bar__spinner qr-spinner qr-spinner--sm" aria-hidden="true" />
437
+ )}
438
+
439
+ {/* Clear button */}
440
+ {searchQuery && !searchLoading && (
441
+ <button
442
+ type="button"
443
+ className="qr-search-bar__clear"
444
+ onClick={() => { setSearchQuery(''); setSuggestions([]); setDropdownOpen(false); setSearchError(null); }}
445
+ aria-label="Clear search"
446
+ tabIndex={-1}
447
+ >
448
+ ×
449
+ </button>
450
+ )}
451
+ </div>
452
+
453
+ {/* Inline error */}
454
+ {searchError && (
455
+ <p className="qr-search-bar__error" role="alert">{searchError}</p>
456
+ )}
457
+
458
+ {/* Suggestions dropdown */}
459
+ {dropdownOpen && suggestions.length > 0 && (
460
+ <ul
461
+ id={listboxId}
462
+ className="qr-search-bar__dropdown"
463
+ role="listbox"
464
+ aria-label="Address suggestions"
465
+ >
466
+ {suggestions.map((s, i) => (
467
+ <li
468
+ key={i}
469
+ className="qr-search-bar__suggestion"
470
+ role="option"
471
+ aria-selected="false"
472
+ onMouseDown={(e) => {
473
+ e.preventDefault(); // keep input focus until after click
474
+ handleSuggestionSelect(s);
475
+ }}
476
+ >
477
+ <svg
478
+ className="qr-search-bar__suggestion-icon"
479
+ aria-hidden="true"
480
+ viewBox="0 0 24 24"
481
+ fill="none"
482
+ stroke="currentColor"
483
+ strokeWidth="1.8"
484
+ strokeLinecap="round"
485
+ strokeLinejoin="round"
486
+ >
487
+ <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" />
488
+ <circle cx="12" cy="9" r="2.5" />
489
+ </svg>
490
+ <div className="qr-search-bar__suggestion-text">
491
+ <span className="qr-search-bar__suggestion-name">{s.displayName}</span>
492
+ {s.address && s.address !== s.displayName && (
493
+ <span className="qr-search-bar__suggestion-sub">{s.address}</span>
494
+ )}
495
+ </div>
496
+ </li>
497
+ ))}
498
+ </ul>
499
+ )}
500
+
501
+ {/* DigiPin hint chip */}
502
+ <p className="qr-search-bar__hint">
503
+ <span className="qr-search-bar__hint-chip">DigiPin</span>
504
+ Type your DigiPin code for instant offline lookup — no API call
505
+ </p>
506
+ </div>
507
+ )}
508
+
294
509
  {/* ── Map area ── */}
295
510
  <div className="qr-map-outer" style={{ height: mapHeight }}>
296
511
  {/* 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.