All files / src/hooks useSharedHover.ts

17.39% Statements 12/69
2.32% Branches 1/43
33.33% Functions 4/12
20% Lines 12/60

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                                                                                                                                      880x 880x   880x 70x   880x 70x 70x         880x               880x             880x             880x                                                                                                                                                   880x                
import { useState, useCallback, useEffect, useRef } from 'react';
import { canonicalAttr, formatLegendLabel } from '../utils/utils';
import {
  enumLabelsForAttr,
  hasTangoStateColor,
  isTangoStateAttr,
  toDisplayValue,
  valueForPlot
} from '../timeline/stateUtils';
import { shouldDisplayEnumLabels } from '../timeline/types';
import type { AttrLabelMap, DataMap, EnumLabelsByAttr } from '../timeline/types';
 
export type HoverRow = {
  label: string;
  time: string;
  value: string;
  isStateChip: boolean;
  color?: string;
  dash?: string;
};
export type HoverState = { x: number; y: number; ts: number; rows: HoverRow[] };
 
export interface UseSharedHoverParams {
  sharedHover: boolean;
  barView: boolean;
  safeAttributes: string[];
  dataMap: DataMap;
  effectiveAttrLabelMap: AttrLabelMap;
  perAttrLegendFormats: string[];
  resolvedLegendFormat: string;
  effectiveEnumLabelsByAttr: EnumLabelsByAttr;
  enumDisplay: 'value' | 'label';
  attrsSig: string;
  /** Series label → line/marker colour, derived from the rendered line traces. */
  colorByLabel?: Record<string, string>;
  /** Series label → line dash style, derived from the rendered line traces. */
  dashByLabel?: Record<string, string>;
}
 
/** Look up a series property by label: exact match, else a "label [n]" component trace. */
function resolveByLabel(
  byLabel: Record<string, string> | undefined,
  label: string
): string | undefined {
  if (!byLabel) return undefined;
  if (byLabel[label]) return byLabel[label];
  const prefix = `${label} [`;
  for (const name of Object.keys(byLabel)) {
    if (name.startsWith(prefix)) return byLabel[name];
  }
  return undefined;
}
 
export function useSharedHover({
  sharedHover,
  barView,
  safeAttributes,
  dataMap,
  effectiveAttrLabelMap,
  perAttrLegendFormats,
  resolvedLegendFormat,
  effectiveEnumLabelsByAttr,
  enumDisplay,
  attrsSig,
  colorByLabel,
  dashByLabel
}: UseSharedHoverParams) {
  const [hoverState, setHoverState] = useState<HoverState | null>(null);
  const hoverLeaveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
 
  useEffect(() => {
    setHoverState(null);
  }, [attrsSig]);
  useEffect(
    () => () => {
      Iif (hoverLeaveTimer.current) clearTimeout(hoverLeaveTimer.current);
    },
    []
  );
 
  const handlePlotUnhover = useCallback(() => {
    if (!sharedHover) return;
    hoverLeaveTimer.current = setTimeout(() => {
      setHoverState(null);
      hoverLeaveTimer.current = null;
    }, 300);
  }, [sharedHover]);
 
  const handleCardMouseEnter = useCallback(() => {
    if (hoverLeaveTimer.current) {
      clearTimeout(hoverLeaveTimer.current);
      hoverLeaveTimer.current = null;
    }
  }, []);
 
  const handleCardMouseLeave = useCallback(() => {
    hoverLeaveTimer.current = setTimeout(() => {
      setHoverState(null);
      hoverLeaveTimer.current = null;
    }, 150);
  }, []);
 
  const handlePlotHover = useCallback(
    (e: any) => {
      if (!sharedHover || barView) return;
      const pt = e?.points?.[0];
      if (!pt) return;
      const hoveredTs = new Date(pt.x as string).getTime();
      if (!Number.isFinite(hoveredTs)) return;
 
      if (hoverLeaveTimer.current) {
        clearTimeout(hoverLeaveTimer.current);
        hoverLeaveTimer.current = null;
      }
 
      const useLabelDisplay = shouldDisplayEnumLabels(enumDisplay);
      const dispMode = useLabelDisplay ? 'label' : ('value' as const);
 
      const rows: HoverRow[] = [];
      safeAttributes.forEach((attr, attrIdx) => {
        const key = canonicalAttr(attr);
        const pts = dataMap[key];
        if (!pts || pts.length === 0) return;
 
        let closest = pts[0];
        let minDist = Math.abs(pts[0].t - hoveredTs);
        for (const p of pts) {
          const d = Math.abs(p.t - hoveredTs);
          if (d < minDist) {
            minDist = d;
            closest = p;
          }
        }
 
        const attrLabel = effectiveAttrLabelMap[key] ?? '';
        const fmt = perAttrLegendFormats[attrIdx]?.trim() || resolvedLegendFormat;
        const hasExplicitFmt = !!perAttrLegendFormats[attrIdx]?.trim();
        const label = formatLegendLabel(attr, fmt, attrLabel, hasExplicitFmt) || key;
 
        const enumLabels = enumLabelsForAttr(effectiveEnumLabelsByAttr, key);
        const isState = isTangoStateAttr(key);
        const val = valueForPlot(closest.v, isState, enumLabels);
        const display = String(toDisplayValue(val, enumLabels, dispMode) ?? closest.v ?? '');
 
        rows.push({
          label,
          time: new Date(closest.t).toISOString().slice(11, 23),
          value: display,
          isStateChip: hasTangoStateColor(display),
          color: resolveByLabel(colorByLabel, label),
          dash: resolveByLabel(dashByLabel, label)
        });
      });
 
      setHoverState({
        x: e?.event?.clientX ?? 0,
        y: e?.event?.clientY ?? 0,
        ts: hoveredTs,
        rows
      });
    },
    [
      sharedHover,
      barView,
      safeAttributes,
      dataMap,
      effectiveAttrLabelMap,
      perAttrLegendFormats,
      resolvedLegendFormat,
      effectiveEnumLabelsByAttr,
      enumDisplay,
      colorByLabel,
      dashByLabel
    ]
  );
 
  return {
    hoverState,
    handlePlotHover,
    handlePlotUnhover,
    handleCardMouseEnter,
    handleCardMouseLeave
  };
}