@yarrow-uz/rn-map-sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,634 @@ 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
+ async function fetchPlaceLocation(id) {
560
+ const controller = new AbortController();
561
+ const timeout = setTimeout(() => controller.abort(), PLACE_TIMEOUT_MS);
562
+ try {
563
+ const url = addApiKeyToUrl(`${YARROW_SEARCH_API_URL}/api/search/${id}?is_bus_stop=false`);
564
+ const res = await fetch(url, { signal: controller.signal });
565
+ if (!res.ok) return null;
566
+ const data = (await res.json())?.search?.data;
567
+ const loc = data?.address?.location;
568
+ if (!loc) return null;
569
+ return {
570
+ lng: loc.lng,
571
+ lat: loc.lat,
572
+ iconUrl: data?.icon_img,
573
+ title: data?.name
574
+ };
575
+ } catch (error) {
576
+ if (error?.name !== "AbortError") console.warn(`[YarrowMap] fetchPlaceLocation(${id}) failed:`, error);
577
+ return null;
578
+ } finally {
579
+ clearTimeout(timeout);
580
+ }
581
+ }
582
+ /**
583
+ * Reads a POI's point geometry from the style's POI layer within the current
584
+ * viewport — the free, no-network resolution step. Native can only query
585
+ * *rendered* features (no `querySourceFeatures` on undeclared sources), so
586
+ * off-screen POIs fall through to the place-detail API. Icons are resolved
587
+ * best-effort from the registry via the feature's `node_type`.
588
+ */
589
+ async function lookupPoiInViewport(mapRef, id, iconsByName) {
590
+ let features = [];
591
+ try {
592
+ features = await mapRef.queryRenderedFeatures({
593
+ layers: [POI_BASE_LAYER],
594
+ filter: [
595
+ "==",
596
+ ["get", "id"],
597
+ id
598
+ ]
599
+ });
600
+ } catch {
601
+ return null;
602
+ }
603
+ const feature = features.find((f) => f.geometry?.type === "Point");
604
+ if (!feature) return null;
605
+ const coordinates = feature.geometry.coordinates;
606
+ const properties = feature.properties ?? {};
607
+ const nodeType = typeof properties.node_type === "string" ? properties.node_type : void 0;
608
+ const name = typeof properties.name === "string" ? properties.name : void 0;
609
+ return {
610
+ lng: coordinates[0],
611
+ lat: coordinates[1],
612
+ iconUrl: nodeType ? resolveCategoryIcon(iconsByName, nodeType) : void 0,
613
+ title: name
614
+ };
615
+ }
616
+ /**
617
+ * Resolves a POI's coordinates, icon and title cheapest-first:
618
+ * 1. caller-provided `location` / `icon` / `title`
619
+ * 2. local lookup in the rendered POI layer (no network)
620
+ * 3. the place-detail API (off-screen / below the POI zoom range, or when
621
+ * anything is still missing — web parity: the API fills icon and title
622
+ * too, not just coordinates)
623
+ *
624
+ * The web SDK additionally evaluates the style's `icon-image` expression for
625
+ * the tile step; native approximates it with a registry lookup by
626
+ * `node_type`. Coordinate resolution is the hard requirement — if it fails,
627
+ * the highlight is rolled back by the caller.
628
+ */
629
+ async function resolvePoiData(id, options, runtime) {
630
+ let lng = options.location?.lng;
631
+ let lat = options.location?.lat;
632
+ let iconUrl = options.icon;
633
+ let title = options.title;
634
+ if (lng === void 0 || iconUrl === void 0 || title === void 0) {
635
+ const mapRef = runtime.mapRef.current;
636
+ const local = mapRef ? await lookupPoiInViewport(mapRef, id, runtime.iconsByName) : null;
637
+ if (local) {
638
+ if (lng === void 0) {
639
+ lng = local.lng;
640
+ lat = local.lat;
641
+ }
642
+ if (iconUrl === void 0) iconUrl = local.iconUrl;
643
+ if (title === void 0) title = local.title;
644
+ }
645
+ }
646
+ if (lng === void 0 || iconUrl === void 0 || title === void 0) {
647
+ const remote = await fetchPlaceLocation(id);
648
+ if (remote) {
649
+ if (lng === void 0) {
650
+ lng = remote.lng;
651
+ lat = remote.lat;
652
+ }
653
+ if (iconUrl === void 0) iconUrl = remote.iconUrl;
654
+ if (title === void 0) title = remote.title;
655
+ }
656
+ }
657
+ if (lng === void 0 || lat === void 0) return null;
658
+ return {
659
+ lng,
660
+ lat,
661
+ iconUrl,
662
+ title
663
+ };
664
+ }
665
+
666
+ // src/runtime/context.ts
667
+ const YarrowMapContext = createContext(null);
668
+ /** Reads the enclosing `<YarrowMapView>` runtime, or `null` outside one. */
669
+ function useYarrowMapRuntime() {
670
+ return useContext(YarrowMapContext);
671
+ }
672
+
673
+ // src/events/useYarrowLayerPress.ts
674
+ const YARROW_CLICK_LAYER_IDS = {
675
+ pois: [POI_BASE_LAYER],
676
+ buildings: ["buildings_tile_layer"],
677
+ mahalla: ["mahallah_label_tile_layer"],
678
+ district: ["districts_label_tile_layer"],
679
+ region: ["regions_label_tile_layer"],
680
+ country: ["countries_label_tile_layer"]
681
+ };
682
+ /**
683
+ * Base-style-layer press handler — the native counterpart of the web SDK's
684
+ * `onIconClick('pois' | 'buildings')` and `onLayerClick(<admin label>)`. On
685
+ * every map press it queries the rendered features at the press point for the
686
+ * target layers and invokes `handler` with the topmost hit. Must be called
687
+ * inside `<YarrowMapView>` — extract a child component rendered as a map
688
+ * child (hooks outside the map can't see the runtime):
689
+ *
690
+ * ```tsx
691
+ * function PoiPressReporter() {
692
+ * useYarrowLayerPress('pois', ({ lat, lng, properties, selected }) => {
693
+ * console.log('POI pressed', properties.id, selected);
694
+ * });
695
+ * return null;
696
+ * }
697
+ *
698
+ * <YarrowMapView apiKey={KEY}>
699
+ * <PoiPressReporter />
700
+ * </YarrowMapView>
701
+ * ```
702
+ *
703
+ * Unlike the web SDK, targets resolve to the canonical Yarrow style layer
704
+ * ids (verified against the served `/styles/` document, identical in light
705
+ * and dark) instead of dynamic style inspection — override `layerIds` if
706
+ * your style variant names them differently.
707
+ */
708
+ function useYarrowLayerPress(target, handler, options) {
709
+ const runtime = useYarrowMapRuntime();
710
+ const targets = Array.isArray(target) ? target : [target];
711
+ const targetsKey = targets.join(",");
712
+ const handlerRef = useRef(handler);
713
+ handlerRef.current = handler;
714
+ useEffect(() => {
715
+ if (!runtime) {
716
+ console.warn("[YarrowMap] useYarrowLayerPress: no map runtime — call it inside <YarrowMapView>.");
717
+ return;
718
+ }
719
+ const layerIds = targets.flatMap((t) => options?.layerIds?.[t] ?? YARROW_CLICK_LAYER_IDS[t]);
720
+ const includesPois = targets.includes("pois");
721
+ return runtime.subscribePress((press) => {
722
+ const map = runtime.mapRef.current;
723
+ if (!map || layerIds.length === 0) return;
724
+ map.queryRenderedFeatures(press.point, { layers: layerIds }).then((features) => {
725
+ const feature = features[0];
726
+ if (!feature?.properties) return;
727
+ const properties = feature.properties;
728
+ let selected;
729
+ if (includesPois) {
730
+ const fid = properties.id;
731
+ selected = typeof fid === "number" ? runtime.highlightedPoiIds.current.has(fid) : false;
732
+ }
733
+ handlerRef.current({
734
+ lat: press.lngLat[1],
735
+ lng: press.lngLat[0],
736
+ properties,
737
+ selected
738
+ });
739
+ }).catch(() => {});
740
+ });
741
+ }, [
742
+ runtime,
743
+ targetsKey,
744
+ options?.layerIds
745
+ ]);
746
+ }
747
+
748
+ // src/hooks/useYarrowSearch.ts
749
+ /**
750
+ * Debounced, abortable search against the Yarrow search API.
751
+ *
752
+ * Requires the API key to be configured (`YarrowMapView` does this on mount;
753
+ * otherwise call `setYarrowApiKey()` first).
754
+ *
755
+ * ```tsx
756
+ * const { results, isLoading } = useYarrowSearch(query, {
757
+ * lat: position?.lat ?? 41.2995,
758
+ * lon: position?.lng ?? 69.2401,
759
+ * });
760
+ * ```
761
+ */
762
+ const useYarrowSearch = (query, options) => {
763
+ const { lat, lon, page = 1, pageSize = 15, debounceMs = 300, enabled = true } = options;
764
+ const [results, setResults] = useState([]);
765
+ const [isLoading, setIsLoading] = useState(false);
766
+ const [error, setError] = useState(null);
767
+ const latestRequestRef = useRef(0);
768
+ useEffect(() => {
769
+ const trimmed = query.trim();
770
+ if (!enabled || trimmed.length === 0) {
771
+ latestRequestRef.current += 1;
772
+ setResults([]);
773
+ setError(null);
774
+ setIsLoading(false);
775
+ return;
776
+ }
777
+ const controller = new AbortController();
778
+ const requestId = ++latestRequestRef.current;
779
+ setIsLoading(true);
780
+ const timeout = setTimeout(() => {
781
+ fetchSearchResults(trimmed, {
782
+ lat,
783
+ lon,
784
+ page,
785
+ pageSize,
786
+ signal: controller.signal
787
+ }).then((resolved) => {
788
+ if (latestRequestRef.current === requestId) {
789
+ setResults(resolved);
790
+ setError(null);
791
+ }
792
+ }).catch((caught) => {
793
+ if (controller.signal.aborted) return;
794
+ if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
795
+ }).finally(() => {
796
+ if (latestRequestRef.current === requestId) setIsLoading(false);
797
+ });
798
+ }, debounceMs);
799
+ return () => {
800
+ clearTimeout(timeout);
801
+ controller.abort();
802
+ };
803
+ }, [
804
+ query,
805
+ enabled,
806
+ lat,
807
+ lon,
808
+ page,
809
+ pageSize,
810
+ debounceMs
811
+ ]);
812
+ return {
813
+ results,
814
+ isLoading,
815
+ error
816
+ };
817
+ };
818
+
819
+ // src/hooks/useYarrowMapSearch.ts
820
+ const DEFAULT_THRESHOLD_METERS = 500;
821
+ const DEFAULT_MOVE_DEBOUNCE_MS = 250;
822
+ /**
823
+ * `useYarrowSearch` plus web-parity re-query on camera movement: when the map
824
+ * moves ≥ 500 m from where the current results were fetched for, the search
825
+ * re-runs around the new center. Must be called inside `<YarrowMapView>` to
826
+ * observe camera moves (outside one it behaves exactly like `useYarrowSearch`).
827
+ *
828
+ * ```tsx
829
+ * const { results, isLoading, center } = useYarrowMapSearch(query, {
830
+ * lat: 41.2995,
831
+ * lon: 69.2401,
832
+ * refetchOnMove: true,
833
+ * });
834
+ * <SearchResultsLayer results={results} />
835
+ * ```
836
+ */
837
+ function useYarrowMapSearch(query, options) {
838
+ const { lat, lon, refetchOnMove, ...searchOptions } = options;
839
+ const runtime = useYarrowMapRuntime();
840
+ const [center, setCenter] = useState({
841
+ lat,
842
+ lon
843
+ });
844
+ const centerRef = useRef(center);
845
+ centerRef.current = center;
846
+ const callerKey = `${lat},${lon}`;
847
+ useEffect(() => {
848
+ const [callerLat, callerLon] = callerKey.split(",").map(Number);
849
+ setCenter((current) => current.lat === callerLat && current.lon === callerLon ? current : {
850
+ lat: callerLat,
851
+ lon: callerLon
852
+ });
853
+ }, [callerKey]);
854
+ useEffect(() => {
855
+ if (!refetchOnMove || !runtime) return;
856
+ const { thresholdMeters = DEFAULT_THRESHOLD_METERS, debounceMs = DEFAULT_MOVE_DEBOUNCE_MS } = typeof refetchOnMove === "object" ? refetchOnMove : {};
857
+ let timeout = null;
858
+ const unsubscribe = runtime.subscribeRegionChange(({ center: [lng, mapLat] }) => {
859
+ if (timeout) clearTimeout(timeout);
860
+ timeout = setTimeout(() => {
861
+ timeout = null;
862
+ const current = centerRef.current;
863
+ if (haversineDistance(current.lat, current.lon, mapLat, lng) >= thresholdMeters) setCenter({
864
+ lat: mapLat,
865
+ lon: lng
866
+ });
867
+ }, debounceMs);
868
+ });
869
+ return () => {
870
+ if (timeout) clearTimeout(timeout);
871
+ unsubscribe();
872
+ };
873
+ }, [refetchOnMove, runtime]);
874
+ return {
875
+ ...useYarrowSearch(query, {
876
+ ...searchOptions,
877
+ lat: center.lat,
878
+ lon: center.lon
879
+ }),
880
+ center
881
+ };
882
+ }
883
+
884
+ // src/hooks/useYarrowRouting.ts
885
+ /**
886
+ * Headless routing state for the Yarrow routing API — pairs with
887
+ * `<RouteLayer>` for rendering.
888
+ *
889
+ * ```tsx
890
+ * const { routes, isLoading, buildRoute } = useYarrowRouting({ profile: 'driving' });
891
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
892
+ * <RouteLayer routes={routes} />
893
+ * </YarrowMapView>
894
+ * ```
895
+ */
896
+ const useYarrowRouting = (options = {}) => {
897
+ const { profile = "driving", language } = options;
898
+ const [result, setResult] = useState(null);
899
+ const [isLoading, setIsLoading] = useState(false);
900
+ const [error, setError] = useState(null);
901
+ const latestRequestRef = useRef(0);
902
+ const buildRoute = useCallback(async (input) => {
903
+ const requestId = ++latestRequestRef.current;
904
+ setIsLoading(true);
905
+ setError(null);
906
+ try {
907
+ const resolved = await fetchRoutes({
908
+ profile: input.profile ?? profile,
909
+ coordinates: input.coordinates,
910
+ language: input.language ?? language,
911
+ signal: input.signal
912
+ });
913
+ if (latestRequestRef.current === requestId) setResult(resolved);
914
+ return resolved;
915
+ } catch (caught) {
916
+ if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
917
+ throw caught;
918
+ } finally {
919
+ if (latestRequestRef.current === requestId) setIsLoading(false);
920
+ }
921
+ }, [profile, language]);
922
+ const clearRoutes = useCallback(() => {
923
+ latestRequestRef.current += 1;
924
+ setResult(null);
925
+ setError(null);
926
+ setIsLoading(false);
927
+ }, []);
928
+ return {
929
+ routes: result?.features ?? [],
930
+ directions: result?.directions ?? [],
931
+ meta: result?.meta ?? null,
932
+ isLoading,
933
+ error,
934
+ buildRoute,
935
+ clearRoutes
936
+ };
937
+ };
938
+
939
+ // src/icons/YarrowImages.tsx
940
+ /**
941
+ * Adds the Yarrow icon images to the native style so symbol layers can
942
+ * resolve their `icon-image` names — the native counterpart of the web SDK's
943
+ * `addIconsToMap` prefetch plus its missing-image resolver. `Images` accepts
944
+ * remote URLs and downloads them natively; `onImageMissing` covers icons
945
+ * referenced before the registry fetch lands or after a failed fetch.
946
+ */
947
+ const YarrowImages = memo(function YarrowImages({ iconsByName, onMissingIcon }) {
948
+ const images = useMemo(() => ({ ...iconsByName }), [iconsByName]);
949
+ const handleMissing = useCallback((event) => {
950
+ const name = event.nativeEvent?.image;
951
+ if (name) onMissingIcon?.(name);
952
+ }, [onMissingIcon]);
953
+ return /* @__PURE__ */ jsx(Images, {
954
+ images,
955
+ onImageMissing: handleMissing
956
+ });
957
+ });
351
958
 
