All files / src GeoMapWidget.tsx

79.35% Statements 296/373
60.48% Branches 176/291
77.27% Functions 34/44
84.88% Lines 264/311

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771                                                                                                                                                        11x 38x       38x 38x 45x 38x       38x 2x 2x 2x 2x 2x 1x 1x 2x 2x 6x 2x   1x   1x                                       38x 38x 38x 38x 38x 38x   38x 17x 17x                             38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x     38x 38x 38x 38x 38x 17x         17x             17x 17x 17x 17x   38x 17x                 38x 38x 38x 38x 17x     38x   38x 17x     38x   1x 1x                 38x           38x   38x         38x 38x 27x 29x 27x     38x 38x 27x 27x 29x 29x   27x       38x 38x         38x 38x   38x 38x 38x   38x   18x       18x       18x 18x 18x 18x 18x 23x 23x         20x 10x 23x 44x           5x 5x   3x 2x 2x   3x   18x             38x 29x 20x 18x 18x   18x 29x 29x 18x 18x 18x         38x 22x 22x 13x 44x 44x   13x       38x 38x 27x       38x 38x     38x 38x 38x 38x 38x 17x 17x               38x 17x                         38x     38x       38x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x 1x       1x 1x 1x   1x 1x   1x 1x 1x 1x           1x 1x 1x 1x   1x 1x   1x   1x 1x 1x         7x 7x 7x 2x 2x 2x 2x 7x 2x 7x         7x       1x 1x 1x 1x   1x                   1x 7x   7x 7x   7x 7x   2x 2x         2x           2x       1x 1x 1x 1x   1x   1x 31x 31x 504x   31x   31x 31x 31x 30x 30x       1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x       38x                                                                                             1x                                                                                                                                                                                                                                                                                                                
// File: src/GeoMapWidget.tsx
import { useMemo, useState, useRef, useLayoutEffect, useEffect, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { useApolloClient, useQuery } from '@apollo/client';
import {
  formatInputFormattedTemplate,
  normalizeTangoAttributeInputs,
  useWidgetRefreshRate,
  RefreshingBadge,
  useHostVariables,
  useWidgetConfigPersistence
} from '@ska-octopus-widget-sdk/widget-sdk';
import { layoutDocs, OP_POLL } from './graphql/ops';
import styles from './GeoMapWidget.module.css';
 
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTowerBroadcast, faDownload } from '@fortawesome/free-solid-svg-icons';
 
import type { LayoutRow, Antenna, RGB, ColorScaleName } from './utils/geomap';
import {
  buildFullNames,
  buildAntennas,
  computePowerRange,
  computeTicks,
  fmt2,
  DEFAULT_COLOR_SCHEME,
  getColorScaleLabel
} from './utils/geomap';
 
import { AntennaMap } from './components/AntennaMap';
import { Legend } from './components/Legend';
import { normalizeEndpoints } from './utils/endpoint';
import type { GroupByMode } from './components/SmartboxGroups';
import type { TangoAttributeInput } from '@ska-octopus-widget-sdk/widget-sdk';
 
export interface GeoMapWidgetProps {
  instanceId?: string;
  stationId?: string;
  title?: string;
  endpoint?: string | string[] | TangoAttributeInput[];
  /** kept for backwards-compat (title only) */
  tpmSuffix: string;
  /** kept for backwards-compat (title only) */
  smartboxSuffix: string;
  antennaFilter?: number[];
  maskedAntennae?: Record<number, boolean>;
  legendPosition?: 'left' | 'right' | 'top' | 'bottom' | 'none';
  /** @deprecated legacy config; title visibility is now driven by non-empty `title` */
  showTitle?: boolean;
  titleMode?:
    | 'auto'
    | 'station'
    | 'stationAndCount'
    | 'stationAndBatch'
    | 'stationAndScale'
    | 'full'
    | 'hidden';
  showAntennas: boolean;
  groupBy?: GroupByMode;
 
  /** MCCS batch size (how many attributes to query at once) */
  mccsBatchSize?: number;
 
  /** visual radius control in *pixels* (can be < 1) */
  radiusMinPx?: number; // default 1
  radiusMaxPx?: number; // default 12
 
