All files / src/hooks useTimelineData.ts

73.68% Statements 98/133
60% Branches 60/100
72.41% Functions 21/29
79.43% Lines 85/107

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                            720x 720x 720x 105x               105x                                                                         880x 880x 880x   880x   880x 880x 880x 880x 915x 915x 915x 915x 915x 915x   880x     880x 807x 807x 807x 807x 807x     807x   807x 807x         807x 722x 722x 722x 722x 682x 682x 682x 682x   682x 682x 682x 682x 682x 2411x 616x 616x 616x     722x 722x 720x   722x                   807x 807x 807x         880x     880x 880x   880x 880x                             880x                         880x               880x 880x       880x 880x 880x 213x   880x 70x             880x 880x 880x 70x   880x         880x 880x 880x 915x 915x 915x 915x 915x 915x   883x             880x                            
import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import type { ApolloClient, NormalizedCacheObject } from '@apollo/client';
import { useQuery } from '@apollo/client';
import { useWidgetRuntimeSnapshot, useWidgetRefreshRate } from '@ska-octopus-widget-sdk/widget-sdk';
import { useInitialHistory, type Pt } from './useInitialHistory';
import { deriveEnumLabelsFromData } from '../timeline/stateUtils';
import { queryCurrentValueRows } from '../timeline/currentValueQueries';
import type { EndpointByAttribute, HdbByEndpoint } from '../timeline/currentValueQueries';
import { GET_ENDPOINT_SOURCES } from '../graphql/operations';
import { canonicalAttr } from '../utils/utils';
import type { AttrLabelMap, EnumLabelsByAttr } from '../timeline/types';
import type { StreamMeta } from './useLiveStream';
 
function enumLabelsEqual(a: EnumLabelsByAttr, b: EnumLabelsByAttr): boolean {
  const aKeys = Object.keys(a);
  const bKeys = Object.keys(b);
  if (aKeys.length !== bKeys.length) return false;
  for (const key of aKeys) {
    const av = a[key] ?? [];
    const bv = b[key] ?? [];
    if (av.length !== bv.length) return false;
    for (let i = 0; i < av.length; i++) {
      if (av[i] !== bv[i]) return false;
    }
  }
  return true;
}
 
export interface UseTimelineDataParams {
  instanceId: string;
  client: ApolloClient<NormalizedCacheObject>;
  safeAttributes: string[];
  sourceAttributes: string[];
  endpointByAttribute: EndpointByAttribute;
  fallbackHdbByEndpoint: HdbByEndpoint;
  maxPoints: number;
  epochStart: number;
  epochEnd: number;
  rangeMs: number;
  downsample: 'minmax' | 'avg' | 'lttb' | 'none';
  useLiveData: boolean;
  replayModeActive: boolean;
  enumAttrsSig: string;
}
 
