All files / src TangoExplorerLogic.tsx

84.52% Statements 142/168
70.33% Branches 83/118
93.1% Functions 27/29
86.8% Lines 125/144

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                              10x       16x 16x 16x 16x 9x 9x       21x 21x 2x 2x     21x 21x                                       21x       25x 25x 25x 25x 25x 25x 25x   20x   25x     25x               25x           25x 25x 25x 25x   25x 25x 4x 4x 4x 4x 4x   8x         8x       4x 4x 4x 4x 8x 8x 8x 8x 8x 8x     4x 4x       4x           25x 18x 4x 4x 4x 4x   4x 4x 18x         4x     4x 4x 4x       25x 25x 25x 25x   25x 23x     34x 25x     25x 23x 23x 34x 34x 34x   23x       34x 25x         25x 25x 25x 2x       2x 2x 4x 4x 4x 4x   2x   4x             4x     2x       25x 25x   25x 12x     25x 22x 22x 6x 6x     22x       25x 25x     25x 10x 1x 1x       25x 17x 17x 24x 24x     24x   24x 2x   24x 24x   24x 24x       17x     25x                          
// ─────────────────────────────────────────────────────────────
// src/TangoExplorerLogic.tsx
// ─────────────────────────────────────────────────────────────
import { useMemo, useEffect, useRef, useState } from 'react';
import * as Apollo from '@apollo/client';
import { useWidgetRefreshRate } from '@ska-octopus-widget-sdk/widget-sdk';
import { OP_DEVICES, OP_ATTRIBUTES } from './graphql/ops';
 
export interface TangoExplorerLogicConfig {
  instanceId?: string;
  tangoDB?: string | string[];
  useEnumLabels?: boolean;
}
 
type DeviceInfo = { name: string; server: { id: string }; state?: string | number };
const useQuery = Apollo.useQuery;
 
/* shallow compare for { deviceName → state } maps */
function shallowEqual(a: Record<string, string>, b: Record<string, string>): boolean {
  Iif (a === b) return true;
  const ka = Object.keys(a);
  const kb = Object.keys(b);
  if (ka.length !== kb.length) return false;
  for (const k of ka) Iif (a[k] !== b[k]) return false;
  return true;
}
 
function normalizeEndpoints(input: unknown): string[] {
  const uniq = new Set<string>();
  const push = (value: unknown) => {
    const normalized = String(value ?? '').trim();
    Eif (normalized) uniq.add(normalized);
  };
 
  if (Array.isArray(input)) {
    input.forEach(push);
  E} else if (typeof input === 'string') {
    const raw = input.trim();
    if (!raw) return [];
    if (raw.startsWith('[') && raw.endsWith(']')) {
      try {
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed)) parsed.forEach(push);
      } catch {
        raw.split(',').forEach(push);
      }
    } else if (raw.includes(',')) {
      raw.split(',').forEach(push);
    } else {
      push(raw);
    }
  } else if (input != null) {
    push(input);
  }
 
  return Array.from(uniq);
}
 