  /** SDK color scheme selection */
  colorScheme?: ColorScaleName;
  /** Deprecated legacy color scale selection (fallback only). */
  colorScale?: ColorScaleName;
  /** Custom palette as a JSON string of RGB triplets. If non-empty & valid, overrides color scheme. */
  customColorScale?: string;
}
 
type Row = { device: string; name: string; value: any };
const isGroupByMode = (value: unknown): value is GroupByMode =>
  value === 'smartbox' || value === 'tpm';
 
/** Split array into chunks of size n (>=1). */
function chunk<T>(arr: T[], n: number): T[][] {
  const size = Math.max(1, Math.floor(n));
  const out: T[][] = [];
  for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
  return out;
}
 
function parseCustomPalette(input?: string): RGB[] | undefined {
  if (!input) return undefined;
  const s = String(input).trim();
  Iif (!s) return undefined;
  try {
    const parsed = JSON.parse(s);
    Iif (!Array.isArray(parsed)) return undefined;
    const palette: RGB[] = [];
    for (const item of parsed) {
      Iif (!Array.isArray(item) || item.length !== 3) return undefined;
      const [r, g, b] = item;
      Iif (![r, g, b].every((x) => Number.isFinite(x) && x >= 0 && x <= 255)) return undefined;
      palette.push([r, g, b]);
    }
    return palette.length ? palette : undefined;
  } catch {
    return undefined;
  }
}
 
function stripMccsScheme(s: string): string {
  const m = String(s || '')
    .trim()
    .match(/^mccs:\/{1,2}(.*)$/i);
  return m ? m[1] : String(s || '').trim();
}
 
function normalizeStationIdFromSource(raw: string): string {
  const input = String(raw ?? '').trim();
  if (!input) return 's8-1';
  const parts = input.split('/').filter(Boolean);
  if (parts.length === 0) return 's8-1';
  return parts[parts.length - 1] || 's8-1';
}
 