352
959
  // src/maps/config.ts
353
960
  /**
@@ -370,6 +977,62 @@ var YarrowMapConfig = class {
370
977
  }
371
978
  };
372
979
 
980
+ // src/maps/routing/types.ts
981
+ /** Best-route + alternatives palette — same values as the web SDK's
982
+ * `buildRoute()` defaults (index 0 is the best route). */
983
+ const ROUTE_LAYER_COLORS = [
984
+ "#22c55e",
985
+ "#aaaaaa",
986
+ "#cccccc",
987
+ "#dddddd",
988
+ "#eeeeee"
989
+ ];
990
+
991
+ // src/maps/routing/RouteLayer.tsx
992
+ const DEFAULT_LAYER_PREFIX = "yarrow-route";
993
+ const toFeatureCollection = (route) => ({
994
+ type: "FeatureCollection",
995
+ features: [route]
996
+ });
997
+ /**
998
+ * Declarative route rendering: one GeoJSON source + line layer per route.
999
+ * Compose inside `<YarrowMapView>` and drive it with `useYarrowRouting()`:
1000
+ *
1001
+ * ```tsx
1002
+ * const { routes } = useYarrowRouting();
1003
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
1004
+ * <RouteLayer routes={routes} onPressRoute={…} />
1005
+ * </YarrowMapView>
1006
+ * ```
1007
+ */
1008
+ 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 }) {
1009
+ return routes.map((route, index) => {
1010
+ const isBest = index === bestIndex;
1011
+ const sourceId = `${layerPrefix}-${index}`;
1012
+ const color = isBest ? routeColor : alternativeColor ?? ROUTE_LAYER_COLORS[index % ROUTE_LAYER_COLORS.length];
1013
+ const width = isBest ? routeWidth : alternativeWidth;
1014
+ const opacity = isBest ? routeOpacity : alternativeOpacity;
1015
+ return /* @__PURE__ */ jsx(GeoJSONSource, {
1016
+ id: sourceId,
1017
+ data: toFeatureCollection(route),
1018
+ onPress: onPressRoute ? (event) => onPressRoute(event, index) : void 0,
1019
+ children: /* @__PURE__ */ jsx(Layer, {
1020
+ id: `${layerPrefix}-line-${index}`,
1021
+ type: "line",
1022
+ layout: {
1023
+ "line-cap": "round",
1024
+ "line-join": "round"
1025
+ },
1026
+ paint: {
1027
+ "line-color": color,
1028
+ "line-width": width,
1029
+ "line-opacity": opacity
1030
+ }
1031
+ })
1032
+ }, sourceId);
1033
+ });
1034
+ });
1035
+
373
1036
  // src/maps/styles.ts
