@wherabouts/react 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,15 @@
1
- MIT License
1
+ Copyright (c) 2026 Wherabouts. All rights reserved.
2
2
 
3
- Copyright (c) 2026 Joseph Amani
3
+ This software and associated documentation files (the "SDK") are the proprietary
4
+ property of Wherabouts. The SDK is licensed, not sold, and is made available solely
5
+ for use in connection with the Wherabouts location API by parties holding valid
6
+ Wherabouts API credentials, subject to the Wherabouts Terms of Service.
4
7
 
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
8
+ Permission is NOT granted to use, copy, modify, merge, publish, distribute,
9
+ sublicense, or sell copies of the SDK except as expressly permitted in writing by
10
+ Wherabouts or as necessary to integrate with the Wherabouts API under a valid account.
11
11
 
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
12
+ THE SDK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
14
+ PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL WHERABOUTS BE LIABLE FOR
15
+ ANY CLAIM, DAMAGES, OR OTHER LIABILITY ARISING FROM THE USE OF THE SDK.
package/README.md ADDED
@@ -0,0 +1,385 @@
1
+ # @wherabouts/react
2
+
3
+ React hooks for the [Wherabouts](https://wherabouts.com) location API — address autocomplete, reverse geocoding, and geofence detection with built-in debouncing, cancellation, and loading/error state.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@wherabouts/react)](https://www.npmjs.com/package/@wherabouts/react)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ---
9
+
10
+ ## Requirements
11
+
12
+ | Peer dependency | Version |
13
+ |--------------------|----------|
14
+ | `react` | `>= 18` |
15
+ | `@wherabouts/sdk` | `>= 0.4.1` |
16
+
17
+ ---
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ # npm
23
+ npm install @wherabouts/react @wherabouts/sdk
24
+
25
+ # pnpm
26
+ pnpm add @wherabouts/react @wherabouts/sdk
27
+
28
+ # yarn
29
+ yarn add @wherabouts/react @wherabouts/sdk
30
+ ```
31
+
32
+ ---
33
+
34
+ ## Quick start
35
+
36
+ All hooks accept a `WheraboutsClient` instance as their first argument. Create one with your publishable API key from the [Wherabouts dashboard](https://wherabouts.com/dashboard).
37
+
38
+ ```ts
39
+ import { createWheraboutsClient } from "@wherabouts/sdk";
40
+
41
+ const client = createWheraboutsClient({
42
+ apiKey: "pk_live_...", // publishable key — safe in browser
43
+ });
44
+ ```
45
+
46
+ > Use a **publishable key** (`pk_live_…`) in browser code. Secret keys must stay server-side only.
47
+
48
+ > **Keep a stable client reference.** Create the client once — at module scope or
49
+ > with `useMemo` — and reuse it. The hooks list `client` in their effect
50
+ > dependencies, so passing a freshly-created client on every render restarts the
51
+ > request (and debounce) each render.
52
+ >
53
+ > ```tsx
54
+ > const client = useMemo(() => createWheraboutsClient({ apiKey }), [apiKey]);
55
+ > ```
56
+
57
+ ---
58
+
59
+ ## Hooks
60
+
61
+ ### `useAutocomplete`
62
+
63
+ Type-ahead address search with automatic debouncing and in-flight request cancellation.
64
+
65
+ ```tsx
66
+ import { useAutocomplete } from "@wherabouts/react";
67
+
68
+ function AddressSearch({ client }) {
69
+ const { query, setQuery, results, loading, error } = useAutocomplete(client, {
70
+ debounceMs: 300, // default — waits 300ms after last keystroke
71
+ limit: 5, // max results to return
72
+ country: "AU", // optional ISO 3166-1 alpha-2 country filter
73
+ state: "QLD", // optional state/region filter
74
+ });
75
+
76
+ return (
77
+ <div>
78
+ <input
79
+ value={query}
80
+ onChange={(e) => setQuery(e.target.value)}
81
+ placeholder="Start typing an address..."
82
+ />
83
+ {loading && <p>Searching…</p>}
84
+ {error && <p>Error: {error.message}</p>}
85
+ <ul>
86
+ {results.map((r) => (
87
+ <li key={r.id}>{r.formattedAddress}</li>
88
+ ))}
89
+ </ul>
90
+ </div>
91
+ );
92
+ }
93
+ ```
94
+
95
+ #### Signature
96
+
97
+ ```ts
98
+ function useAutocomplete(
99
+ client: WheraboutsClient,
100
+ options?: UseAutocompleteOptions
101
+ ): UseAutocompleteResult
102
+ ```
103
+
104
+ #### `UseAutocompleteOptions`
105
+
106
+ | Option | Type | Default | Description |
107
+ |--------------------|---------------------------------|---------|------------------------------------------------------|
108
+ | `debounceMs` | `number` | `300` | Milliseconds to wait after last keystroke |
109
+ | `minLength` | `number` | `2` | Minimum trimmed query length before a request fires (the API requires `q` ≥ 2) |
110
+ | `limit` | `number` | — | Maximum number of suggestions to return |
111
+ | `country` | `string` | — | ISO 3166-1 alpha-2 country code filter (e.g. `"AU"`) |
112
+ | `state` | `string` | — | State or region name filter |
113
+ | `lat` / `lng` | `number` | — | Bias results toward a coordinate (proximity) |
114
+ | `sessionToken` | `string` | — | Groups a run of keystrokes into one billable search (see `newSessionToken()`) |
115
+ | `keepPreviousData` | `boolean` | `false` | Keep previous results visible while the next search loads (avoids dropdown flicker) |
116
+ | `cache` | `{ storage; ttlMs?: number }` | — | Opt-in client cache, e.g. `{ storage: sessionStorage, ttlMs: 60_000 }` |
117
+
118
+ #### `UseAutocompleteResult`
119
+
120
+ | Field | Type | Description |
121
+ |---------------|------------------------|---------------------------------------------------|
122
+ | `query` | `string` | Current search string |
123
+ | `setQuery` | `(q: string) => void` | Stable setter — safe to pass directly to `onChange` |
124
+ | `results` | `AddressSuggestion[]` | Matching address suggestions |
125
+ | `status` | `"idle" \| "loading" \| "success" \| "empty" \| "error"` | Coarse state machine for rendering |
126
+ | `loading` | `boolean` | `true` while a request is in flight |
127
+ | `rateLimited` | `boolean` | `true` when the last request was rejected with HTTP 429 |
128
+ | `error` | `Error \| null` | Last error, or `null` |
129
+ | `reset` | `() => void` | Clear the query, results, and any in-flight request |
130
+
131
+ **Behaviour notes:**
132
+ - Queries shorter than `minLength` (default 2) never fire a request.
133
+ - Empty or whitespace-only query immediately clears results without firing a request.
134
+ - Each new keystroke cancels the previous pending request via `AbortController`.
135
+ - `setQuery` is memoised with `useCallback` — it will not cause unnecessary re-renders.
136
+
137
+ ---
138
+
139
+ ### `useCombobox`
140
+
141
+ Headless [WAI-ARIA combobox](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/)
142
+ helpers for an accessible autocomplete dropdown — keyboard navigation
143
+ (↑/↓/Home/End/Enter/Esc, with wrapping) and ARIA wiring. Bring your own markup;
144
+ pair it with `useAutocomplete`.
145
+
146
+ ```tsx
147
+ import { useAutocomplete, useCombobox } from "@wherabouts/react";
148
+
149
+ function AddressCombobox({ client }) {
150
+ const { query, setQuery, results } = useAutocomplete(client);
151
+ const { getInputProps, getListboxProps, getItemProps, activeIndex } =
152
+ useCombobox({
153
+ id: "address",
154
+ count: results.length,
155
+ onSelect: (i) => setQuery(results[i]?.formattedAddress ?? ""),
156
+ });
157
+
158
+ return (
159
+ <>
160
+ <input
161
+ {...getInputProps()}
162
+ value={query}
163
+ onChange={(e) => setQuery(e.target.value)}
164
+ />
165
+ <ul {...getListboxProps()}>
166
+ {results.map((r, i) => (
167
+ <li key={r.id} {...getItemProps(i)} data-active={i === activeIndex}>
168
+ {r.formattedAddress}
169
+ </li>
170
+ ))}
171
+ </ul>
172
+ </>
173
+ );
174
+ }
175
+ ```
176
+
177
+ `getInputProps()` / `getListboxProps()` / `getItemProps(index)` return the
178
+ `role`, `aria-*`, and event handlers for each element. The pure building blocks
179
+ (`comboboxReducer`, `keyToAction`, `buildInputProps`/`buildListboxProps`/`buildItemProps`)
180
+ are also exported for advanced use.
181
+
182
+ ---
183
+
184
+ ### `useReverseGeocode`
185
+
186
+ Resolves a latitude/longitude coordinate to the nearest address. Pass `null` to reset.
187
+
188
+ ```tsx
189
+ import { useReverseGeocode } from "@wherabouts/react";
190
+
191
+ function NearestAddress({ client, userLocation }) {
192
+ // userLocation: { lat: number; lng: number } | null
193
+ const { address, distance, loading, error } = useReverseGeocode(client, userLocation);
194
+
195
+ if (loading) return <p>Locating…</p>;
196
+ if (error) return <p>Error: {error.message}</p>;
197
+ if (!address) return <p>No location set</p>;
198
+
199
+ return (
200
+ <div>
201
+ <p>{address.formattedAddress}</p>
202
+ <p>{distance != null ? `${distance.toFixed(0)}m away` : ""}</p>
203
+ </div>
204
+ );
205
+ }
206
+ ```
207
+
208
+ #### Signature
209
+
210
+ ```ts
211
+ function useReverseGeocode(
212
+ client: WheraboutsClient,
213
+ coords: LatLng | null
214
+ ): UseReverseGeocodeResult
215
+ ```
216
+
217
+ #### `LatLng`
218
+
219
+ ```ts
220
+ interface LatLng {
221
+ lat: number;
222
+ lng: number;
223
+ }
224
+ ```
225
+
226
+ #### `UseReverseGeocodeResult`
227
+
228
+ | Field | Type | Description |
229
+ |------------|-------------------------------|----------------------------------------------|
230
+ | `address` | `ReverseGeocodeAddress \| null` | Nearest address, or `null` if not yet resolved |
231
+ | `distance` | `number \| null` | Distance in metres from `coords` to `address` |
232
+ | `loading` | `boolean` | `true` while a request is in flight |
233
+ | `error` | `Error \| null` | Last error, or `null` |
234
+
235
+ **Behaviour notes:**
236
+ - Passing `null` as `coords` immediately resets `address` and `distance` to `null` without firing a request.
237
+ - The effect re-runs only when `coords.lat` or `coords.lng` changes — passing a new object reference with the same values does **not** re-fetch.
238
+ - In-flight requests are cancelled on unmount or when `coords` changes.
239
+
240
+ ---
241
+
242
+ ### `useZoneContains`
243
+
244
+ Returns all geofence zones that contain a given coordinate. Useful for entry/exit detection, location-gating, and proximity-based UI.
245
+
246
+ ```tsx
247
+ import { useZoneContains } from "@wherabouts/react";
248
+
249
+ function ZoneStatus({ client, userLocation }) {
250
+ const { zones, loading, error } = useZoneContains(client, userLocation);
251
+
252
+ if (loading) return <p>Checking zones…</p>;
253
+ if (error) return <p>Error: {error.message}</p>;
254
+
255
+ return (
256
+ <div>
257
+ {zones.length === 0 ? (
258
+ <p>Not inside any zone</p>
259
+ ) : (
260
+ <ul>
261
+ {zones.map((z) => (
262
+ <li key={z.id}>{z.name}</li>
263
+ ))}
264
+ </ul>
265
+ )}
266
+ </div>
267
+ );
268
+ }
269
+ ```
270
+
271
+ #### Signature
272
+
273
+ ```ts
274
+ function useZoneContains(
275
+ client: WheraboutsClient,
276
+ coords: LatLng | null
277
+ ): UseZoneContainsResult
278
+ ```
279
+
280
+ #### `UseZoneContainsResult`
281
+
282
+ | Field | Type | Description |
283
+ |-----------|-------------------|------------------------------------------|
284
+ | `zones` | `ZoneRecord[]` | Zones that contain `coords` |
285
+ | `loading` | `boolean` | `true` while a request is in flight |
286
+ | `error` | `Error \| null` | Last error, or `null` |
287
+
288
+ **Behaviour notes:**
289
+ - Passing `null` as `coords` immediately clears `zones` without firing a request.
290
+ - Same coordinate-stability semantics as `useReverseGeocode` — object identity is ignored, only `lat`/`lng` values matter.
291
+ - In-flight requests are cancelled on unmount or when `coords` changes.
292
+
293
+ ---
294
+
295
+ ### Routing hooks — `useDirections` / `useMatrix` / `useIsochrone`
296
+
297
+ Fetch routing results that re-run when their params change and abort the previous
298
+ request. Pass `null` params to stay idle. Each returns `{ data, loading, error }`.
299
+
300
+ ```tsx
301
+ import { useDirections } from "@wherabouts/react";
302
+
303
+ function Route({ client }) {
304
+ const { data, loading, error } = useDirections(client, {
305
+ from: "-33.865,151.209",
306
+ to: "-33.8,151.0",
307
+ profile: "driving", // "driving" | "walking" | "cycling"
308
+ });
309
+
310
+ if (loading) return <p>Routing…</p>;
311
+ if (error) return <p>Error: {error.message}</p>;
312
+ return <p>{data ? `${data.distance_m} m, ${data.duration_s} s` : null}</p>;
313
+ }
314
+ ```
315
+
316
+ - `useMatrix(client, { sources, destinations, profile? } | null)` — duration/distance matrix.
317
+ - `useIsochrone(client, { origin, durationSeconds | distanceMeters, profile? } | null)` — reachability polygon.
318
+
319
+ ---
320
+
321
+ ## Using the browser Geolocation API
322
+
323
+ A common pattern — combine the browser's `navigator.geolocation` with these hooks:
324
+
325
+ ```tsx
326
+ import { useState, useEffect } from "react";
327
+ import { useReverseGeocode, useZoneContains, type LatLng } from "@wherabouts/react";
328
+
329
+ function LocationAwareComponent({ client }) {
330
+ const [coords, setCoords] = useState<LatLng | null>(null);
331
+
332
+ useEffect(() => {
333
+ if (!navigator.geolocation) return;
334
+ const id = navigator.geolocation.watchPosition(
335
+ (pos) => setCoords({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
336
+ console.error,
337
+ { enableHighAccuracy: true }
338
+ );
339
+ return () => navigator.geolocation.clearWatch(id);
340
+ }, []);
341
+
342
+ const { address } = useReverseGeocode(client, coords);
343
+ const { zones } = useZoneContains(client, coords);
344
+
345
+ return (
346
+ <div>
347
+ <p>Address: {address?.formattedAddress ?? "Locating…"}</p>
348
+ <p>Zones: {zones.map((z) => z.name).join(", ") || "None"}</p>
349
+ </div>
350
+ );
351
+ }
352
+ ```
353
+
354
+ ---
355
+
356
+ ## TypeScript
357
+
358
+ All hooks and their option/result types are exported:
359
+
360
+ ```ts
361
+ import type {
362
+ LatLng,
363
+ UseAutocompleteOptions,
364
+ UseAutocompleteResult,
365
+ UseReverseGeocodeResult,
366
+ UseZoneContainsResult,
367
+ } from "@wherabouts/react";
368
+ ```
369
+
370
+ The package ships with bundled type declarations (`.d.ts` and `.d.cts`) for both ESM and CJS consumers.
371
+
372
+ ---
373
+
374
+ ## Bundle formats
375
+
376
+ | Format | Entry | Use case |
377
+ |--------|-------------------------|-----------------------|
378
+ | ESM | `dist/index.js` | Bundlers (Vite, Next) |
379
+ | CJS | `dist/index.cjs` | Node / Jest |
380
+
381
+ ---
382
+
383
+ ## License
384
+
385
+ [MIT](./LICENSE) © Joseph Amani