export function useTangoExplorerLogic(config: TangoExplorerLogicConfig) {
  const { instanceId = 'tangoExplorer', tangoDB = [], useEnumLabels = true } = config;
  const endpoints = useMemo(() => normalizeEndpoints(tangoDB), [tangoDB]);
  const selectedEndpoint = endpoints[0] ?? '';
  const multiEndpointMode = endpoints.length > 1;
  let useApolloClientHook: unknown = null;
  try {
    useApolloClientHook = (Apollo as any).useApolloClient;
  } catch {
    useApolloClientHook = null;
  }
  const client = typeof useApolloClientHook === 'function' ? (useApolloClientHook as any)() : null;
 
  // Refresh rate (seconds) – controlled via widgetDef.polls
  const refresh = useWidgetRefreshRate(instanceId);
 
  // 1. Query devices (incl. their latest state) on a polling interval
  const {
    data: devData,
    loading: devicesLoading,
    error: devicesError,
    refetch: refetchDevices
  } = useQuery<{ devices: DeviceInfo[] }>(OP_DEVICES, {
    skip: multiEndpointMode,
    variables: selectedEndpoint ? { endpoint: selectedEndpoint } : undefined,
    pollInterval: refresh * 1000,
    fetchPolicy: 'network-only'
  });
  const [multiDevData, setMultiDevData] = useState<{ devices: DeviceInfo[] }>({ devices: [] });
  const [multiDevicesLoading, setMultiDevicesLoading] = useState(false);
  const [multiDevicesError, setMultiDevicesError] = useState<unknown>(null);
  const [deviceEndpointByName, setDeviceEndpointByName] = useState<Record<string, string>>({});
 
  const fetchMultiDevices = useMemo(
    () => async () => {
      Iif (!client) return;
      setMultiDevicesLoading(true);
      setMultiDevicesError(null);
      try {
        const responses = await Promise.all(
          endpoints.map(async (endpoint) => {
            const res = (await client.query({
              query: OP_DEVICES,
              variables: endpoint ? { endpoint } : undefined,
              fetchPolicy: 'network-only'
            })) as { data?: { devices?: DeviceInfo[] } };
            return { endpoint, devices: Array.isArray(res.data?.devices) ? res.data.devices : [] };
          })
        );
 
        const merged: DeviceInfo[] = [];
        const endpointMap: Record<string, string> = {};
        const seen = new Set<string>();
        for (const response of responses) {
          for (const device of response.devices) {
            const key = String(device?.name ?? '').trim();
            Iif (!key || seen.has(key)) continue;
            seen.add(key);
            merged.push(device);
            endpointMap[key] = response.endpoint;
          }
        }
        setDeviceEndpointByName(endpointMap);
        setMultiDevData({ devices: merged });
      } catch (error) {
        setMultiDevicesError(error);
      } finally {
        setMultiDevicesLoading(false);
      }
    },
    [client, endpoints]
  );
 
  useEffect(() => {
    if (!multiEndpointMode) return;
    let alive = true;
    const run = async () => {
      Iif (!alive) return;
      await fetchMultiDevices();
    };
    void run();
    const intervalMs = Math.max(0, Number(refresh) || 0) * 1000;
    Iif (intervalMs <= 0) {
      return () => {
        alive = false;
      };
    }
    const timer = setInterval(() => {
      void run();
    }, intervalMs);
    return () => {
      alive = false;
      clearInterval(timer);
    };
  }, [multiEndpointMode, fetchMultiDevices, refresh]);
 
  const activeDevData = multiEndpointMode ? multiDevData : devData;
  const activeDevicesLoading = multiEndpointMode ? multiDevicesLoading : devicesLoading;
  const activeDevicesError = multiEndpointMode ? multiDevicesError : devicesError;
  const activeRefetchDevices = multiEndpointMode ? fetchMultiDevices : refetchDevices;
 
  const devices: DeviceInfo[] = useMemo(
    () => (activeDevData?.devices as DeviceInfo[] | undefined) ?? [],
    [activeDevData]
  );
  const deviceNames = useMemo(() => devices.map((d) => d.name), [devices]);
  const deviceNamesKey = useMemo(() => [...deviceNames].sort().join(','), [deviceNames]);
 
  // Group devices by server to build the sunburst later
  const byServer = useMemo(() => {
    const m = new Map<string, DeviceInfo[]>();
    for (const d of devices) {
      const sid = d.server?.id ?? 'unknown';
      if (!m.has(sid)) m.set(sid, []);
      m.get(sid)!.push(d);
    }
    return m;
  }, [devices]);
 
  // 2. Fetch enum-label metadata (optional)
  const fullNames = useMemo(() => deviceNames.map((n) => `${n}/state`), [deviceNames]);
  const { data: singleMetaData, refetch: refetchSingleMeta } = useQuery(OP_ATTRIBUTES, {
    skip: multiEndpointMode || !useEnumLabels || fullNames.length === 0,
    variables: selectedEndpoint ? { fullNames, endpoint: selectedEndpoint } : { fullNames },
    fetchPolicy: 'network-only'
  });
  const [multiMetaData, setMultiMetaData] = useState<{ attributes: any[] }>({ attributes: [] });
  const fetchMultiMeta = useMemo(
    () => async () => {
      Iif (!client || !useEnumLabels || deviceNames.length === 0) {
        setMultiMetaData({ attributes: [] });
        return;
      }
      const endpointBuckets = new Map<string, string[]>();
      for (const name of deviceNames) {
        const endpoint = deviceEndpointByName[name] ?? '';
        const bucket = endpointBuckets.get(endpoint) ?? [];
        bucket.push(`${name}/state`);
        endpointBuckets.set(endpoint, bucket);
      }
      const responses = await Promise.all(
        Array.from(endpointBuckets.entries()).map(async ([endpoint, scopedFullNames]) => {
          const res = (await client.query({
            query: OP_ATTRIBUTES,
            variables: endpoint
              ? { fullNames: scopedFullNames, endpoint }
              : { fullNames: scopedFullNames },
            fetchPolicy: 'network-only'
          })) as { data?: { attributes?: any[] } };
          return Array.isArray(res.data?.attributes) ? res.data.attributes : [];
        })
      );
      setMultiMetaData({ attributes: responses.flat() });
    },
    [client, useEnumLabels, deviceNames, deviceEndpointByName]
  );
  const activeMetaData = multiEndpointMode ? multiMetaData : singleMetaData;
  const activeRefetchMeta = multiEndpointMode ? fetchMultiMeta : refetchSingleMeta;
 
  useEffect(() => {
    if (useEnumLabels && fullNames.length) activeRefetchMeta?.();
  }, [useEnumLabels, activeRefetchMeta, deviceNamesKey, fullNames.length]);
 
  const enumMap = useMemo(() => {
    const out: Record<string, string[]> = {};
    activeMetaData?.attributes?.forEach((a: any) => {
      Eif (Array.isArray(a.enumLabels)) {
        out[`${a.device}|${a.name}`] = a.enumLabels;
      }
    });
    return out;
  }, [activeMetaData]);
 
  // 3. Build a { deviceName → displayState } map from polled data
  const [deviceStates, setDeviceStates] = useState<Record<string, string>>({});
  const prevDeviceKey = useRef(deviceNamesKey);
 
  // Reset states if device list changed
  useEffect(() => {
    if (prevDeviceKey.current !== deviceNamesKey) {
      prevDeviceKey.current = deviceNamesKey;
      setDeviceStates({});
    }
  }, [deviceNamesKey]);
 
  useEffect(() => {
    const next: Record<string, string> = {};
    for (const d of devices) {
      const raw = d.state ?? 'unknown';
      const enumKey = `${d.name}|state`;
 
      let display: string | undefined;
      Eif (useEnumLabels) {
        let idx: number | undefined;
        if (typeof raw === 'number') idx = raw;
        else if (typeof raw === 'string' && /^\d+$/.test(raw)) idx = parseInt(raw, 10);
 
        const labels = enumMap[enumKey];
        if (labels && idx != null && labels[idx] != null) display = labels[idx];
      }
      if (!display) display = String(raw);
      next[d.name] = display;
    }
 
    /* avoid infinite re‑render loops – update state only when it changed */
    setDeviceStates((prev) => (shallowEqual(prev, next) ? prev : next));
  }, [devices, enumMap, useEnumLabels]);
 
  return {
    devices,
    deviceNames,
    byServer,
    deviceStates,
    devicesLoading: activeDevicesLoading,
    devicesError: activeDevicesError,
    refetchDevices: activeRefetchDevices,
    enumMap,
    useEnumLabels,
    refetchMeta: activeRefetchMeta
  } as const;
}