374
1037
  /**
375
1038
  * Full style URL for MapLibre React Native's `mapStyle` prop, built from the
@@ -383,9 +1046,15 @@ function buildStyleUrl(styleType, theme = "light") {
383
1046
  }
384
1047
 
385
1048
  // src/maps/YarrowMapView.tsx
1049
+ const assignRef = (ref, instance) => {
1050
+ if (typeof ref === "function") ref(instance);
1051
+ else if (ref) ref.current = instance;
1052
+ };
386
1053
  /**
387
1054
  * React Native Yarrow map. Renders MapLibre Native with a Yarrow style URL
388
- * (theme + styleType aware, API key attached) and a default camera.
1055
+ * (theme + styleType aware, API key attached) and a default camera, and
1056
+ * provides the runtime (refs, icon registry, camera/event subscriptions) to
1057
+ * the SDK layers rendered inside it.
389
1058
  *
390
1059
  * ```tsx
391
1060
  * const mapRef = useRef<MapRef>(null);
@@ -402,7 +1071,7 @@ function buildStyleUrl(styleType, theme = "light") {
402
1071
  * `cameraRef` (`flyTo`, `jumpTo`, `fitBounds`). Theme and styleType changes
403
1072
  * hot-swap the style URL natively.
404
1073
  */
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) => {
1074
+ 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
1075
  const config = useMemo(() => new YarrowMapConfig({
407
1076
  apiKey,
408
1077
  center,
@@ -424,6 +1093,75 @@ const YarrowMapView = forwardRef(({ apiKey, center, zoom, minZoom, maxZoom, them
424
1093
  readyRef.current = onReady;
425
1094
  const dauTrackedRef = useRef(false);
426
1095
  const mapRef = useRef(null);
1096
+ const internalCameraRef = useRef(null);
1097
+ const highlightedPoiIds = useRef(/* @__PURE__ */ new Set());
1098
+ const [iconsByName, setIconsByName] = useState({});
1099
+ const iconsFetchAttemptedRef = useRef(false);
1100
+ useEffect(() => {
1101
+ iconsFetchAttemptedRef.current = false;
1102
+ if (!icons) {
1103
+ setIconsByName({});
1104
+ return;
1105
+ }
1106
+ let cancelled = false;
1107
+ fetchYarrowIcons(config.apiKey).then((map) => {
1108
+ if (!cancelled) {
1109
+ iconsFetchAttemptedRef.current = true;
1110
+ setIconsByName(map);
1111
+ }
1112
+ }).catch((error) => {
1113
+ console.warn("[YarrowMap] icon registry fetch failed:", error);
1114
+ });
1115
+ return () => {
1116
+ cancelled = true;
1117
+ };
1118
+ }, [config.apiKey, icons]);
1119
+ const handleMissingIcon = useCallback(() => {
1120
+ if (!icons || iconsFetchAttemptedRef.current) return;
1121
+ iconsFetchAttemptedRef.current = true;
1122
+ fetchYarrowIcons(config.apiKey).then(setIconsByName).catch(() => {
1123
+ iconsFetchAttemptedRef.current = false;
1124
+ });
1125
+ }, [config.apiKey, icons]);
1126
+ const regionListeners = useRef(/* @__PURE__ */ new Set());
1127
+ const pressListeners = useRef(/* @__PURE__ */ new Set());
1128
+ const onMoveEndRef = useRef(onMoveEnd);
1129
+ onMoveEndRef.current = onMoveEnd;
1130
+ const onPressRef = useRef(onPress);
1131
+ onPressRef.current = onPress;
1132
+ const subscribeRegionChange = useCallback((listener) => {
1133
+ regionListeners.current.add(listener);
1134
+ return () => {
1135
+ regionListeners.current.delete(listener);
1136
+ };
1137
+ }, []);
1138
+ const subscribePress = useCallback((listener) => {
1139
+ pressListeners.current.add(listener);
1140
+ return () => {
1141
+ pressListeners.current.delete(listener);
1142
+ };
1143
+ }, []);
1144
+ const handleRegionDidChange = useCallback((event) => {
1145
+ const { center: lngLat, zoom: eventZoom } = event.nativeEvent;
1146
+ const [lng, lat] = lngLat;
1147
+ for (const listener of regionListeners.current) listener({
1148
+ center: [lng, lat],
1149
+ zoom: eventZoom
1150
+ });
1151
+ onMoveEndRef.current?.(lat, lng, eventZoom);
1152
+ }, []);
1153
+ const handleMapPress = useCallback((event) => {
1154
+ const lngLat = event.nativeEvent?.lngLat;
1155
+ const point = event.nativeEvent?.point;
1156
+ if (lngLat && point) {
1157
+ const press = {
1158
+ lngLat: [lngLat[0], lngLat[1]],
1159
+ point: [point[0], point[1]]
1160
+ };
1161
+ for (const listener of pressListeners.current) listener(press);
1162
+ }
1163
+ onPressRef.current?.(event);
1164
+ }, []);
427
1165
  const mapStyle = useMemo(() => {
428
1166
  setYarrowApiKey(config.apiKey);
429
1167
  return buildStyleUrl(config.styleType, config.theme);
@@ -439,213 +1177,234 @@ const YarrowMapView = forwardRef(({ apiKey, center, zoom, minZoom, maxZoom, them
439
1177
  const handleDidFailLoadingMap = useCallback(() => {
440
1178
  onLoadError?.(/* @__PURE__ */ new Error("Yarrow map failed to load — check the API key/network."));
441
1179
  }, [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
1180
+ const runtime = useMemo(() => ({
1181
+ apiKey: config.apiKey,
1182
+ theme: config.theme,
1183
+ mapRef,
1184
+ cameraRef: internalCameraRef,
1185
+ iconsByName,
1186
+ highlightedPoiIds,
1187
+ subscribeRegionChange,
1188
+ subscribePress
1189
+ }), [
1190
+ config.apiKey,
1191
+ config.theme,
1192
+ iconsByName,
1193
+ subscribeRegionChange,
1194
+ subscribePress
1195
+ ]);
1196
+ return /* @__PURE__ */ jsx(YarrowMapContext.Provider, {
1197
+ value: runtime,
1198
+ children: /* @__PURE__ */ jsxs(Map$1, {
1199
+ ref: (instance) => {
1200
+ mapRef.current = instance;
1201
+ assignRef(ref, instance);
461
1202
  },
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);
1203
+ mapStyle,
1204
+ style,
1205
+ attribution,
1206
+ logo,
1207
+ compass,
1208
+ onPress: handleMapPress,
1209
+ onRegionDidChange: handleRegionDidChange,
1210
+ onDidFinishLoadingMap: handleDidFinishLoadingMap,
1211
+ onDidFailLoadingMap: handleDidFailLoadingMap,
1212
+ children: [
1213
+ /* @__PURE__ */ jsx(Camera, {
1214
+ ref: (instance) => {
1215
+ internalCameraRef.current = instance;
1216
+ assignRef(cameraRef, instance);
1217
+ },
1218
+ initialViewState: {
1219
+ center: config.center,
1220
+ zoom: config.zoom
1221
+ },
1222
+ minZoom: config.minZoom,
1223
+ maxZoom: config.maxZoom
1224
+ }),
1225
+ icons ? /* @__PURE__ */ jsx(YarrowImages, {
1226
+ iconsByName,
1227
+ onMissingIcon: handleMissingIcon
1228
+ }) : null,
1229
+ children
1230
+ ]
1231
+ })
521
1232
  });
522
1233
  });
523
1234
 
524
- // src/hooks/useYarrowSearch.ts
1235
+ // src/markers/HighlightMarkerView.tsx
1236
+ const ENTER_MS = 280;
1237
+ const EXIT_MS = 200;
1238
+ const DEFAULT_ICON_SIZE = 56;
525
1239
  /**
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
- * ```
1240
+ * The animated icon+label marker shared by `<PoiHighlightLayer>` and
1241
+ * `<SearchResultsLayer>` — the native counterpart of the web SDK's
1242
+ * `createMarkerElement` + enter/exit CSS transitions. The scale/fade runs on
1243
+ * an inner view (never on the `Marker` itself, which the map repositions
1244
+ * every frame).
537
1245
  */
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);
1246
+ const HighlightMarkerView = memo(function HighlightMarkerView({ lngLat, iconUrl, title, iconSize, leaving = false, onPress }) {
1247
+ const progress = useRef(new Animated.Value(0)).current;
544
1248
  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;
1249
+ Animated.timing(progress, {
1250
+ toValue: leaving ? 0 : 1,
1251
+ duration: leaving ? EXIT_MS : ENTER_MS,
1252
+ useNativeDriver: true
1253
+ }).start();
1254
+ }, [progress, leaving]);
1255
+ const [width, height] = iconSize ? Array.isArray(iconSize) ? iconSize : [iconSize, iconSize] : [DEFAULT_ICON_SIZE, DEFAULT_ICON_SIZE];
1256
+ return /* @__PURE__ */ jsx(Marker, {
1257
+ lngLat,
1258
+ anchor: "center",
1259
+ onPress: onPress ? () => onPress() : void 0,
1260
+ children: /* @__PURE__ */ jsxs(Animated.View, {
1261
+ style: [styles.inner, {
1262
+ transform: [{ scale: progress }],
1263
+ opacity: progress
1264
+ }],
1265
+ children: [iconUrl ? /* @__PURE__ */ jsx(Image, {
1266
+ source: { uri: iconUrl },
1267
+ style: {
1268
+ width,
1269
+ height
1270
+ },
1271
+ resizeMode: "contain"
1272
+ }) : /* @__PURE__ */ jsx(View, { style: styles.dot }), title ? /* @__PURE__ */ jsx(View, {
1273
+ style: styles.titleWrap,
1274
+ pointerEvents: "none",
1275
+ children: /* @__PURE__ */ jsx(Text, {
1276
+ style: styles.title,
1277
+ children: title
1278
+ })
1279
+ }) : null]
1280
+ })
1281
+ });
1282
+ });
1283
+ const styles = StyleSheet.create({
1284
+ inner: {
1285
+ alignItems: "center",
1286
+ opacity: 0
1287
+ },
1288
+ dot: {
1289
+ width: 18,
1290
+ height: 18,
1291
+ borderRadius: 9,
1292
+ backgroundColor: "#2f80ed",
1293
+ borderWidth: 3,
1294
+ borderColor: "#ffffff"
1295
+ },
1296
+ titleWrap: {
1297
+ position: "absolute",
1298
+ top: "100%",
1299
+ width: "100%",
1300
+ alignItems: "center"
1301
+ },
1302
+ title: {
1303
+ marginTop: 3,
1304
+ maxWidth: 200,
1305
+ fontSize: 15,
1306
+ lineHeight: 18,
1307
+ fontWeight: "600",
1308
+ color: "#1a1a1a",
1309
+ textAlign: "center",
1310
+ textShadowColor: "#ffffff",
1311
+ textShadowRadius: 3,
1312
+ textShadowOffset: {
1313
+ width: 0,
1314
+ height: 0
552
1315
  }
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
- };
1316
+ }
1317
+ });
594
1318
 
595
- // src/hooks/useYarrowRouting.ts
1319
+ // src/markers/YarrowMarker.tsx
596
1320
  /**
597
- * Headless routing state for the Yarrow routing API — pairs with
598
- * `<RouteLayer>` for rendering.
1321
+ * Declarative counterpart of the web SDK's `addMarker()` / `removeMarker()`.
1322
+ * Mounting places the marker, unmounting removes it; the React lifecycle
1323
+ * replaces the imperative manager pair.
599
1324
  *
600
1325
  * ```tsx
601
- * const { routes, isLoading, buildRoute } = useYarrowRouting({ profile: 'driving' });
602
1326
  * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
603
- * <RouteLayer routes={routes} />
1327
+ * <YarrowMarker lngLat={[69.2401, 41.2995]} onPress={() => …}>
1328
+ * <PinIcon />
1329
+ * </YarrowMarker>
604
1330
  * </YarrowMapView>
605
1331
  * ```
606
1332
  */
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
- };
1333
+ const YarrowMarker = memo(function YarrowMarker({ lngLat, anchor = "bottom", offset, onPress, children }) {
1334
+ return /* @__PURE__ */ jsx(Marker, {
1335
+ lngLat,
1336
+ anchor,
1337
+ offset,
1338
+ onPress: onPress ? () => onPress() : void 0,
1339
+ children
1340
+ });
1341
+ });
1342
+
1343
+ // src/navigation/useYarrowCamera.ts
1344
+ const MIN_DIMENSION_DEGREES = .003;
1345
+ const DEFAULT_PADDING = 50;
1346
+ const DEFAULT_DURATION_MS = 1e3;
1347
+ /**
1348
+ * Web-parity camera helpers on top of a `CameraRef`. Reads the enclosing
1349
+ * `<YarrowMapView>` camera when called inside the map; otherwise pass a ref:
1350
+ *
1351
+ * ```tsx
1352
+ * const cameraRef = useRef<CameraRef>(null);
1353
+ * <YarrowMapView apiKey={KEY} cameraRef={cameraRef}>…</YarrowMapView>
1354
+ * const camera = useYarrowCamera(cameraRef);
1355
+ * camera.zoomTo(41.2995, 69.2401, 14);
1356
+ * ```
1357
+ */
1358
+ function useYarrowCamera(cameraRefInput) {
1359
+ const runtime = useYarrowMapRuntime();
1360
+ const cameraRef = cameraRefInput ?? runtime?.cameraRef ?? null;
1361
+ return useMemo(() => {
1362
+ const getCamera = () => cameraRef?.current ?? null;
1363
+ return {
1364
+ zoomTo(lat, lng, zoom, options) {
1365
+ const camera = getCamera();
1366
+ if (!camera) return;
1367
+ camera.flyTo({
1368
+ center: [lng, lat],
1369
+ zoom,
1370
+ ...options?.duration !== void 0 ? { duration: options.duration } : {}
1371
+ });
1372
+ },
1373
+ fitBounds(data, options) {
1374
+ const camera = getCamera();
1375
+ if (!camera) return;
1376
+ const box = getBoundingBox(data);
1377
+ const padding = options?.padding ?? DEFAULT_PADDING;
1378
+ const duration = options?.duration ?? DEFAULT_DURATION_MS;
1379
+ if (Math.abs(box.xMax - box.xMin) < MIN_DIMENSION_DEGREES) {
1380
+ box.xMin -= MIN_DIMENSION_DEGREES / 2;
1381
+ box.xMax += MIN_DIMENSION_DEGREES / 2;
1382
+ }
1383
+ if (Math.abs(box.yMax - box.yMin) < MIN_DIMENSION_DEGREES) {
1384
+ box.yMin -= MIN_DIMENSION_DEGREES / 2;
1385
+ box.yMax += MIN_DIMENSION_DEGREES / 2;
1386
+ }
1387
+ camera.fitBounds([
1388
+ box.xMin,
1389
+ box.yMin,
1390
+ box.xMax,
1391
+ box.yMax
1392
+ ], {
1393
+ padding: {
1394
+ top: padding,
1395
+ right: padding,
1396
+ bottom: padding,
1397
+ left: padding
1398
+ },
1399
+ duration
1400
+ });
1401
+ },
1402
+ getBoundingBox(data) {
1403
+ return getBoundingBox(data);
1404
+ }
1405
+ };
1406
+ }, [cameraRef]);
1407
+ }
649
1408
 
650
1409
  // src/offline/estimate.ts
651
1410
  /**
@@ -1180,6 +1939,546 @@ const useYarrowOfflineRegions = (options) => {
1180
1939
  };
1181
1940
  };
1182
1941
 
1942
+ // src/clustering/usePixelClusters.ts
1943
+ const REGION_DEBOUNCE_MS = 120;
1944
+ /**
1945
+ * Clusters marker points by screen distance — the runtime counterpart of the
1946
+ * web SDK's `PoiClusterController`. Native MapLibre can only cluster GeoJSON
1947
+ * *sources*, not marker views, so this re-projects the points on every map
1948
+ * move and regroups them: members of a group large enough (`minPoints`) are
1949
+ * hidden and replaced by a single count badge.
1950
+ *
1951
+ * Recompute runs when the points/config change and (debounced) on every map
1952
+ * move; badges are keyed by their first member id so React reuses them
1953
+ * across recomputes instead of flickering.
1954
+ */
1955
+ function usePixelClusters(points, config, runtime) {
1956
+ const normalized = useMemo(() => normalizeClusteringConfig(config), [config]);
1957
+ const [clusters, setClusters] = useState([]);
1958
+ const [clusteredIds, setClusteredIds] = useState(() => /* @__PURE__ */ new Set());
1959
+ const debounceRef = useRef(null);
1960
+ const runIdRef = useRef(0);
1961
+ const pointsRef = useRef(points);
1962
+ pointsRef.current = points;
1963
+ const pointsKey = useMemo(() => points.map((p) => `${p.id}:${p.lng},${p.lat}`).join("|"), [points]);
1964
+ useEffect(() => {
1965
+ const mapRef = runtime?.mapRef;
1966
+ if (!mapRef) {
1967
+ setClusters([]);
1968
+ setClusteredIds(/* @__PURE__ */ new Set());
1969
+ return;
1970
+ }
1971
+ const recompute = async () => {
1972
+ const map = mapRef.current;
1973
+ const current = pointsRef.current;
1974
+ if (!(normalized.enabled && map != null && current.length >= normalized.minPoints) || !map) {
1975
+ runIdRef.current += 1;
1976
+ setClusters([]);
1977
+ setClusteredIds(/* @__PURE__ */ new Set());
1978
+ return;
1979
+ }
1980
+ let zoom;
1981
+ try {
1982
+ zoom = await map.getZoom();
1983
+ } catch {
1984
+ return;
1985
+ }
1986
+ if (zoom > normalized.maxZoom) {
1987
+ runIdRef.current += 1;
1988
+ setClusters([]);
1989
+ setClusteredIds(/* @__PURE__ */ new Set());
1990
+ return;
1991
+ }
1992
+ const runId = ++runIdRef.current;
1993
+ const projected = await Promise.all(current.map(async (point) => {
1994
+ const pixel = await map.project([point.lng, point.lat]);
1995
+ return {
1996
+ point,
1997
+ x: pixel[0],
1998
+ y: pixel[1]
1999
+ };
2000
+ }));
2001
+ if (runId !== runIdRef.current) return;
2002
+ const nextClusters = [];
2003
+ const nextIds = /* @__PURE__ */ new Set();
2004
+ for (const group of groupByPixelRadius(projected, normalized.radius)) {
2005
+ if (group.length < normalized.minPoints) continue;
2006
+ const members = group.map((g) => g.point);
2007
+ let sumLng = 0;
2008
+ let sumLat = 0;
2009
+ for (const m of members) {
2010
+ sumLng += m.lng;
2011
+ sumLat += m.lat;
2012
+ nextIds.add(m.id);
2013
+ }
2014
+ nextClusters.push({
2015
+ key: members[0]?.id ?? 0,
2016
+ lng: sumLng / members.length,
2017
+ lat: sumLat / members.length,
2018
+ members: members.map((m) => ({
2019
+ id: m.id,
2020
+ lng: m.lng,
2021
+ lat: m.lat
2022
+ }))
2023
+ });
2024
+ }
2025
+ setClusters(nextClusters);
2026
+ setClusteredIds(nextIds);
2027
+ };
2028
+ recompute();
2029
+ const unsubscribe = runtime.subscribeRegionChange(() => {
2030
+ if (debounceRef.current) clearTimeout(debounceRef.current);
2031
+ debounceRef.current = setTimeout(() => {
2032
+ debounceRef.current = null;
2033
+ recompute();
2034
+ }, REGION_DEBOUNCE_MS);
2035
+ });
2036
+ return () => {
2037
+ unsubscribe();
2038
+ if (debounceRef.current) {
2039
+ clearTimeout(debounceRef.current);
2040
+ debounceRef.current = null;
2041
+ }
2042
+ };
2043
+ }, [
2044
+ runtime,
2045
+ normalized,
2046
+ pointsKey
2047
+ ]);
2048
+ return {
2049
+ clusters,
2050
+ clusteredIds
2051
+ };
2052
+ }
2053
+
2054
+ // src/utils/useExitAnimation.ts
2055
+ /**
2056
+ * Duration of the marker exit animation: 200 ms of visible ease-out (web
2057
+ * parity) plus a small buffer before the marker unmounts.
2058
+ */
2059
+ const EXIT_ANIMATION_MS = 220;
2060
+ /**
2061
+ * Tracks ids that left an "active" list so their exit animation can play
2062
+ * before unmount — the declarative replacement of the web SDK's
2063
+ * `animateOutMarker`. Returns the active ids unchanged and the ids that are
2064
+ * currently animating out; a caller renders those with a `leaving` flag and
2065
+ * keeps their last-resolved data until the animation finishes.
2066
+ *
2067
+ * Each removed id gets its own timer (per-id map, not one shared timeout), so
2068
+ * removing A and then B within the window removes both when their own timers
2069
+ * fire, and an id that comes back before its timer fires stops leaving
2070
+ * immediately.
2071
+ */
2072
+ function useExitAnimation(ids, exitMs = 220) {
2073
+ const [leavingIds, setLeavingIds] = useState([]);
2074
+ const prevRef = useRef(ids);
2075
+ const timersRef = useRef(/* @__PURE__ */ new Map());
2076
+ useEffect(() => {
2077
+ const prevSet = new Set(prevRef.current);
2078
+ prevRef.current = ids;
2079
+ const activeSet = new Set(ids);
2080
+ for (const id of activeSet) {
2081
+ const timer = timersRef.current.get(id);
2082
+ if (timer !== void 0) {
2083
+ clearTimeout(timer);
2084
+ timersRef.current.delete(id);
2085
+ }
2086
+ }
2087
+ for (const id of prevSet) {
2088
+ if (activeSet.has(id) || timersRef.current.has(id)) continue;
2089
+ timersRef.current.set(id, setTimeout(() => {
2090
+ timersRef.current.delete(id);
2091
+ setLeavingIds((current) => {
2092
+ if (!current.includes(id)) return current;
2093
+ return current.filter((x) => x !== id);
2094
+ });
2095
+ }, exitMs));
2096
+ }
2097
+ setLeavingIds((current) => {
2098
+ const pending = [...timersRef.current.keys()];
2099
+ if (pending.length === current.length) {
2100
+ const currentSet = new Set(current);
2101
+ if (pending.every((id) => currentSet.has(id))) return current;
2102
+ }
2103
+ return pending;
2104
+ });
2105
+ }, [ids, exitMs]);
2106
+ useEffect(() => {
2107
+ const timers = timersRef.current;
2108
+ return () => {
2109
+ for (const timer of timers.values()) clearTimeout(timer);
2110
+ timers.clear();
2111
+ };
2112
+ }, []);
2113
+ const activeSet = useMemo(() => new Set(ids), [ids]);
2114
+ return {
2115
+ activeIds: ids,
2116
+ leavingIds: useMemo(() => leavingIds.filter((id) => !activeSet.has(id)), [leavingIds, activeSet])
2117
+ };
2118
+ }
2119
+
2120
+ // src/poiHighlight/PoiHighlightLayer.tsx
2121
+ const DEFAULT_PAN_ZOOM = 13;
2122
+ /** Milliseconds after an exit before an id's resolved data is pruned. */
2123
+ const EXIT_PRUNE_MS = 250;
2124
+ /**
2125
+ * Declarative counterpart of the web SDK's `highlightPOI()`: renders an
2126
+ * animated icon+label marker for each highlighted POI id, resolving each id
2127
+ * cheapest-first (caller data → rendered tiles → place-detail API).
2128
+ * Highlight state is owned by the `ids` prop (or
2129
+ * `useYarrowPoiHighlight().highlightedIds`); removing an id plays the exit
2130
+ * animation and unmounts the marker.
2131
+ *
2132
+ * Known native limitation (documented in the README): the base style's own
2133
+ * POI icon is not hidden behind the highlight marker — native has no runtime
2134
+ * `setFilter`, so the marker simply draws on top of it.
2135
+ *
2136
+ * ```tsx
2137
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
2138
+ * <PoiHighlightLayer ids={[123]} dataById={{ 123: { location } }} panTo />
2139
+ * </YarrowMapView>
2140
+ * ```
2141
+ */
2142
+ function PoiHighlightLayer({ ids, dataById, iconSize, panTo = false, zoom, clustering, onHighlightPress, onResolveError }) {
2143
+ const runtime = useYarrowMapRuntime();
2144
+ const camera = useYarrowCamera();
2145
+ const idList = useMemo(() => {
2146
+ return [...new Set(Array.isArray(ids) ? ids : [ids])];
2147
+ }, [ids]);
2148
+ const { activeIds, leavingIds } = useExitAnimation(idList);
2149
+ const [resolved, setResolved] = useState({});
2150
+ const resolveCacheRef = useRef(/* @__PURE__ */ new Map());
2151
+ const failedIdsRef = useRef(/* @__PURE__ */ new Set());
2152
+ const dataByIdRef = useRef(dataById);
2153
+ dataByIdRef.current = dataById;
2154
+ const onResolveErrorRef = useRef(onResolveError);
2155
+ onResolveErrorRef.current = onResolveError;
2156
+ const resolveOnce = useMemo(() => (id) => {
2157
+ if (!runtime) return Promise.resolve(null);
2158
+ const pending = resolveCacheRef.current.get(id);
2159
+ if (pending) return pending;
2160
+ const promise = resolvePoiData(id, dataByIdRef.current?.[id] ?? {}, runtime).then((result) => {
2161
+ if (result === null) {
2162
+ if (resolveCacheRef.current.get(id) === promise) resolveCacheRef.current.delete(id);
2163
+ onResolveErrorRef.current?.(id);
2164
+ }
2165
+ return result;
2166
+ });
2167
+ resolveCacheRef.current.set(id, promise);
2168
+ return promise;
2169
+ }, [runtime]);
2170
+ useEffect(() => {
2171
+ if (!runtime) return;
2172
+ let cancelled = false;
2173
+ for (const id of activeIds) {
2174
+ if (resolved[id] !== void 0 || failedIdsRef.current.has(id)) continue;
2175
+ resolveOnce(id).then((data) => {
2176
+ if (cancelled) return;
2177
+ if (!data) {
2178
+ failedIdsRef.current.add(id);
2179
+ return;
2180
+ }
2181
+ setResolved((current) => current[id] !== void 0 ? current : {
2182
+ ...current,
2183
+ [id]: data
2184
+ });
2185
+ });
2186
+ }
2187
+ return () => {
2188
+ cancelled = true;
2189
+ };
2190
+ }, [
2191
+ runtime,
2192
+ activeIds,
2193
+ resolved,
2194
+ resolveOnce
2195
+ ]);
2196
+ useEffect(() => {
2197
+ const failed = failedIdsRef.current;
2198
+ for (const id of [...failed]) if (!idList.includes(id)) failed.delete(id);
2199
+ }, [idList]);
2200
+ useEffect(() => {
2201
+ if (!runtime) return;
2202
+ const registry = runtime.highlightedPoiIds.current;
2203
+ if (!registry) return;
2204
+ const next = new Set(activeIds);
2205
+ let changed = registry.size !== next.size;
2206
+ if (!changed) {
2207
+ for (const id of next) if (!registry.has(id)) {
2208
+ changed = true;
2209
+ break;
2210
+ }
2211
+ }
2212
+ if (changed) runtime.highlightedPoiIds.current = next;
2213
+ }, [runtime, activeIds]);
2214
+ useEffect(() => {
2215
+ if (leavingIds.length === 0) return;
2216
+ const timers = leavingIds.map((id) => setTimeout(() => {
2217
+ setResolved((current) => {
2218
+ if (current[id] === void 0) return current;
2219
+ const next = { ...current };
2220
+ delete next[id];
2221
+ return next;
2222
+ });
2223
+ resolveCacheRef.current.delete(id);
2224
+ }, EXIT_PRUNE_MS));
2225
+ return () => {
2226
+ for (const timer of timers) clearTimeout(timer);
2227
+ };
2228
+ }, [leavingIds]);
2229
+ const points = useMemo(() => activeIds.flatMap((id) => {
2230
+ const data = resolved[id];
2231
+ return data ? [{
2232
+ id,
2233
+ lng: data.lng,
2234
+ lat: data.lat
2235
+ }] : [];
2236
+ }), [activeIds, resolved]);
2237
+ const { clusters, clusteredIds } = usePixelClusters(points, clustering, runtime);
2238
+ const panToKey = panTo ? idList.join(",") : "";
2239
+ useEffect(() => {
2240
+ if (!panToKey || !runtime) return;
2241
+ let cancelled = false;
2242
+ const idsToPan = panToKey.split(",").map(Number);
2243
+ (async () => {
2244
+ const places = (await Promise.all(idsToPan.map((id) => resolveOnce(id)))).filter((p) => p !== null);
2245
+ if (cancelled || places.length === 0) return;
2246
+ const [first] = places;
2247
+ if (!first) return;
2248
+ if (places.length === 1) {
2249
+ const currentZoom = await runtime.mapRef.current?.getZoom().catch(() => null);
2250
+ const targetZoom = zoom ?? Math.max(DEFAULT_PAN_ZOOM, currentZoom ?? DEFAULT_PAN_ZOOM);
2251
+ camera.zoomTo(first.lat, first.lng, targetZoom);
2252
+ return;
2253
+ }
2254
+ camera.fitBounds({
2255
+ type: "FeatureCollection",
2256
+ features: places.map((p) => ({ geometry: {
2257
+ type: "Point",
2258
+ coordinates: [p.lng, p.lat]
2259
+ } }))
2260
+ });
2261
+ })();
2262
+ return () => {
2263
+ cancelled = true;
2264
+ };
2265
+ }, [
2266
+ panToKey,
2267
+ zoom,
2268
+ runtime,
2269
+ camera,
2270
+ resolveOnce
2271
+ ]);
2272
+ const handleClusterPress = (children) => {
2273
+ let zoomToExpand = true;
2274
+ if (clustering && typeof clustering === "object") {
2275
+ if (clustering.onClusterClick?.(children) === false) zoomToExpand = false;
2276
+ }
2277
+ if (!zoomToExpand || children.length === 0) return;
2278
+ camera.fitBounds({
2279
+ type: "FeatureCollection",
2280
+ features: children.map((c) => ({ geometry: {
2281
+ type: "Point",
2282
+ coordinates: [c.lng, c.lat]
2283
+ } }))
2284
+ });
2285
+ };
2286
+ if (!runtime) return null;
2287
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2288
+ activeIds.map((id) => {
2289
+ const data = resolved[id];
2290
+ if (!data || clusteredIds.has(id)) return null;
2291
+ return /* @__PURE__ */ jsx(HighlightMarkerView, {
2292
+ lngLat: [data.lng, data.lat],
2293
+ iconUrl: data.iconUrl,
2294
+ title: data.title,
2295
+ iconSize,
2296
+ onPress: () => onHighlightPress?.({
2297
+ id,
2298
+ lng: data.lng,
2299
+ lat: data.lat,
2300
+ title: data.title,
2301
+ iconUrl: data.iconUrl
2302
+ })
2303
+ }, id);
2304
+ }),
2305
+ leavingIds.map((id) => {
2306
+ const data = resolved[id];
2307
+ if (!data) return null;
2308
+ return /* @__PURE__ */ jsx(HighlightMarkerView, {
2309
+ lngLat: [data.lng, data.lat],
2310
+ iconUrl: data.iconUrl,
2311
+ title: data.title,
2312
+ iconSize,
2313
+ leaving: true
2314
+ }, `leaving-${id}`);
2315
+ }),
2316
+ clusters.map((cluster) => /* @__PURE__ */ jsx(ClusterBadge, {
2317
+ lngLat: [cluster.lng, cluster.lat],
2318
+ count: cluster.members.length,
2319
+ theme: runtime.theme,
2320
+ onPress: () => handleClusterPress(cluster.members)
2321
+ }, cluster.key))
2322
+ ] });
2323
+ }
2324
+
2325
+ // src/poiHighlight/useYarrowPoiHighlight.ts
2326
+ /**
2327
+ * Headless highlight state — the declarative counterpart of the web SDK's
2328
+ * `highlightPOI` / `resetPOIHighlight` / `isPOIHighlighted` /
2329
+ * `getHighlightedPOIs` quartet. Rendering is owned by `<PoiHighlightLayer>`:
2330
+ *
2331
+ * ```tsx
2332
+ * const { highlightedIds, highlight } = useYarrowPoiHighlight();
2333
+ * <YarrowMapView apiKey={KEY}>
2334
+ * <PoiHighlightLayer ids={highlightedIds} panTo />
2335
+ * </YarrowMapView>
2336
+ * ```
2337
+ */
2338
+ function useYarrowPoiHighlight() {
2339
+ const [highlightedIds, setHighlightedIds] = useState([]);
2340
+ const reset = useCallback((input) => {
2341
+ setHighlightedIds((current) => {
2342
+ if (input === void 0) return [];
2343
+ const remove = new Set(Array.isArray(input) ? input : [input]);
2344
+ return current.filter((id) => !remove.has(id));
2345
+ });
2346
+ }, []);
2347
+ const highlight = useCallback((input, options) => {
2348
+ const ids = Array.isArray(input) ? input : [input];
2349
+ setHighlightedIds((current) => {
2350
+ const next = [...options?.replace ? [] : current];
2351
+ for (const id of ids) if (!next.includes(id)) next.push(id);
2352
+ return next;
2353
+ });
2354
+ return ids.map((id) => ({
2355
+ id,
2356
+ remove: () => reset(id)
2357
+ }));
2358
+ }, [reset]);
2359
+ const isHighlighted = useCallback((id) => highlightedIds.includes(id), [highlightedIds]);
2360
+ return useMemo(() => ({
2361
+ highlightedIds,
2362
+ highlight,
2363
+ reset,
2364
+ isHighlighted
2365
+ }), [
2366
+ highlightedIds,
2367
+ highlight,
2368
+ reset,
2369
+ isHighlighted
2370
+ ]);
2371
+ }
2372
+
2373
+ // src/search/SearchResultsLayer.tsx
2374
+ /**
2375
+ * Renders search results on the map — the declarative counterpart of the web
2376
+ * SDK's `highlightSearchResults()`. Icon precedence per result:
2377
+ * `icon_img` → registry icon by `category.name` → blue-dot fallback.
2378
+ *
2379
+ * ```tsx
2380
+ * const { results, isLoading } = useYarrowSearch(query, { lat, lon });
2381
+ * <YarrowMapView apiKey={KEY}>
2382
+ * <SearchResultsLayer results={results} onResultPress={…} />
2383
+ * </YarrowMapView>
2384
+ * ```
2385
+ */
2386
+ function SearchResultsLayer({ results, iconSize, zoomToResults = true, fitKey, clustering, onResultPress }) {
2387
+ const runtime = useYarrowMapRuntime();
2388
+ const camera = useYarrowCamera();
2389
+ const markers = useMemo(() => {
2390
+ const keyed = [];
2391
+ const seen = /* @__PURE__ */ new Set();
2392
+ results.forEach((result) => {
2393
+ const { latitude, longitude } = result;
2394
+ if (typeof latitude !== "number" || typeof longitude !== "number") return;
2395
+ const id = result.id;
2396
+ let key;
2397
+ if (id !== void 0 && !seen.has(id)) key = id;
2398
+ else key = `idx:${keyed.length}`;
2399
+ seen.add(key);
2400
+ keyed.push({
2401
+ key,
2402
+ result,
2403
+ lng: longitude,
2404
+ lat: latitude
2405
+ });
2406
+ });
2407
+ return keyed;
2408
+ }, [results]);
2409
+ const points = useMemo(() => markers.map((m) => ({
2410
+ id: m.key,
2411
+ lng: m.lng,
2412
+ lat: m.lat
2413
+ })), [markers]);
2414
+ useEffect(() => {
2415
+ if (results.length > 0 && markers.length === 0) console.warn(`[YarrowMap] SearchResultsLayer: ${results.length} result(s) returned, none with displayable coordinates`);
2416
+ }, [results, markers]);
2417
+ const { clusters, clusteredIds } = usePixelClusters(points, clustering, runtime);
2418
+ const fittedRef = useRef(false);
2419
+ const lastFitKeyRef = useRef(fitKey);
2420
+ if (lastFitKeyRef.current !== fitKey) {
2421
+ lastFitKeyRef.current = fitKey;
2422
+ fittedRef.current = false;
2423
+ }
2424
+ const firstCoords = useMemo(() => {
2425
+ const [first] = markers;
2426
+ return first ? `${first.lat},${first.lng}` : null;
2427
+ }, [markers]);
2428
+ useEffect(() => {
2429
+ if (!zoomToResults || !runtime || fittedRef.current) return;
2430
+ if (!firstCoords) return;
2431
+ fittedRef.current = true;
2432
+ camera.fitBounds({
2433
+ type: "FeatureCollection",
2434
+ features: markers.map((m) => ({
2435
+ geometry: {
2436
+ type: "Point",
2437
+ coordinates: [m.lng, m.lat]
2438
+ },
2439
+ properties: { name: m.result.name }
2440
+ }))
2441
+ });
2442
+ }, [
2443
+ firstCoords,
2444
+ zoomToResults,
2445
+ runtime,
2446
+ camera,
2447
+ markers
2448
+ ]);
2449
+ const handleClusterPress = (children) => {
2450
+ let zoomToExpand = true;
2451
+ if (clustering && typeof clustering === "object") {
2452
+ if (clustering.onClusterClick?.(children) === false) zoomToExpand = false;
2453
+ }
2454
+ if (!zoomToExpand || children.length === 0) return;
2455
+ camera.fitBounds({
2456
+ type: "FeatureCollection",
2457
+ features: children.map((c) => ({ geometry: {
2458
+ type: "Point",
2459
+ coordinates: [c.lng, c.lat]
2460
+ } }))
2461
+ });
2462
+ };
2463
+ if (!runtime) return null;
2464
+ return /* @__PURE__ */ jsxs(Fragment, { children: [markers.map(({ key, result, lng, lat }) => {
2465
+ if (clusteredIds.has(key)) return null;
2466
+ const iconUrl = result.icon_img ?? resolveCategoryIcon(runtime.iconsByName, result.category?.name);
2467
+ return /* @__PURE__ */ jsx(HighlightMarkerView, {
2468
+ lngLat: [lng, lat],
2469
+ iconUrl: typeof iconUrl === "string" ? iconUrl : void 0,
2470
+ title: result.name,
2471
+ iconSize,
2472
+ onPress: () => onResultPress?.(lat, lng, result)
2473
+ }, key);
2474
+ }), clusters.map((cluster) => /* @__PURE__ */ jsx(ClusterBadge, {
2475
+ lngLat: [cluster.lng, cluster.lat],
2476
+ count: cluster.members.length,
2477
+ theme: runtime.theme,
2478
+ onPress: () => handleClusterPress(cluster.members)
2479
+ }, cluster.key))] });
2480
+ }
2481
+
1183
2482
  // src/utils/userToken.ts
1184
2483
  /**
1185
2484
  * Bridges the async AsyncStorage API onto core's synchronous TokenStorage
@@ -1219,4 +2518,4 @@ async function setAsyncStorageTokenStorage(storage) {
1219
2518
  });
1220
2519
  }
1221
2520
 
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 };
2521
+ 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 };