export function useTimelineData({
  instanceId,
  client,
  safeAttributes,
  sourceAttributes,
  endpointByAttribute,
  fallbackHdbByEndpoint,
  maxPoints,
  epochStart,
  epochEnd,
  rangeMs,
  downsample,
  useLiveData,
  replayModeActive,
  enumAttrsSig
}: UseTimelineDataParams) {
  /* ── Enum metadata ─────────────────────────────────────────── */
  const [enumLabelsByAttr, setEnumLabelsByAttr] = useState<EnumLabelsByAttr>({});
  const [attrLabelMap, setAttrLabelMap] = useState<AttrLabelMap>({});
  const [defaultYAxisUnit, setDefaultYAxisUnit] = useState('');
 
  const enumMetadataAttributes = useMemo(() => {
    const raw =
      Array.isArray(sourceAttributes) && sourceAttributes.length > 0 ? sourceAttributes : [];
    const seen = new Set<string>();
    const next: string[] = [];
    raw.forEach((attr) => {
      const original = String(attr ?? '').trim();
      Iif (!original) return;
      const key = canonicalAttr(original).toLowerCase();
      Iif (!key || seen.has(key)) return;
      seen.add(key);
      next.push(original);
    });
    return next;
  }, [sourceAttributes]);
 
  useEffect(() => {
    Iif (replayModeActive) return;
    let cancelled = false;
    setEnumLabelsByAttr((prev) => (Object.keys(prev).length === 0 ? prev : {}));
    setAttrLabelMap((prev) => (Object.keys(prev).length === 0 ? prev : {}));
    setDefaultYAxisUnit('');
 
    async function loadEnumLabels() {
      Iif (!client || typeof client.query !== 'function' || enumMetadataAttributes.length === 0)
        return;
      try {
        const rows = await queryCurrentValueRows(
          client,
          enumMetadataAttributes,
          endpointByAttribute
        );
        if (cancelled) return;
        const next: EnumLabelsByAttr = {};
        const nextLabelMap: AttrLabelMap = {};
        let nextDefaultYAxisUnit = '';
        rows.forEach((row: any) => {
          Iif (!row?.name) return;
          Eif (!nextDefaultYAxisUnit) {
            const unit = String(row?.unit ?? '').trim();
            if (unit) nextDefaultYAxisUnit = unit;
          }
          const raw = row.device ? `${row.device}/${row.name}` : row.name;
          const key = canonicalAttr(raw).toLowerCase();
          const attrLabel = typeof row.label === 'string' ? row.label.trim() : '';
          if (attrLabel) nextLabelMap[key] = attrLabel;
          if (!Array.isArray(row.enumLabels) || row.enumLabels.length === 0) return;
          const labels = row.enumLabels.filter((x: unknown) => typeof x === 'string');
          Eif (labels.length > 0) {
            next[key] = labels;
            next[key.toLowerCase()] = labels;
          }
        });
        setEnumLabelsByAttr((prev) => (enumLabelsEqual(prev, next) ? prev : next));
        setAttrLabelMap((prev) =>
          JSON.stringify(prev) === JSON.stringify(nextLabelMap) ? prev : nextLabelMap
        );
        setDefaultYAxisUnit(nextDefaultYAxisUnit);
      } catch {
        if (!cancelled) {
          setEnumLabelsByAttr((prev) => (Object.keys(prev).length === 0 ? prev : {}));
          setAttrLabelMap((prev) => (Object.keys(prev).length === 0 ? prev : {}));
          setDefaultYAxisUnit('');
        }
      }
    }
 
    loadEnumLabels();
    return () => {
      cancelled = true;
    };
  }, [client, enumAttrsSig, enumMetadataAttributes, endpointByAttribute, replayModeActive]);
 
  /* ── HDB routing ───────────────────────────────────────────── */
  const { data: endpointSourcesData } = useQuery(GET_ENDPOINT_SOURCES, {
    fetchPolicy: 'cache-first'
  });
  const hdbByEndpoint = useMemo(() => {
    const tangoDbKey: string = endpointSourcesData?.endpointSources?.types?.TANGO_DB ?? 'TANGO_DBS';
    const tangoDbs: Array<{ value?: string }> =
      endpointSourcesData?.endpointSources?.vars?.[tangoDbKey] ?? [];
    Eif (tangoDbs.length === 0) return fallbackHdbByEndpoint;
    const map: Record<string, number> = {};
    tangoDbs.forEach(({ value }, idx) => {
      const v = String(value ?? '').trim();
      if (v) map[v] = idx;
    });
    return map;
  }, [endpointSourcesData, fallbackHdbByEndpoint]);
 
  /* ── History ───────────────────────────────────────────────── */
  const {
    dataMap,
    setDataMap,
    status: histStatus,
    refetch: refetchHistory
  } = useInitialHistory(
    client,
    safeAttributes,
    maxPoints,
    epochStart,
    epochEnd,
    rangeMs,
    downsample,
    endpointByAttribute,
    hdbByEndpoint,
    replayModeActive
  );
 
  useWidgetRuntimeSnapshot(instanceId, {
    capture: () => ({ timeline: { dataMap } }),
    apply: (snapshot) => {
      const next = (snapshot as any)?.timeline?.dataMap;
      if (next && typeof next === 'object') setDataMap(next as Record<string, Pt[]>);
    }
  });
 
  const effectiveEnumLabelsByAttr = useMemo(
    () => deriveEnumLabelsFromData(safeAttributes, dataMap, enumLabelsByAttr),
    [safeAttributes, dataMap, enumLabelsByAttr]
  );
 
  const refreshSec = useWidgetRefreshRate(instanceId);
  const refetchRef = useRef(refetchHistory);
  useEffect(() => {
    refetchRef.current = refetchHistory;
  }, [refetchHistory]);
  useEffect(() => {
    Eif (replayModeActive || useLiveData || !refreshSec || refreshSec <= 0) return;
    refetchRef.current();
    const id = setInterval(() => refetchRef.current(), refreshSec * 1000);
    return () => clearInterval(id);
  }, [useLiveData, refreshSec, replayModeActive]);
 
  /* ── Live subscription state ───────────────────────────────── */
  const canSubscribe = useLiveData && !replayModeActive && safeAttributes.length > 0;
  const [streamStatus, setStreamStatus] = useState<'idle' | 'loading' | 'ok' | 'failed'>('idle');
  useEffect(() => {
    if (!canSubscribe) setStreamStatus('idle');
  }, [canSubscribe]);
  const handleStreamMeta = useCallback((m: StreamMeta) => {
    setStreamStatus(m.status ?? 'idle');
  }, []);
 
  /* ── Live stream groups ────────────────────────────────────── */
  const liveStreamGroups = useMemo(() => {
    const groups = new Map<string, string[]>();
    safeAttributes.forEach((attr) => {
      const key = canonicalAttr(attr).toLowerCase();
      const endpointName = String(endpointByAttribute[key] ?? '').trim();
      const groupKey = endpointName || '__default__';
      const list = groups.get(groupKey) ?? [];
      list.push(attr);
      groups.set(groupKey, list);
    });
    return Array.from(groups.entries()).map(([groupKey, attrs]) => ({
      key: groupKey,
      endpoint: groupKey === '__default__' ? undefined : groupKey,
      attrs: Array.from(new Set(attrs)).sort()
    }));
  }, [safeAttributes, endpointByAttribute]);
 
  return {
    dataMap,
    setDataMap,
    histStatus,
    enumLabelsByAttr,
    attrLabelMap,
    defaultYAxisUnit,
    effectiveEnumLabelsByAttr,
    liveStreamGroups,
    canSubscribe,
    streamStatus,
    handleStreamMeta
  };
}