@yarrow-uz/rn-map-sdk 0.1.0 → 0.3.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,6 +1,7 @@
1
- import { Camera, GeoJSONSource, Layer, Map as Map$1, OfflineManager } from "@maplibre/maplibre-react-native";
2
- import { forwardRef, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
3
- import { jsx, jsxs } from "react/jsx-runtime";
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";
4
5
 
5
6
  // ../core/dist/index.js
6
7
  const YARROW_MAP_URL = "https://gis.yarrow.uz";
@@ -28,63 +29,41 @@ function addApiKeyToUrl(url) {
28
29
  return url;
29
30
  }
30
31
  }
31
- const STORAGE_KEY = "yarrow:user_token";
32
32
  /**
33
- * Public alias of `STORAGE_KEY` so platform SDKs can build storage adapters
34
- * (e.g. React Native AsyncStorage bridges) without hard-coding the key.
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.
35
36
  */
36
- const USER_TOKEN_STORAGE_KEY = STORAGE_KEY;
37
- let override = null;
38
- function setTokenStorage(storage) {
39
- override = storage;
40
- }
41
- function resolveStorage() {
42
- if (override) return override;
43
- try {
44
- if (typeof localStorage !== "undefined") return localStorage;
45
- } catch {}
46
- return null;
47
- }
48
- function generateUuid() {
49
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
50
- const bytes = /* @__PURE__ */ new Uint8Array(16);
51
- if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(bytes);
52
- else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
53
- bytes[6] = bytes[6] & 15 | 64;
54
- bytes[8] = bytes[8] & 63 | 128;
55
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
56
- 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("")}`;
57
- }
58
- function getOrCreateUserToken() {
59
- const storage = resolveStorage();
60
- if (storage) try {
61
- const existing = storage.getItem(STORAGE_KEY);
62
- if (existing) return existing;
63
- const token = generateUuid();
64
- storage.setItem(STORAGE_KEY, token);
65
- return token;
66
- } catch {}
67
- return generateUuid();
68
- }
69
- /** Hard cap on how long a single tracking request may stay open. */
70
- const TRACK_REQUEST_TIMEOUT_MS = 5e3;
71
- function trackDau(apiKey, sdkType = "javascript") {
72
- try {
73
- const user_token = getOrCreateUserToken();
74
- const controller = new AbortController();
75
- const timeout = setTimeout(() => controller.abort(), TRACK_REQUEST_TIMEOUT_MS);
76
- fetch(`${YARROW_SEARCH_API_URL}/api/tracking/track-dau`, {
77
- method: "POST",
78
- headers: { "Content-Type": "application/json" },
79
- body: JSON.stringify({
80
- api_key: apiKey,
81
- sdk_type: sdkType,
82
- user_token
83
- }),
84
- signal: controller.signal
85
- }).catch(() => {}).finally(() => clearTimeout(timeout));
86
- } catch {}
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;
87
64
  }
65
+ /** Style-API endpoint returning the icon registry (`IconListItem[]`). */
66
+ const ICONS_ENDPOINT = "/icons-image";
88
67
  const DEFAULT_CACHE_LIFESPAN_DAYS = 30;
89
68
  const MILLISECONDS_PER_DAY = 864e5;
90
69
  const TILE_CACHE_NAME = "yarrow-cache-v1-tile";
@@ -209,8 +188,6 @@ const fetchArrayBufferWithCache = async (url, cacheName, lifespanMs, abortContro
209
188
  await saveToCache(cache, url, networkResponse);
210
189
  return networkResponse;
211
190
  };
212
- /** Routing API endpoint used by `fetchRoutes()`. */
213
- const ROUTE_API_URL = "https://api.yarrow.uz/api/routing/route";
214
191
  const transformRouteCoordinates = (features) => {
215
192
  return features.map((feature) => {
216
193
  const transformedCoords = feature.geometry.coordinates.map((coord) => [coord.lng, coord.lat]);
@@ -223,6 +200,8 @@ const transformRouteCoordinates = (features) => {
223
200
  };
224
201
  });
225
202
  };
203
+ /** Routing API endpoint used by `fetchRoutes()`. */
204
+ const ROUTE_API_URL = "https://api.yarrow.uz/api/routing/route";
226
205
  const emptyResult = (profile) => ({
227
206
  features: [],
228
207
  directions: [],
@@ -348,6 +327,642 @@ function buildStyleEndpoint(styleType, theme) {
348
327
  if (theme === "dark") endpoint += endpoint.includes("?") ? "&dark=true" : "?dark=true";
349
328
  return endpoint;
350
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
+ });
351
966
 
352
967
  // src/maps/config.ts
353
968
  /**
@@ -370,6 +985,88 @@ var YarrowMapConfig = class {
370
985
  }
371
986
  };
372
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
+
373
1070
  // src/maps/styles.ts
374
1071
  /**
375
1072
  * Full style URL for MapLibre React Native's `mapStyle` prop, built from the
@@ -383,9 +1080,15 @@ function buildStyleUrl(styleType, theme = "light") {
383
1080
  }
384
1081
 
385
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
+ };
386
1087
  /**
387
1088
  * React Native Yarrow map. Renders MapLibre Native with a Yarrow style URL
388
- * (theme + styleType aware, API key attached) and a default camera.
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.
389
1092
  *
390
1093
  * ```tsx
