@yarrow-uz/rn-map-sdk 0.3.0 → 0.5.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/dist/index.js CHANGED
@@ -1,2555 +1,4 @@
1
- import { Camera, GeoJSONSource, Images, Layer, Map as Map$1, Marker, OfflineManager } from "@maplibre/maplibre-react-native";
2
- import { createContext, forwardRef, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
3
- import { Animated, Image, StyleSheet, Text, View } from "react-native";
4
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
1
+ import "./preflight.js";
2
+ import { $ as buildStyleEndpoint, A as fetchPlaceLocation, B as ClusterBadge, C as useYarrowMapSearch, D as YarrowMapContext, E as useYarrowLayerPress, F as DEFAULT_CLUSTER_MAX_ZOOM, G as ICON_CACHE_NAME, H as CACHE_PROTOCOL, I as DEFAULT_CLUSTER_MIN_POINTS, J as TILE_CACHE_NAME, K as MILLISECONDS_PER_DAY, L as DEFAULT_CLUSTER_RADIUS_PX, M as resolvePoiData, N as fetchYarrowIcons, O as useYarrowMapRuntime, P as resolveCategoryIcon, Q as addApiKeyToUrl, R as groupByPixelRadius, S as useYarrowRouting, T as YARROW_CLICK_LAYER_IDS, U as DEFAULT_CACHE_LIFESPAN_DAYS, V as CACHED_AT_HEADER, W as ICONS_ENDPOINT, X as YARROW_MAP_URL, Y as USER_TOKEN_STORAGE_KEY, Z as YARROW_SEARCH_API_URL, _ as buildStyleUrl, a as PoiHighlightLayer, at as getYarrowApiKey, b as DEFAULT_BRAND_BADGE_SCALE, c as DEFAULT_OFFLINE_MAX_ZOOM, ct as normalizeStyleType, d as AVG_TILE_BYTES, dt as transformRouteCoordinates, et as fetchArrayBufferWithCache, f as estimateRegion, g as YarrowMapView, h as HighlightMarkerView, i as useYarrowPoiHighlight, it as getOrCreateUserToken, j as lookupPoiInViewport, k as POI_BASE_LAYER, l as DEFAULT_OFFLINE_MIN_ZOOM, lt as setTokenStorage, m as YarrowMarker, n as trackDau, nt as fetchSearchResults, o as useYarrowOfflineRegions, ot as hasCacheStorage, p as useYarrowCamera, q as ROUTE_API_URL, r as SearchResultsLayer, rt as getBoundingBox, s as YarrowOfflineManager, st as haversineDistance, t as setAsyncStorageTokenStorage, tt as fetchRoutes, u as OFFLINE_METADATA_VERSION, ut as setYarrowApiKey, v as RouteLayer, w as useYarrowSearch, x as YarrowImages, y as YarrowMapConfig, z as normalizeClusteringConfig } from "./surface-BY-U7jnq.js";
5
3
 
6
- // ../core/dist/index.js
7
- const YARROW_MAP_URL = "https://gis.yarrow.uz";
8
- const YARROW_SEARCH_API_URL = "https://api.yarrow.uz";
9
- let _apiKey = null;
10
- function setYarrowApiKey(apiKey) {
11
- if (!apiKey) throw new Error("apiKey is required");
12
- _apiKey = apiKey;
13
- }
14
- function getYarrowApiKey() {
15
- if (!_apiKey) throw new Error("Yarrow API key not configured");
16
- return _apiKey;
17
- }
18
- /**
19
- * Appends the configured API key as the `api_key` query parameter. Returns the
20
- * url unchanged when no key is configured yet or the url cannot be parsed.
21
- */
22
- function addApiKeyToUrl(url) {
23
- if (!_apiKey) return url;
24
- try {
25
- const parsedUrl = new URL(url);
26
- parsedUrl.searchParams.set("api_key", _apiKey);
27
- return parsedUrl.toString();
28
- } catch {
29
- return url;
30
- }
31
- }
32
- /**
33
- * Computes the geographic bounding box of a FeatureCollection whose features
34
- * are Points, LineStrings or Polygons. Pure platform-agnostic math shared by
35
- * the web and React Native SDKs' camera helpers.
36
- */
37
- function getBoundingBox(data) {
38
- const bounds = {
39
- xMin: 180,
40
- yMin: 90,
41
- xMax: -180,
42
- yMax: -90
43
- };
44
- const checkBounds = (coordinate) => {
45
- const [longitude, latitude] = coordinate;
46
- bounds.xMin = Math.min(bounds.xMin, longitude);
47
- bounds.xMax = Math.max(bounds.xMax, longitude);
48
- bounds.yMin = Math.min(bounds.yMin, latitude);
49
- bounds.yMax = Math.max(bounds.yMax, latitude);
50
- };
51
- const isLngLat = (value) => Array.isArray(value) && value.length >= 2 && typeof value[0] === "number" && typeof value[1] === "number";
52
- for (const feature of data.features) {
53
- const type = feature.geometry?.type;
54
- const coordinates = feature.geometry?.coordinates;
55
- if (type === "Point" && isLngLat(coordinates)) checkBounds(coordinates);
56
- else if (type === "LineString" && Array.isArray(coordinates)) {
57
- for (const coord of coordinates) if (isLngLat(coord)) checkBounds(coord);
58
- } else if (type === "Polygon" && Array.isArray(coordinates)) for (const ring of coordinates) {
59
- if (!Array.isArray(ring)) continue;
60
- for (const coord of ring) if (isLngLat(coord)) checkBounds(coord);
61
- }
62
- }
63
- return bounds;
64
- }
65
- /** Style-API endpoint returning the icon registry (`IconListItem[]`). */
66
- const ICONS_ENDPOINT = "/icons-image";
67
- const DEFAULT_CACHE_LIFESPAN_DAYS = 30;
68
- const MILLISECONDS_PER_DAY = 864e5;
69
- const TILE_CACHE_NAME = "yarrow-cache-v1-tile";
70
- const ICON_CACHE_NAME = "yarrow-cache-v1-icon";
71
- const CACHE_PROTOCOL = "yarrowcache";
72
- const CACHED_AT_HEADER = "x-yarrow-cached-at";
73
- const hasCacheStorage = () => typeof globalThis !== "undefined" && typeof globalThis.caches !== "undefined" && typeof globalThis.caches.open === "function";
74
- const extractCachedAt = (response) => {
75
- const raw = response.headers.get(CACHED_AT_HEADER);
76
- if (!raw) return null;
77
- const parsed = Number(raw);
78
- return Number.isFinite(parsed) ? parsed : null;
79
- };
80
- /**
81
- * Pulls a `max-age=N` value (in seconds) out of a `Cache-Control` header, if
82
- * present. Returns `null` when the header is missing or doesn't carry a
83
- * numeric `max-age`. Returns 0 for `max-age=0` (treat as immediately stale).
84
- *
85
- * The Yarrow backend does not currently emit `Cache-Control` headers, so this
86
- * is dead in production today. It's plumbed in so a future fix on the
87
- * backend starts being honored without an SDK release.
88
- */
89
- const parseMaxAge = (cacheControl) => {
90
- if (!cacheControl) return null;
91
- for (const directive of cacheControl.split(",")) {
92
- const [rawKey, rawValue] = directive.trim().split("=");
93
- if (rawKey?.toLowerCase() !== "max-age") continue;
94
- if (rawValue === void 0) return 0;
95
- const parsed = Number(rawValue);
96
- return Number.isFinite(parsed) ? parsed : null;
97
- }
98
- return null;
99
- };
100
- const toCachedArrayBufferResponse = async (response) => {
101
- return {
102
- data: await response.arrayBuffer(),
103
- cacheControl: response.headers.get("cache-control"),
104
- expires: response.headers.get("expires"),
105
- contentType: response.headers.get("content-type")
106
- };
107
- };
108
- const fetchFromNetwork = async (url, abortController, requestParameters) => {
109
- const response = await fetch(url, {
110
- method: requestParameters?.method ?? "GET",
111
- headers: requestParameters?.headers,
112
- body: requestParameters?.body,
113
- credentials: requestParameters?.credentials,
114
- signal: abortController.signal
115
- });
116
- if (!response.ok) throw new Error(`Request failed: ${response.status} ${response.statusText}`);
117
- return toCachedArrayBufferResponse(response);
118
- };
119
- /**
120
- * Best-effort LRU eviction for quota errors. Removes the oldest entries (by
121
- * `x-yarrow-cached-at` header) until the new write fits, or until nothing
122
- * remains to drop. Silently stops evicting when the cache becomes empty —
123
- * callers still treat the original quota error as non-fatal.
124
- */
125
- const evictOldest = async (cache) => {
126
- try {
127
- const keys = await cache.keys();
128
- if (keys.length === 0) return false;
129
- let oldestKey = null;
130
- let oldestAt = Number.POSITIVE_INFINITY;
131
- for (const key of keys) {
132
- const match = await cache.match(key);
133
- if (!match) continue;
134
- const at = extractCachedAt(match) ?? 0;
135
- if (at < oldestAt) {
136
- oldestAt = at;
137
- oldestKey = key;
138
- }
139
- }
140
- if (oldestKey === null) return false;
141
- await cache.delete(oldestKey);
142
- return true;
143
- } catch {
144
- return false;
145
- }
146
- };
147
- const saveToCache = async (cache, cacheKey, response) => {
148
- const headers = new Headers();
149
- if (response.contentType) headers.set("content-type", response.contentType);
150
- if (response.cacheControl) headers.set("cache-control", response.cacheControl);
151
- if (response.expires) headers.set("expires", response.expires);
152
- headers.set(CACHED_AT_HEADER, Date.now().toString());
153
- const MAX_WRITE_EVICTIONS = 4;
154
- let lastError;
155
- for (let attempt = 0;; attempt++) {
156
- const body = new Response(response.data.slice(0), {
157
- status: 200,
158
- headers
159
- });
160
- try {
161
- await cache.put(cacheKey, body);
162
- return;
163
- } catch (error) {
164
- lastError = error;
165
- }
166
- if (attempt >= MAX_WRITE_EVICTIONS || !await evictOldest(cache)) break;
167
- }
168
- console.warn("[YarrowMap] cache write failed:", lastError);
169
- };
170
- const fetchArrayBufferWithCache = async (url, cacheName, lifespanMs, abortController, requestParameters) => {
171
- if (!hasCacheStorage()) return fetchFromNetwork(url, abortController, requestParameters);
172
- const cache = await caches.open(cacheName);
173
- const cachedResponse = await cache.match(url);
174
- if (cachedResponse) {
175
- const cachedAt = extractCachedAt(cachedResponse);
176
- const maxAgeSeconds = parseMaxAge(cachedResponse.headers.get("cache-control"));
177
- const effectiveLifespanMs = maxAgeSeconds !== null ? maxAgeSeconds * 1e3 : lifespanMs;
178
- if (!(cachedAt === null || Date.now() - cachedAt > effectiveLifespanMs)) return toCachedArrayBufferResponse(cachedResponse);
179
- try {
180
- const refreshed = await fetchFromNetwork(url, abortController, requestParameters);
181
- await saveToCache(cache, url, refreshed);
182
- return refreshed;
183
- } catch {
184
- return toCachedArrayBufferResponse(cachedResponse);
185
- }
186
- }
187
- const networkResponse = await fetchFromNetwork(url, abortController, requestParameters);
188
- await saveToCache(cache, url, networkResponse);
189
- return networkResponse;
190
- };
191
- const transformRouteCoordinates = (features) => {
192
- return features.map((feature) => {
193
- const transformedCoords = feature.geometry.coordinates.map((coord) => [coord.lng, coord.lat]);
194
- return {
195
- ...feature,
196
- geometry: {
197
- ...feature.geometry,
198
- coordinates: transformedCoords
199
- }
200
- };
201
- });
202
- };
203
- /** Routing API endpoint used by `fetchRoutes()`. */
204
- const ROUTE_API_URL = "https://api.yarrow.uz/api/routing/route";
205
- const emptyResult = (profile) => ({
206
- features: [],
207
- directions: [],
208
- meta: {
209
- profile,
210
- totalRoutes: 0,
211
- bestRouteIndex: 0,
212
- duration: 0,
213
- distance: 0
214
- }
215
- });
216
- /**
217
- * Network half of the routing flow: POSTs the route request to the Yarrow
218
- * routing API, parses and normalizes the response (coordinate order fix
219
- * included). Rendering, events and camera work stay in the platform SDKs —
220
- * they consume the returned features/directions/meta verbatim.
221
- *
222
- * Early "no route" outcomes resolve to an empty result (never throw), exactly
223
- * like the web SDK's historic `buildRoute()` behavior.
224
- */
225
- async function fetchRoutes(input) {
226
- const { profile, coordinates, language, signal } = input;
227
- if (coordinates.length < 2) throw new Error("At least two coordinates are required to build a route.");
228
- const url = addApiKeyToUrl(ROUTE_API_URL);
229
- const response = await fetch(url, {
230
- method: "POST",
231
- signal,
232
- headers: {
233
- "Content-Type": "application/json",
234
- ...language ? { "Accept-Language": language } : {}
235
- },
236
- body: JSON.stringify({
237
- profile: profile.toUpperCase(),
238
- coordinates: coordinates.map((coord) => ({
239
- lng: coord[0],
240
- lat: coord[1]
241
- }))
242
- })
243
- });
244
- if (!response.ok) throw new Error(`Request failed: ${response.status} ${response.statusText}`);
245
- const data = await response.json();
246
- if (!data.success) {
247
- console.warn("[YarrowMap] buildRoute: no route found");
248
- return emptyResult(profile);
249
- }
250
- let features = data.data.path?.features || [];
251
- features = transformRouteCoordinates(features);
252
- if (!features.length) {
253
- console.warn("[YarrowMap] buildRoute: route has no features to render");
254
- return emptyResult(profile);
255
- }
256
- const bestCoords = features[0]?.geometry?.coordinates;
257
- if (bestCoords?.every(([lng, lat]) => lng === bestCoords[0][0] && lat === bestCoords[0][1])) console.warn("[YarrowMap] buildRoute: the returned route has zero length — the requested coordinates may be outside the routing coverage area.");
258
- const directions = data.data.directions?.routes?.map((r) => r.properties || []) || [];
259
- return {
260
- features,
261
- directions,
262
- meta: {
263
- profile,
264
- totalRoutes: features.length,
265
- bestRouteIndex: 0,
266
- duration: features[0]?.properties.duration || 0,
267
- distance: features[0]?.properties.distance || 0
268
- }
269
- };
270
- }
271
- const haversineDistance = (lat1, lon1, lat2, lon2) => {
272
- const toRad = (value) => value * Math.PI / 180;
273
- const R = 6371e3;
274
- const phi1 = toRad(lat1);
275
- const phi2 = toRad(lat2);
276
- const deltaPhi = toRad(lat2 - lat1);
277
- const deltaLambda = toRad(lon2 - lon1);
278
- const a = Math.sin(deltaPhi / 2) ** 2 + Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda / 2) ** 2;
279
- return R * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
280
- };
281
- /**
282
- * Queries the Yarrow search API around a coordinate. Pure network + mapping —
283
- * marker rendering stays in the platform SDKs.
284
- */
285
- async function fetchSearchResults(query, input) {
286
- const searchUrl = addApiKeyToUrl(`${YARROW_SEARCH_API_URL}/api/search/`);
287
- const url = new URL(searchUrl);
288
- url.searchParams.set("q", query);
289
- url.searchParams.set("lat", String(input.lat));
290
- url.searchParams.set("lng", String(input.lon));
291
- url.searchParams.set("country", "Uzbekistan");
292
- url.searchParams.set("sort_by", "relevance");
293
- url.searchParams.set("page", String(input.page ?? 1));
294
- url.searchParams.set("page_size", String(input.pageSize ?? 15));
295
- const response = await fetch(url.toString(), {
296
- headers: { "Content-Type": "application/json" },
297
- signal: input.signal
298
- });
299
- if (!response.ok) throw new Error(`Request failed: ${response.status} ${response.statusText}`);
300
- return ((await response.json())?.results || []).map((r) => ({
301
- id: r.id,
302
- name: r.name,
303
- icon_img: r.icon_img,
304
- latitude: r.address?.location?.lat,
305
- longitude: r.address?.location?.lng,
306
- category: r.category
307
- }));
308
- }
309
- /**
310
- * Validates a user-supplied style type, warning (and falling back to
311
- * `"default"`) on anything unrecognized. Verbatim behavior of the web SDK's
312
- * `changeStyles()` guard.
313
- */
314
- function normalizeStyleType(styleType) {
315
- if (styleType !== void 0 && styleType !== "default" && styleType !== "satellite" && styleType !== "hybrid") console.warn(`[YarrowMap] changeStyles: unknown style type "${styleType}", falling back to "default".`);
316
- return styleType === "satellite" || styleType === "hybrid" ? styleType : "default";
317
- }
318
- /**
319
- * Style-fetch endpoint for a style type/theme combination, e.g.
320
- * `/styles/satellite/?dark=true`. Verbatim behavior of the web SDK's
321
- * `YarrowStylesManager.buildStyleEndpoint()`.
322
- */
323
- function buildStyleEndpoint(styleType, theme) {
324
- let endpoint = "/styles/";
325
- if (styleType === "satellite") endpoint = "/styles/satellite/";
326
- else if (styleType === "hybrid") endpoint = "/styles/hybrid/";
327
- if (theme === "dark") endpoint += endpoint.includes("?") ? "&dark=true" : "?dark=true";
328
- return endpoint;
329
- }
330
- const STORAGE_KEY = "yarrow:user_token";
331
- /**
332
- * Public alias of `STORAGE_KEY` so platform SDKs can build storage adapters
333
- * (e.g. React Native AsyncStorage bridges) without hard-coding the key.
334
- */
335
- const USER_TOKEN_STORAGE_KEY = STORAGE_KEY;
336
- let override = null;
337
- function setTokenStorage(storage) {
338
- override = storage;
339
- }
340
- function resolveStorage() {
341
- if (override) return override;
342
- try {
343
- if (typeof localStorage !== "undefined") return localStorage;
344
- } catch {}
345
- return null;
346
- }
347
- function generateUuid() {
348
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
349
- const bytes = /* @__PURE__ */ new Uint8Array(16);
350
- if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(bytes);
351
- else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
352
- bytes[6] = bytes[6] & 15 | 64;
353
- bytes[8] = bytes[8] & 63 | 128;
354
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
355
- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
356
- }
357
- function getOrCreateUserToken() {
358
- const storage = resolveStorage();
359
- if (storage) try {
360
- const existing = storage.getItem(STORAGE_KEY);
361
- if (existing) return existing;
362
- const token = generateUuid();
363
- storage.setItem(STORAGE_KEY, token);
364
- return token;
365
- } catch {}
366
- return generateUuid();
367
- }
368
- /** Hard cap on how long a single tracking request may stay open. */
369
- const TRACK_REQUEST_TIMEOUT_MS = 5e3;
370
- function trackDau(apiKey, sdkType = "javascript") {
371
- try {
372
- const user_token = getOrCreateUserToken();
373
- const controller = new AbortController();
374
- const timeout = setTimeout(() => controller.abort(), TRACK_REQUEST_TIMEOUT_MS);
375
- fetch(`${YARROW_SEARCH_API_URL}/api/tracking/track-dau`, {
376
- method: "POST",
377
- headers: { "Content-Type": "application/json" },
378
- body: JSON.stringify({
379
- api_key: apiKey,
380
- sdk_type: sdkType,
381
- user_token
382
- }),
383
- signal: controller.signal
384
- }).catch(() => {}).finally(() => clearTimeout(timeout));
385
- } catch {}
386
- }
387
-
388
- // src/clustering/ClusterBadge.tsx
389
- const CLUSTER_COLORS = {
390
- light: {
391
- bg: "#2f80ed",
392
- text: "#ffffff"
393
- },
394
- dark: {
395
- bg: "#3b6fd4",
396
- text: "#ffffff"
397
- }
398
- };
399
- const ENTER_MS$1 = 280;
400
- /**
401
- * The count badge that stands in for clustered highlight/search markers —
402
- * the native counterpart of the web SDK's cluster DOM marker (blue circle,
403
- * white border, bold count).
404
- */
405
- const ClusterBadge = memo(function ClusterBadge({ lngLat, count, theme, onPress }) {
406
- const progress = useRef(new Animated.Value(0)).current;
407
- useEffect(() => {
408
- Animated.timing(progress, {
409
- toValue: 1,
410
- duration: ENTER_MS$1,
411
- useNativeDriver: true
412
- }).start();
413
- }, [progress]);
414
- const colors = CLUSTER_COLORS[theme];
415
- return /* @__PURE__ */ jsx(Marker, {
416
- lngLat,
417
- anchor: "center",
418
- onPress: onPress ? () => onPress() : void 0,
419
- children: /* @__PURE__ */ jsx(Animated.View, {
420
- style: [styles$1.inner, {
421
- transform: [{ scale: progress }],
422
- opacity: progress
423
- }],
424
- children: /* @__PURE__ */ jsx(Text, {
425
- style: [styles$1.badge, {
426
- backgroundColor: colors.bg,
427
- color: colors.text
428
- }],
429
- children: count
430
- })
431
- })
432
- });
433
- });
434
- const styles$1 = StyleSheet.create({
435
- inner: {
436
- alignItems: "center",
437
- justifyContent: "center"
438
- },
439
- badge: {
440
- minWidth: 40,
441
- height: 40,
442
- paddingHorizontal: 10,
443
- borderRadius: 20,
444
- borderWidth: 3,
445
- borderColor: "#ffffff",
446
- fontSize: 15,
447
- fontWeight: "700",
448
- lineHeight: 34,
449
- textAlign: "center",
450
- textAlignVertical: "center"
451
- }
452
- });
453
-
454
- // src/clustering/config.ts
455
- /**
456
- * Clustering configuration and normalization — the declarative counterpart of
457
- * the web SDK's `setClustering`. Defaults match the web SDK exactly:
458
- * 60 px merge radius, no clustering above zoom 16, clusters need ≥ 2 markers.
459
- */
460
- const DEFAULT_CLUSTER_RADIUS_PX = 60;
461
- const DEFAULT_CLUSTER_MAX_ZOOM = 16;
462
- const DEFAULT_CLUSTER_MIN_POINTS = 2;
463
- /**
464
- * Normalizes the public clustering option (`true` / config object / falsy)
465
- * into a fully-resolved config. Passing an object enables clustering.
466
- * `minPoints` is clamped to at least 2 — a "cluster" of one is just the
467
- * marker itself.
468
- */
469
- function normalizeClusteringConfig(input) {
470
- const disabled = {
471
- enabled: false,
472
- radius: 60,
473
- maxZoom: 16,
474
- minPoints: 2
475
- };
476
- if (input === void 0 || input === false) return disabled;
477
- if (input === true) return {
478
- ...disabled,
479
- enabled: true
480
- };
481
- return {
482
- enabled: true,
483
- radius: input.radius ?? 60,
484
- maxZoom: input.maxZoom ?? 16,
485
- minPoints: Math.max(2, input.minPoints ?? 2),
486
- onClusterClick: input.onClusterClick
487
- };
488
- }
489
- /**
490
- * Groups projected points greedily by pixel distance: each unvisited point
491
- * seeds a group and absorbs every remaining point within `radius`. O(n²), but
492
- * the highlighted/search-marker count is small (dozens at most), so this
493
- * stays cheap and deterministic. Ported from the web SDK's cluster engine.
494
- */
495
- function groupByPixelRadius(items, radius) {
496
- const radiusSq = radius * radius;
497
- const visited = new Array(items.length).fill(false);
498
- const groups = [];
499
- for (let i = 0; i < items.length; i++) {
500
- if (visited[i]) continue;
501
- visited[i] = true;
502
- const seed = items[i];
503
- const group = [seed];
504
- for (let j = i + 1; j < items.length; j++) {
505
- if (visited[j]) continue;
506
- const candidate = items[j];
507
- const dx = seed.x - candidate.x;
508
- const dy = seed.y - candidate.y;
509
- if (dx * dx + dy * dy <= radiusSq) {
510
- visited[j] = true;
511
- group.push(candidate);
512
- }
513
- }
514
- groups.push(group);
515
- }
516
- return groups;
517
- }
518
-
519
- // src/icons/registry.ts
520
- /**
521
- * Fetches the Yarrow icon registry (`/icons-image`) and reduces it to a
522
- * name → URL map. Native has no Cache Storage, so the result is not persisted
523
- * — `<YarrowMapView>` fetches it once per mount when icons are enabled.
524
- *
525
- * Also seeds core's API-key module state (like every standalone client), so
526
- * the key is current even if the hook runs before a map mounts.
527
- */
528
- async function fetchYarrowIcons(apiKey) {
529
- if (apiKey) setYarrowApiKey(apiKey);
530
- const response = await fetch(addApiKeyToUrl(`${YARROW_MAP_URL}${ICONS_ENDPOINT}`));
531
- if (!response.ok) throw new Error(`Request failed: ${response.status} ${response.statusText}`);
532
- return (await response.json()).reduce((acc, icon) => {
533
- acc[icon.icon_image_name] = icon.icon_image_url;
534
- return acc;
535
- }, {});
536
- }
537
- /**
538
- * Best-effort icon URL for a search-result `category.name` / tile
539
- * `node_type`. The registry is keyed by sprite names, which usually match
540
- * category names — the same fallback the web SDK applies via its icon
541
- * expression.
542
- */
543
- function resolveCategoryIcon(iconsByName, name) {
544
- if (!name) return void 0;
545
- const icons = iconsByName;
546
- if (!icons) return void 0;
547
- return Object.hasOwn(icons, name) ? icons[name] : void 0;
548
- }
549
-
550
- // src/poiHighlight/resolve.ts
551
- /** The base style's POI symbol layer (`node_tile` source). */
552
- const POI_BASE_LAYER = "pois_tile_layer";
553
- const PLACE_TIMEOUT_MS = 15e3;
554
- /**
555
- * Fetches a POI's coordinates and icon from the place-detail API — the
556
- * off-screen / below-zoom fallback of the resolution chain. Returns `null`
557
- * on any failure or missing coordinates (web parity).
558
- *
559
- * When the response carries no `icon_img`, the icon is derived from
560
- * `node_type` (falling back to `category.name`) — the web SDK resolves it
561
- * through its style `icon-image` expression; native approximates that with
562
- * an icon-registry lookup by the same name, since the detail endpoint
563
- * returns the node type rather than an icon URL.
564
- */
565
- async function fetchPlaceLocation(id, iconsByName) {
566
- const controller = new AbortController();
567
- const timeout = setTimeout(() => controller.abort(), PLACE_TIMEOUT_MS);
568
- try {
569
- const url = addApiKeyToUrl(`${YARROW_SEARCH_API_URL}/api/search/${id}?is_bus_stop=false`);
570
- const res = await fetch(url, { signal: controller.signal });
571
- if (!res.ok) return null;
572
- const data = (await res.json())?.search?.data;
573
- const loc = data?.address?.location;
574
- if (!loc) return null;
575
- const nodeType = typeof data?.node_type === "string" ? data.node_type : typeof data?.category?.name === "string" ? data.category.name : void 0;
576
- const iconUrl = data?.icon_img ?? (nodeType ? resolveCategoryIcon(iconsByName, nodeType) : void 0);
577
- return {
578
- lng: loc.lng,
579
- lat: loc.lat,
580
- iconUrl,
581
- title: data?.name
582
- };
583
- } catch (error) {
584
- if (error?.name !== "AbortError") console.warn(`[YarrowMap] fetchPlaceLocation(${id}) failed:`, error);
585
- return null;
586
- } finally {
587
- clearTimeout(timeout);
588
- }
589
- }
590
- /**
591
- * Reads a POI's point geometry from the style's POI layer within the current
592
- * viewport — the free, no-network resolution step. Native can only query
593
- * *rendered* features (no `querySourceFeatures` on undeclared sources), so
594
- * off-screen POIs fall through to the place-detail API. Icons are resolved
595
- * best-effort from the registry via the feature's `node_type`.
596
- */
597
- async function lookupPoiInViewport(mapRef, id, iconsByName) {
598
- let features = [];
599
- try {
600
- features = await mapRef.queryRenderedFeatures({
601
- layers: [POI_BASE_LAYER],
602
- filter: [
603
- "==",
604
- ["get", "id"],
605
- id
606
- ]
607
- });
608
- } catch {
609
- return null;
610
- }
611
- const feature = features.find((f) => f.geometry?.type === "Point");
612
- if (!feature) return null;
613
- const coordinates = feature.geometry.coordinates;
614
- const properties = feature.properties ?? {};
615
- const nodeType = typeof properties.node_type === "string" ? properties.node_type : void 0;
616
- const name = typeof properties.name === "string" ? properties.name : void 0;
617
- return {
618
- lng: coordinates[0],
619
- lat: coordinates[1],
620
- iconUrl: nodeType ? resolveCategoryIcon(iconsByName, nodeType) : void 0,
621
- title: name
622
- };
623
- }
624
- /**
625
- * Resolves a POI's coordinates, icon and title cheapest-first:
626
- * 1. caller-provided `location` / `icon` / `title`
627
- * 2. local lookup in the rendered POI layer (no network)
628
- * 3. the place-detail API (off-screen / below the POI zoom range, or when
629
- * anything is still missing — web parity: the API fills icon and title
630
- * too, not just coordinates)
631
- *
632
- * The web SDK additionally evaluates the style's `icon-image` expression for
633
- * both the tile and the place-detail steps; native approximates it with a
634
- * registry lookup by `node_type`. Coordinate resolution is the hard
635
- * requirement — if it fails, the highlight is rolled back by the caller.
636
- */
637
- async function resolvePoiData(id, options, runtime) {
638
- let lng = options.location?.lng;
639
- let lat = options.location?.lat;
640
- let iconUrl = options.icon;
641
- let title = options.title;
642
- if (lng === void 0 || iconUrl === void 0 || title === void 0) {
643
- const mapRef = runtime.mapRef.current;
644
- const local = mapRef ? await lookupPoiInViewport(mapRef, id, runtime.iconsByName) : null;
645
- if (local) {
646
- if (lng === void 0) {
647
- lng = local.lng;
648
- lat = local.lat;
649
- }
650
- if (iconUrl === void 0) iconUrl = local.iconUrl;
651
- if (title === void 0) title = local.title;
652
- }
653
- }
654
- if (lng === void 0 || iconUrl === void 0 || title === void 0) {
655
- const remote = await fetchPlaceLocation(id, runtime.iconsByName);
656
- if (remote) {
657
- if (lng === void 0) {
658
- lng = remote.lng;
659
- lat = remote.lat;
660
- }
661
- if (iconUrl === void 0) iconUrl = remote.iconUrl;
662
- if (title === void 0) title = remote.title;
663
- }
664
- }
665
- if (lng === void 0 || lat === void 0) return null;
666
- return {
667
- lng,
668
- lat,
669
- iconUrl,
670
- title
671
- };
672
- }
673
-
674
- // src/runtime/context.ts
675
- const YarrowMapContext = createContext(null);
676
- /** Reads the enclosing `<YarrowMapView>` runtime, or `null` outside one. */
677
- function useYarrowMapRuntime() {
678
- return useContext(YarrowMapContext);
679
- }
680
-
681
- // src/events/useYarrowLayerPress.ts
682
- const YARROW_CLICK_LAYER_IDS = {
683
- pois: [POI_BASE_LAYER],
684
- buildings: ["buildings_tile_layer"],
685
- mahalla: ["mahallah_label_tile_layer"],
686
- district: ["districts_label_tile_layer"],
687
- region: ["regions_label_tile_layer"],
688
- country: ["countries_label_tile_layer"]
689
- };
690
- /**
691
- * Base-style-layer press handler — the native counterpart of the web SDK's
692
- * `onIconClick('pois' | 'buildings')` and `onLayerClick(<admin label>)`. On
693
- * every map press it queries the rendered features at the press point for the
694
- * target layers and invokes `handler` with the topmost hit. Must be called
695
- * inside `<YarrowMapView>` — extract a child component rendered as a map
696
- * child (hooks outside the map can't see the runtime):
697
- *
698
- * ```tsx
699
- * function PoiPressReporter() {
700
- * useYarrowLayerPress('pois', ({ lat, lng, properties, selected }) => {
701
- * console.log('POI pressed', properties.id, selected);
702
- * });
703
- * return null;
704
- * }
705
- *
706
- * <YarrowMapView apiKey={KEY}>
707
- * <PoiPressReporter />
708
- * </YarrowMapView>
709
- * ```
710
- *
711
- * Unlike the web SDK, targets resolve to the canonical Yarrow style layer
712
- * ids (verified against the served `/styles/` document, identical in light
713
- * and dark) instead of dynamic style inspection — override `layerIds` if
714
- * your style variant names them differently.
715
- */
716
- function useYarrowLayerPress(target, handler, options) {
717
- const runtime = useYarrowMapRuntime();
718
- const targets = Array.isArray(target) ? target : [target];
719
- const targetsKey = targets.join(",");
720
- const handlerRef = useRef(handler);
721
- handlerRef.current = handler;
722
- useEffect(() => {
723
- if (!runtime) {
724
- console.warn("[YarrowMap] useYarrowLayerPress: no map runtime — call it inside <YarrowMapView>.");
725
- return;
726
- }
727
- const layerIds = targets.flatMap((t) => options?.layerIds?.[t] ?? YARROW_CLICK_LAYER_IDS[t]);
728
- const includesPois = targets.includes("pois");
729
- return runtime.subscribePress((press) => {
730
- const map = runtime.mapRef.current;
731
- if (!map || layerIds.length === 0) return;
732
- map.queryRenderedFeatures(press.point, { layers: layerIds }).then((features) => {
733
- const feature = features[0];
734
- if (!feature?.properties) return;
735
- const properties = feature.properties;
736
- let selected;
737
- if (includesPois) {
738
- const fid = properties.id;
739
- selected = typeof fid === "number" ? runtime.highlightedPoiIds.current.has(fid) : false;
740
- }
741
- handlerRef.current({
742
- lat: press.lngLat[1],
743
- lng: press.lngLat[0],
744
- properties,
745
- selected
746
- });
747
- }).catch(() => {});
748
- });
749
- }, [
750
- runtime,
751
- targetsKey,
752
- options?.layerIds
753
- ]);
754
- }
755
-
756
- // src/hooks/useYarrowSearch.ts
757
- /**
758
- * Debounced, abortable search against the Yarrow search API.
759
- *
760
- * Requires the API key to be configured (`YarrowMapView` does this on mount;
761
- * otherwise call `setYarrowApiKey()` first).
762
- *
763
- * ```tsx
764
- * const { results, isLoading } = useYarrowSearch(query, {
765
- * lat: position?.lat ?? 41.2995,
766
- * lon: position?.lng ?? 69.2401,
767
- * });
768
- * ```
769
- */
770
- const useYarrowSearch = (query, options) => {
771
- const { lat, lon, page = 1, pageSize = 15, debounceMs = 300, enabled = true } = options;
772
- const [results, setResults] = useState([]);
773
- const [isLoading, setIsLoading] = useState(false);
774
- const [error, setError] = useState(null);
775
- const latestRequestRef = useRef(0);
776
- useEffect(() => {
777
- const trimmed = query.trim();
778
- if (!enabled || trimmed.length === 0) {
779
- latestRequestRef.current += 1;
780
- setResults([]);
781
- setError(null);
782
- setIsLoading(false);
783
- return;
784
- }
785
- const controller = new AbortController();
786
- const requestId = ++latestRequestRef.current;
787
- setIsLoading(true);
788
- const timeout = setTimeout(() => {
789
- fetchSearchResults(trimmed, {
790
- lat,
791
- lon,
792
- page,
793
- pageSize,
794
- signal: controller.signal
795
- }).then((resolved) => {
796
- if (latestRequestRef.current === requestId) {
797
- setResults(resolved);
798
- setError(null);
799
- }
800
- }).catch((caught) => {
801
- if (controller.signal.aborted) return;
802
- if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
803
- }).finally(() => {
804
- if (latestRequestRef.current === requestId) setIsLoading(false);
805
- });
806
- }, debounceMs);
807
- return () => {
808
- clearTimeout(timeout);
809
- controller.abort();
810
- };
811
- }, [
812
- query,
813
- enabled,
814
- lat,
815
- lon,
816
- page,
817
- pageSize,
818
- debounceMs
819
- ]);
820
- return {
821
- results,
822
- isLoading,
823
- error
824
- };
825
- };
826
-
827
- // src/hooks/useYarrowMapSearch.ts
828
- const DEFAULT_THRESHOLD_METERS = 500;
829
- const DEFAULT_MOVE_DEBOUNCE_MS = 250;
830
- /**
831
- * `useYarrowSearch` plus web-parity re-query on camera movement: when the map
832
- * moves ≥ 500 m from where the current results were fetched for, the search
833
- * re-runs around the new center. Must be called inside `<YarrowMapView>` to
834
- * observe camera moves (outside one it behaves exactly like `useYarrowSearch`).
835
- *
836
- * ```tsx
837
- * const { results, isLoading, center } = useYarrowMapSearch(query, {
838
- * lat: 41.2995,
839
- * lon: 69.2401,
840
- * refetchOnMove: true,
841
- * });
842
- * <SearchResultsLayer results={results} />
843
- * ```
844
- */
845
- function useYarrowMapSearch(query, options) {
846
- const { lat, lon, refetchOnMove, ...searchOptions } = options;
847
- const runtime = useYarrowMapRuntime();
848
- const [center, setCenter] = useState({
849
- lat,
850
- lon
851
- });
852
- const centerRef = useRef(center);
853
- centerRef.current = center;
854
- const callerKey = `${lat},${lon}`;
855
- useEffect(() => {
856
- const [callerLat, callerLon] = callerKey.split(",").map(Number);
857
- setCenter((current) => current.lat === callerLat && current.lon === callerLon ? current : {
858
- lat: callerLat,
859
- lon: callerLon
860
- });
861
- }, [callerKey]);
862
- useEffect(() => {
863
- if (!refetchOnMove || !runtime) return;
864
- const { thresholdMeters = DEFAULT_THRESHOLD_METERS, debounceMs = DEFAULT_MOVE_DEBOUNCE_MS } = typeof refetchOnMove === "object" ? refetchOnMove : {};
865
- let timeout = null;
866
- const unsubscribe = runtime.subscribeRegionChange(({ center: [lng, mapLat] }) => {
867
- if (timeout) clearTimeout(timeout);
868
- timeout = setTimeout(() => {
869
- timeout = null;
870
- const current = centerRef.current;
871
- if (haversineDistance(current.lat, current.lon, mapLat, lng) >= thresholdMeters) setCenter({
872
- lat: mapLat,
873
- lon: lng
874
- });
875
- }, debounceMs);
876
- });
877
- return () => {
878
- if (timeout) clearTimeout(timeout);
879
- unsubscribe();
880
- };
881
- }, [refetchOnMove, runtime]);
882
- return {
883
- ...useYarrowSearch(query, {
884
- ...searchOptions,
885
- lat: center.lat,
886
- lon: center.lon
887
- }),
888
- center
889
- };
890
- }
891
-
892
- // src/hooks/useYarrowRouting.ts
893
- /**
894
- * Headless routing state for the Yarrow routing API — pairs with
895
- * `<RouteLayer>` for rendering.
896
- *
897
- * ```tsx
898
- * const { routes, isLoading, buildRoute } = useYarrowRouting({ profile: 'driving' });
899
- * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
900
- * <RouteLayer routes={routes} />
901
- * </YarrowMapView>
902
- * ```
903
- */
904
- const useYarrowRouting = (options = {}) => {
905
- const { profile = "driving", language } = options;
906
- const [result, setResult] = useState(null);
907
- const [isLoading, setIsLoading] = useState(false);
908
- const [error, setError] = useState(null);
909
- const latestRequestRef = useRef(0);
910
- const buildRoute = useCallback(async (input) => {
911
- const requestId = ++latestRequestRef.current;
912
- setIsLoading(true);
913
- setError(null);
914
- try {
915
- const resolved = await fetchRoutes({
916
- profile: input.profile ?? profile,
917
- coordinates: input.coordinates,
918
- language: input.language ?? language,
919
- signal: input.signal
920
- });
921
- if (latestRequestRef.current === requestId) setResult(resolved);
922
- return resolved;
923
- } catch (caught) {
924
- if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
925
- throw caught;
926
- } finally {
927
- if (latestRequestRef.current === requestId) setIsLoading(false);
928
- }
929
- }, [profile, language]);
930
- const clearRoutes = useCallback(() => {
931
- latestRequestRef.current += 1;
932
- setResult(null);
933
- setError(null);
934
- setIsLoading(false);
935
- }, []);
936
- return {
937
- routes: result?.features ?? [],
938
- directions: result?.directions ?? [],
939
- meta: result?.meta ?? null,
940
- isLoading,
941
- error,
942
- buildRoute,
943
- clearRoutes
944
- };
945
- };
946
-
947
- // src/icons/YarrowImages.tsx
948
- /**
949
- * Adds the Yarrow icon images to the native style so symbol layers can
950
- * resolve their `icon-image` names — the native counterpart of the web SDK's
951
- * `addIconsToMap` prefetch plus its missing-image resolver. `Images` accepts
952
- * remote URLs and downloads them natively; `onImageMissing` covers icons
953
- * referenced before the registry fetch lands or after a failed fetch.
954
- */
955
- const YarrowImages = memo(function YarrowImages({ iconsByName, onMissingIcon }) {
956
- const images = useMemo(() => ({ ...iconsByName }), [iconsByName]);
957
- const handleMissing = useCallback((event) => {
958
- const name = event.nativeEvent?.image;
959
- if (name) onMissingIcon?.(name);
960
- }, [onMissingIcon]);
961
- return /* @__PURE__ */ jsx(Images, {
962
- images,
963
- onImageMissing: handleMissing
964
- });
965
- });
966
-
967
- // src/maps/config.ts
968
- /**
969
- * Validated, defaulted RN map configuration. Mirrors the web SDK's
970
- * `YarrowMapConfig` minus the DOM container (the native view is sized by the
971
- * consuming app's layout) and minus web-only rendering options (hover,
972
- * clustering, controls, tile cache — none of which exist on native).
973
- */
974
- var YarrowMapConfig = class {
975
- constructor(config) {
976
- const { apiKey, center, zoom: resolvedZoom = 10, minZoom: resolvedMinZoom = 0, maxZoom: resolvedMaxZoom = 19, theme: resolvedTheme = "light", styleType: resolvedStyleType } = config;
977
- if (!apiKey) throw new Error("apiKey is required");
978
- this.center = center;
979
- this.zoom = resolvedZoom;
980
- this.minZoom = resolvedMinZoom;
981
- this.maxZoom = resolvedMaxZoom;
982
- this.theme = resolvedTheme;
983
- this.styleType = normalizeStyleType(resolvedStyleType);
984
- this.apiKey = apiKey;
985
- }
986
- };
987
-
988
- // src/maps/routing/types.ts
989
- /** Best-route + alternatives palette — same values as the web SDK's
990
- * `buildRoute()` defaults (index 0 is the best route, index 1 the shared
991
- * alternative color). */
992
- const ROUTE_LAYER_COLORS = [
993
- "#22c55e",
994
- "#aaaaaa",
995
- "#cccccc",
996
- "#dddddd",
997
- "#eeeeee"
998
- ];
999
- /** Distinct-series palette — same values as the web SDK's `renderRoutes()`. */
1000
- const ROUTE_COLORS = [
1001
- "#3b82f6",
1002
- "#10b981",
1003
- "#f59e0b",
1004
- "#ef4444",
1005
- "#8b5cf6"
1006
- ];
1007
-
1008
- // src/maps/routing/RouteLayer.tsx
1009
- const DEFAULT_LAYER_PREFIX = "yarrow-route";
1010
- /** Line styling of `renderRoutes()` — web parity for the distinct series. */
1011
- const DISTINCT_ROUTE_WIDTH = 4;
1012
- const DISTINCT_ROUTE_OPACITY = .8;
1013
- const toFeatureCollection = (route) => ({
1014
- type: "FeatureCollection",
1015
- features: [route]
1016
- });
1017
- /**
1018
- * Declarative route rendering: one GeoJSON source + line layer per route.
1019
- * Compose inside `<YarrowMapView>` and drive it with `useYarrowRouting()`:
1020
- *
1021
- * ```tsx
1022
- * const { routes } = useYarrowRouting();
1023
- * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
1024
- * <RouteLayer routes={routes} onPressRoute={…} />
1025
- * </YarrowMapView>
1026
- * ```
1027
- *
1028
- * Pass `distinct` to render independent series instead of best-route-plus-
1029
- * alternatives — the declarative counterpart of the web SDK's
1030
- * `renderRoutes()`.
1031
- */
1032
- const RouteLayer = memo(function RouteLayer({ routes, bestIndex = 0, routeColor = ROUTE_LAYER_COLORS[0], routeWidth = 5, routeOpacity = 1, alternativeColor = ROUTE_LAYER_COLORS[1], alternativeWidth = 2.5, alternativeOpacity = .5, layerPrefix = DEFAULT_LAYER_PREFIX, onPressRoute, distinct = false }) {
1033
- const styleFor = (index) => {
1034
- if (distinct) return {
1035
- color: ROUTE_COLORS[index % ROUTE_COLORS.length],
1036
- width: DISTINCT_ROUTE_WIDTH,
1037
- opacity: DISTINCT_ROUTE_OPACITY
1038
- };
1039
- const isBest = index === bestIndex;
1040
- return {
1041
- color: isBest ? routeColor : alternativeColor,
1042
- width: isBest ? routeWidth : alternativeWidth,
1043
- opacity: isBest ? routeOpacity : alternativeOpacity
1044
- };
1045
- };
1046
- return routes.map((route, index) => {
1047
- const sourceId = `${layerPrefix}-${index}`;
1048
- const { color, width, opacity } = styleFor(index);
1049
- return /* @__PURE__ */ jsx(GeoJSONSource, {
1050
- id: sourceId,
1051
- data: toFeatureCollection(route),
1052
- onPress: onPressRoute ? (event) => onPressRoute(event, index) : void 0,
1053
- children: /* @__PURE__ */ jsx(Layer, {
1054
- id: `${layerPrefix}-line-${index}`,
1055
- type: "line",
1056
- layout: {
1057
- "line-cap": "round",
1058
- "line-join": "round"
1059
- },
1060
- paint: {
1061
- "line-color": color,
1062
- "line-width": width,
1063
- "line-opacity": opacity
1064
- }
1065
- })
1066
- }, sourceId);
1067
- });
1068
- });
1069
-
1070
- // src/maps/styles.ts
1071
- /**
1072
- * Full style URL for MapLibre React Native's `mapStyle` prop, built from the
1073
- * platform-agnostic style endpoint plus the configured API key. The key comes
1074
- * from core's module state (`setYarrowApiKey`) — `YarrowMapView` calls it for
1075
- * you; standalone callers must set it first.
1076
- */
1077
- function buildStyleUrl(styleType, theme = "light") {
1078
- const endpoint = buildStyleEndpoint(normalizeStyleType(styleType), theme);
1079
- return addApiKeyToUrl(`${YARROW_MAP_URL}${endpoint}`);
1080
- }
1081
-
1082
- // src/maps/YarrowMapView.tsx
1083
- const assignRef = (ref, instance) => {
1084
- if (typeof ref === "function") ref(instance);
1085
- else if (ref) ref.current = instance;
1086
- };
1087
- /**
1088
- * React Native Yarrow map. Renders MapLibre Native with a Yarrow style URL
1089
- * (theme + styleType aware, API key attached) and a default camera, and
1090
- * provides the runtime (refs, icon registry, camera/event subscriptions) to
1091
- * the SDK layers rendered inside it.
1092
- *
1093
- * ```tsx
1094
- * const mapRef = useRef<MapRef>(null);
1095
- * <YarrowMapView
1096
- * apiKey="YOUR_API_KEY"
1097
- * center={[69.2401, 41.2995]} // Tashkent
1098
- * zoom={12}
1099
- * theme="dark"
1100
- * onReady={(map) => map.getCenter().then(console.log)}
1101
- * />
1102
- * ```
1103
- *
1104
- * Camera props (`center`, `zoom`) apply only on mount — recenter through
1105
- * `cameraRef` (`flyTo`, `jumpTo`, `fitBounds`). Theme and styleType changes
1106
- * hot-swap the style URL natively.
1107
- */
1108
- const YarrowMapView = forwardRef(({ apiKey, center, zoom, minZoom, maxZoom, theme, styleType, onReady, onLoadError, onPress, onMoveEnd, cameraRef, attribution = true, logo = true, compass = true, dauTracking = true, icons = true, style, children }, ref) => {
1109
- const config = useMemo(() => new YarrowMapConfig({
1110
- apiKey,
1111
- center,
1112
- zoom,
1113
- minZoom,
1114
- maxZoom,
1115
- theme,
1116
- styleType
1117
- }), [
1118
- apiKey,
1119
- center,
1120
- zoom,
1121
- minZoom,
1122
- maxZoom,
1123
- theme,
1124
- styleType
1125
- ]);
1126
- const readyRef = useRef(onReady);
1127
- readyRef.current = onReady;
1128
- const dauTrackedRef = useRef(false);
1129
- const mapRef = useRef(null);
1130
- const internalCameraRef = useRef(null);
1131
- const highlightedPoiIds = useRef(/* @__PURE__ */ new Set());
1132
- const [iconsByName, setIconsByName] = useState({});
1133
- const iconsFetchAttemptedRef = useRef(false);
1134
- useEffect(() => {
1135
- iconsFetchAttemptedRef.current = false;
1136
- if (!icons) {
1137
- setIconsByName({});
1138
- return;
1139
- }
1140
- let cancelled = false;
1141
- fetchYarrowIcons(config.apiKey).then((map) => {
1142
- if (!cancelled) {
1143
- iconsFetchAttemptedRef.current = true;
1144
- setIconsByName(map);
1145
- }
1146
- }).catch((error) => {
1147
- console.warn("[YarrowMap] icon registry fetch failed:", error);
1148
- });
1149
- return () => {
1150
- cancelled = true;
1151
- };
1152
- }, [config.apiKey, icons]);
1153
- const handleMissingIcon = useCallback(() => {
1154
- if (!icons || iconsFetchAttemptedRef.current) return;
1155
- iconsFetchAttemptedRef.current = true;
1156
- fetchYarrowIcons(config.apiKey).then(setIconsByName).catch(() => {
1157
- iconsFetchAttemptedRef.current = false;
1158
- });
1159
- }, [config.apiKey, icons]);
1160
- const regionListeners = useRef(/* @__PURE__ */ new Set());
1161
- const pressListeners = useRef(/* @__PURE__ */ new Set());
1162
- const onMoveEndRef = useRef(onMoveEnd);
1163
- onMoveEndRef.current = onMoveEnd;
1164
- const onPressRef = useRef(onPress);
1165
- onPressRef.current = onPress;
1166
- const subscribeRegionChange = useCallback((listener) => {
1167
- regionListeners.current.add(listener);
1168
- return () => {
1169
- regionListeners.current.delete(listener);
1170
- };
1171
- }, []);
1172
- const subscribePress = useCallback((listener) => {
1173
- pressListeners.current.add(listener);
1174
- return () => {
1175
- pressListeners.current.delete(listener);
1176
- };
1177
- }, []);
1178
- const handleRegionDidChange = useCallback((event) => {
1179
- const { center: lngLat, zoom: eventZoom } = event.nativeEvent;
1180
- const [lng, lat] = lngLat;
1181
- for (const listener of regionListeners.current) listener({
1182
- center: [lng, lat],
1183
- zoom: eventZoom
1184
- });
1185
- onMoveEndRef.current?.(lat, lng, eventZoom);
1186
- }, []);
1187
- const handleMapPress = useCallback((event) => {
1188
- const lngLat = event.nativeEvent?.lngLat;
1189
- const point = event.nativeEvent?.point;
1190
- if (lngLat && point) {
1191
- const press = {
1192
- lngLat: [lngLat[0], lngLat[1]],
1193
- point: [point[0], point[1]]
1194
- };
1195
- for (const listener of pressListeners.current) listener(press);
1196
- }
1197
- onPressRef.current?.(event);
1198
- }, []);
1199
- const mapStyle = useMemo(() => {
1200
- setYarrowApiKey(config.apiKey);
1201
- return buildStyleUrl(config.styleType, config.theme);
1202
- }, [config]);
1203
- const handleDidFinishLoadingMap = useCallback(() => {
1204
- if (dauTracking && !dauTrackedRef.current) {
1205
- dauTrackedRef.current = true;
1206
- trackDau(config.apiKey, "react-native");
1207
- }
1208
- const map = mapRef.current;
1209
- if (map) readyRef.current?.(map);
1210
- }, [config.apiKey, dauTracking]);
1211
- const handleDidFailLoadingMap = useCallback(() => {
1212
- onLoadError?.(/* @__PURE__ */ new Error("Yarrow map failed to load — check the API key/network."));
1213
- }, [onLoadError]);
1214
- const runtime = useMemo(() => ({
1215
- apiKey: config.apiKey,
1216
- theme: config.theme,
1217
- mapRef,
1218
- cameraRef: internalCameraRef,
1219
- iconsByName,
1220
- highlightedPoiIds,
1221
- subscribeRegionChange,
1222
- subscribePress
1223
- }), [
1224
- config.apiKey,
1225
- config.theme,
1226
- iconsByName,
1227
- subscribeRegionChange,
1228
- subscribePress
1229
- ]);
1230
- return /* @__PURE__ */ jsx(YarrowMapContext.Provider, {
1231
- value: runtime,
1232
- children: /* @__PURE__ */ jsxs(Map$1, {
1233
- ref: (instance) => {
1234
- mapRef.current = instance;
1235
- assignRef(ref, instance);
1236
- },
1237
- mapStyle,
1238
- style,
1239
- attribution,
1240
- logo,
1241
- compass,
1242
- onPress: handleMapPress,
1243
- onRegionDidChange: handleRegionDidChange,
1244
- onDidFinishLoadingMap: handleDidFinishLoadingMap,
1245
- onDidFailLoadingMap: handleDidFailLoadingMap,
1246
- children: [
1247
- /* @__PURE__ */ jsx(Camera, {
1248
- ref: (instance) => {
1249
- internalCameraRef.current = instance;
1250
- assignRef(cameraRef, instance);
1251
- },
1252
- initialViewState: {
1253
- center: config.center,
1254
- zoom: config.zoom
1255
- },
1256
- minZoom: config.minZoom,
1257
- maxZoom: config.maxZoom
1258
- }),
1259
- icons ? /* @__PURE__ */ jsx(YarrowImages, {
1260
- iconsByName,
1261
- onMissingIcon: handleMissingIcon
1262
- }) : null,
1263
- children
1264
- ]
1265
- })
1266
- });
1267
- });
1268
-
1269
- // src/markers/HighlightMarkerView.tsx
1270
- const ENTER_MS = 280;
1271
- const EXIT_MS = 200;
1272
- const DEFAULT_ICON_SIZE = 56;
1273
- /**
1274
- * The animated icon+label marker shared by `<PoiHighlightLayer>` and
1275
- * `<SearchResultsLayer>` — the native counterpart of the web SDK's
1276
- * `createMarkerElement` + enter/exit CSS transitions. The scale/fade runs on
1277
- * an inner view (never on the `Marker` itself, which the map repositions
1278
- * every frame).
1279
- */
1280
- const HighlightMarkerView = memo(function HighlightMarkerView({ lngLat, iconUrl, title, iconSize, leaving = false, onPress }) {
1281
- const progress = useRef(new Animated.Value(0)).current;
1282
- useEffect(() => {
1283
- Animated.timing(progress, {
1284
- toValue: leaving ? 0 : 1,
1285
- duration: leaving ? EXIT_MS : ENTER_MS,
1286
- useNativeDriver: true
1287
- }).start();
1288
- }, [progress, leaving]);
1289
- const [width, height] = iconSize ? Array.isArray(iconSize) ? iconSize : [iconSize, iconSize] : [DEFAULT_ICON_SIZE, DEFAULT_ICON_SIZE];
1290
- return /* @__PURE__ */ jsx(Marker, {
1291
- lngLat,
1292
- anchor: "center",
1293
- onPress: onPress ? () => onPress() : void 0,
1294
- children: /* @__PURE__ */ jsxs(Animated.View, {
1295
- style: [styles.inner, {
1296
- transform: [{ scale: progress }],
1297
- opacity: progress
1298
- }],
1299
- children: [iconUrl ? /* @__PURE__ */ jsx(Image, {
1300
- source: { uri: iconUrl },
1301
- style: {
1302
- width,
1303
- height
1304
- },
1305
- resizeMode: "contain"
1306
- }) : /* @__PURE__ */ jsx(View, { style: styles.dot }), title ? /* @__PURE__ */ jsx(View, {
1307
- style: styles.titleWrap,
1308
- pointerEvents: "none",
1309
- children: /* @__PURE__ */ jsx(Text, {
1310
- style: styles.title,
1311
- children: title
1312
- })
1313
- }) : null]
1314
- })
1315
- });
1316
- });
1317
- const styles = StyleSheet.create({
1318
- inner: {
1319
- alignItems: "center",
1320
- opacity: 0
1321
- },
1322
- dot: {
1323
- width: 18,
1324
- height: 18,
1325
- borderRadius: 9,
1326
- backgroundColor: "#2f80ed",
1327
- borderWidth: 3,
1328
- borderColor: "#ffffff"
1329
- },
1330
- titleWrap: {
1331
- position: "absolute",
1332
- top: "100%",
1333
- width: "100%",
1334
- alignItems: "center"
1335
- },
1336
- title: {
1337
- marginTop: 3,
1338
- maxWidth: 200,
1339
- fontSize: 15,
1340
- lineHeight: 18,
1341
- fontWeight: "600",
1342
- color: "#1a1a1a",
1343
- textAlign: "center",
1344
- textShadowColor: "#ffffff",
1345
- textShadowRadius: 3,
1346
- textShadowOffset: {
1347
- width: 0,
1348
- height: 0
1349
- }
1350
- }
1351
- });
1352
-
1353
- // src/markers/YarrowMarker.tsx
1354
- /**
1355
- * Declarative counterpart of the web SDK's `addMarker()` / `removeMarker()`.
1356
- * Mounting places the marker, unmounting removes it; the React lifecycle
1357
- * replaces the imperative manager pair.
1358
- *
1359
- * ```tsx
1360
- * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
1361
- * <YarrowMarker lngLat={[69.2401, 41.2995]} onPress={() => …}>
1362
- * <PinIcon />
1363
- * </YarrowMarker>
1364
- * </YarrowMapView>
1365
- * ```
1366
- */
1367
- const YarrowMarker = memo(function YarrowMarker({ lngLat, anchor = "bottom", offset, onPress, children }) {
1368
- return /* @__PURE__ */ jsx(Marker, {
1369
- lngLat,
1370
- anchor,
1371
- offset,
1372
- onPress: onPress ? () => onPress() : void 0,
1373
- children
1374
- });
1375
- });
1376
-
1377
- // src/navigation/useYarrowCamera.ts
1378
- const MIN_DIMENSION_DEGREES = .003;
1379
- const DEFAULT_PADDING = 50;
1380
- const DEFAULT_DURATION_MS = 1e3;
1381
- /**
1382
- * Web-parity camera helpers on top of a `CameraRef`. Reads the enclosing
1383
- * `<YarrowMapView>` camera when called inside the map; otherwise pass a ref:
1384
- *
1385
- * ```tsx
1386
- * const cameraRef = useRef<CameraRef>(null);
1387
- * <YarrowMapView apiKey={KEY} cameraRef={cameraRef}>…</YarrowMapView>
1388
- * const camera = useYarrowCamera(cameraRef);
1389
- * camera.zoomTo(41.2995, 69.2401, 14);
1390
- * ```
1391
- */
1392
- function useYarrowCamera(cameraRefInput) {
1393
- const runtime = useYarrowMapRuntime();
1394
- const cameraRef = cameraRefInput ?? runtime?.cameraRef ?? null;
1395
- return useMemo(() => {
1396
- const getCamera = () => cameraRef?.current ?? null;
1397
- return {
1398
- zoomTo(lat, lng, zoom, options) {
1399
- const camera = getCamera();
1400
- if (!camera) return;
1401
- camera.flyTo({
1402
- center: [lng, lat],
1403
- zoom,
1404
- ...options?.duration !== void 0 ? { duration: options.duration } : {}
1405
- });
1406
- },
1407
- fitBounds(data, options) {
1408
- const camera = getCamera();
1409
- if (!camera) return;
1410
- const box = getBoundingBox(data);
1411
- const padding = options?.padding ?? DEFAULT_PADDING;
1412
- const duration = options?.duration ?? DEFAULT_DURATION_MS;
1413
- if (Math.abs(box.xMax - box.xMin) < MIN_DIMENSION_DEGREES) {
1414
- box.xMin -= MIN_DIMENSION_DEGREES / 2;
1415
- box.xMax += MIN_DIMENSION_DEGREES / 2;
1416
- }
1417
- if (Math.abs(box.yMax - box.yMin) < MIN_DIMENSION_DEGREES) {
1418
- box.yMin -= MIN_DIMENSION_DEGREES / 2;
1419
- box.yMax += MIN_DIMENSION_DEGREES / 2;
1420
- }
1421
- camera.fitBounds([
1422
- box.xMin,
1423
- box.yMin,
1424
- box.xMax,
1425
- box.yMax
1426
- ], {
1427
- padding: {
1428
- top: padding,
1429
- right: padding,
1430
- bottom: padding,
1431
- left: padding
1432
- },
1433
- duration
1434
- });
1435
- },
1436
- getBoundingBox(data) {
1437
- return getBoundingBox(data);
1438
- }
1439
- };
1440
- }, [cameraRef]);
1441
- }
1442
-
1443
- // src/offline/estimate.ts
1444
- /**
1445
- * Web-Mercator latitude limit — tiles outside it don't exist.
1446
- */
1447
- const MAX_LAT = 85.05112878;
1448
- /**
1449
- * Rough bytes per downloaded `z/x/y` tile, empirically measured from a
1450
- * Tashkent z14 tile: ≈64 KB × ~8 sources carrying data ≈ 0.5 MB. A region's
1451
- * true size depends on the style's source count and local data density —
1452
- * pass `avgTileBytes` for a tighter estimate.
1453
- */
1454
- const AVG_TILE_BYTES = 5e5;
1455
- /**
1456
- * Bounds must not cross the antimeridian — `west < east` strictly. Regions
1457
- * spanning ±180° need two downloads or a shifted projection.
1458
- */
1459
- const validateBounds = (bounds) => {
1460
- if (!Array.isArray(bounds) || bounds.length !== 4 || !bounds.every((value) => typeof value === "number" && Number.isFinite(value))) throw new Error("bounds must be [west, south, east, north] with four finite numbers");
1461
- const [west, south, east, north] = bounds;
1462
- if (west < -180 || west > 180 || east < -180 || east > 180) throw new Error("bounds longitudes must be within [-180, 180]");
1463
- if (south < -85.05112878 || south > MAX_LAT || north < -85.05112878 || north > MAX_LAT) throw new Error(`bounds latitudes must be within [-85.05112878, ${MAX_LAT}]`);
1464
- if (west >= east) throw new Error("bounds west longitude must be less than east");
1465
- if (south >= north) throw new Error("bounds south latitude must be less than north");
1466
- };
1467
- const validateZoomRange = (minZoom, maxZoom) => {
1468
- if (!Number.isFinite(minZoom) || !Number.isFinite(maxZoom) || minZoom < 0 || maxZoom > 22 || minZoom > maxZoom) throw new Error("zoom range must satisfy 0 <= minZoom <= maxZoom <= 22");
1469
- };
1470
- const lngToWorldX = (lng, zoom) => {
1471
- return (Math.min(180, Math.max(-180, lng)) + 180) / 360 * 2 ** zoom;
1472
- };
1473
- const latToWorldY = (lat, zoom) => {
1474
- const radians = Math.min(MAX_LAT, Math.max(-85.05112878, lat)) * Math.PI / 180;
1475
- return (1 - Math.log(Math.tan(radians) + 1 / Math.cos(radians)) / Math.PI) / 2 * 2 ** zoom;
1476
- };
1477
- /** Unique `z/x/y` tiles covering the bounds at one zoom level. */
1478
- const countTilesAtZoom = (bounds, zoom) => {
1479
- const [west, south, east, north] = bounds;
1480
- const maxTile = 2 ** zoom - 1;
1481
- const clamp = (index) => Math.min(maxTile, Math.max(0, index));
1482
- const x0 = clamp(Math.floor(lngToWorldX(west, zoom)));
1483
- const x1 = clamp(Math.floor(lngToWorldX(east, zoom)));
1484
- const y0 = clamp(Math.floor(latToWorldY(north, zoom)));
1485
- const y1 = clamp(Math.floor(latToWorldY(south, zoom)));
1486
- return (x1 - x0 + 1) * (y1 - y0 + 1);
1487
- };
1488
- /**
1489
- * Estimates the download/storage cost of an offline region — pure tile math,
1490
- * no native calls. Tile counts are exact for the XYZ scheme; byte estimates
1491
- * are rough (see `AVG_TILE_BYTES`).
1492
- *
1493
- * ```ts
1494
- * const { tileCount, estSizeBytes } = estimateRegion({
1495
- * bounds: [69.15, 41.2, 69.4, 41.4], // Tashkent
1496
- * minZoom: 8,
1497
- * maxZoom: 15,
1498
- * });
1499
- * ```
1500
- */
1501
- const estimateRegion = (input) => {
1502
- validateBounds(input.bounds);
1503
- const { bounds, avgTileBytes = AVG_TILE_BYTES, minZoom, maxZoom } = input;
1504
- validateZoomRange(minZoom, maxZoom);
1505
- const tilesPerLevel = [];
1506
- let tileCount = 0;
1507
- for (let zoom = Math.floor(minZoom); zoom <= Math.ceil(maxZoom); zoom++) {
1508
- const tiles = countTilesAtZoom(bounds, zoom);
1509
- tilesPerLevel.push({
1510
- zoom,
1511
- tiles
1512
- });
1513
- tileCount += tiles;
1514
- }
1515
- return {
1516
- tileCount,
1517
- estSizeBytes: tileCount * avgTileBytes,
1518
- tilesPerLevel
1519
- };
1520
- };
1521
-
1522
- // src/offline/types.ts
1523
- /** Default minimum zoom for offline regions. */
1524
- const DEFAULT_OFFLINE_MIN_ZOOM = 8;
1525
- /** Default maximum zoom for offline regions. */
1526
- const DEFAULT_OFFLINE_MAX_ZOOM = 15;
1527
- /** Schema version of the pack metadata this SDK writes. */
1528
- const OFFLINE_METADATA_VERSION = 1;
1529
-
1530
- // src/offline/manager.ts
1531
- const DAY_MS = MILLISECONDS_PER_DAY;
1532
- const stripId = (status) => {
1533
- const { id: _id, ...progress } = status;
1534
- return progress;
1535
- };
1536
- /** Reads pack status, treating bridge-level absence (Android resolves null
1537
- * for unknown ids — e.g. after `resetDatabase` without an app restart) as
1538
- * `null` instead of a crash. */
1539
- const statusOrNull = async (pack) => {
1540
- try {
1541
- return await pack.status() ?? null;
1542
- } catch {
1543
- return null;
1544
- }
1545
- };
1546
- const notFoundError = (name, regionId) => {
1547
- const error = /* @__PURE__ */ new Error(`Offline region "${name}" is no longer available natively — resetDatabase() requires an app restart to clear the JS cache.`);
1548
- error.code = "not-found";
1549
- error.regionId = regionId;
1550
- return error;
1551
- };
1552
- const asYarrowMetadata = (pack) => {
1553
- const meta = pack.metadata;
1554
- if (!meta || meta.v !== 1 || typeof meta.name !== "string") return null;
1555
- return meta;
1556
- };
1557
- const classifyError = (raw, regionId) => {
1558
- const message = raw instanceof Error ? raw.message : typeof raw === "string" ? raw : "Unknown offline error";
1559
- let code = "unknown";
1560
- if (/tile (count )?limit|tile limit exceeded/i.test(message)) code = "tile-count-limit-exceeded";
1561
- else if (/too large|region exceeds/i.test(message)) code = "region-too-large";
1562
- else if (/disk|storage|space/i.test(message)) code = "disk";
1563
- else if (/not\s*found/i.test(message)) code = "not-found";
1564
- else if (/network|connection|offline|unreachable|timeout|resolve|host/i.test(message)) code = "network";
1565
- const error = new Error(message);
1566
- error.code = code;
1567
- if (regionId) error.regionId = regionId;
1568
- return error;
1569
- };
1570
- /**
1571
- * Offline region manager for React Native — a Yarrow-flavoured wrapper around
1572
- * MapLibre React Native's `OfflineManager`.
1573
- *
1574
- * The web SDK's `yarrowcache` protocol cannot exist on native (no
1575
- * `addProtocol`), so offline support here is region packs: pick a bounding
1576
- * box and zoom range, download it once, and the map renders from the native
1577
- * offline database with no network.
1578
- *
1579
- * ```ts
1580
- * const offline = new YarrowOfflineManager({ apiKey: 'YOUR_API_KEY' });
1581
- * const { tileCount, estSizeBytes } = offline.estimateRegion({
1582
- * bounds: [69.15, 41.2, 69.4, 41.4], // Tashkent
1583
- * minZoom: 8,
1584
- * maxZoom: 15,
1585
- * });
1586
- * const region = await offline.downloadRegion({
1587
- * name: 'tashkent-city',
1588
- * bounds: [69.15, 41.2, 69.4, 41.4],
1589
- * maxAgeDays: 30,
1590
- * onProgress: (p) => console.log(`${p.percentage}%`),
1591
- * });
1592
- * await region.done;
1593
- * ```
1594
- */
1595
- var YarrowOfflineManager = class {
1596
- constructor(options) {
1597
- this.activeDownloads = /* @__PURE__ */ new Map();
1598
- if (!options.apiKey) throw new Error("apiKey is required");
1599
- this.apiKey = options.apiKey;
1600
- setYarrowApiKey(this.apiKey);
1601
- }
1602
- /**
1603
- * Pure tile-math estimate of a region's download/storage cost — no native
1604
- * calls. See `estimateRegion` for the math and caveats.
1605
- */
1606
- estimateRegion(input) {
1607
- return estimateRegion(input);
1608
- }
1609
- /**
1610
- * Starts (or resumes) a region download. Resolves with a handle once the
1611
- * pack is created and downloading — progress arrives via `options.onProgress`
1612
- * and `handle.done` settles with the outcome.
1613
- *
1614
- * Idempotent by `name`: an existing matching region is returned as-is
1615
- * (resumed when incomplete); a name reused with different parameters throws
1616
- * a `params-mismatch` error. Pass `force: true` to delete and re-download.
1617
- */
1618
- async downloadRegion(options) {
1619
- const name = options.name?.trim();
1620
- if (!name) throw new Error("name is required");
1621
- const bounds = options.bounds;
1622
- validateBounds(bounds);
1623
- const minZoom = options.minZoom ?? 8;
1624
- const maxZoom = options.maxZoom ?? 15;
1625
- validateZoomRange(minZoom, maxZoom);
1626
- const styleType = normalizeStyleType(options.styleType);
1627
- const theme = options.theme === "dark" ? "dark" : "light";
1628
- await this.hydrate();
1629
- const existing = await this.findRegionPacks(name);
1630
- const target = existing.find((pack) => pack.meta.styleType === styleType && pack.meta.theme === theme);
1631
- if (target && !options.force) {
1632
- const mismatches = this.findParamMismatches(target.meta, {
1633
- bounds,
1634
- minZoom,
1635
- maxZoom,
1636
- maxAgeDays: options.maxAgeDays ?? null
1637
- });
1638
- if (mismatches.length > 0) {
1639
- const error = /* @__PURE__ */ new Error(`Region "${name}" already exists with different ${mismatches.join(", ")}. Use a different name or pass force: true to re-download.`);
1640
- error.code = "params-mismatch";
1641
- error.regionId = target.pack.id;
1642
- throw error;
1643
- }
1644
- return this.reattachExisting(target, { resumeIfIncomplete: true });
1645
- }
1646
- if (existing.length > 0 && !options.force) {
1647
- const styles = existing.map(({ meta }) => `${meta.styleType}/${meta.theme}`).join(", ");
1648
- const error = /* @__PURE__ */ new Error(`Region "${name}" is pinned to ${styles}. Use a different name or pass force: true to replace it.`);
1649
- error.code = "params-mismatch";
1650
- throw error;
1651
- }
1652
- for (const { pack } of existing) await this.deletePack(pack.id);
1653
- setYarrowApiKey(this.apiKey);
1654
- const metadata = {
1655
- v: 1,
1656
- name,
1657
- styleType,
1658
- theme,
1659
- bounds,
1660
- minZoom,
1661
- maxZoom,
1662
- maxAgeDays: options.maxAgeDays ?? null,
1663
- createdAt: Date.now(),
1664
- ...options.metadata ? { user: options.metadata } : {}
1665
- };
1666
- let settle = () => {};
1667
- const done = new Promise((resolve, reject) => {
1668
- settle = ({ progress, error }) => {
1669
- if (error) reject(error);
1670
- else if (progress) resolve(progress);
1671
- };
1672
- });
1673
- const routeProgress = (_pack, status) => {
1674
- const progress = stripId(status);
1675
- if (status.state === "complete") {
1676
- this.activeDownloads.delete(_pack.id);
1677
- settle({ progress });
1678
- } else options.onProgress?.(progress);
1679
- };
1680
- const routeError = (_pack, raw) => {
1681
- this.activeDownloads.delete(_pack.id);
1682
- const error = classifyError(raw.message, _pack.id);
1683
- options.onError?.(error);
1684
- settle({ error });
1685
- };
1686
- try {
1687
- const pack = await OfflineManager.createPack({
1688
- mapStyle: buildStyleUrl(styleType, theme),
1689
- bounds,
1690
- minZoom,
1691
- maxZoom,
1692
- metadata
1693
- }, routeProgress, routeError);
1694
- this.activeDownloads.set(pack.id, { done });
1695
- const status = await statusOrNull(pack);
1696
- if (status?.state === "complete") {
1697
- OfflineManager.removeListener(pack.id);
1698
- this.activeDownloads.delete(pack.id);
1699
- settle({ progress: stripId(status) });
1700
- }
1701
- return this.toHandle(pack, metadata, done);
1702
- } catch (caught) {
1703
- throw classifyError(caught);
1704
- }
1705
- }
1706
- /** Lists regions created through this SDK (native packs created directly
1707
- * against `OfflineManager` are not included), newest first. */
1708
- async listRegions() {
1709
- const packs = await OfflineManager.getPacks();
1710
- const summaries = [];
1711
- for (const pack of packs) {
1712
- const meta = asYarrowMetadata(pack);
1713
- if (!meta) continue;
1714
- const status = await statusOrNull(pack);
1715
- if (!status) continue;
1716
- summaries.push({
1717
- id: pack.id,
1718
- name: meta.name,
1719
- styleType: meta.styleType,
1720
- theme: meta.theme,
1721
- bounds: meta.bounds,
1722
- minZoom: meta.minZoom,
1723
- maxZoom: meta.maxZoom,
1724
- status: status.state,
1725
- percentage: status.percentage,
1726
- completedTileSize: status.completedTileSize,
1727
- userMetadata: meta.user,
1728
- isStale: meta.maxAgeDays !== null && Date.now() - meta.createdAt > meta.maxAgeDays * DAY_MS,
1729
- createdAt: meta.createdAt
1730
- });
1731
- }
1732
- return summaries.sort((a, b) => b.createdAt - a.createdAt);
1733
- }
1734
- /** Returns the handle for a region by name, or `null`. */
1735
- async getRegion(name) {
1736
- const entry = (await this.findRegionPacks(name.trim()))[0];
1737
- if (!entry) return null;
1738
- return this.reattachExisting(entry);
1739
- }
1740
- /** Ambient cache (seen-tiles LRU) max size in bytes. May erase resources
1741
- * when shrinking — call once at app startup. `0` disables the cache. */
1742
- async setAmbientCacheSize(size) {
1743
- await OfflineManager.setMaximumAmbientCacheSize(size);
1744
- }
1745
- /** Revalidates ambient-cache tiles against the server — the recommended
1746
- * way to refresh cached data. */
1747
- async invalidateAmbientCache() {
1748
- await OfflineManager.invalidateAmbientCache();
1749
- }
1750
- /** Erases ambient-cache resources. Computationally expensive. */
1751
- async clearAmbientCache() {
1752
- await OfflineManager.clearAmbientCache();
1753
- }
1754
- /** Maximum number of tiles offline packs may store. Raise it when large
1755
- * regions fail with a `tile-count-limit-exceeded` error. */
1756
- setTileCountLimit(limit) {
1757
- OfflineManager.setTileCountLimit(limit);
1758
- }
1759
- /** Download status event throttle in ms. Platform-defined default (300 ms
1760
- * today on both iOS and Android). Note errors bypass the throttle. */
1761
- setProgressEventThrottle(ms) {
1762
- OfflineManager.setProgressEventThrottle(ms);
1763
- }
1764
- /** Deletes the offline database (ambient cache + packs), then
1765
- * reinitializes it. Destructive — and MLRN's JS pack cache only clears
1766
- * on app restart, so subsequent reads may hit stale ids (guarded as
1767
- * `not-found`). Prefer per-region `invalidate`/`delete`. */
1768
- async resetDatabase() {
1769
- await OfflineManager.resetDatabase();
1770
- }
1771
- async hydrate() {
1772
- await OfflineManager.getPacks();
1773
- }
1774
- async findRegionPacks(name) {
1775
- return (await OfflineManager.getPacks()).map((pack) => ({
1776
- pack,
1777
- meta: asYarrowMetadata(pack)
1778
- })).filter((entry) => entry.meta !== null && entry.meta.name === name);
1779
- }
1780
- findParamMismatches(meta, params) {
1781
- const mismatches = [];
1782
- if (!(meta.bounds.length === params.bounds.length && meta.bounds.every((value, index) => value === params.bounds[index]))) mismatches.push("bounds");
1783
- if (meta.minZoom !== params.minZoom) mismatches.push("minZoom");
1784
- if (meta.maxZoom !== params.maxZoom) mismatches.push("maxZoom");
1785
- if (meta.maxAgeDays !== params.maxAgeDays) mismatches.push("maxAgeDays");
1786
- return mismatches;
1787
- }
1788
- /** Attaches listeners to a pack that may have outlived the JS layer
1789
- * (created in a previous app session) and builds a fresh handle.
1790
- *
1791
- * Deliberately cautious: it never hijacks a download this session owns,
1792
- * never attaches listeners to packs that don't need them, and — on
1793
- * Android, where attaching an observer *activates* the region — never
1794
- * wakes a paused pack unless the caller explicitly asked for a download. */
1795
- async reattachExisting(entry, { resumeIfIncomplete = false } = {}) {
1796
- const { pack, meta } = entry;
1797
- const known = this.activeDownloads.get(pack.id);
1798
- if (known) return this.toHandle(pack, meta, known.done);
1799
- const status = await statusOrNull(pack);
1800
- if (!status) throw notFoundError(meta.name, pack.id);
1801
- if (status.state === "complete") return this.toHandle(pack, meta, Promise.resolve(stripId(status)));
1802
- let settle = () => {};
1803
- const done = new Promise((resolve, reject) => {
1804
- settle = ({ progress, error }) => {
1805
- if (error) reject(error);
1806
- else if (progress) resolve(progress);
1807
- };
1808
- });
1809
- const routeProgress = (_pack, progressEvent) => {
1810
- if (progressEvent.state === "complete") settle({ progress: stripId(progressEvent) });
1811
- };
1812
- const routeError = (_pack, raw) => {
1813
- settle({ error: classifyError(raw.message, pack.id) });
1814
- };
1815
- if (status.state === "active" || resumeIfIncomplete) {
1816
- OfflineManager.addListener(pack.id, routeProgress, routeError);
1817
- if (status.state !== "active") await pack.resume();
1818
- }
1819
- return this.toHandle(pack, meta, done);
1820
- }
1821
- toHandle(pack, meta, done) {
1822
- return {
1823
- id: pack.id,
1824
- name: meta.name,
1825
- done,
1826
- refreshStatus: async () => {
1827
- const status = await statusOrNull(pack);
1828
- if (!status) throw notFoundError(meta.name, pack.id);
1829
- return stripId(status);
1830
- },
1831
- pause: () => pack.pause(),
1832
- resume: () => pack.resume(),
1833
- invalidate: async () => {
1834
- await OfflineManager.invalidatePack(pack.id);
1835
- },
1836
- delete: async () => {
1837
- await this.deletePack(pack.id);
1838
- }
1839
- };
1840
- }
1841
- async deletePack(id) {
1842
- try {
1843
- await OfflineManager.deletePack(id);
1844
- } catch (caught) {
1845
- throw classifyError(caught, id);
1846
- } finally {
1847
- this.activeDownloads.delete(id);
1848
- }
1849
- }
1850
- };
1851
-
1852
- // src/offline/hook.ts
1853
- /**
1854
- * Offline region state for settings/offline screens — pairs with
1855
- * `YarrowOfflineManager`. Polls the native layer while downloads run, so
1856
- * `regions` (and progress bars) stay current.
1857
- *
1858
- * ```tsx
1859
- * const { regions, download, remove } = useYarrowOfflineRegions({ apiKey });
1860
- * await download({ name: 'tashkent', bounds: [69.15, 41.2, 69.4, 41.4] });
1861
- * ```
1862
- */
1863
- const useYarrowOfflineRegions = (options) => {
1864
- const { apiKey, pollMs = 1e3 } = options;
1865
- const [regions, setRegions] = useState([]);
1866
- const [isLoading, setIsLoading] = useState(true);
1867
- const [error, setError] = useState(null);
1868
- const managerRef = useRef(null);
1869
- const getManager = useCallback(() => {
1870
- const cached = managerRef.current;
1871
- if (cached && cached.key === apiKey) return cached.manager;
1872
- const manager = new YarrowOfflineManager({ apiKey });
1873
- managerRef.current = {
1874
- key: apiKey,
1875
- manager
1876
- };
1877
- return manager;
1878
- }, [apiKey]);
1879
- const recordError = useCallback((caught) => {
1880
- const error = caught instanceof Error ? caught : new Error(String(caught));
1881
- setError(error);
1882
- return error;
1883
- }, []);
1884
- const refresh = useCallback(async () => {
1885
- try {
1886
- setRegions(await getManager().listRegions());
1887
- setError(null);
1888
- } catch (caught) {
1889
- recordError(caught);
1890
- }
1891
- }, [getManager, recordError]);
1892
- useEffect(() => {
1893
- if (!apiKey) {
1894
- setIsLoading(false);
1895
- return;
1896
- }
1897
- let cancelled = false;
1898
- (async () => {
1899
- setIsLoading(true);
1900
- try {
1901
- const summaries = await getManager().listRegions();
1902
- if (!cancelled) {
1903
- setRegions(summaries);
1904
- setError(null);
1905
- }
1906
- } catch (caught) {
1907
- if (!cancelled) recordError(caught);
1908
- } finally {
1909
- if (!cancelled) setIsLoading(false);
1910
- }
1911
- })();
1912
- return () => {
1913
- cancelled = true;
1914
- };
1915
- }, [
1916
- apiKey,
1917
- getManager,
1918
- recordError
1919
- ]);
1920
- const hasActive = regions.some((region) => region.status === "active");
1921
- useEffect(() => {
1922
- if (!hasActive) return;
1923
- const timer = setInterval(() => {
1924
- refresh();
1925
- }, pollMs);
1926
- return () => clearInterval(timer);
1927
- }, [
1928
- hasActive,
1929
- pollMs,
1930
- refresh
1931
- ]);
1932
- const download = useCallback(async (downloadOptions) => {
1933
- try {
1934
- const handle = await getManager().downloadRegion(downloadOptions);
1935
- await refresh();
1936
- return handle;
1937
- } catch (caught) {
1938
- throw recordError(caught);
1939
- }
1940
- }, [
1941
- getManager,
1942
- recordError,
1943
- refresh
1944
- ]);
1945
- const withRegion = useCallback(async (name, run) => {
1946
- try {
1947
- const handle = await getManager().getRegion(name.trim());
1948
- if (!handle) {
1949
- const error = /* @__PURE__ */ new Error(`Offline region "${name}" not found`);
1950
- error.code = "not-found";
1951
- throw error;
1952
- }
1953
- await run(handle);
1954
- await refresh();
1955
- } catch (caught) {
1956
- throw recordError(caught);
1957
- }
1958
- }, [
1959
- getManager,
1960
- recordError,
1961
- refresh
1962
- ]);
1963
- return {
1964
- regions,
1965
- isLoading,
1966
- error,
1967
- refresh,
1968
- download,
1969
- pause: (name) => withRegion(name, (handle) => handle.pause()),
1970
- resume: (name) => withRegion(name, (handle) => handle.resume()),
1971
- invalidate: (name) => withRegion(name, (handle) => handle.invalidate()),
1972
- remove: (name) => withRegion(name, (handle) => handle.delete())
1973
- };
1974
- };
1975
-
1976
- // src/clustering/usePixelClusters.ts
1977
- const REGION_DEBOUNCE_MS = 120;
1978
- /**
1979
- * Clusters marker points by screen distance — the runtime counterpart of the
1980
- * web SDK's `PoiClusterController`. Native MapLibre can only cluster GeoJSON
1981
- * *sources*, not marker views, so this re-projects the points on every map
1982
- * move and regroups them: members of a group large enough (`minPoints`) are
1983
- * hidden and replaced by a single count badge.
1984
- *
1985
- * Recompute runs when the points/config change and (debounced) on every map
1986
- * move; badges are keyed by their first member id so React reuses them
1987
- * across recomputes instead of flickering.
1988
- */
1989
- function usePixelClusters(points, config, runtime) {
1990
- const normalized = useMemo(() => normalizeClusteringConfig(config), [config]);
1991
- const [clusters, setClusters] = useState([]);
1992
- const [clusteredIds, setClusteredIds] = useState(() => /* @__PURE__ */ new Set());
1993
- const debounceRef = useRef(null);
1994
- const runIdRef = useRef(0);
1995
- const pointsRef = useRef(points);
1996
- pointsRef.current = points;
1997
- const pointsKey = useMemo(() => points.map((p) => `${p.id}:${p.lng},${p.lat}`).join("|"), [points]);
1998
- useEffect(() => {
1999
- const mapRef = runtime?.mapRef;
2000
- if (!mapRef) {
2001
- setClusters([]);
2002
- setClusteredIds(/* @__PURE__ */ new Set());
2003
- return;
2004
- }
2005
- const recompute = async () => {
2006
- const map = mapRef.current;
2007
- const current = pointsRef.current;
2008
- if (!(normalized.enabled && map != null && current.length >= normalized.minPoints) || !map) {
2009
- runIdRef.current += 1;
2010
- setClusters([]);
2011
- setClusteredIds(/* @__PURE__ */ new Set());
2012
- return;
2013
- }
2014
- let zoom;
2015
- try {
2016
- zoom = await map.getZoom();
2017
- } catch {
2018
- return;
2019
- }
2020
- if (zoom > normalized.maxZoom) {
2021
- runIdRef.current += 1;
2022
- setClusters([]);
2023
- setClusteredIds(/* @__PURE__ */ new Set());
2024
- return;
2025
- }
2026
- const runId = ++runIdRef.current;
2027
- const projected = await Promise.all(current.map(async (point) => {
2028
- const pixel = await map.project([point.lng, point.lat]);
2029
- return {
2030
- point,
2031
- x: pixel[0],
2032
- y: pixel[1]
2033
- };
2034
- }));
2035
- if (runId !== runIdRef.current) return;
2036
- const nextClusters = [];
2037
- const nextIds = /* @__PURE__ */ new Set();
2038
- for (const group of groupByPixelRadius(projected, normalized.radius)) {
2039
- if (group.length < normalized.minPoints) continue;
2040
- const members = group.map((g) => g.point);
2041
- let sumLng = 0;
2042
- let sumLat = 0;
2043
- for (const m of members) {
2044
- sumLng += m.lng;
2045
- sumLat += m.lat;
2046
- nextIds.add(m.id);
2047
- }
2048
- nextClusters.push({
2049
- key: members[0]?.id ?? 0,
2050
- lng: sumLng / members.length,
2051
- lat: sumLat / members.length,
2052
- members: members.map((m) => ({
2053
- id: m.id,
2054
- lng: m.lng,
2055
- lat: m.lat
2056
- }))
2057
- });
2058
- }
2059
- setClusters(nextClusters);
2060
- setClusteredIds(nextIds);
2061
- };
2062
- recompute();
2063
- const unsubscribe = runtime.subscribeRegionChange(() => {
2064
- if (debounceRef.current) clearTimeout(debounceRef.current);
2065
- debounceRef.current = setTimeout(() => {
2066
- debounceRef.current = null;
2067
- recompute();
2068
- }, REGION_DEBOUNCE_MS);
2069
- });
2070
- return () => {
2071
- unsubscribe();
2072
- if (debounceRef.current) {
2073
- clearTimeout(debounceRef.current);
2074
- debounceRef.current = null;
2075
- }
2076
- };
2077
- }, [
2078
- runtime,
2079
- normalized,
2080
- pointsKey
2081
- ]);
2082
- return {
2083
- clusters,
2084
- clusteredIds
2085
- };
2086
- }
2087
-
2088
- // src/utils/useExitAnimation.ts
2089
- /**
2090
- * Duration of the marker exit animation: 200 ms of visible ease-out (web
2091
- * parity) plus a small buffer before the marker unmounts.
2092
- */
2093
- const EXIT_ANIMATION_MS = 220;
2094
- /**
2095
- * Tracks ids that left an "active" list so their exit animation can play
2096
- * before unmount — the declarative replacement of the web SDK's
2097
- * `animateOutMarker`. Returns the active ids unchanged and the ids that are
2098
- * currently animating out; a caller renders those with a `leaving` flag and
2099
- * keeps their last-resolved data until the animation finishes.
2100
- *
2101
- * Each removed id gets its own timer (per-id map, not one shared timeout), so
2102
- * removing A and then B within the window removes both when their own timers
2103
- * fire, and an id that comes back before its timer fires stops leaving
2104
- * immediately.
2105
- */
2106
- function useExitAnimation(ids, exitMs = 220) {
2107
- const [leavingIds, setLeavingIds] = useState([]);
2108
- const prevRef = useRef(ids);
2109
- const timersRef = useRef(/* @__PURE__ */ new Map());
2110
- useEffect(() => {
2111
- const prevSet = new Set(prevRef.current);
2112
- prevRef.current = ids;
2113
- const activeSet = new Set(ids);
2114
- for (const id of activeSet) {
2115
- const timer = timersRef.current.get(id);
2116
- if (timer !== void 0) {
2117
- clearTimeout(timer);
2118
- timersRef.current.delete(id);
2119
- }
2120
- }
2121
- for (const id of prevSet) {
2122
- if (activeSet.has(id) || timersRef.current.has(id)) continue;
2123
- timersRef.current.set(id, setTimeout(() => {
2124
- timersRef.current.delete(id);
2125
- setLeavingIds((current) => {
2126
- if (!current.includes(id)) return current;
2127
- return current.filter((x) => x !== id);
2128
- });
2129
- }, exitMs));
2130
- }
2131
- setLeavingIds((current) => {
2132
- const pending = [...timersRef.current.keys()];
2133
- if (pending.length === current.length) {
2134
- const currentSet = new Set(current);
2135
- if (pending.every((id) => currentSet.has(id))) return current;
2136
- }
2137
- return pending;
2138
- });
2139
- }, [ids, exitMs]);
2140
- useEffect(() => {
2141
- const timers = timersRef.current;
2142
- return () => {
2143
- for (const timer of timers.values()) clearTimeout(timer);
2144
- timers.clear();
2145
- };
2146
- }, []);
2147
- const activeSet = useMemo(() => new Set(ids), [ids]);
2148
- return {
2149
- activeIds: ids,
2150
- leavingIds: useMemo(() => leavingIds.filter((id) => !activeSet.has(id)), [leavingIds, activeSet])
2151
- };
2152
- }
2153
-
2154
- // src/poiHighlight/PoiHighlightLayer.tsx
2155
- const DEFAULT_PAN_ZOOM = 13;
2156
- /** Milliseconds after an exit before an id's resolved data is pruned. */
2157
- const EXIT_PRUNE_MS = 250;
2158
- /**
2159
- * Declarative counterpart of the web SDK's `highlightPOI()`: renders an
2160
- * animated icon+label marker for each highlighted POI id, resolving each id
2161
- * cheapest-first (caller data → rendered tiles → place-detail API).
2162
- * Highlight state is owned by the `ids` prop (or
2163
- * `useYarrowPoiHighlight().highlightedIds`); removing an id plays the exit
2164
- * animation and unmounts the marker.
2165
- *
2166
- * Known native limitation (documented in the README): the base style's own
2167
- * POI icon is not hidden behind the highlight marker — native has no runtime
2168
- * `setFilter`, so the marker simply draws on top of it.
2169
- *
2170
- * ```tsx
2171
- * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
2172
- * <PoiHighlightLayer ids={[123]} dataById={{ 123: { location } }} panTo />
2173
- * </YarrowMapView>
2174
- * ```
2175
- */
2176
- function PoiHighlightLayer({ ids, dataById, iconSize, panTo = false, zoom, clustering, onHighlightPress, onResolveError }) {
2177
- const runtime = useYarrowMapRuntime();
2178
- const camera = useYarrowCamera();
2179
- const idList = useMemo(() => {
2180
- return [...new Set(Array.isArray(ids) ? ids : [ids])];
2181
- }, [ids]);
2182
- const { activeIds, leavingIds } = useExitAnimation(idList);
2183
- const [resolved, setResolved] = useState({});
2184
- const resolveCacheRef = useRef(/* @__PURE__ */ new Map());
2185
- const failedIdsRef = useRef(/* @__PURE__ */ new Set());
2186
- const dataByIdRef = useRef(dataById);
2187
- dataByIdRef.current = dataById;
2188
- const onResolveErrorRef = useRef(onResolveError);
2189
- onResolveErrorRef.current = onResolveError;
2190
- const resolveOnce = useMemo(() => (id) => {
2191
- if (!runtime) return Promise.resolve(null);
2192
- const pending = resolveCacheRef.current.get(id);
2193
- if (pending) return pending;
2194
- const promise = resolvePoiData(id, dataByIdRef.current?.[id] ?? {}, runtime).then((result) => {
2195
- if (result === null) {
2196
- if (resolveCacheRef.current.get(id) === promise) resolveCacheRef.current.delete(id);
2197
- onResolveErrorRef.current?.(id);
2198
- }
2199
- return result;
2200
- });
2201
- resolveCacheRef.current.set(id, promise);
2202
- return promise;
2203
- }, [runtime]);
2204
- useEffect(() => {
2205
- if (!runtime) return;
2206
- let cancelled = false;
2207
- for (const id of activeIds) {
2208
- if (resolved[id] !== void 0 || failedIdsRef.current.has(id)) continue;
2209
- resolveOnce(id).then((data) => {
2210
- if (cancelled) return;
2211
- if (!data) {
2212
- failedIdsRef.current.add(id);
2213
- return;
2214
- }
2215
- setResolved((current) => current[id] !== void 0 ? current : {
2216
- ...current,
2217
- [id]: data
2218
- });
2219
- });
2220
- }
2221
- return () => {
2222
- cancelled = true;
2223
- };
2224
- }, [
2225
- runtime,
2226
- activeIds,
2227
- resolved,
2228
- resolveOnce
2229
- ]);
2230
- useEffect(() => {
2231
- const failed = failedIdsRef.current;
2232
- for (const id of [...failed]) if (!idList.includes(id)) failed.delete(id);
2233
- }, [idList]);
2234
- useEffect(() => {
2235
- if (!runtime) return;
2236
- const registry = runtime.highlightedPoiIds.current;
2237
- if (!registry) return;
2238
- const next = new Set(activeIds);
2239
- let changed = registry.size !== next.size;
2240
- if (!changed) {
2241
- for (const id of next) if (!registry.has(id)) {
2242
- changed = true;
2243
- break;
2244
- }
2245
- }
2246
- if (changed) runtime.highlightedPoiIds.current = next;
2247
- }, [runtime, activeIds]);
2248
- useEffect(() => {
2249
- if (leavingIds.length === 0) return;
2250
- const timers = leavingIds.map((id) => setTimeout(() => {
2251
- setResolved((current) => {
2252
- if (current[id] === void 0) return current;
2253
- const next = { ...current };
2254
- delete next[id];
2255
- return next;
2256
- });
2257
- resolveCacheRef.current.delete(id);
2258
- }, EXIT_PRUNE_MS));
2259
- return () => {
2260
- for (const timer of timers) clearTimeout(timer);
2261
- };
2262
- }, [leavingIds]);
2263
- const points = useMemo(() => activeIds.flatMap((id) => {
2264
- const data = resolved[id];
2265
- return data ? [{
2266
- id,
2267
- lng: data.lng,
2268
- lat: data.lat
2269
- }] : [];
2270
- }), [activeIds, resolved]);
2271
- const { clusters, clusteredIds } = usePixelClusters(points, clustering, runtime);
2272
- const panToKey = panTo ? idList.join(",") : "";
2273
- useEffect(() => {
2274
- if (!panToKey || !runtime) return;
2275
- let cancelled = false;
2276
- const idsToPan = panToKey.split(",").map(Number);
2277
- (async () => {
2278
- const places = (await Promise.all(idsToPan.map((id) => resolveOnce(id)))).filter((p) => p !== null);
2279
- if (cancelled || places.length === 0) return;
2280
- const [first] = places;
2281
- if (!first) return;
2282
- if (places.length === 1) {
2283
- const currentZoom = await runtime.mapRef.current?.getZoom().catch(() => null);
2284
- const targetZoom = zoom ?? Math.max(DEFAULT_PAN_ZOOM, currentZoom ?? DEFAULT_PAN_ZOOM);
2285
- camera.zoomTo(first.lat, first.lng, targetZoom);
2286
- return;
2287
- }
2288
- camera.fitBounds({
2289
- type: "FeatureCollection",
2290
- features: places.map((p) => ({ geometry: {
2291
- type: "Point",
2292
- coordinates: [p.lng, p.lat]
2293
- } }))
2294
- });
2295
- })();
2296
- return () => {
2297
- cancelled = true;
2298
- };
2299
- }, [
2300
- panToKey,
2301
- zoom,
2302
- runtime,
2303
- camera,
2304
- resolveOnce
2305
- ]);
2306
- const handleClusterPress = (children) => {
2307
- let zoomToExpand = true;
2308
- if (clustering && typeof clustering === "object") {
2309
- if (clustering.onClusterClick?.(children) === false) zoomToExpand = false;
2310
- }
2311
- if (!zoomToExpand || children.length === 0) return;
2312
- camera.fitBounds({
2313
- type: "FeatureCollection",
2314
- features: children.map((c) => ({ geometry: {
2315
- type: "Point",
2316
- coordinates: [c.lng, c.lat]
2317
- } }))
2318
- });
2319
- };
2320
- if (!runtime) return null;
2321
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2322
- activeIds.map((id) => {
2323
- const data = resolved[id];
2324
- if (!data || clusteredIds.has(id)) return null;
2325
- return /* @__PURE__ */ jsx(HighlightMarkerView, {
2326
- lngLat: [data.lng, data.lat],
2327
- iconUrl: data.iconUrl,
2328
- title: data.title,
2329
- iconSize,
2330
- onPress: () => onHighlightPress?.({
2331
- id,
2332
- lng: data.lng,
2333
- lat: data.lat,
2334
- title: data.title,
2335
- iconUrl: data.iconUrl
2336
- })
2337
- }, id);
2338
- }),
2339
- leavingIds.map((id) => {
2340
- const data = resolved[id];
2341
- if (!data) return null;
2342
- return /* @__PURE__ */ jsx(HighlightMarkerView, {
2343
- lngLat: [data.lng, data.lat],
2344
- iconUrl: data.iconUrl,
2345
- title: data.title,
2346
- iconSize,
2347
- leaving: true
2348
- }, `leaving-${id}`);
2349
- }),
2350
- clusters.map((cluster) => /* @__PURE__ */ jsx(ClusterBadge, {
2351
- lngLat: [cluster.lng, cluster.lat],
2352
- count: cluster.members.length,
2353
- theme: runtime.theme,
2354
- onPress: () => handleClusterPress(cluster.members)
2355
- }, cluster.key))
2356
- ] });
2357
- }
2358
-
2359
- // src/poiHighlight/useYarrowPoiHighlight.ts
2360
- /**
2361
- * Headless highlight state — the declarative counterpart of the web SDK's
2362
- * `highlightPOI` / `resetPOIHighlight` / `isPOIHighlighted` /
2363
- * `getHighlightedPOIs` quartet. Rendering is owned by `<PoiHighlightLayer>`:
2364
- *
2365
- * ```tsx
2366
- * const { highlightedIds, highlight } = useYarrowPoiHighlight();
2367
- * <YarrowMapView apiKey={KEY}>
2368
- * <PoiHighlightLayer ids={highlightedIds} panTo />
2369
- * </YarrowMapView>
2370
- * ```
2371
- */
2372
- function useYarrowPoiHighlight() {
2373
- const [highlightedIds, setHighlightedIds] = useState([]);
2374
- const reset = useCallback((input) => {
2375
- setHighlightedIds((current) => {
2376
- if (input === void 0) return [];
2377
- const remove = new Set(Array.isArray(input) ? input : [input]);
2378
- return current.filter((id) => !remove.has(id));
2379
- });
2380
- }, []);
2381
- const highlight = useCallback((input, options) => {
2382
- const ids = Array.isArray(input) ? input : [input];
2383
- setHighlightedIds((current) => {
2384
- const next = [...options?.replace ? [] : current];
2385
- for (const id of ids) if (!next.includes(id)) next.push(id);
2386
- return next;
2387
- });
2388
- return ids.map((id) => ({
2389
- id,
2390
- remove: () => reset(id)
2391
- }));
2392
- }, [reset]);
2393
- const isHighlighted = useCallback((id) => highlightedIds.includes(id), [highlightedIds]);
2394
- return useMemo(() => ({
2395
- highlightedIds,
2396
- highlight,
2397
- reset,
2398
- isHighlighted
2399
- }), [
2400
- highlightedIds,
2401
- highlight,
2402
- reset,
2403
- isHighlighted
2404
- ]);
2405
- }
2406
-
2407
- // src/search/SearchResultsLayer.tsx
2408
- /**
2409
- * Renders search results on the map — the declarative counterpart of the web
2410
- * SDK's `highlightSearchResults()`. Icon precedence per result:
2411
- * `icon_img` → registry icon by `category.name` → blue-dot fallback.
2412
- *
2413
- * ```tsx
2414
- * const { results, isLoading } = useYarrowSearch(query, { lat, lon });
2415
- * <YarrowMapView apiKey={KEY}>
2416
- * <SearchResultsLayer results={results} onResultPress={…} />
2417
- * </YarrowMapView>
2418
- * ```
2419
- */
2420
- function SearchResultsLayer({ results, iconSize, zoomToResults = true, fitKey, clustering, onResultPress }) {
2421
- const runtime = useYarrowMapRuntime();
2422
- const camera = useYarrowCamera();
2423
- const markers = useMemo(() => {
2424
- const keyed = [];
2425
- const seen = /* @__PURE__ */ new Set();
2426
- results.forEach((result) => {
2427
- const { latitude, longitude } = result;
2428
- if (typeof latitude !== "number" || typeof longitude !== "number") return;
2429
- const id = result.id;
2430
- let key;
2431
- if (id !== void 0 && !seen.has(id)) key = id;
2432
- else key = `idx:${keyed.length}`;
2433
- seen.add(key);
2434
- keyed.push({
2435
- key,
2436
- result,
2437
- lng: longitude,
2438
- lat: latitude
2439
- });
2440
- });
2441
- return keyed;
2442
- }, [results]);
2443
- const points = useMemo(() => markers.map((m) => ({
2444
- id: m.key,
2445
- lng: m.lng,
2446
- lat: m.lat
2447
- })), [markers]);
2448
- useEffect(() => {
2449
- if (results.length > 0 && markers.length === 0) console.warn(`[YarrowMap] SearchResultsLayer: ${results.length} result(s) returned, none with displayable coordinates`);
2450
- }, [results, markers]);
2451
- const { clusters, clusteredIds } = usePixelClusters(points, clustering, runtime);
2452
- const fittedRef = useRef(false);
2453
- const lastFitKeyRef = useRef(fitKey);
2454
- if (lastFitKeyRef.current !== fitKey) {
2455
- lastFitKeyRef.current = fitKey;
2456
- fittedRef.current = false;
2457
- }
2458
- const firstCoords = useMemo(() => {
2459
- const [first] = markers;
2460
- return first ? `${first.lat},${first.lng}` : null;
2461
- }, [markers]);
2462
- useEffect(() => {
2463
- if (!zoomToResults || !runtime || fittedRef.current) return;
2464
- if (!firstCoords) return;
2465
- fittedRef.current = true;
2466
- camera.fitBounds({
2467
- type: "FeatureCollection",
2468
- features: markers.map((m) => ({
2469
- geometry: {
2470
- type: "Point",
2471
- coordinates: [m.lng, m.lat]
2472
- },
2473
- properties: { name: m.result.name }
2474
- }))
2475
- });
2476
- }, [
2477
- firstCoords,
2478
- zoomToResults,
2479
- runtime,
2480
- camera,
2481
- markers
2482
- ]);
2483
- const handleClusterPress = (children) => {
2484
- let zoomToExpand = true;
2485
- if (clustering && typeof clustering === "object") {
2486
- if (clustering.onClusterClick?.(children) === false) zoomToExpand = false;
2487
- }
2488
- if (!zoomToExpand || children.length === 0) return;
2489
- camera.fitBounds({
2490
- type: "FeatureCollection",
2491
- features: children.map((c) => ({ geometry: {
2492
- type: "Point",
2493
- coordinates: [c.lng, c.lat]
2494
- } }))
2495
- });
2496
- };
2497
- if (!runtime) return null;
2498
- return /* @__PURE__ */ jsxs(Fragment, { children: [markers.map(({ key, result, lng, lat }) => {
2499
- if (clusteredIds.has(key)) return null;
2500
- const iconUrl = result.icon_img ?? resolveCategoryIcon(runtime.iconsByName, result.category?.name);
2501
- return /* @__PURE__ */ jsx(HighlightMarkerView, {
2502
- lngLat: [lng, lat],
2503
- iconUrl: typeof iconUrl === "string" ? iconUrl : void 0,
2504
- title: result.name,
2505
- iconSize,
2506
- onPress: () => onResultPress?.(lat, lng, result)
2507
- }, key);
2508
- }), clusters.map((cluster) => /* @__PURE__ */ jsx(ClusterBadge, {
2509
- lngLat: [cluster.lng, cluster.lat],
2510
- count: cluster.members.length,
2511
- theme: runtime.theme,
2512
- onPress: () => handleClusterPress(cluster.members)
2513
- }, cluster.key))] });
2514
- }
2515
-
2516
- // src/utils/userToken.ts
2517
- /**
2518
- * Bridges the async AsyncStorage API onto core's synchronous TokenStorage
2519
- * contract: the existing token hydrates into memory once, reads are served
2520
- * synchronously from that cache, and writes mirror in-memory before flushing
2521
- * to AsyncStorage (fire-and-forget).
2522
- *
2523
- * If the initial read throws, the override is left unset entirely: core then
2524
- * degrades to ephemeral tokens *without persisting anything*, so a transient
2525
- * read failure can never overwrite the stored identity with a fresh token.
2526
- *
2527
- * Await this once during app startup, before the first map or tracking call
2528
- * (tokens generated before this resolves are ephemeral by design):
2529
- *
2530
- * ```ts
2531
- * import AsyncStorage from '@react-native-async-storage/async-storage';
2532
- * import { setAsyncStorageTokenStorage } from '@yarrow-uz/rn-map-sdk';
2533
- *
2534
- * await setAsyncStorageTokenStorage(AsyncStorage);
2535
- * ```
2536
- */
2537
- async function setAsyncStorageTokenStorage(storage) {
2538
- let existing;
2539
- try {
2540
- existing = await storage.getItem(USER_TOKEN_STORAGE_KEY);
2541
- } catch {
2542
- return;
2543
- }
2544
- const cache = /* @__PURE__ */ new Map();
2545
- if (existing) cache.set(USER_TOKEN_STORAGE_KEY, existing);
2546
- setTokenStorage({
2547
- getItem: (key) => cache.get(key) ?? null,
2548
- setItem: (key, value) => {
2549
- cache.set(key, value);
2550
- Promise.resolve(storage.setItem(key, value)).catch(() => {});
2551
- }
2552
- });
2553
- }
2554
-
2555
- export { AVG_TILE_BYTES, CACHED_AT_HEADER, CACHE_PROTOCOL, ClusterBadge, DEFAULT_CACHE_LIFESPAN_DAYS, DEFAULT_CLUSTER_MAX_ZOOM, DEFAULT_CLUSTER_MIN_POINTS, DEFAULT_CLUSTER_RADIUS_PX, DEFAULT_OFFLINE_MAX_ZOOM, DEFAULT_OFFLINE_MIN_ZOOM, HighlightMarkerView, ICONS_ENDPOINT, ICON_CACHE_NAME, MILLISECONDS_PER_DAY, OFFLINE_METADATA_VERSION, POI_BASE_LAYER, PoiHighlightLayer, ROUTE_API_URL, RouteLayer, SearchResultsLayer, TILE_CACHE_NAME, USER_TOKEN_STORAGE_KEY, YARROW_CLICK_LAYER_IDS, YARROW_MAP_URL, YARROW_SEARCH_API_URL, YarrowImages, YarrowMapConfig, YarrowMapContext, YarrowMapView, YarrowMarker, YarrowOfflineManager, addApiKeyToUrl, buildStyleEndpoint, buildStyleUrl, estimateRegion, fetchArrayBufferWithCache, fetchPlaceLocation, fetchRoutes, fetchSearchResults, fetchYarrowIcons, getBoundingBox, getOrCreateUserToken, getYarrowApiKey, groupByPixelRadius, hasCacheStorage, haversineDistance, lookupPoiInViewport, normalizeClusteringConfig, normalizeStyleType, resolveCategoryIcon, resolvePoiData, setAsyncStorageTokenStorage, setTokenStorage, setYarrowApiKey, trackDau, transformRouteCoordinates, useYarrowCamera, useYarrowLayerPress, useYarrowMapRuntime, useYarrowMapSearch, useYarrowOfflineRegions, useYarrowPoiHighlight, useYarrowRouting, useYarrowSearch };
4
+ export { AVG_TILE_BYTES, CACHED_AT_HEADER, CACHE_PROTOCOL, ClusterBadge, DEFAULT_BRAND_BADGE_SCALE, DEFAULT_CACHE_LIFESPAN_DAYS, DEFAULT_CLUSTER_MAX_ZOOM, DEFAULT_CLUSTER_MIN_POINTS, DEFAULT_CLUSTER_RADIUS_PX, DEFAULT_OFFLINE_MAX_ZOOM, DEFAULT_OFFLINE_MIN_ZOOM, HighlightMarkerView, ICONS_ENDPOINT, ICON_CACHE_NAME, MILLISECONDS_PER_DAY, OFFLINE_METADATA_VERSION, POI_BASE_LAYER, PoiHighlightLayer, ROUTE_API_URL, RouteLayer, SearchResultsLayer, TILE_CACHE_NAME, USER_TOKEN_STORAGE_KEY, YARROW_CLICK_LAYER_IDS, YARROW_MAP_URL, YARROW_SEARCH_API_URL, YarrowImages, YarrowMapConfig, YarrowMapContext, YarrowMapView, YarrowMarker, YarrowOfflineManager, addApiKeyToUrl, buildStyleEndpoint, buildStyleUrl, estimateRegion, fetchArrayBufferWithCache, fetchPlaceLocation, fetchRoutes, fetchSearchResults, fetchYarrowIcons, getBoundingBox, getOrCreateUserToken, getYarrowApiKey, groupByPixelRadius, hasCacheStorage, haversineDistance, lookupPoiInViewport, normalizeClusteringConfig, normalizeStyleType, resolveCategoryIcon, resolvePoiData, setAsyncStorageTokenStorage, setTokenStorage, setYarrowApiKey, trackDau, transformRouteCoordinates, useYarrowCamera, useYarrowLayerPress, useYarrowMapRuntime, useYarrowMapSearch, useYarrowOfflineRegions, useYarrowPoiHighlight, useYarrowRouting, useYarrowSearch };