export default function GeoMapWidget(props: GeoMapWidgetProps) {
  const client = useApolloClient();
  const variables = useHostVariables();
  const refresh = useWidgetRefreshRate(props.instanceId ?? 'geoMap');
  const { currentConfig, persistConfig } = useWidgetConfigPersistence(props.instanceId);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [containerSize, setContainerSize] = useState<{ w: number; h: number } | null>(null);
 
  useLayoutEffect(() => {
    const el = containerRef.current;
    Eif (!el || typeof ResizeObserver === 'undefined') return;
    const obs = new ResizeObserver((entries) => {
      const entry = entries[0];
      if (!entry) return;
      const width = entry.contentRect?.width ?? 0;
      const height = entry.contentRect?.height ?? 0;
      setContainerSize((prev) => {
        if (prev && prev.w === width && prev.h === height) return prev;
        return { w: width, h: height };
      });
    });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
 
  const rMin = props.radiusMinPx ?? 1; // can be < 1
  const rMax = props.radiusMaxPx ?? 12;
  const pos = props.legendPosition ?? 'bottom';
  const persistedGroupBy = isGroupByMode(currentConfig.groupBy) ? currentConfig.groupBy : undefined;
  const preferredGroupBy = persistedGroupBy ?? props.groupBy ?? 'smartbox';
  const [groupBySelection, setGroupBySelection] = useState<GroupByMode>(() => preferredGroupBy);
  const compactSpace = !!containerSize && (containerSize.h < 230 || containerSize.w < 280);
  const veryCompactSpace = !!containerSize && (containerSize.h < 260 || containerSize.w < 380);
  const hideLegend = pos === 'none' || compactSpace;
  const showTop = pos === 'top';
  const showBottom = pos === 'bottom';
  const showLeft = pos === 'left';
  const showRight = pos === 'right';
 
  const colorScaleName: ColorScaleName =
    props.colorScheme ?? props.colorScale ?? DEFAULT_COLOR_SCHEME;
  const customPalette = parseCustomPalette(props.customColorScale);
  const usingCustom = Array.isArray(customPalette) && customPalette.length > 0;
  const colorScaleLabel = getColorScaleLabel(colorScaleName);
  const stationId = useMemo(() => {
    const legacyStationId = formatInputFormattedTemplate({
      template: props.stationId,
      variables,
      fallback: typeof props.stationId === 'string' ? props.stationId : ''
    }).trim();
    Eif (legacyStationId) return legacyStationId;
 
    const normalized = normalizeTangoAttributeInputs({
      attributes: Array.isArray(props.endpoint) ? props.endpoint : undefined,
      fallbackAttributes: ['low-mccs/station/s8-1'],
      variables
    });
    const first = String(normalized[0] ?? '').trim() || 'low-mccs/station/s8-1';
    const sep = first.lastIndexOf('://');
    const stationRaw = sep > 0 ? first.slice(sep + 3) : first;
    return normalizeStationIdFromSource(stripMccsScheme(stationRaw));
  }, [props.stationId, props.endpoint, variables]);
  const titleText = useMemo(
    () =>
      formatInputFormattedTemplate({
        template: props.title,
        variables,
        legendFullName: stationId,
        fallback: ''
      }).trim(),
    [props.title, stationId, variables]
  );
  const showTitle = titleText.length > 0;
  const showHeader = showTitle || props.showAntennas;
  const showHoverTitleChip = showTitle && veryCompactSpace;
  const endpoints = useMemo(
    () => normalizeEndpoints(props.endpoint, { variables }),
    [props.endpoint, variables]
  );
  const selectedEndpoint = endpoints[0] ?? '1';
 
  useEffect(() => {
    setGroupBySelection(preferredGroupBy);
  }, [preferredGroupBy]);
 
  const handleGroupBySelect = useCallback(
    (next: GroupByMode) => {
      setGroupBySelection(next);
      persistConfig({ groupBy: next });
    },
    [persistConfig]
  );
 
  /** ─────────────────────────────────────────────────────────────
   *  1) Station layout (antenna positions)
   *     -> IMPORTANT: when showAntennas === false, we SKIP queries entirely.
   *  ────────────────────────────────────────────────────────────*/
  const { data: layoutData, loading: layoutLoading } = useQuery(layoutDocs, {
    variables: { station: stationId },
    fetchPolicy: 'cache-first',
    skip: !props.showAntennas // ← do NOT query when antennas are hidden
  });
 
  const layoutRows: LayoutRow[] = useMemo(
    () =>
      props.showAntennas ? ((layoutData?.antennaLocations?.antenna_locations ?? []) as any) : [],
    [props.showAntennas, layoutData]
  );
 
  // Distinct smartboxes & TPMs present in this station
  const smartboxes = useMemo(() => {
    if (!props.showAntennas) return [];
    const set = new Set<string>();
    for (const r of layoutRows) Eif (r?.smartbox) set.add(String(r.smartbox).trim());
    return Array.from(set);
  }, [props.showAntennas, layoutRows]);
 
  const tpmIds = useMemo(() => {
    if (!props.showAntennas) return [];
    const set = new Set<string>();
    for (const r of layoutRows) {
      Iif (!r?.tpm) continue;
      set.add(`${stationId}-${String(r.tpm).trim()}`); // e.g., "s8-1-tpm01"
    }
    return Array.from(set);
  }, [props.showAntennas, layoutRows, stationId]);
 
  // 2) Build MCCS fullNames only when needed
  const fullNames = useMemo(
    () => (props.showAntennas ? buildFullNames(smartboxes, tpmIds, stationId) : []),
    [props.showAntennas, smartboxes, tpmIds, stationId]
  );
 
  /** ============ Batched MCCS polling (SKIPPED when antennas are hidden) ============ */
  const batchSize = Math.max(1, Math.floor(props.mccsBatchSize ?? 5));
  const fullNameBatches = useMemo(() => chunk(fullNames, batchSize), [fullNames, batchSize]);
 
  const [rows, setRows] = useState<Row[]>([]);
  const [fetching, setFetching] = useState(false);
  const [fetchError, setFetchError] = useState<string | null>(null);
 
  const runFetchOnce = useCallback(
    async (cancelledRef: { v: boolean }) => {
      Iif (!props.showAntennas) {
        setRows([]);
        return;
      }
      Iif (fullNameBatches.length === 0) {
        setRows([]);
        return;
      }
      setFetching(true);
      setFetchError(null);
      try {
        const all: Row[] = [];
        for (const names of fullNameBatches) {
          Iif (cancelledRef.v) return;
          const res = await client.query({
            query: OP_POLL,
            variables: { fullNames: names, endpoint: selectedEndpoint },
            fetchPolicy: 'network-only'
          });
          if (cancelledRef.v) return;
          const arr = (res.data?.attributes ?? []) as any[];
          for (const r of arr)
            all.push({
              device: String(r.device || ''),
              name: String(r.name || ''),
              value: r.value
            });
        }
        Iif (cancelledRef.v) return;
        setRows(all);
      } catch (e) {
        if (!cancelledRef.v) {
          setRows([]);
          setFetchError(e instanceof Error ? e.message : String(e));
        }
        console.error('GeoMapWidget: failed to fetch MCCS data', e);
      } finally {
        if (!cancelledRef.v) setFetching(false);
      }
    },
    [client, fullNameBatches, props.showAntennas, selectedEndpoint]
  );
 
  // Kick off initial fetch + poll
  useEffect(() => {
    if (!props.showAntennas) return; // ← do nothing when antennas are hidden
    if (tpmIds.length === 0 && smartboxes.length === 0) return;
    const cancelled = { v: false };
    runFetchOnce(cancelled);
 
    const sec = Math.max(0, refresh ?? 0);
    let id: any = null;
    if (sec > 0) id = setInterval(() => runFetchOnce(cancelled), sec * 1000);
    return () => {
      cancelled.v = true;
      if (id) clearInterval(id);
    };
  }, [props.showAntennas, runFetchOnce, refresh, tpmIds.length, smartboxes.length]);
 
  // dev -> (name.lower -> value)
  const byDev = useMemo(() => {
    const m = new Map<string, Map<string, any>>();
    if (!props.showAntennas) return m;
    for (const r of rows) {
      if (!m.has(r.device)) m.set(r.device, new Map());
      m.get(r.device)!.set(r.name.toLowerCase(), r.value);
    }
    return m;
  }, [rows, props.showAntennas]);
 
  // Build antenna list (one per label)
  const antennas: Antenna[] = useMemo(() => {
    if (!props.showAntennas) return [];
    return buildAntennas(layoutRows, byDev, stationId);
  }, [props.showAntennas, layoutRows, byDev, stationId]);
 
  // Power range & ticks (safe defaults when empty)
  const powerRange = useMemo(() => computePowerRange(antennas), [antennas]);
  const ticks = useMemo(() => computeTicks(powerRange), [powerRange]);
 
  // Tooltip state for portal
  const tipRef = useRef<HTMLDivElement | null>(null);
  const [hover, _setHover] = useState<null | { pageX: number; pageY: number; a: Antenna }>(null);
  const [tipSize, setTipSize] = useState({ w: 0, h: 0 });
  const [isCapturing, setIsCapturing] = useState(false);
  useLayoutEffect(() => {
    const el = tipRef.current;
    Eif (!el) return;
    const raf = requestAnimationFrame(() => {
      if (!el.isConnected) return;
      const r = el.getBoundingClientRect();
      setTipSize({ w: r.width, h: r.height });
    });
    return () => cancelAnimationFrame(raf);
  }, [hover]);
  const tipPos = useMemo(() => {
    Eif (!hover) return null;
    const vw = window.innerWidth,
      vh = window.innerHeight,
      d = 8;
    let left = hover.pageX + d,
      top = hover.pageY + d;
    if (left + tipSize.w > vw) left = hover.pageX - d - tipSize.w;
    if (top + tipSize.h > vh) top = hover.pageY - d - tipSize.h;
    return { left, top };
  }, [hover, tipSize]);
 
  // Legend helpers
  const sizeHelpText =
    `Dot size is based on attenuation (preaduLevels X/Y): lower attenuation ⇒ larger dot. ` +
    `Range ${rMin}px-${rMax}px (screen pixels). Size remains constant while zooming.`;
 
  const legendScaleLabel = usingCustom
    ? 'ADC RMS power (custom)'
    : `ADC RMS power (${colorScaleLabel})`;
 
  const handleDownloadSvg = useCallback(async () => {
    const node = containerRef.current;
    Iif (!node) return;
    Iif (typeof window === 'undefined') return;
    const svg = node.querySelector('svg[data-geomap-export="map"]');
    Iif (!svg) return;
 
    try {
      setIsCapturing(true);
      const containerRect = node.getBoundingClientRect();
      const containerStyles = window.getComputedStyle(node);
      const rootBg = containerStyles.backgroundColor || '#ffffff';
 
      const exportSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      exportSvg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
      exportSvg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
      exportSvg.setAttribute('width', `${containerRect.width}`);
      exportSvg.setAttribute('height', `${containerRect.height}`);
      exportSvg.setAttribute('viewBox', `0 0 ${containerRect.width} ${containerRect.height}`);
 
      const rootBgRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
      rootBgRect.setAttribute('x', '0');
      rootBgRect.setAttribute('y', '0');
      rootBgRect.setAttribute('width', `${containerRect.width}`);
      rootBgRect.setAttribute('height', `${containerRect.height}`);
      rootBgRect.setAttribute('fill', rootBg);
      exportSvg.appendChild(rootBgRect);
 
      const mapWrap = svg.closest(`.${styles.mapWrap}`) as HTMLElement | null;
      const mapRect = mapWrap?.getBoundingClientRect() ?? svg.getBoundingClientRect();
      const mapBgColor = mapWrap
        ? window.getComputedStyle(mapWrap).backgroundColor || rootBg
        : rootBg;
 
      const clone = svg.cloneNode(true) as SVGElement;
      clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
      clone.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
 
      const viewBox = svg.getAttribute('viewBox');
      Iif (viewBox) clone.setAttribute('viewBox', viewBox);
 
      const addMapBackground = () => {
        const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
        const nums = viewBox?.split(/\s+/).map(Number);
        Iif (nums && nums.length === 4 && nums.every((n) => Number.isFinite(n))) {
          rect.setAttribute('x', `${nums[0]}`);
          rect.setAttribute('y', `${nums[1]}`);
          rect.setAttribute('width', `${nums[2]}`);
          rect.setAttribute('height', `${nums[3]}`);
        } else {
          rect.setAttribute('x', '0');
          rect.setAttribute('y', '0');
          rect.setAttribute('width', `${mapRect.width}`);
          rect.setAttribute('height', `${mapRect.height}`);
        }
        rect.setAttribute('fill', mapBgColor);
        clone.insertBefore(rect, clone.firstChild);
      };
      addMapBackground();
 
      const originalNodes = svg.querySelectorAll<SVGElement>('*');
      const clonedNodes = clone.querySelectorAll<SVGElement>('*');
      const resolveVar = (
        attrValue: string | null,
        initialValue: string,
        styleDecl: CSSStyleDeclaration
      ): string => {
        const base = initialValue?.trim() ?? '';
        Iif (base && !base.includes('var(')) return base;
        if (!attrValue || !attrValue.includes('var(')) return base;
        const match = attrValue.match(/var\((--[^, )]+)(?:,\s*([^)]+))?\)/);
        Iif (!match) return base;
        const [, varName, fallback] = match;
        const fromElement = styleDecl.getPropertyValue(varName)?.trim();
        Iif (fromElement) return fromElement;
        const fromContainer = window.getComputedStyle(node).getPropertyValue(varName)?.trim();
        if (fromContainer) return fromContainer;
        const fromRoot = window
          .getComputedStyle(document.documentElement)
          .getPropertyValue(varName)
          ?.trim();
        Iif (fromRoot) return fromRoot;
        return fallback?.trim() ?? base;
      };
 
      originalNodes.forEach((orig, idx) => {
        const copy = clonedNodes[idx];
        Iif (!copy) return;
        const computed = window.getComputedStyle(orig as Element);
 
        const attrsToResolve: Array<{ attr: string; computed: string }> = [
          { attr: 'fill', computed: computed.fill },
          { attr: 'stroke', computed: computed.stroke },
          { attr: 'stroke-width', computed: computed.strokeWidth },
          { attr: 'stroke-opacity', computed: computed.strokeOpacity },
          { attr: 'fill-opacity', computed: computed.fillOpacity },
          { attr: 'font-size', computed: computed.fontSize },
          { attr: 'font-family', computed: computed.fontFamily }
        ];
 
        for (const { attr, computed: computedValue } of attrsToResolve) {
          const currentAttr = orig.getAttribute(attr);
          const needsResolve =
            !currentAttr || currentAttr.includes('var(') || currentAttr.trim() === '';
          Iif (!needsResolve) continue;
 
          const resolvedRaw = resolveVar(currentAttr, computedValue ?? '', computed).trim();
          if (!resolvedRaw || resolvedRaw === 'initial' || resolvedRaw === 'inherit') continue;
 
          let finalValue = resolvedRaw;
          Iif (finalValue === 'transparent' || finalValue === 'rgba(0, 0, 0, 0)') {
            if (attr === 'fill' || attr === 'stroke') finalValue = 'none';
            else continue;
          }
 
          Iif (!currentAttr && (attr === 'fill' || attr === 'stroke')) {
            if (finalValue === 'none' || finalValue === 'rgb(0, 0, 0)' || finalValue === '#000') {
              continue;
            }
          }
 
          Eif (finalValue) copy.setAttribute(attr, finalValue);
        }
      });
 
      clone.setAttribute('width', `${mapRect.width}`);
      clone.setAttribute('height', `${mapRect.height}`);
      clone.setAttribute('x', `${mapRect.left - containerRect.left}`);
      clone.setAttribute('y', `${mapRect.top - containerRect.top}`);
 
      exportSvg.appendChild(clone);
 
      const inlineStyles = (sourceEl: Element, targetEl: Element) => {
        const computed = window.getComputedStyle(sourceEl as Element);
        const cssText = Array.from(computed)
          .map((prop) => `${prop}: ${computed.getPropertyValue(prop)};`)
          .join(' ');
        Eif (cssText) (targetEl as HTMLElement).setAttribute('style', cssText);
 
        const sourceChildren = Array.from(sourceEl.children);
        const targetChildren = Array.from(targetEl.children);
        for (let i = 0; i < sourceChildren.length; i += 1) {
          const targetChild = targetChildren[i];
          Eif (targetChild) inlineStyles(sourceChildren[i], targetChild);
        }
      };
 
      const legendEls = node.querySelectorAll(`.${styles.legend}`);
      legendEls.forEach((legendEl) => {
        Iif (!(legendEl instanceof HTMLElement)) return;
        const legendRect = legendEl.getBoundingClientRect();
        const foreign = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
        foreign.setAttribute('x', `${legendRect.left - containerRect.left}`);
        foreign.setAttribute('y', `${legendRect.top - containerRect.top}`);
        foreign.setAttribute('width', `${legendRect.width}`);
        foreign.setAttribute('height', `${legendRect.height}`);
 
        const legendClone = legendEl.cloneNode(true) as HTMLElement;
        legendClone.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
        legendClone.style.width = `${legendRect.width}px`;
        legendClone.style.height = `${legendRect.height}px`;
        legendClone.style.boxSizing = 'border-box';
        inlineStyles(legendEl, legendClone);
        foreign.appendChild(legendClone);
        exportSvg.appendChild(foreign);
      });
 
      const serializer = new XMLSerializer();
      let source = serializer.serializeToString(exportSvg);
      Eif (!source.startsWith('<?xml')) {
        source = `<?xml version="1.0" encoding="UTF-8"?>\n${source}`;
      }
 
      const blob = new Blob([source], { type: 'image/svg+xml;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      link.download = `geo-map-${stationId}-${timestamp}.svg`;
      link.href = url;
      document.body.appendChild(link);
      link.click();
      link.remove();
      URL.revokeObjectURL(url);
    } catch (err) {
      console.error('GeoMapWidget: failed to capture screenshot', err);
    } finally {
      setIsCapturing(false);
    }
  }, [stationId]);
 
  return (
    <div ref={containerRef} className={styles.container}>
      <div className={styles.topActions}>
        <button
          type="button"
          className={`${styles.controlButton} ${styles.iconButton}`}
          onClick={handleDownloadSvg}
          title="Download SVG"
          aria-label="Download SVG"
          disabled={isCapturing}
        >
          <FontAwesomeIcon icon={faDownload} />
        </button>
      </div>
 
      {showHeader && (
        <div className={styles.header}>
          <div className={styles.title}>
            {showTitle && (
              <>
                <FontAwesomeIcon icon={faTowerBroadcast} />
                <span>{titleText}</span>
                {fetchError && (
                  <span className={styles.status} role="alert">
                    {`Error: ${fetchError}`}
                  </span>
                )}
              </>
            )}
            {props.showAntennas && (
              <span className={styles.groupByChips} role="group" aria-label="Group map by">
                <button
                  type="button"
                  className={`${styles.groupByChip} ${
                    groupBySelection === 'smartbox' ? styles.groupByChipActive : ''
                  }`}
                  onClick={() => handleGroupBySelect('smartbox')}
                  aria-pressed={groupBySelection === 'smartbox'}
                  title="Group outlines by smartbox"
                >
                  Smartbox
                </button>
                <button
                  type="button"
                  className={`${styles.groupByChip} ${
                    groupBySelection === 'tpm' ? styles.groupByChipActive : ''
                  }`}
                  onClick={() => handleGroupBySelect('tpm')}
                  aria-pressed={groupBySelection === 'tpm'}
                  title="Group outlines by TPM"
                >
                  TPM
                </button>
              </span>
            )}
          </div>
          {props.showAntennas && (layoutLoading || fetching) && (
            <div className={styles.status}>Loading…</div>
          )}
        </div>
      )}
 
      {!hideLegend && showTop && (
        <Legend
          position="top"
          legendScaleLabel={legendScaleLabel}
          colorScaleName={colorScaleName}
          customPalette={customPalette}
          ticks={ticks}
          sizeHelpText={sizeHelpText}
        />
      )}
 
      <div className={styles.middle}>
        {!hideLegend && showLeft && (
          <Legend
            position="left"
            legendScaleLabel={legendScaleLabel}
            colorScaleName={colorScaleName}
            customPalette={customPalette}
            ticks={ticks}
            sizeHelpText={sizeHelpText}
          />
        )}
 
        {props.showAntennas && (
          <AntennaMap
            antennas={antennas}
            powerRange={powerRange}
            stationId={stationId}
            radiusMinPx={rMin}
            radiusMaxPx={rMax}
            showAntennas={props.showAntennas}
            groupBy={groupBySelection}
            colorScaleName={colorScaleName}
            customPalette={customPalette}
            showTitleChipOnHover={showHoverTitleChip}
            titleChipText={titleText}
            compactGroupBy={groupBySelection}
            onCompactGroupByChange={handleGroupBySelect}
          />
        )}
 
        {!hideLegend && showRight && (
          <Legend
            position="right"
            legendScaleLabel={legendScaleLabel}
            colorScaleName={colorScaleName}
            customPalette={customPalette}
            ticks={ticks}
            sizeHelpText={sizeHelpText}
          />
        )}
      </div>
 
      {!hideLegend && showBottom && (
        <Legend
          position="bottom"
          legendScaleLabel={legendScaleLabel}
          colorScaleName={colorScaleName}
          customPalette={customPalette}
          ticks={ticks}
          sizeHelpText={sizeHelpText}
        />
      )}
 
      {props.showAntennas &&
        hover &&
        tipPos &&
        ReactDOM.createPortal(
          <div
            ref={tipRef}
            className={styles.tooltip}
            style={{ left: tipPos.left, top: tipPos.top }}
          >
            <table>
              <tbody>
                <tr>
                  <th>Label</th>
                  <td>{hover.a.label}</td>
                </tr>
                <tr>
                  <th>Smartbox</th>
                  <td>{hover.a.sb}</td>
                </tr>
                <tr>
                  <th>Port</th>
                  <td>{hover.a.port}</td>
                </tr>
                <tr>
                  <th>TPM</th>
                  <td>{hover.a.tpmFull}</td>
                </tr>
                <tr>
                  <th>FEM current (mA)</th>
                  <td>{hover.a.fem_current ?? '—'}</td>
                </tr>
                <tr>
                  <th>Tripped</th>
                  <td>{String(hover.a.tripped ?? false)}</td>
                </tr>
                <tr>
                  <th>ADC X / Y</th>
                  <td>
                    {fmt2(hover.a.pwr_x)} / {fmt2(hover.a.pwr_y)}
                  </td>
                </tr>
                <tr>
                  <th>Atten X / Y (dB)</th>
                  <td>
                    {fmt2(hover.a.atten_x)} / {fmt2(hover.a.atten_y)}
                  </td>
                </tr>
                <tr>
                  <th>chX / chY</th>
                  <td>
                    {hover.a.chX ?? '—'} / {hover.a.chY ?? '—'}
                  </td>
                </tr>
                <tr>
                  <th>East / North (m)</th>
                  <td>
                    {fmt2(hover.a.east)} / {fmt2(hover.a.north)}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>,
          document.body
        )}
 
      <RefreshingBadge
        active={props.showAntennas && !!(layoutLoading || fetching)}
        text={refresh > 0 ? `Refreshing every (${refresh}s)` : 'Refreshing…'}
        position="top-right"
      />
    </div>
  );
}