391
1094
  * const mapRef = useRef<MapRef>(null);
@@ -402,7 +1105,7 @@ function buildStyleUrl(styleType, theme = "light") {
402
1105
  * `cameraRef` (`flyTo`, `jumpTo`, `fitBounds`). Theme and styleType changes
403
1106
  * hot-swap the style URL natively.
404
1107
  */
405
- const YarrowMapView = forwardRef(({ apiKey, center, zoom, minZoom, maxZoom, theme, styleType, onReady, onLoadError, onPress, cameraRef, attribution = true, logo = true, compass = true, dauTracking = true, style, children }, ref) => {
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) => {
406
1109
  const config = useMemo(() => new YarrowMapConfig({
407
1110
  apiKey,
408
1111
  center,
@@ -424,6 +1127,75 @@ const YarrowMapView = forwardRef(({ apiKey, center, zoom, minZoom, maxZoom, them
424
1127
  readyRef.current = onReady;
425
1128
  const dauTrackedRef = useRef(false);
426
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
+ }, []);
427
1199
  const mapStyle = useMemo(() => {
428
1200
  setYarrowApiKey(config.apiKey);
429
1201
  return buildStyleUrl(config.styleType, config.theme);
@@ -439,213 +1211,234 @@ const YarrowMapView = forwardRef(({ apiKey, center, zoom, minZoom, maxZoom, them
439
1211
  const handleDidFailLoadingMap = useCallback(() => {
440
1212
  onLoadError?.(/* @__PURE__ */ new Error("Yarrow map failed to load — check the API key/network."));
441
1213
  }, [onLoadError]);
442
- return /* @__PURE__ */ jsxs(Map$1, {
443
- ref: (instance) => {
444
- mapRef.current = instance;
445
- if (typeof ref === "function") ref(instance);
446
- else if (ref) ref.current = instance;
447
- },
448
- mapStyle,
449
- style,
450
- attribution,
451
- logo,
452
- compass,
453
- onPress,
454
- onDidFinishLoadingMap: handleDidFinishLoadingMap,
455
- onDidFailLoadingMap: handleDidFailLoadingMap,
456
- children: [/* @__PURE__ */ jsx(Camera, {
457
- ref: cameraRef,
458
- initialViewState: {
459
- center: config.center,
460
- zoom: config.zoom
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);
461
1236
  },
462
- minZoom: config.minZoom,
463
- maxZoom: config.maxZoom
464
- }), children]
465
- });
466
- });
467
-
468
- // src/maps/routing/types.ts
469
- /** Best-route + alternatives palette — same values as the web SDK's
470
- * `buildRoute()` defaults (index 0 is the best route). */
471
- const ROUTE_LAYER_COLORS = [
472
- "#22c55e",
473
- "#aaaaaa",
474
- "#cccccc",
475
- "#dddddd",
476
- "#eeeeee"
477
- ];
478
-
479
- // src/maps/routing/RouteLayer.tsx
480
- const DEFAULT_LAYER_PREFIX = "yarrow-route";
481
- const toFeatureCollection = (route) => ({
482
- type: "FeatureCollection",
483
- features: [route]
484
- });
485
- /**
486
- * Declarative route rendering: one GeoJSON source + line layer per route.
487
- * Compose inside `<YarrowMapView>` and drive it with `useYarrowRouting()`:
488
- *
489
- * ```tsx
490
- * const { routes } = useYarrowRouting();
491
- * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
492
- * <RouteLayer routes={routes} onPressRoute={…} />
493
- * </YarrowMapView>
494
- * ```
495
- */
496
- const RouteLayer = memo(function RouteLayer({ routes, bestIndex = 0, routeColor = ROUTE_LAYER_COLORS[0], routeWidth = 5, routeOpacity = 1, alternativeColor, alternativeWidth = 2.5, alternativeOpacity = .5, layerPrefix = DEFAULT_LAYER_PREFIX, onPressRoute }) {
497
- return routes.map((route, index) => {
498
- const isBest = index === bestIndex;
499
- const sourceId = `${layerPrefix}-${index}`;
500
- const color = isBest ? routeColor : alternativeColor ?? ROUTE_LAYER_COLORS[index % ROUTE_LAYER_COLORS.length];
501
- const width = isBest ? routeWidth : alternativeWidth;
502
- const opacity = isBest ? routeOpacity : alternativeOpacity;
503
- return /* @__PURE__ */ jsx(GeoJSONSource, {
504
- id: sourceId,
505
- data: toFeatureCollection(route),
506
- onPress: onPressRoute ? (event) => onPressRoute(event, index) : void 0,
507
- children: /* @__PURE__ */ jsx(Layer, {
508
- id: `${layerPrefix}-line-${index}`,
509
- type: "line",
510
- layout: {
511
- "line-cap": "round",
512
- "line-join": "round"
513
- },
514
- paint: {
515
- "line-color": color,
516
- "line-width": width,
517
- "line-opacity": opacity
518
- }
519
- })
520
- }, sourceId);
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
+ })
521
1266
  });
522
1267
  });
523
1268
 
524
- // src/hooks/useYarrowSearch.ts
1269
+ // src/markers/HighlightMarkerView.tsx
1270
+ const ENTER_MS = 280;
1271
+ const EXIT_MS = 200;
1272
+ const DEFAULT_ICON_SIZE = 56;
525
1273
  /**
526
- * Debounced, abortable search against the Yarrow search API.
527
- *
528
- * Requires the API key to be configured (`YarrowMapView` does this on mount;
529
- * otherwise call `setYarrowApiKey()` first).
530
- *
531
- * ```tsx
532
- * const { results, isLoading } = useYarrowSearch(query, {
533
- * lat: position?.lat ?? 41.2995,
534
- * lon: position?.lng ?? 69.2401,
535
- * });
536
- * ```
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).
537
1279
  */
538
- const useYarrowSearch = (query, options) => {
539
- const { lat, lon, page = 1, pageSize = 15, debounceMs = 300, enabled = true } = options;
540
- const [results, setResults] = useState([]);
541
- const [isLoading, setIsLoading] = useState(false);
542
- const [error, setError] = useState(null);
543
- const latestRequestRef = useRef(0);
1280
+ const HighlightMarkerView = memo(function HighlightMarkerView({ lngLat, iconUrl, title, iconSize, leaving = false, onPress }) {
1281
+ const progress = useRef(new Animated.Value(0)).current;
544
1282
  useEffect(() => {
545
- const trimmed = query.trim();
546
- if (!enabled || trimmed.length === 0) {
547
- latestRequestRef.current += 1;
548
- setResults([]);
549
- setError(null);
550
- setIsLoading(false);
551
- return;
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
552
1349
  }
553
- const controller = new AbortController();
554
- const requestId = ++latestRequestRef.current;
555
- setIsLoading(true);
556
- const timeout = setTimeout(() => {
557
- fetchSearchResults(trimmed, {
558
- lat,
559
- lon,
560
- page,
561
- pageSize,
562
- signal: controller.signal
563
- }).then((resolved) => {
564
- if (latestRequestRef.current === requestId) {
565
- setResults(resolved);
566
- setError(null);
567
- }
568
- }).catch((caught) => {
569
- if (controller.signal.aborted) return;
570
- if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
571
- }).finally(() => {
572
- if (latestRequestRef.current === requestId) setIsLoading(false);
573
- });
574
- }, debounceMs);
575
- return () => {
576
- clearTimeout(timeout);
577
- controller.abort();
578
- };
579
- }, [
580
- query,
581
- enabled,
582
- lat,
583
- lon,
584
- page,
585
- pageSize,
586
- debounceMs
587
- ]);
588
- return {
589
- results,
590
- isLoading,
591
- error
592
- };
593
- };
1350
+ }
1351
+ });
594
1352
 
595
- // src/hooks/useYarrowRouting.ts
1353
+ // src/markers/YarrowMarker.tsx
596
1354
  /**
597
- * Headless routing state for the Yarrow routing API — pairs with
598
- * `<RouteLayer>` for rendering.
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.
599
1358
  *
600
1359
  * ```tsx
601
- * const { routes, isLoading, buildRoute } = useYarrowRouting({ profile: 'driving' });
602
1360
  * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
603
- * <RouteLayer routes={routes} />
1361
+ * <YarrowMarker lngLat={[69.2401, 41.2995]} onPress={() => …}>
1362
+ * <PinIcon />
1363
+ * </YarrowMarker>
604
1364
  * </YarrowMapView>
605
1365
  * ```
606
1366
  */
607
- const useYarrowRouting = (options = {}) => {
608
- const { profile = "driving", language } = options;
609
- const [result, setResult] = useState(null);
610
- const [isLoading, setIsLoading] = useState(false);
611
- const [error, setError] = useState(null);
612
- const latestRequestRef = useRef(0);
613
- const buildRoute = useCallback(async (input) => {
614
- const requestId = ++latestRequestRef.current;
615
- setIsLoading(true);
616
- setError(null);
617
- try {
618
- const resolved = await fetchRoutes({
619
- profile: input.profile ?? profile,
620
- coordinates: input.coordinates,
621
- language: input.language ?? language,
622
- signal: input.signal
623
- });
624
- if (latestRequestRef.current === requestId) setResult(resolved);
625
- return resolved;
626
- } catch (caught) {
627
- if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
628
- throw caught;
629
- } finally {
630
- if (latestRequestRef.current === requestId) setIsLoading(false);
631
- }
632
- }, [profile, language]);
633
- const clearRoutes = useCallback(() => {
634
- latestRequestRef.current += 1;
635
- setResult(null);
636
- setError(null);
637
- setIsLoading(false);
638
- }, []);
639
- return {
640
- routes: result?.features ?? [],
641
- directions: result?.directions ?? [],
642
- meta: result?.meta ?? null,
643
- isLoading,
644
- error,
645
- buildRoute,
646
- clearRoutes
647
- };
648
- };
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
+ }
649
1442
 
650
1443
  // src/offline/estimate.ts
651
1444
  /**
@@ -1180,6 +1973,546 @@ const useYarrowOfflineRegions = (options) => {
1180
1973
  };
1181
1974
  };
1182
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
+
1183
2516
  // src/utils/userToken.ts
1184
2517
  /**
1185
2518
  * Bridges the async AsyncStorage API onto core's synchronous TokenStorage
@@ -1219,4 +2552,4 @@ async function setAsyncStorageTokenStorage(storage) {
1219
2552
  });
1220
2553
  }
1221
2554
 
1222
- export { AVG_TILE_BYTES, CACHED_AT_HEADER, CACHE_PROTOCOL, DEFAULT_CACHE_LIFESPAN_DAYS, DEFAULT_OFFLINE_MAX_ZOOM, DEFAULT_OFFLINE_MIN_ZOOM, ICON_CACHE_NAME, MILLISECONDS_PER_DAY, OFFLINE_METADATA_VERSION, ROUTE_API_URL, RouteLayer, TILE_CACHE_NAME, USER_TOKEN_STORAGE_KEY, YARROW_MAP_URL, YARROW_SEARCH_API_URL, YarrowMapConfig, YarrowMapView, YarrowOfflineManager, addApiKeyToUrl, buildStyleEndpoint, buildStyleUrl, estimateRegion, fetchArrayBufferWithCache, fetchRoutes, fetchSearchResults, getOrCreateUserToken, getYarrowApiKey, hasCacheStorage, haversineDistance, normalizeStyleType, setAsyncStorageTokenStorage, setTokenStorage, setYarrowApiKey, trackDau, transformRouteCoordinates, useYarrowOfflineRegions, useYarrowRouting, useYarrowSearch };
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 };