@brightlocal/ui-components 2.14.0 → 2.16.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.
@@ -1,5 +1,12 @@
1
+ "use client";
2
+
1
3
  import * as React from "react";
2
- import { AlertCircle } from "@brightlocal/icons";
4
+ import { cva } from "class-variance-authority";
5
+ import { RefreshCw, Store, TriangleAlert } from "@brightlocal/icons";
6
+ import {
7
+ GlobeyFixingFault,
8
+ MapBackground as MapBackgroundImage,
9
+ } from "@brightlocal/illustrations";
3
10
  import { Button } from "@brightlocal/ui-components/button";
4
11
  import { Card, CardContent } from "@brightlocal/ui-components/card";
5
12
  import { cn } from "@brightlocal/ui-components/lib/utils";
@@ -24,7 +31,7 @@ import {
24
31
  const MapTypeId = {
25
32
  /** Default road map view */
26
33
  ROADMAP: "roadmap",
27
- /** Satellite imagery */
34
+ /** @deprecated Satellite imagery — prefer cloud-based map styling via Map ID */
28
35
  SATELLITE: "satellite",
29
36
  } as const;
30
37
 
@@ -33,37 +40,286 @@ const MapTypeId = {
33
40
  */
34
41
  type MapTypeIdValue = (typeof MapTypeId)[keyof typeof MapTypeId];
35
42
 
43
+ // ──────────────────────────────────────
44
+ // MapStyleVariant & useMapStyles
45
+ // ──────────────────────────────────────
46
+
47
+ /**
48
+ * Visual variant for map styling.
49
+ * - `"default"` — Standard Google Maps appearance (no custom styles in light mode)
50
+ * - `"muted"` — Desaturated, softened map appearance so UI elements stand out
51
+ */
52
+ type MapStyleVariant = "default" | "muted";
53
+
54
+ /**
55
+ * A single Google Maps JSON style rule.
56
+ * Matches the `google.maps.MapTypeStyle` shape so values can be passed
57
+ * directly to the `styles` prop of `@vis.gl/react-google-maps` `<Map>`.
58
+ */
59
+ type MapStyleRule = {
60
+ featureType?: string;
61
+ elementType?: string;
62
+ stylers: Record<string, string | number>[];
63
+ };
64
+
65
+ const FEATURE_TYPES = ["water", "landscape", "road", "poi", "transit"] as const;
66
+
67
+ function makeSatLightPreset(
68
+ saturation: number,
69
+ lightness: number
70
+ ): MapStyleRule[] {
71
+ return [
72
+ ...FEATURE_TYPES.map((ft) => ({
73
+ featureType: ft,
74
+ elementType: "geometry",
75
+ stylers: [{ saturation, lightness }],
76
+ })),
77
+ {
78
+ elementType: "labels.text.fill",
79
+ stylers: [{ saturation, lightness: lightness - 10 }],
80
+ },
81
+ {
82
+ elementType: "labels.icon",
83
+ stylers: [{ saturation, lightness }],
84
+ },
85
+ ];
86
+ }
87
+
88
+ const DARK_PRESET: MapStyleRule[] = [
89
+ { elementType: "geometry", stylers: [{ color: "#444444" }] },
90
+ { elementType: "labels.text.fill", stylers: [{ color: "#aaaaaa" }] },
91
+ { elementType: "labels.text.stroke", stylers: [{ color: "#323232" }] },
92
+ {
93
+ featureType: "water",
94
+ elementType: "geometry",
95
+ stylers: [{ color: "#30405a" }],
96
+ },
97
+ {
98
+ featureType: "landscape",
99
+ elementType: "geometry",
100
+ stylers: [{ color: "#4b4b4b" }],
101
+ },
102
+ {
103
+ featureType: "road",
104
+ elementType: "geometry",
105
+ stylers: [{ color: "#5c5c5c" }],
106
+ },
107
+ {
108
+ featureType: "road",
109
+ elementType: "geometry.stroke",
110
+ stylers: [{ color: "#3e3e3e" }],
111
+ },
112
+ {
113
+ featureType: "poi",
114
+ elementType: "geometry",
115
+ stylers: [{ color: "#525252" }],
116
+ },
117
+ {
118
+ featureType: "transit",
119
+ elementType: "geometry",
120
+ stylers: [{ color: "#505050" }],
121
+ },
122
+ { elementType: "labels.icon", stylers: [{ visibility: "off" }] },
123
+ ];
124
+
125
+ /**
126
+ * Built-in map style presets keyed by `variant.theme`.
127
+ *
128
+ * - `default.light` — empty (uses native Google Maps styling)
129
+ * - `default.dark` — dark colour palette based on "Example 3 Dark"
130
+ * - `muted.light` — desaturated/lightened based on "Example 2" (`sat -40, light +20`)
131
+ * - `muted.dark` — same dark palette as `default.dark`
132
+ */
133
+ const MAP_STYLES: Record<
134
+ MapStyleVariant,
135
+ { light: MapStyleRule[]; dark: MapStyleRule[] }
136
+ > = {
137
+ default: { light: [], dark: DARK_PRESET },
138
+ muted: { light: makeSatLightPreset(-40, 20), dark: DARK_PRESET },
139
+ };
140
+
141
+ // Shared dark mode store — one MutationObserver for all consumers
142
+ const _darkModeListeners = new Set<() => void>();
143
+ let _isDark =
144
+ typeof document !== "undefined" && document.body.classList.contains("dark");
145
+ let _darkModeObserverStarted = false;
146
+
147
+ function _initDarkModeObserver() {
148
+ if (_darkModeObserverStarted || typeof document === "undefined") return;
149
+ _darkModeObserverStarted = true;
150
+ const observer = new MutationObserver(() => {
151
+ const next = document.body.classList.contains("dark");
152
+ if (next !== _isDark) {
153
+ _isDark = next;
154
+ for (const fn of _darkModeListeners) fn();
155
+ }
156
+ });
157
+ observer.observe(document.body, {
158
+ attributes: true,
159
+ attributeFilter: ["class"],
160
+ });
161
+ }
162
+
163
+ function _subscribeDarkMode(onStoreChange: () => void): () => void {
164
+ _darkModeListeners.add(onStoreChange);
165
+ _initDarkModeObserver();
166
+ return () => {
167
+ _darkModeListeners.delete(onStoreChange);
168
+ };
169
+ }
170
+
171
+ function _getDarkModeSnapshot(): boolean {
172
+ return _isDark;
173
+ }
174
+
175
+ function _getDarkModeServerSnapshot(): boolean {
176
+ return false;
177
+ }
178
+
179
+ function useIsDarkMode(): boolean {
180
+ return React.useSyncExternalStore(
181
+ _subscribeDarkMode,
182
+ _getDarkModeSnapshot,
183
+ _getDarkModeServerSnapshot
184
+ );
185
+ }
186
+
187
+ /**
188
+ * Returns the appropriate `google.maps.MapTypeStyle[]` for the given variant
189
+ * and the current color scheme (light/dark). Pass the returned array to the
190
+ * `styles` prop of `@vis.gl/react-google-maps` `<Map>`.
191
+ *
192
+ * Dark mode is detected automatically via the `dark` class on `document.body`.
193
+ *
194
+ * > **Note:** JSON styling works with **raster maps only** (no `mapId` prop).
195
+ * > For vector maps use [Cloud-based Map Styling](https://developers.google.com/maps/documentation/javascript/cloud-based-map-styling).
196
+ *
197
+ * @example
198
+ * ```tsx
199
+ * import { useMapStyles } from "@brightlocal/ui-components/map";
200
+ *
201
+ * function MyMap() {
202
+ * const styles = useMapStyles("muted");
203
+ * return <Map styles={styles} defaultCenter={center} defaultZoom={14} />;
204
+ * }
205
+ * ```
206
+ */
207
+ function useMapStyles(variant: MapStyleVariant = "default"): MapStyleRule[] {
208
+ const isDark = useIsDarkMode();
209
+ return MAP_STYLES[variant][isDark ? "dark" : "light"];
210
+ }
211
+
36
212
  // ──────────────────────────────────────
37
213
  // MapGridPin
38
214
  // ──────────────────────────────────────
39
215
 
40
- type MapGridPinVariant =
216
+ type ResolvedVariant = "strong" | "moderate" | "weak" | "unranked" | "error";
217
+
218
+ /** @deprecated Legacy variant names kept for backward compatibility. */
219
+ type LegacyVariant =
41
220
  | "primary"
42
221
  | "secondary"
43
222
  | "destructive"
44
223
  | "outline"
45
224
  | "warning";
46
225
 
47
- const gridPinPulseVar: Record<MapGridPinVariant, string> = {
48
- primary: "var(--primary)",
49
- secondary: "var(--secondary)",
50
- destructive: "var(--destructive)",
51
- outline: "var(--muted)",
52
- warning: "var(--warning-background)",
226
+ type MapGridPinVariant = ResolvedVariant | LegacyVariant;
227
+
228
+ /** @deprecated Maps legacy variant names to current ones. */
229
+ const legacyVariantMap: Record<LegacyVariant, ResolvedVariant> = {
230
+ primary: "strong",
231
+ secondary: "moderate",
232
+ warning: "moderate",
233
+ destructive: "unranked",
234
+ outline: "unranked",
235
+ };
236
+
237
+ function isLegacyVariant(v: string): v is LegacyVariant {
238
+ return v in legacyVariantMap;
239
+ }
240
+
241
+ function resolveVariant(variant: MapGridPinVariant): ResolvedVariant {
242
+ return isLegacyVariant(variant) ? legacyVariantMap[variant] : variant;
243
+ }
244
+
245
+ /**
246
+ * Single source of truth for ranking variant colors.
247
+ * Tailwind classes power MapGridPin / MapLegendItem; CSS vars + hex
248
+ * fallbacks power the cluster-pin SVG renderer.
249
+ */
250
+ const RANKING_COLORS: Record<
251
+ ResolvedVariant,
252
+ { className: string; cssVar: string; fallback: string }
253
+ > = {
254
+ strong: {
255
+ className: "bg-primary dark:bg-green-400",
256
+ cssVar: "--ds-tailwind-colors-green-400",
257
+ fallback: "#2ae855",
258
+ },
259
+ moderate: {
260
+ className: "bg-chart-4",
261
+ cssVar: "--ds-tailwind-colors-yellow-400",
262
+ fallback: "#facc15",
263
+ },
264
+ weak: {
265
+ className: "bg-orange-400",
266
+ cssVar: "--ds-tailwind-colors-orange-400",
267
+ fallback: "#fb923c",
268
+ },
269
+ unranked: {
270
+ className: "bg-red-600",
271
+ cssVar: "--ds-tailwind-colors-red-600",
272
+ fallback: "#dc2626",
273
+ },
274
+ error: {
275
+ className: "bg-warning-background dark:bg-orange-200",
276
+ cssVar: "--ds-tailwind-colors-orange-200",
277
+ fallback: "#fed7aa",
278
+ },
53
279
  };
54
280
 
281
+ /**
282
+ * Background color classes for each ranking variant.
283
+ * Derived from {@link RANKING_COLORS} — used by MapGridPin (CVA) and MapLegendItem.
284
+ */
285
+ const mapGridPinColorMap: Record<ResolvedVariant, string> = Object.fromEntries(
286
+ Object.entries(RANKING_COLORS).map(([k, v]) => [k, v.className])
287
+ ) as Record<ResolvedVariant, string>;
288
+
289
+ const mapGridPinVariants = cva(
290
+ "inline-flex items-center justify-center rounded-full font-sans text-sm font-semibold text-foreground dark:text-neutral-900 border-2 border-white shadow-sm transition-shadow duration-200 ease-out hover:shadow-md",
291
+ {
292
+ variants: {
293
+ variant: {
294
+ strong: `${mapGridPinColorMap.strong}`,
295
+ moderate: `${mapGridPinColorMap.moderate}`,
296
+ weak: `${mapGridPinColorMap.weak}`,
297
+ unranked: `${mapGridPinColorMap.unranked} text-white dark:text-white`,
298
+ error: `${mapGridPinColorMap.error}`,
299
+ },
300
+ },
301
+ defaultVariants: {
302
+ variant: "strong",
303
+ },
304
+ }
305
+ );
306
+
55
307
  /**
56
308
  * Props for the MapGridPin component.
57
309
  */
58
310
  interface MapGridPinProps extends Omit<
59
- React.ComponentProps<"button">,
60
- "children" | "type"
311
+ React.ComponentProps<"div">,
312
+ "children"
61
313
  > {
62
314
  /** Value displayed inside the pin (number or short label) */
63
315
  value: number | string;
64
- /** Button variant — consumer controls this based on value thresholds */
316
+ /** Color variant — consumer controls this based on value thresholds */
65
317
  variant?: MapGridPinVariant;
66
- /** Enable infinite pulse animation radiating from the pin */
318
+ /** Show loading appearance (neutral styling, overrides variant colors) */
319
+ loading?: boolean;
320
+ /**
321
+ * @deprecated No longer rendered. Kept for backward compatibility.
322
+ */
67
323
  pulse?: boolean;
68
324
  /** Required test hook identifier */
69
325
  dataHook: string;
@@ -74,56 +330,386 @@ interface MapGridPinProps extends Omit<
74
330
  }
75
331
 
76
332
  /**
77
- * A circular map pin button that displays a numeric value with a colored background.
78
- * Uses the Button component internally. Color is determined by the `variant` prop —
79
- * the consumer controls which variant to apply based on the value.
80
- * Supports an optional `pulse` animation for emphasis.
333
+ * A circular map pin that displays a numeric value with a colored background.
334
+ * Renders as a non-focusable `div` (compatible with Google Maps AdvancedMarkerElement).
335
+ * Color is determined by the `variant` prop — the consumer controls which variant
336
+ * to apply based on the value.
81
337
  */
82
- const MapGridPin = React.forwardRef<HTMLButtonElement, MapGridPinProps>(
338
+ const MapGridPin = React.forwardRef<HTMLDivElement, MapGridPinProps>(
83
339
  (
84
340
  {
85
341
  value,
86
- variant = "primary",
87
- pulse = false,
342
+ variant: variantProp = "strong",
343
+ loading = false,
344
+ pulse: _pulse, // eslint-disable-line @typescript-eslint/no-unused-vars -- absorbed from ...props to prevent DOM passthrough
88
345
  dataHook,
89
346
  className,
90
347
  trackingEl,
91
348
  trackingLabel,
349
+ style,
92
350
  ...props
93
351
  },
94
352
  ref
95
353
  ) => {
354
+ const variant = resolveVariant(variantProp);
355
+
96
356
  return (
97
- <Button
357
+ <div
98
358
  ref={ref}
99
359
  className={cn(
360
+ loading
361
+ ? "border-border bg-accent rounded-full border"
362
+ : mapGridPinVariants({ variant }),
100
363
  "size-8 p-0",
101
- pulse &&
102
- "animate-grid-pin-pulse transition-none motion-reduce:animate-none",
103
364
  className
104
365
  )}
105
- dataHook={dataHook}
106
- size="sm"
107
- style={
108
- pulse
109
- ? ({
110
- "--grid-pin-pulse-color": gridPinPulseVar[variant],
111
- } as React.CSSProperties)
112
- : undefined
113
- }
114
- trackingEl={trackingEl || "map-grid-pin"}
115
- trackingLabel={trackingLabel}
116
- variant={variant}
366
+ data-hook={dataHook}
367
+ data-slot="map-grid-pin"
368
+ data-state={loading ? "loading" : undefined}
369
+ data-tracking-el={trackingEl || "map-grid-pin"}
370
+ data-tracking-label={trackingLabel}
371
+ style={style}
117
372
  {...props}
118
373
  >
119
- {String(value)}
120
- </Button>
374
+ {variant === "error" && !loading ? (
375
+ <TriangleAlert
376
+ aria-hidden="true"
377
+ className="text-warning-foreground"
378
+ size={14}
379
+ />
380
+ ) : (
381
+ String(value)
382
+ )}
383
+ </div>
121
384
  );
122
385
  }
123
386
  );
124
387
 
125
388
  MapGridPin.displayName = "MapGridPin";
126
389
 
390
+ // ──────────────────────────────────────
391
+ // MapClusterPin
392
+ // ──────────────────────────────────────
393
+
394
+ interface ClusterPinResolvedStyles {
395
+ colors: Record<ResolvedVariant, string>;
396
+ fontFamily: string;
397
+ textColor: string;
398
+ }
399
+
400
+ function resolveClusterPinStyles(): ClusterPinResolvedStyles {
401
+ const fallbackColors = Object.fromEntries(
402
+ Object.entries(RANKING_COLORS).map(([k, v]) => [k, v.fallback])
403
+ ) as Record<ResolvedVariant, string>;
404
+ const fallback: ClusterPinResolvedStyles = {
405
+ colors: fallbackColors,
406
+ fontFamily: "Inter, system-ui, sans-serif",
407
+ textColor: "#111412",
408
+ };
409
+ if (typeof document === "undefined") return fallback;
410
+ const style = getComputedStyle(document.documentElement);
411
+ return {
412
+ colors: Object.fromEntries(
413
+ Object.entries(RANKING_COLORS).map(([k, { cssVar, fallback: fb }]) => [
414
+ k,
415
+ style.getPropertyValue(cssVar).trim() || fb,
416
+ ])
417
+ ) as Record<ResolvedVariant, string>,
418
+ fontFamily:
419
+ style.getPropertyValue("--ds-font-font-sans").trim() ||
420
+ fallback.fontFamily,
421
+ textColor:
422
+ style.getPropertyValue("--ds-tailwind-colors-neutral-950").trim() ||
423
+ fallback.textColor,
424
+ };
425
+ }
426
+
427
+ function resolveClusterPinColors(): Record<ResolvedVariant, string> {
428
+ return resolveClusterPinStyles().colors;
429
+ }
430
+
431
+ /**
432
+ * Resolved hex color values for each ranking variant.
433
+ * Reads from CSS custom properties at runtime so colors stay in sync
434
+ * with the design-token pipeline. Falls back to hardcoded hex for SSR.
435
+ *
436
+ * @deprecated Prefer calling {@link resolveClusterPinColors} directly
437
+ * for guaranteed up-to-date values. This static snapshot is kept for
438
+ * backward compatibility.
439
+ */
440
+ const clusterPinHexColors: Record<ResolvedVariant, string> = Object.fromEntries(
441
+ Object.entries(RANKING_COLORS).map(([k, v]) => [k, v.fallback])
442
+ ) as Record<ResolvedVariant, string>;
443
+
444
+ /** A single segment in a cluster pin pie chart. */
445
+ interface ClusterPinSegment {
446
+ /** Ranking variant that determines this segment's color */
447
+ variant: ResolvedVariant;
448
+ /** Number of pins with this variant */
449
+ count: number;
450
+ }
451
+
452
+ /** Consistent ordering: best → worst ranking. */
453
+ const VARIANT_ORDER: ResolvedVariant[] = [
454
+ "strong",
455
+ "moderate",
456
+ "weak",
457
+ "unranked",
458
+ "error",
459
+ ];
460
+
461
+ /**
462
+ * Generates an SVG string for a cluster pie-chart pin.
463
+ *
464
+ * The SVG is a circle divided into colored sectors proportional to each
465
+ * segment's count, with a white inner circle displaying the total count.
466
+ * Colors are resolved from design-token CSS custom properties at runtime
467
+ * via {@link resolveClusterPinColors} and match the {@link MapGridPin}
468
+ * ranking palette.
469
+ *
470
+ * @param segments - Ranking variant distribution for the cluster
471
+ * @param total - Total count displayed in the center
472
+ *
473
+ * @example
474
+ * ```tsx
475
+ * // Generate SVG for a cluster with mixed rankings
476
+ * const svg = createClusterPinSvg(
477
+ * [
478
+ * { variant: "strong", count: 5 },
479
+ * { variant: "moderate", count: 3 },
480
+ * { variant: "weak", count: 1 },
481
+ * ],
482
+ * 9
483
+ * );
484
+ * ```
485
+ *
486
+ * @example
487
+ * ```tsx
488
+ * // Wire up with @googlemaps/markerclusterer
489
+ * import { createClusterPinElement } from "@brightlocal/ui-components/map";
490
+ *
491
+ * new MarkerClusterer({
492
+ * map,
493
+ * markers,
494
+ * renderer: {
495
+ * render(cluster) {
496
+ * const el = createClusterPinElement({
497
+ * markers: cluster.markers,
498
+ * count: cluster.count,
499
+ * getVariant: (m) => dataMap.get(m)?.variant ?? "unranked",
500
+ * });
501
+ * return new google.maps.marker.AdvancedMarkerElement({
502
+ * position: cluster.position,
503
+ * content: el,
504
+ * zIndex: 1000 + cluster.count,
505
+ * });
506
+ * },
507
+ * },
508
+ * });
509
+ * ```
510
+ */
511
+ function createClusterPinSvg(
512
+ segments: ClusterPinSegment[],
513
+ total: number
514
+ ): string {
515
+ const { colors, fontFamily, textColor } = resolveClusterPinStyles();
516
+ const size = 40;
517
+ const half = size / 2;
518
+ const border = 2;
519
+ const outerR = half - border;
520
+ const innerR = outerR * 0.55;
521
+
522
+ const sorted = [...segments].sort(
523
+ (a, b) =>
524
+ VARIANT_ORDER.indexOf(a.variant) - VARIANT_ORDER.indexOf(b.variant)
525
+ );
526
+ const nonEmpty = sorted.filter((s) => s.count > 0);
527
+ const segmentTotal = nonEmpty.reduce((sum, s) => sum + s.count, 0) || 1;
528
+ const displayTotal = Math.max(Number(total) || 0, 1);
529
+
530
+ let sectors: string;
531
+
532
+ const only = nonEmpty[0];
533
+ if (nonEmpty.length <= 1) {
534
+ const fill = only ? colors[only.variant] : "#e5e7eb";
535
+ sectors = `<circle cx="${half}" cy="${half}" r="${outerR}" fill="${fill}"/>`;
536
+ } else {
537
+ sectors = "";
538
+ let angle = -Math.PI / 2;
539
+ for (const seg of nonEmpty) {
540
+ const sweep = (seg.count / segmentTotal) * Math.PI * 2;
541
+ const end = angle + sweep;
542
+ const x1 = half + outerR * Math.cos(angle);
543
+ const y1 = half + outerR * Math.sin(angle);
544
+ const x2 = half + outerR * Math.cos(end);
545
+ const y2 = half + outerR * Math.sin(end);
546
+ const large = sweep > Math.PI ? 1 : 0;
547
+ sectors += `<path d="M${half},${half}L${x1.toFixed(2)},${y1.toFixed(2)}A${outerR},${outerR} 0 ${large} 1 ${x2.toFixed(2)},${y2.toFixed(2)}Z" fill="${colors[seg.variant]}"/>`;
548
+ angle = end;
549
+ }
550
+ }
551
+
552
+ const fontSize = Math.round(size * 0.3);
553
+
554
+ return [
555
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" style="filter:drop-shadow(0 1px 2px rgba(0,0,0,.15))">`,
556
+ `<circle cx="${half}" cy="${half}" r="${half}" fill="white"/>`,
557
+ sectors,
558
+ `<circle cx="${half}" cy="${half}" r="${outerR}" fill="none" stroke="white" stroke-width="${border}"/>`,
559
+ `<circle cx="${half}" cy="${half}" r="${innerR}" fill="white"/>`,
560
+ `<text x="${half}" y="${half}" text-anchor="middle" dominant-baseline="central" font-family="${fontFamily}" font-size="${fontSize}" font-weight="600" fill="${textColor}">${displayTotal}</text>`,
561
+ `</svg>`,
562
+ ].join("");
563
+ }
564
+
565
+ /**
566
+ * Options for {@link createClusterPinElement}.
567
+ */
568
+ interface CreateClusterPinElementOptions {
569
+ /** Markers grouped in this cluster. Each is passed to `getVariant`. */
570
+ markers: unknown[];
571
+ /** Total marker count for the cluster label. */
572
+ count: number;
573
+ /**
574
+ * Extracts the ranking variant from a single marker.
575
+ * Called once per marker; unknown markers should return `"unranked"`.
576
+ */
577
+ getVariant: (marker: unknown) => ResolvedVariant;
578
+ }
579
+
580
+ /**
581
+ * Creates an SVG DOM element for a cluster pin, ready to be used as
582
+ * `content` for a Google Maps `AdvancedMarkerElement`.
583
+ *
584
+ * Tallies the ranking variants across all markers in the cluster,
585
+ * generates a pie-chart SVG via {@link createClusterPinSvg}, and
586
+ * returns the parsed `SVGElement`.
587
+ *
588
+ * @example
589
+ * ```tsx
590
+ * import { createClusterPinElement } from "@brightlocal/ui-components/map";
591
+ * import { MarkerClusterer } from "@googlemaps/markerclusterer";
592
+ *
593
+ * // Store per-marker data in a WeakMap
594
+ * const pinData = new WeakMap<google.maps.marker.AdvancedMarkerElement, { variant: "strong" | "moderate" | "weak" | "unranked" }>();
595
+ *
596
+ * new MarkerClusterer({
597
+ * map,
598
+ * markers,
599
+ * renderer: {
600
+ * render(cluster) {
601
+ * const el = createClusterPinElement({
602
+ * markers: cluster.markers,
603
+ * count: cluster.count,
604
+ * getVariant: (m) => pinData.get(m)?.variant ?? "unranked",
605
+ * });
606
+ * return new google.maps.marker.AdvancedMarkerElement({
607
+ * position: cluster.position,
608
+ * content: el,
609
+ * zIndex: 1000 + cluster.count,
610
+ * });
611
+ * },
612
+ * },
613
+ * });
614
+ * ```
615
+ */
616
+ function createClusterPinElement(
617
+ options: CreateClusterPinElementOptions
618
+ ): SVGElement {
619
+ if (typeof DOMParser === "undefined") {
620
+ throw new Error(
621
+ "createClusterPinElement requires a browser environment (DOMParser). Use createClusterPinSvg for SSR."
622
+ );
623
+ }
624
+
625
+ const { markers, count, getVariant } = options;
626
+
627
+ const tally = new Map<ResolvedVariant, number>();
628
+ for (const marker of markers) {
629
+ const v = getVariant(marker);
630
+ tally.set(v, (tally.get(v) ?? 0) + 1);
631
+ }
632
+
633
+ const segments: ClusterPinSegment[] = [];
634
+ for (const v of VARIANT_ORDER) {
635
+ const c = tally.get(v);
636
+ if (c) segments.push({ variant: v, count: c });
637
+ }
638
+
639
+ const svgStr = createClusterPinSvg(segments, count);
640
+ const parser = new DOMParser();
641
+ const doc = parser.parseFromString(svgStr, "image/svg+xml");
642
+ const svg = doc.documentElement;
643
+ if (!(svg instanceof SVGElement)) {
644
+ throw new Error("createClusterPinElement: failed to parse SVG");
645
+ }
646
+ return svg;
647
+ }
648
+
649
+ /**
650
+ * Props for the MapClusterPin component.
651
+ */
652
+ interface MapClusterPinProps extends Omit<
653
+ React.ComponentProps<"div">,
654
+ "children"
655
+ > {
656
+ /** Distribution of ranking variants to display as pie sectors */
657
+ segments: ClusterPinSegment[];
658
+ /** Total count displayed in the center */
659
+ count: number;
660
+ /** Required test hook identifier */
661
+ dataHook: string;
662
+ /** Analytics element identifier */
663
+ trackingEl?: string;
664
+ /** Analytics label */
665
+ trackingLabel?: string;
666
+ }
667
+
668
+ /**
669
+ * A cluster pin that visualises the ranking distribution of grouped map pins
670
+ * as a pie chart. Each colored sector is proportional to the number of pins
671
+ * with that ranking variant; the total count is displayed in the center.
672
+ *
673
+ * Use as a standalone React component in stories or documentation.
674
+ * For Google Maps integration, use {@link createClusterPinElement} instead.
675
+ */
676
+ const MapClusterPin = React.forwardRef<HTMLDivElement, MapClusterPinProps>(
677
+ (
678
+ {
679
+ segments,
680
+ count,
681
+ dataHook,
682
+ className,
683
+ trackingEl,
684
+ trackingLabel,
685
+ ...props
686
+ },
687
+ ref
688
+ ) => {
689
+ const segmentsKey = JSON.stringify(segments);
690
+ const svg = React.useMemo(
691
+ () => createClusterPinSvg(segments, count),
692
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- serialised key for stable comparison
693
+ [segmentsKey, count]
694
+ );
695
+
696
+ return (
697
+ <div
698
+ dangerouslySetInnerHTML={{ __html: svg }}
699
+ ref={ref}
700
+ className={cn("inline-flex items-center justify-center", className)}
701
+ data-hook={dataHook}
702
+ data-slot="map-cluster-pin"
703
+ data-tracking-el={trackingEl || "map-cluster-pin"}
704
+ data-tracking-label={trackingLabel}
705
+ {...props}
706
+ />
707
+ );
708
+ }
709
+ );
710
+
711
+ MapClusterPin.displayName = "MapClusterPin";
712
+
127
713
  // ──────────────────────────────────────
128
714
  // MapLocationPin
129
715
  // ──────────────────────────────────────
@@ -131,20 +717,135 @@ MapGridPin.displayName = "MapGridPin";
131
717
  /**
132
718
  * Props for the MapLocationPin component.
133
719
  */
134
- interface MapLocationPinProps extends Omit<MapGridPinProps, "value"> {
135
- /** Numeric value displayed inside the pin */
720
+ interface MapLocationPinProps extends Omit<
721
+ React.ComponentProps<"div">,
722
+ "children"
723
+ > {
724
+ /** Icon rendered inside the pin marker @default Store icon */
725
+ icon?: React.ReactNode;
726
+ /** Play a one-time entrance — the pin springs into place from its anchor point when it mounts @default false */
727
+ animateIn?: boolean;
728
+ /** Required test hook identifier */
729
+ dataHook: string;
730
+ /** Analytics element identifier */
731
+ trackingEl?: string;
732
+ /** Analytics label */
733
+ trackingLabel?: string;
734
+ /**
735
+ * Accessible label for the pin marker.
736
+ * @default "Location"
737
+ */
738
+ ariaLabel?: string;
739
+ /**
740
+ * Numeric value displayed inside the pin.
741
+ * @deprecated Use {@link MapGridPin} for numbered pins. Provided only for
742
+ * backward compatibility — passing it renders the legacy numbered-circle marker.
743
+ */
136
744
  value?: number;
745
+ /**
746
+ * Colour variant for the legacy numbered pin.
747
+ * @deprecated Use {@link MapGridPin} for numbered pins. Provided only for
748
+ * backward compatibility — passing it renders the legacy numbered-circle marker.
749
+ */
750
+ variant?: MapGridPinVariant;
751
+ /**
752
+ * Enable the legacy pulse animation. Prefer {@link MapLocationPinProps.animateIn}
753
+ * for the teardrop entrance.
754
+ * @deprecated Use {@link MapGridPin} for numbered pins. Provided only for
755
+ * backward compatibility — passing it renders the legacy numbered-circle marker.
756
+ */
757
+ pulse?: boolean;
137
758
  }
138
759
 
139
760
  /**
140
- * A map location pin marker.
141
- * Thin wrapper around MapGridPin with a default value of 1.
761
+ * A teardrop-shaped map location pin with an icon inside.
762
+ * Renders an SVG pin marker with a circular icon area and drop shadow.
142
763
  * Designed to be placed inside any map marker component (e.g. AdvancedMarker).
764
+ *
765
+ * Backward compatibility: the previously published `MapLocationPin` was a thin
766
+ * wrapper around {@link MapGridPin} (a numbered circle). Passing any legacy prop
767
+ * (`value`, `variant`, or `pulse`) renders that original numbered-pin marker so
768
+ * existing consumers keep working; otherwise the new teardrop marker is rendered.
143
769
  */
144
- const MapLocationPin = React.forwardRef<HTMLButtonElement, MapLocationPinProps>(
145
- ({ value = 1, dataHook, ...props }, ref) => {
770
+ const MapLocationPin = React.forwardRef<HTMLDivElement, MapLocationPinProps>(
771
+ (
772
+ {
773
+ icon,
774
+ animateIn = false,
775
+ value,
776
+ variant,
777
+ pulse,
778
+ dataHook,
779
+ className,
780
+ trackingEl,
781
+ trackingLabel,
782
+ ariaLabel,
783
+ ...props
784
+ },
785
+ ref
786
+ ) => {
787
+ // Backward compatibility: the previously published MapLocationPin was a thin
788
+ // wrapper around MapGridPin (a numbered circle). If any legacy prop is
789
+ // supplied, preserve that exact behaviour so existing consumers keep working.
790
+ if (value !== undefined || variant !== undefined || pulse !== undefined) {
791
+ return (
792
+ <MapGridPin
793
+ ref={ref}
794
+ className={className}
795
+ dataHook={dataHook}
796
+ pulse={pulse}
797
+ trackingEl={trackingEl}
798
+ trackingLabel={trackingLabel}
799
+ value={value ?? 1}
800
+ variant={variant}
801
+ {...props}
802
+ />
803
+ );
804
+ }
805
+
806
+ // Rendered as a non-focusable `div` (compatible with Google Maps
807
+ // AdvancedMarkerElement), with role="img" so the icon marker has an
808
+ // accessible name.
146
809
  return (
147
- <MapGridPin ref={ref} dataHook={dataHook} value={value} {...props} />
810
+ <div
811
+ ref={ref}
812
+ aria-label={ariaLabel ?? "Location"}
813
+ className={cn(
814
+ "relative inline-flex h-[46px] w-[38px] items-start justify-center",
815
+ className
816
+ )}
817
+ data-hook={dataHook}
818
+ data-slot="map-location-pin"
819
+ data-tracking-el={trackingEl || "map-location-pin"}
820
+ data-tracking-label={trackingLabel}
821
+ role="img"
822
+ {...props}
823
+ >
824
+ <span
825
+ aria-hidden="true"
826
+ className={cn(
827
+ "relative flex size-full",
828
+ animateIn &&
829
+ "animate-pop-in origin-bottom will-change-transform motion-reduce:animate-none"
830
+ )}
831
+ >
832
+ <svg
833
+ aria-hidden="true"
834
+ className="size-full overflow-visible drop-shadow-sm"
835
+ fill="none"
836
+ viewBox="0 0 38 46"
837
+ >
838
+ <path
839
+ className="fill-white"
840
+ d="M38 19.15C38 29.21 29.4 35.77 20.38 44.63C19.61 45.39 18.37 45.41 17.58 44.67C8.01 35.79 0 29.23 0 19.15C0 8.57 8.51 0 19 0C29.49 0 38 8.57 38 19.15Z"
841
+ />
842
+ <circle className="fill-sky-500" cx="19" cy="19" r="16" />
843
+ </svg>
844
+ <span className="absolute top-[19px] left-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center text-white">
845
+ {icon ?? <Store size={16} />}
846
+ </span>
847
+ </span>
848
+ </div>
148
849
  );
149
850
  }
150
851
  );
@@ -170,11 +871,15 @@ interface MapControlButtonProps extends Omit<
170
871
  trackingLabel?: string;
171
872
  /** Button type attribute */
172
873
  type?: "button" | "submit";
874
+ /** Render as compact icon-only button or with text @default true */
875
+ iconOnly?: boolean;
173
876
  }
174
877
 
175
878
  /**
176
879
  * A floating control button for map UIs.
177
- * Renders a square, shadowed button designed to overlay a map surface.
880
+ * Uses `outline` in light mode and `secondary` in dark mode.
881
+ * In icon-only mode (default) renders a circular icon button.
882
+ * With `iconOnly={false}` renders a pill-shaped button with text and icon.
178
883
  * Use for zoom, locate, layer toggles, and other map controls.
179
884
  */
180
885
  const MapControlButton = React.forwardRef<
@@ -182,18 +887,29 @@ const MapControlButton = React.forwardRef<
182
887
  MapControlButtonProps
183
888
  >(
184
889
  (
185
- { className, dataHook, trackingEl, trackingLabel, children, ...props },
890
+ {
891
+ className,
892
+ dataHook,
893
+ trackingEl,
894
+ trackingLabel,
895
+ children,
896
+ iconOnly = true,
897
+ ...props
898
+ },
186
899
  ref
187
900
  ) => {
901
+ const isDark = useIsDarkMode();
902
+
188
903
  return (
189
904
  <Button
190
905
  ref={ref}
191
- className={cn("rounded-lg shadow-sm", className)}
906
+ className={className}
192
907
  data-slot="map-control-button"
193
908
  dataHook={dataHook}
909
+ iconOnly={iconOnly}
194
910
  trackingEl={trackingEl || "map-control-button"}
195
911
  trackingLabel={trackingLabel}
196
- variant="outline"
912
+ variant={isDark ? "secondary" : "outline"}
197
913
  {...props}
198
914
  >
199
915
  {children}
@@ -212,29 +928,36 @@ MapControlButton.displayName = "MapControlButton";
212
928
  * Props for the MapLoadingState component.
213
929
  */
214
930
  interface MapLoadingStateProps extends React.ComponentProps<"div"> {
215
- /** Optional loading message */
216
- message?: string;
931
+ /** Content displayed centered over the map background */
932
+ children?: React.ReactNode;
217
933
  /** Required test hook identifier */
218
934
  dataHook: string;
219
935
  /** Analytics element identifier */
220
936
  trackingEl?: string;
221
937
  /** Analytics label */
222
938
  trackingLabel?: string;
939
+ /**
940
+ * Accessible label for the loading status region.
941
+ * @default "Loading map"
942
+ */
943
+ ariaLabel?: string;
223
944
  }
224
945
 
225
946
  /**
226
947
  * A loading placeholder for map containers.
227
- * Uses the same spinner pattern as ComboboxLoading.
228
- * Use as a fallback while the map provider is loading.
948
+ * Displays the map background image with consumer-provided content
949
+ * centered vertically and horizontally. Fills its parent container.
950
+ * Use as a fallback while the map provider is initialising.
229
951
  */
230
952
  const MapLoadingState = React.forwardRef<HTMLDivElement, MapLoadingStateProps>(
231
953
  (
232
954
  {
233
955
  className,
234
- message = "Loading map…",
956
+ children,
235
957
  dataHook,
236
958
  trackingEl,
237
959
  trackingLabel,
960
+ ariaLabel,
238
961
  ...props
239
962
  },
240
963
  ref
@@ -242,9 +965,9 @@ const MapLoadingState = React.forwardRef<HTMLDivElement, MapLoadingStateProps>(
242
965
  return (
243
966
  <div
244
967
  ref={ref}
245
- aria-live="polite"
968
+ aria-label={ariaLabel ?? "Loading map"}
246
969
  className={cn(
247
- "text-muted-foreground flex items-center justify-center gap-2 py-6 text-sm",
970
+ "border-border relative flex h-full w-full items-center justify-center overflow-hidden rounded-lg border",
248
971
  className
249
972
  )}
250
973
  data-hook={dataHook}
@@ -254,11 +977,8 @@ const MapLoadingState = React.forwardRef<HTMLDivElement, MapLoadingStateProps>(
254
977
  role="status"
255
978
  {...props}
256
979
  >
257
- <div
258
- aria-hidden="true"
259
- className="size-4 animate-spin rounded-full border-2 border-current border-t-transparent"
260
- />
261
- {message}
980
+ <MapBackground />
981
+ {children && <div className="relative">{children}</div>}
262
982
  </div>
263
983
  );
264
984
  }
@@ -266,6 +986,27 @@ const MapLoadingState = React.forwardRef<HTMLDivElement, MapLoadingStateProps>(
266
986
 
267
987
  MapLoadingState.displayName = "MapLoadingState";
268
988
 
989
+ // ──────────────────────────────────────
990
+ // MapBackground (internal)
991
+ // ──────────────────────────────────────
992
+
993
+ const MapBackground = React.memo(function MapBackground({
994
+ rounded,
995
+ }: {
996
+ rounded?: boolean;
997
+ }) {
998
+ return (
999
+ <MapBackgroundImage
1000
+ aria-hidden="true"
1001
+ className={cn(
1002
+ "absolute inset-0 h-full w-full object-cover",
1003
+ rounded && "rounded-[inherit]"
1004
+ )}
1005
+ mode="auto"
1006
+ />
1007
+ );
1008
+ });
1009
+
269
1010
  // ──────────────────────────────────────
270
1011
  // MapErrorState
271
1012
  // ──────────────────────────────────────
@@ -274,12 +1015,31 @@ MapLoadingState.displayName = "MapLoadingState";
274
1015
  * Props for the MapErrorState component.
275
1016
  */
276
1017
  interface MapErrorStateProps extends React.ComponentProps<"div"> {
277
- /** Error title */
1018
+ /**
1019
+ * Error title displayed as a heading.
1020
+ * @default "We couldn't load your map rankings."
1021
+ */
278
1022
  title?: string;
279
- /** Error description */
1023
+ /**
1024
+ * Error description displayed below the title.
1025
+ * @default "Reloading usually fixes it, and it won't use any credits"
1026
+ */
280
1027
  message?: string;
281
- /** Retry callback — renders a "Try again" button when provided */
1028
+ /**
1029
+ * Retry callback. When provided, renders a retry button.
1030
+ * Omit to hide the retry button entirely.
1031
+ */
282
1032
  onRetry?: () => void;
1033
+ /**
1034
+ * Show the retry button in its loading state while the map reloads.
1035
+ * @default false
1036
+ */
1037
+ retryLoading?: boolean;
1038
+ /**
1039
+ * Label for the retry button.
1040
+ * @default "Reload"
1041
+ */
1042
+ retryLabel?: string;
283
1043
  /** Required test hook identifier */
284
1044
  dataHook: string;
285
1045
  /** Analytics element identifier */
@@ -290,16 +1050,18 @@ interface MapErrorStateProps extends React.ComponentProps<"div"> {
290
1050
 
291
1051
  /**
292
1052
  * An error state for map containers.
293
- * Displays an alert icon, title, message, and an optional retry button.
294
- * Use when the map provider fails to initialise or a network error occurs.
1053
+ * Displays the Globey "fixing fault" illustration, title, and message.
1054
+ * Pass `onRetry` to render a retry button; omit it to hide the button entirely.
295
1055
  */
296
1056
  const MapErrorState = React.forwardRef<HTMLDivElement, MapErrorStateProps>(
297
1057
  (
298
1058
  {
299
1059
  className,
300
- title = "Unable to load map",
301
- message = "Something went wrong while loading the map. Please try again.",
1060
+ title = "We couldn't load your map rankings.",
1061
+ message = "Reloading usually fixes it, and it won't use any credits",
302
1062
  onRetry,
1063
+ retryLoading = false,
1064
+ retryLabel = "Reload",
303
1065
  dataHook,
304
1066
  trackingEl,
305
1067
  trackingLabel,
@@ -311,7 +1073,7 @@ const MapErrorState = React.forwardRef<HTMLDivElement, MapErrorStateProps>(
311
1073
  <div
312
1074
  ref={ref}
313
1075
  className={cn(
314
- "bg-muted/50 flex flex-col items-center justify-center gap-3 rounded-xl p-8 text-center",
1076
+ "border-border relative flex h-full w-full flex-col items-center justify-center gap-4 rounded-lg border p-4 text-center sm:gap-6 sm:p-8",
315
1077
  className
316
1078
  )}
317
1079
  data-hook={dataHook}
@@ -321,39 +1083,45 @@ const MapErrorState = React.forwardRef<HTMLDivElement, MapErrorStateProps>(
321
1083
  role="alert"
322
1084
  {...props}
323
1085
  >
324
- <AlertCircle
325
- aria-hidden="true"
326
- className="text-muted-foreground/60"
327
- size={40}
328
- strokeWidth={1.5}
329
- />
330
- <div className="flex flex-col gap-1">
331
- <h3
332
- className="text-foreground text-sm font-semibold"
333
- data-slot="map-error-title"
1086
+ <MapBackground rounded />
1087
+ <div className="relative flex flex-col items-center gap-4 sm:gap-6">
1088
+ <div
1089
+ aria-hidden="true"
1090
+ className="flex items-center justify-center"
1091
+ data-slot="map-error-illustration"
334
1092
  >
335
- {title}
336
- </h3>
337
- {message && (
338
- <p
339
- className="text-muted-foreground max-w-xs text-xs"
340
- data-slot="map-error-message"
1093
+ <GlobeyFixingFault className="h-auto w-full max-w-41" />
1094
+ </div>
1095
+ <div className="flex flex-col gap-2">
1096
+ <h3
1097
+ className="text-foreground text-lg font-medium"
1098
+ data-slot="map-error-title"
1099
+ >
1100
+ {title}
1101
+ </h3>
1102
+ {message && (
1103
+ <p
1104
+ className="text-muted-foreground text-sm"
1105
+ data-slot="map-error-message"
1106
+ >
1107
+ {message}
1108
+ </p>
1109
+ )}
1110
+ </div>
1111
+ {onRetry && (
1112
+ <Button
1113
+ className="mt-1"
1114
+ dataHook={`${dataHook}-retry`}
1115
+ loading={retryLoading}
1116
+ size="sm"
1117
+ variant="primary"
1118
+ onClick={onRetry}
341
1119
  >
342
- {message}
343
- </p>
1120
+ {!retryLoading && <RefreshCw aria-hidden="true" />}
1121
+ {retryLabel}
1122
+ </Button>
344
1123
  )}
345
1124
  </div>
346
- {onRetry && (
347
- <Button
348
- className="mt-1"
349
- dataHook={`${dataHook}-retry`}
350
- size="sm"
351
- variant="primary"
352
- onClick={onRetry}
353
- >
354
- Try again
355
- </Button>
356
- )}
357
1125
  </div>
358
1126
  );
359
1127
  }
@@ -361,6 +1129,60 @@ const MapErrorState = React.forwardRef<HTMLDivElement, MapErrorStateProps>(
361
1129
 
362
1130
  MapErrorState.displayName = "MapErrorState";
363
1131
 
1132
+ // ──────────────────────────────────────
1133
+ // MapLegendItem
1134
+ // ──────────────────────────────────────
1135
+
1136
+ /**
1137
+ * Props for the MapLegendItem component.
1138
+ */
1139
+ interface MapLegendItemProps extends React.ComponentProps<"span"> {
1140
+ /**
1141
+ * Pin ranking variant — resolves to the matching MapGridPin background color.
1142
+ * Preferred over `color` so pin and legend stay in sync automatically.
1143
+ */
1144
+ variant?: ResolvedVariant;
1145
+ /**
1146
+ * Dot color as a Tailwind background class (e.g. "bg-primary").
1147
+ * Use for non-ranking legends where no pin variant applies.
1148
+ * Ignored when `variant` is provided.
1149
+ */
1150
+ color?: string;
1151
+ /** Required test hook identifier */
1152
+ dataHook: string;
1153
+ }
1154
+
1155
+ /**
1156
+ * A single legend entry: colored dot + label text.
1157
+ * Pass `variant` to match MapGridPin colors automatically, or `color` for custom dots.
1158
+ */
1159
+ const MapLegendItem = React.forwardRef<HTMLSpanElement, MapLegendItemProps>(
1160
+ ({ variant, color, dataHook, className, children, ...props }, ref) => {
1161
+ const dotColor = variant ? mapGridPinColorMap[variant] : color;
1162
+
1163
+ return (
1164
+ <span
1165
+ ref={ref}
1166
+ className={cn(
1167
+ "text-foreground flex items-center gap-1 font-sans text-xs",
1168
+ className
1169
+ )}
1170
+ data-hook={dataHook}
1171
+ data-slot="map-legend-item"
1172
+ {...props}
1173
+ >
1174
+ <span
1175
+ aria-hidden="true"
1176
+ className={cn("inline-block size-2 shrink-0 rounded-full", dotColor)}
1177
+ />
1178
+ {children}
1179
+ </span>
1180
+ );
1181
+ }
1182
+ );
1183
+
1184
+ MapLegendItem.displayName = "MapLegendItem";
1185
+
364
1186
  // ──────────────────────────────────────
365
1187
  // MapLegend
366
1188
  // ──────────────────────────────────────
@@ -375,6 +1197,11 @@ interface MapLegendProps extends React.ComponentProps<"div"> {
375
1197
  trackingEl?: string;
376
1198
  /** Analytics label */
377
1199
  trackingLabel?: string;
1200
+ /**
1201
+ * Accessible label for the legend group.
1202
+ * @default "Map legend"
1203
+ */
1204
+ ariaLabel?: string;
378
1205
  }
379
1206
 
380
1207
  /**
@@ -383,20 +1210,32 @@ interface MapLegendProps extends React.ComponentProps<"div"> {
383
1210
  */
384
1211
  const MapLegend = React.forwardRef<HTMLDivElement, MapLegendProps>(
385
1212
  (
386
- { className, dataHook, trackingEl, trackingLabel, children, ...props },
1213
+ {
1214
+ className,
1215
+ dataHook,
1216
+ trackingEl,
1217
+ trackingLabel,
1218
+ ariaLabel,
1219
+ children,
1220
+ ...props
1221
+ },
387
1222
  ref
388
1223
  ) => {
389
1224
  return (
390
1225
  <Card
391
1226
  ref={ref}
392
- className={cn("inline-flex w-auto flex-row items-center", className)}
1227
+ aria-label={ariaLabel ?? "Map legend"}
1228
+ className={cn(
1229
+ "inline-flex w-auto max-w-none flex-row items-center bg-white font-sans dark:bg-neutral-800",
1230
+ className
1231
+ )}
393
1232
  data-slot="map-legend"
394
1233
  dataHook={dataHook}
395
1234
  density="condensed"
396
- maxWidth="none"
1235
+ role="group"
397
1236
  trackingEl={trackingEl || "map-legend"}
398
1237
  trackingLabel={trackingLabel}
399
- variant="filled"
1238
+ variant="border"
400
1239
  {...props}
401
1240
  >
402
1241
  <CardContent className="flex items-center gap-3">
@@ -410,61 +1249,132 @@ const MapLegend = React.forwardRef<HTMLDivElement, MapLegendProps>(
410
1249
  MapLegend.displayName = "MapLegend";
411
1250
 
412
1251
  // ──────────────────────────────────────
413
- // useMapPopoverHover
1252
+ // useMapPopoverClick
414
1253
  // ──────────────────────────────────────
415
1254
 
416
1255
  /**
417
- * Return type of {@link useMapPopoverHover}.
1256
+ * Options for {@link useMapPopoverClick}.
418
1257
  */
419
- interface UseMapPopoverHoverReturn<T> {
420
- /** The item currently being hovered, or `null` when idle. Use for `open` prop. */
1258
+ interface UseMapPopoverClickOptions {
1259
+ /**
1260
+ * When `true`, hovering a pin switches the popover to that pin
1261
+ * after any pin has been clicked open (menubar-style interaction).
1262
+ * Mouse-only — touch events are filtered out.
1263
+ * @default false
1264
+ */
1265
+ hoverWhenOpen?: boolean;
1266
+ }
1267
+
1268
+ /**
1269
+ * Pointer interaction props returned by {@link UseMapPopoverClickReturn.getInteractionProps}.
1270
+ */
1271
+ interface MapPinInteractionProps {
1272
+ onClick: () => void;
1273
+ onPointerEnter?: (e: React.PointerEvent) => void;
1274
+ }
1275
+
1276
+ /**
1277
+ * Return type of {@link useMapPopoverClick}.
1278
+ */
1279
+ interface UseMapPopoverClickReturn<T> {
1280
+ /** The item whose popover is open, or `null` when closed. */
421
1281
  activeItem: T | null;
422
- /** Last non-null item — holds position stable during the close animation. Use for anchor positioning. */
1282
+ /** Last non-null item — holds position stable during the close animation. */
423
1283
  anchorItem: T | null;
424
- /** Set a new active item and cancel any pending close timer. */
1284
+ /** Open the popover for the given item. If another item is active, switches instantly. */
425
1285
  showItem: (item: T) => void;
426
- /** Start a delayed close (default 150 ms). Moving to another pin or the popover content cancels it. */
427
- scheduleClose: () => void;
428
- /** Cancel a pending close — call from `MapPopoverContent.onMouseEnter`. */
429
- cancelClose: () => void;
1286
+ /** Close the popover. */
1287
+ close: () => void;
1288
+ /**
1289
+ * Returns event handler props for a pin.
1290
+ * Always includes `onClick`; includes `onPointerEnter` when `hoverWhenOpen` is enabled.
1291
+ * Spread onto the marker element or pass individual handlers.
1292
+ */
1293
+ getInteractionProps: (item: T) => MapPinInteractionProps;
430
1294
  }
431
1295
 
432
1296
  /**
433
- * Manages hover state for a single repositioning Popover on dense map grids.
1297
+ * Manages click-to-open state for a single map popover.
434
1298
  *
435
- * Wire the returned callbacks to `MapGridPin` mouse events and
436
- * `MapPopoverContent` mouse events. The 150 ms grace period prevents
437
- * flicker when the pointer travels between a pin and the popover content.
1299
+ * Designed for use with Google Maps `AdvancedMarker` — register `onClick`
1300
+ * on the `AdvancedMarker` component (not on child DOM elements) to avoid the
1301
+ * "Focusable child elements in AdvancedMarkerElement are not supported" warning.
438
1302
  *
439
- * @param delay - Close timer in ms.
440
- * @default 150
1303
+ * Pass `{ hoverWhenOpen: true }` to enable menubar-style interaction:
1304
+ * the first pin requires a click, but subsequent pins switch on hover.
1305
+ * Only mouse pointers trigger hover — touch is filtered out.
1306
+ *
1307
+ * @example
1308
+ * ```tsx
1309
+ * const { activeItem, anchorItem, showItem, close } = useMapPopoverClick<Pin>();
1310
+ *
1311
+ * <Map onClick={close}>
1312
+ * <AdvancedMarker position={pin} onClick={() => showItem(pin)}>
1313
+ * <MapGridPin dataHook="pin" value={pin.rank} />
1314
+ * </AdvancedMarker>
1315
+ * </Map>
1316
+ *
1317
+ * <MapPopover open={!!activeItem}>
1318
+ * <MapPopoverAnchor ... />
1319
+ * <MapPopoverContent dataHook="popover" onEscapeKeyDown={close}>
1320
+ * {activeItem && <p>{activeItem.rank}</p>}
1321
+ * </MapPopoverContent>
1322
+ * </MapPopover>
1323
+ * ```
1324
+ *
1325
+ * @example
1326
+ * ```tsx
1327
+ * // With hoverWhenOpen — click first pin, then hover to switch
1328
+ * const { activeItem, anchorItem, getInteractionProps, close } =
1329
+ * useMapPopoverClick<Pin>({ hoverWhenOpen: true });
1330
+ *
1331
+ * <AdvancedMarker {...getInteractionProps(pin)}>
1332
+ * <MapGridPin dataHook="pin" value={pin.rank} />
1333
+ * </AdvancedMarker>
1334
+ * ```
441
1335
  */
442
- function useMapPopoverHover<T>(delay = 150): UseMapPopoverHoverReturn<T> {
1336
+ function useMapPopoverClick<T>(
1337
+ options?: UseMapPopoverClickOptions
1338
+ ): UseMapPopoverClickReturn<T> {
1339
+ const { hoverWhenOpen = false } = options ?? {};
1340
+
443
1341
  const [activeItem, setActiveItem] = React.useState<T | null>(null);
444
1342
  const [anchorItem, setAnchorItem] = React.useState<T | null>(null);
445
- const timeoutRef = React.useRef<ReturnType<typeof setTimeout>>(null);
446
1343
 
447
1344
  const showItem = React.useCallback((item: T) => {
448
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
449
1345
  setAnchorItem(item);
450
1346
  setActiveItem(item);
451
1347
  }, []);
452
1348
 
453
- const scheduleClose = React.useCallback(() => {
454
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
455
- timeoutRef.current = setTimeout(() => setActiveItem(null), delay);
456
- }, [delay]);
457
-
458
- const cancelClose = React.useCallback(() => {
459
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
1349
+ const close = React.useCallback(() => {
1350
+ setActiveItem(null);
460
1351
  }, []);
461
1352
 
1353
+ const getInteractionProps = React.useCallback(
1354
+ (item: T): MapPinInteractionProps => {
1355
+ const props: MapPinInteractionProps = {
1356
+ onClick: () => showItem(item),
1357
+ };
1358
+
1359
+ if (hoverWhenOpen) {
1360
+ props.onPointerEnter = (e: React.PointerEvent) => {
1361
+ if (e.pointerType === "mouse" && activeItem != null) {
1362
+ showItem(item);
1363
+ }
1364
+ };
1365
+ }
1366
+
1367
+ return props;
1368
+ },
1369
+ [hoverWhenOpen, showItem, activeItem]
1370
+ );
1371
+
462
1372
  return {
463
1373
  activeItem,
464
1374
  anchorItem,
465
1375
  showItem,
466
- scheduleClose,
467
- cancelClose,
1376
+ close,
1377
+ getInteractionProps,
468
1378
  };
469
1379
  }
470
1380
 
@@ -521,11 +1431,15 @@ interface MapPopoverContentProps extends PopoverContentProps {
521
1431
 
522
1432
  /**
523
1433
  * Popover content panel with map-specific defaults.
524
- * Compact sizing (`w-auto p-3`), top placement, and focus-prevention
525
- * for hover-activated popovers.
1434
+ * Compact sizing (`w-auto max-w-68.25 p-3` — sizes to content, max 273px), top placement, and auto-focus prevention
1435
+ * for click-activated map popovers.
1436
+ *
1437
+ * Both `onOpenAutoFocus` and `onCloseAutoFocus` are prevented by default
1438
+ * to keep focus on the map surface. Override via props if standard
1439
+ * focus-return behavior is needed.
526
1440
  *
527
1441
  * Use inside a controlled `<MapPopover open={!!activeItem}>` together
528
- * with `MapPopoverAnchor` and {@link useMapPopoverHover}.
1442
+ * with `MapPopoverAnchor` and {@link useMapPopoverClick}.
529
1443
  */
530
1444
  const MapPopoverContent = React.forwardRef<
531
1445
  React.ComponentRef<typeof PopoverContent>,
@@ -546,7 +1460,7 @@ const MapPopoverContent = React.forwardRef<
546
1460
  <PopoverContent
547
1461
  ref={ref}
548
1462
  className={cn(
549
- "w-auto p-3 data-[state=closed]:animate-none data-[state=closed]:opacity-0",
1463
+ "w-auto max-w-68.25 p-3 data-[state=closed]:animate-none data-[state=closed]:opacity-0",
550
1464
  className
551
1465
  )}
552
1466
  data-slot="map-popover-content"
@@ -555,6 +1469,7 @@ const MapPopoverContent = React.forwardRef<
555
1469
  dataHook={dataHook}
556
1470
  side={side}
557
1471
  sideOffset={sideOffset}
1472
+ onCloseAutoFocus={(e) => e.preventDefault()}
558
1473
  onOpenAutoFocus={(e) => e.preventDefault()}
559
1474
  {...props}
560
1475
  />
@@ -568,30 +1483,48 @@ MapPopoverContent.displayName = "MapPopoverContent";
568
1483
  // ──────────────────────────────────────
569
1484
 
570
1485
  export {
1486
+ MAP_STYLES,
571
1487
  MapTypeId,
572
1488
  MapLocationPin,
573
1489
  MapGridPin,
1490
+ MapClusterPin,
1491
+ mapGridPinColorMap,
1492
+ clusterPinHexColors,
1493
+ resolveClusterPinColors,
1494
+ createClusterPinSvg,
1495
+ createClusterPinElement,
574
1496
  MapControlButton,
575
1497
  MapLoadingState,
576
1498
  MapErrorState,
577
1499
  MapLegend,
1500
+ MapLegendItem,
578
1501
  MapPopover,
579
1502
  MapPopoverAnchor,
580
1503
  MapPopoverContent,
581
- useMapPopoverHover,
1504
+ useMapStyles,
1505
+ useMapPopoverClick,
582
1506
  };
583
1507
 
584
1508
  export type {
1509
+ MapStyleVariant,
1510
+ MapStyleRule,
585
1511
  MapTypeIdValue,
1512
+ ResolvedVariant as MapPinVariant,
586
1513
  MapLocationPinProps,
587
1514
  MapGridPinProps,
588
1515
  MapGridPinVariant,
1516
+ MapClusterPinProps,
1517
+ ClusterPinSegment,
1518
+ CreateClusterPinElementOptions,
589
1519
  MapControlButtonProps,
590
1520
  MapLoadingStateProps,
591
1521
  MapErrorStateProps,
592
1522
  MapLegendProps,
1523
+ MapLegendItemProps,
593
1524
  MapPopoverProps,
594
1525
  MapPopoverAnchorProps,
595
1526
  MapPopoverContentProps,
596
- UseMapPopoverHoverReturn,
1527
+ UseMapPopoverClickOptions,
1528
+ UseMapPopoverClickReturn,
1529
+ MapPinInteractionProps,
597
1530
  };