All files / src HDBPPLiveWidget.tsx

80.96% Statements 268/331
71.33% Branches 224/314
85.52% Functions 65/76
83.8% Lines 238/284

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 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851                                                                                                          5x       5x 5x         5x 5x 5x     27x 27x           27x             162x       3x 3x 3x               3x 3x 13x 13x 13x 13x   3x             110x       30x   2x                                           2x     26x         41x 41x 41x   30x 41x   30x 30x 41x 41x 20x 41x 41x         32x 20x   12x 12x 12x               69x 69x 30x 30x   59x               3x   3x   3x 3x 3x 3x   1x 3x 2x 2x 2x 2x   2x 2x 2x       1x   1x 2x 1x                       30x 30x 41x 41x 41x 41x   41x 41x 41x 41x 41x   41x 54x 54x 54x 54x 54x       54x 54x       41x                             54x                                               41x 30x 41x 30x 30x 30x 30x     10x 10x 10x       3x   30x     30x 30x 30x                                                 30x 2x 2x   2x 4x 4x 4x 4x       2x       2x 2x 2x 6x   6x   2x 4x 4x 4x   4x 12x 6x 6x 6x   12x         2x               2x     28x 48x 28x 23x   44x   28x 37x 48x   37x 54x 54x       28x               6x 15x                                                   30x 13x 13x   18x             30x 30x         30x 30x 13x     30x 30x   30x 18x 13x 13x   30x   13x                                                   30x   30x 13x 13x     13x 13x 13x         13x   13x 13x 3x 3x 13x 3x 3x 3x 3x       13x           13x 13x 13x                           30x                   30x 30x 30x 13x     30x 13x                 30x 30x   30x 30x 30x   30x 13x 11x 11x 11x       30x                 30x   30x 13x     30x                                     30x                                                     30x   30x                       30x   30x                                               30x 30x 3x           30x 30x 14x 14x 14x 14x               14x 1x   14x 7x 7x 7x 7x     14x     14x 1x                 14x                 14x                         14x 1x     14x                           30x 13x             30x                 30x                           30x       30x   30x                                                                        
// File: src/HDBPPLiveWidget.tsx
import { useMemo, useCallback, useState, useEffect, useRef } from 'react';
import {
  COLOR_PALETTES,
  DataLoadFailed,
  RefreshingBadge,
  sampleColorPaletteById,
  useEffectiveTimeRange,
  useThemeMode,
  useWidgetRefreshRate,
  type ColorPaletteId
} from '@ska-octopus-widget-sdk/widget-sdk';
import { useApolloClient } from '@apollo/client';
import type { ApolloClient, NormalizedCacheObject } from '@apollo/client';
import createPlotlyComponent from 'react-plotly.js/factory';
import Plotly from 'plotly.js-dist-min';
import { Box } from '@mui/material';
 
import { getLegendAndMargin } from './legendUtils';
import styles from './HDBPPLiveWidget.module.css';
import { useInitialHistory, type Pt } from './hooks/useInitialHistory';
import LiveStreamDriver, { StreamMeta } from './hooks/useLiveStream';
import { CURR_VALUE_OP } from './graphql/operations';
import {
  canonicalAttr,
  formatLegendName,
  parseMargins,
  coerceMinMax,
  numericValue
} from './utils/utils';
 
export interface HDBPPLiveWidgetProps {
  instanceId: string;
  attributes?: string[];
  legendPosition?: 'left' | 'right' | 'top' | 'bottom';
  colorMapPosition?: 'left' | 'right' | 'top' | 'bottom' | 'none';
  /** Target max points per trace (used for server-side downsampling and live cap) */
  maxPoints?: number;
  appendInterval?: number;
  showLegend?: boolean;
  useLiveData?: boolean;
  useHeatmap?: boolean;
  heatmapConnectGaps?: boolean;
  colorScheme?: ColorPaletteId;
  customMargins?: string;
  legendFormat?: string;
  plotTitle?: string;
  /** Downsampling strategy for initial history */
  downsample?: 'minmax' | 'avg' | 'lttb' | 'none';
  /** How enum values should be displayed */
  enumDisplay?: 'value' | 'label';
}
 
const FALLBACK_ATTR = ['sys/tg_test/1/short_scalar_ro'];
type EnumDisplayMode = NonNullable<HDBPPLiveWidgetProps['enumDisplay']>;
type ColorMapPosition = NonNullable<HDBPPLiveWidgetProps['colorMapPosition']>;
type EnumLabelsByAttr = Record<string, string[]>;
const AVAILABLE_PALETTES = Object.keys(COLOR_PALETTES) as ColorPaletteId[];
const DEFAULT_COLOR_SCHEME: ColorPaletteId = (AVAILABLE_PALETTES.find(
  (id) => id === 'scientificActon10'
) ??
  AVAILABLE_PALETTES[0] ??
  'tableau10') as ColorPaletteId;
const LINE_FALLBACK_COLOR = '#4cc9f0';
const LINE_LEGEND_FONT_SIZE = 9;
const ENUM_AXIS_FONT_SIZE = 9;
 
function buildPlotlyColorScale(paletteId: ColorPaletteId, stops = 24): Plotly.ColorScale {
  const colors = sampleColorPaletteById(paletteId, Math.max(2, stops));
  Iif (colors.length === 0) {
    return [
      [0, '#0f172a'],
      [1, '#fbbf24']
    ];
  }
  Iif (colors.length === 1) {
    const single = colors[0];
    return [
      [0, single],
      [1, single]
    ];
  }
  return colors.map((hex, idx) => [idx / (colors.length - 1), hex]) as Plotly.ColorScale;
}
 
function buildEnumColorScale(paletteId: ColorPaletteId, statesCount: number): Plotly.ColorScale {
  const safeStates = Math.max(1, statesCount);
  const colors = sampleColorPaletteById(paletteId, safeStates);
  Iif (safeStates === 1) {
    const single = colors[0] ?? LINE_FALLBACK_COLOR;
    return [
      [0, single],
      [1, single]
    ];
  }
 
  const scale: Plotly.ColorScale = [];
  for (let idx = 0; idx < safeStates; idx++) {
    const color = colors[idx] ?? colors[colors.length - 1] ?? LINE_FALLBACK_COLOR;
    const start = idx / safeStates;
    const end = (idx + 1) / safeStates;
    scale.push([start, color], [end, color]);
  }
  return scale;
}
 
function enumLabelsForAttr(
  enumLabelsByAttr: EnumLabelsByAttr,
  attrKey: string
): string[] | undefined {
  return enumLabelsByAttr[attrKey] ?? enumLabelsByAttr[attrKey.toLowerCase()];
}
 
function getColorbarPlacement(pos: ColorMapPosition): Record<string, any> {
  switch (pos) {
    case 'left':
      return { x: -0.04, y: 0.5, xanchor: 'right', yanchor: 'middle', len: 0.72, thickness: 10 };
    case 'top':
      return {
        x: 0.5,
        y: 1.06,
        xanchor: 'center',
        yanchor: 'bottom',
        len: 0.52,
        thickness: 10,
        orientation: 'h'
      };
    case 'bottom':
      return {
        x: 0.5,
        y: -0.16,
        xanchor: 'center',
        yanchor: 'top',
        len: 0.52,
        thickness: 10,
        orientation: 'h'
      };
    case 'none':
      return {};
    case 'right':
    default:
      return { x: 1.01, y: 0.5, xanchor: 'left', yanchor: 'middle', len: 0.72, thickness: 10 };
  }
}
 
function buildHeatmapLabels(attrs: string[], legendFormat: string): string[] {
  const keys = attrs.map((a) => canonicalAttr(a));
  const raw = attrs.map((a) => formatLegendName(a, legendFormat ?? 'lastname').trim());
  const baseLabels = raw.map((lbl, idx) => lbl || keys[idx]);
 
  const counts = new Map<string, number>();
  baseLabels.forEach((lbl) => counts.set(lbl, (counts.get(lbl) ?? 0) + 1));
 
  const seen = new Map<string, number>();
  return baseLabels.map((lbl) => {
    const total = counts.get(lbl) ?? 0;
    if (total <= 1) return lbl;
    const order = (seen.get(lbl) ?? 0) + 1;
    seen.set(lbl, order);
    return order === 1 ? lbl : `${lbl} [${order}]`;
  });
}
 
function enumLabelForValue(enumLabels: string[] | undefined, value: number | null): string | null {
  if (!enumLabels || value === null || !Number.isFinite(value) || !Number.isInteger(value)) {
    return null;
  }
  const idx = value as number;
  Iif (idx < 0 || idx >= enumLabels.length) return null;
  return enumLabels[idx] ?? null;
}
 
function toDisplayValue(
  value: number | null,
  enumLabels: string[] | undefined,
  enumDisplay: EnumDisplayMode
): string {
  Iif (value === null) return 'null';
  if (enumDisplay === 'label') {
    const label = enumLabelForValue(enumLabels, value);
    if (label) return label;
  }
  return String(value);
}
 
function buildEnumAxisTicks(
  attrs: string[],
  dataMap: Record<string, Pt[]>,
  enumLabelsByAttr: EnumLabelsByAttr
): { tickvals: number[]; ticktext: string[] } | null {
  Iif (attrs.length === 0) return null;
 
  const valueToLabel = new Map<number, string>();
 
  for (const attr of attrs) {
    const key = canonicalAttr(attr);
    const labels = enumLabelsForAttr(enumLabelsByAttr, key);
    if (!labels || labels.length === 0) return null;
 
    const pts = dataMap[key] ?? [];
    for (const pt of pts) {
      const val = numericValue(pt.v);
      Iif (val === null || !Number.isFinite(val) || !Number.isInteger(val)) return null;
      const resolved = enumLabelForValue(labels, val);
      Iif (!resolved) return null;
 
      const existing = valueToLabel.get(val);
      Iif (existing && existing !== resolved) return null;
      valueToLabel.set(val, resolved);
    }
  }
 
  Iif (valueToLabel.size === 0) return null;
 
  const tickvals = Array.from(valueToLabel.keys()).sort((a, b) => a - b);
  const ticktext = tickvals.map((v) => valueToLabel.get(v) ?? String(v));
  return { tickvals, ticktext };
}
 
function buildLineTraces(
  attrs: string[],
  dataMap: Record<string, Pt[]>,
  legendFormat: string,
  paletteId: ColorPaletteId,
  hidden: Set<string>,
  enumDisplay: EnumDisplayMode,
  enumLabelsByAttr: EnumLabelsByAttr
): Partial<Plotly.Data>[] {
  const lineColors = sampleColorPaletteById(paletteId, Math.max(2, attrs.length));
  return attrs.map((attr, idx) => {
    const key = canonicalAttr(attr);
    const pts = dataMap[key] ?? [];
    const enumLabels = enumLabelsForAttr(enumLabelsByAttr, key);
    const traceColor = lineColors[idx] ?? LINE_FALLBACK_COLOR;
 
    const x: number[] = [];
    const y: (number | null)[] = [];
    const customData: string[] = [];
    const errPlus: number[] = [];
    const errMinus: number[] = [];
 
    pts.forEach((p) => {
      const { y: val, min, max } = coerceMinMax(p.v);
      x.push(p.t);
      y.push(val);
      customData.push(toDisplayValue(val, enumLabels, enumDisplay));
      Iif (min !== undefined && max !== undefined && val !== null) {
        errPlus.push(Math.max(0, max - val));
        errMinus.push(Math.max(0, val - min));
      } else {
        errPlus.push(0);
        errMinus.push(0);
      }
    });
 
    return {
      type: 'scatter',
      mode: 'lines+markers',
      name: formatLegendName(attr, legendFormat ?? 'lastname'),
      x,
      y,
      line: { color: traceColor },
      marker: { size: 6 },
      visible: hidden.has(key) ? 'legendonly' : true,
      hovertemplate:
        enumDisplay === 'label'
          ? '%{customdata}<br>%{x}<extra></extra>'
          : '%{y}<br>%{x}<extra></extra>',
      customdata: enumDisplay === 'label' ? customData : undefined,
      error_y:
        errPlus.some((v) => v > 0) || errMinus.some((v) => v > 0)
          ? {
              type: 'data',
              array: errPlus,
              arrayminus: errMinus,
              symmetric: false,
              color: traceColor
            }
          : undefined
    } as Partial<Plotly.Data>;
  });
}
 
function buildHeatmap(
  attrs: string[],
  dataMap: Record<string, Pt[]>,
  paletteId: ColorPaletteId,
  maxPoints: number,
  legendFormat: string,
  connectGaps: boolean,
  colorMapPosition: ColorMapPosition,
  enumDisplay: EnumDisplayMode,
  enumLabelsByAttr: EnumLabelsByAttr
): Partial<Plotly.Data> {
  const keys = attrs.map((a) => canonicalAttr(a));
  const y = buildHeatmapLabels(attrs, legendFormat);
  const enumStateCounts = keys.map((key) => enumLabelsForAttr(enumLabelsByAttr, key)?.length ?? 0);
  const hasEnumColors = enumStateCounts.length > 0 && enumStateCounts.every((n) => n > 0);
  const enumStates = hasEnumColors ? Math.max(...enumStateCounts) : 0;
  const enumTickvals = hasEnumColors ? Array.from({ length: enumStates }, (_, idx) => idx) : [];
  const enumTicktext = hasEnumColors
    ? enumDisplay === 'label'
      ? enumTickvals.map((idx) => {
          for (const key of keys) {
            const label = enumLabelsForAttr(enumLabelsByAttr, key)?.[idx];
            Eif (label) return label;
          }
          return String(idx);
        })
      : enumTickvals.map((idx) => String(idx))
    : [];
  const colorscale = hasEnumColors
    ? buildEnumColorScale(paletteId, enumStates)
    : buildPlotlyColorScale(paletteId);
  const showColorMap = colorMapPosition !== 'none';
  const colorbarPos = getColorbarPlacement(colorMapPosition);
  const base: Partial<Plotly.Data> = {
    type: 'heatmap',
    colorscale,
    colorbar: showColorMap
      ? hasEnumColors
        ? {
            ...colorbarPos,
            tickmode: 'array',
            tickvals: enumTickvals,
            ticktext: enumTicktext,
            tickfont: { size: 9 }
          }
        : { ...colorbarPos, tickfont: { size: 9 } }
      : undefined,
    showscale: showColorMap,
    zauto: hasEnumColors ? false : undefined,
    zmin: hasEnumColors ? -0.5 : undefined,
    zmax: hasEnumColors ? enumStates - 0.5 : undefined,
    hovertemplate:
      enumDisplay === 'label'
        ? 'Attr: %{y}<br>Value: %{text}<br>Time: %{x}<extra></extra>'
        : 'Attr: %{y}<br>Value: %{z}<br>Time: %{x}<extra></extra>',
    hoverongaps: false
  };
 
  if (connectGaps) {
    let globalMin = Number.POSITIVE_INFINITY;
    let globalMax = Number.NEGATIVE_INFINITY;
 
    keys.forEach((k) => {
      const pts = dataMap[k] ?? [];
      Eif (pts.length > 0) {
        globalMin = Math.min(globalMin, pts[0].t);
        globalMax = Math.max(globalMax, pts[pts.length - 1].t);
      }
    });
 
    Iif (!Number.isFinite(globalMin) || !Number.isFinite(globalMax) || globalMax <= globalMin) {
      return { ...base, x: [], y, z: [] };
    }
 
    const columns = Math.max(1, maxPoints > 0 ? Math.min(maxPoints, 2000) : 500);
    const step = columns === 1 ? 0 : (globalMax - globalMin) / (columns - 1);
    const timeline = Array.from({ length: columns }, (_, idx) =>
      columns === 1 ? globalMax : Math.round(globalMin + idx * step)
    );
    const x = timeline.map((t) => new Date(t).toISOString());
 
    const z = keys.map((key) => {
      const pts = (dataMap[key] ?? []).slice().sort((a, b) => a.t - b.t);
      let cursor = 0;
      let last: number | null = null;
 
      return timeline.map((t) => {
        while (cursor < pts.length && pts[cursor].t <= t) {
          const val = numericValue(pts[cursor].v);
          Eif (val !== null && Number.isFinite(val)) last = val;
          cursor++;
        }
        return last;
      });
    });
 
    const text =
      enumDisplay === 'label'
        ? z.map((row, idx) =>
            row.map((val) =>
              toDisplayValue(val, enumLabelsForAttr(enumLabelsByAttr, keys[idx]), enumDisplay)
            )
          )
        : undefined;
 
    return { ...base, x, y, z, text, connectgaps: true };
  }
 
  const tsSet = new Set<number>();
  keys.forEach((k) => (dataMap[k] ?? []).forEach((p) => tsSet.add(p.t)));
  const xs = Array.from(tsSet)
    .sort((a, b) => a - b)
    .slice(-Math.max(1, maxPoints));
  const x = xs.map((t) => new Date(t).toISOString());
 
  const z = keys.map((key) => {
    const map = new Map<number, number | null>(
      (dataMap[key] ?? []).map((p) => [p.t, numericValue(p.v)])
    );
    return xs.map((t) => {
      const val = map.get(t);
      return val !== null && Number.isFinite(val) ? (val as number) : null;
    });
  });
 
  return {
    ...base,
    x,
    y,
    z,
    text:
      enumDisplay === 'label'
        ? z.map((row, idx) =>
            row.map((val) =>
              toDisplayValue(val, enumLabelsForAttr(enumLabelsByAttr, keys[idx]), enumDisplay)
            )
          )
        : undefined,
    connectgaps: false
  } as Partial<Plotly.Data>;
}
 
export default function HDBPPLiveWidget({
  instanceId,
  attributes = FALLBACK_ATTR,
  legendPosition = 'bottom',
  colorMapPosition = 'right',
  maxPoints = 100,
  appendInterval = 0,
  showLegend = true,
  useLiveData = true,
  useHeatmap = false,
  heatmapConnectGaps = false,
  customMargins = '',
  colorScheme = DEFAULT_COLOR_SCHEME,
  legendFormat = 'lastname',
  plotTitle = '',
  downsample = 'minmax',
  enumDisplay = 'value'
}: HDBPPLiveWidgetProps) {
  const safeAttributes = useMemo(() => {
    const raw = Array.isArray(attributes) && attributes.length > 0 ? attributes : FALLBACK_ATTR;
    return raw
      .filter(Boolean)
      .map((attr) => String(attr).trim().toLowerCase())
      .filter(Boolean);
  }, [attributes]);
 
  /* ------------------------------------------------------------
   * 1) Time range helper
   * ------------------------------------------------------------ */
  const { epochStart, epochEnd, presetMs } = useEffectiveTimeRange() as any;
  const rangeMs = presetMs ?? epochEnd - epochStart;
 
  /* ------------------------------------------------------------
   * 2) Misc helpers
   * ------------------------------------------------------------ */
  const client = useApolloClient() as ApolloClient<NormalizedCacheObject>;
  const { legend, margin: extraMargin } = useMemo(
    () => getLegendAndMargin(legendPosition, showLegend),
    [legendPosition, showLegend]
  );
  const { isDark } = useThemeMode();
  const Plot = useMemo(() => createPlotlyComponent(Plotly), []);
 
  const attrsSig = useMemo(() => {
    const cleaned = safeAttributes.filter(Boolean).map((a) => a.trim());
    const uniqueSorted = Array.from(new Set(cleaned)).sort();
    return JSON.stringify(uniqueSorted);
  }, [safeAttributes]);
  const plotConfigSig = useMemo(
    () =>
      JSON.stringify({
        useHeatmap,
        heatmapConnectGaps,
        legendPosition,
        colorMapPosition,
        enumDisplay,
        showLegend,
        customMargins,
        plotTitle,
        colorScheme,
        legendFormat
      }),
    [
      useHeatmap,
      heatmapConnectGaps,
      legendPosition,
      colorMapPosition,
      enumDisplay,
      showLegend,
      customMargins,
      plotTitle,
      colorScheme,
      legendFormat
    ]
  );
 
  const [enumLabelsByAttr, setEnumLabelsByAttr] = useState<EnumLabelsByAttr>({});
 
  useEffect(() => {
    let cancelled = false;
    setEnumLabelsByAttr({});
 
    async function loadEnumLabels() {
      Iif (!client || typeof client.query !== 'function' || safeAttributes.length === 0) return;
      try {
        const { data } = await client.query({
          query: CURR_VALUE_OP,
          variables: { fullNames: safeAttributes },
          fetchPolicy: 'network-only'
        });
        Iif (cancelled) return;
 
        const next: EnumLabelsByAttr = {};
        (data?.attributes ?? []).forEach((row: any) => {
          Iif (!row?.name || !Array.isArray(row.enumLabels) || row.enumLabels.length === 0) return;
          const raw = row.device ? `${row.device}/${row.name}` : row.name;
          const labels = row.enumLabels.filter((x: unknown) => typeof x === 'string');
          Eif (labels.length > 0) {
            const key = canonicalAttr(raw);
            next[key] = labels;
            next[key.toLowerCase()] = labels;
          }
        });
 
        setEnumLabelsByAttr(next);
      } catch {
        if (!cancelled) setEnumLabelsByAttr({});
      }
    }
 
    loadEnumLabels();
    return () => {
      cancelled = true;
    };
  }, [client, attrsSig, safeAttributes]);
 
  /* ------------------------------------------------------------
   * 3) Initial history fetch + optional polling
   * ------------------------------------------------------------ */
  const {
    dataMap,
    setDataMap,
    status: histStatus,
    error: histError,
    refetch: refetchHistory,
    missingAttributes
  } = useInitialHistory(
    client,
    safeAttributes,
    maxPoints, // -> server-side `maxPoints`
    epochStart,
    epochEnd,
    rangeMs,
    downsample
  );
 
  const refreshSec = useWidgetRefreshRate(instanceId);
  const refetchRef = useRef(refetchHistory);
  useEffect(() => {
    refetchRef.current = refetchHistory;
  }, [refetchHistory]);
 
  useEffect(() => {
    Eif (useLiveData || !refreshSec || refreshSec <= 0) return;
    refetchRef.current();
    const id = setInterval(() => refetchRef.current(), refreshSec * 1000);
    return () => clearInterval(id);
  }, [useLiveData, refreshSec]);
 
  /* ------------------------------------------------------------
   * 4) Live subscription (conditional)
   * ------------------------------------------------------------ */
  const hasData = Object.keys(dataMap).length > 0;
  const canSubscribe = useLiveData && hasData;
 
  const [streamStatus, setStreamStatus] = useState<'idle' | 'loading' | 'ok' | 'failed'>('idle');
  const [streamError, setStreamError] = useState<any>(null);
  const streamRetryRef = useRef<(() => void) | undefined>(undefined);
 
  useEffect(() => {
    if (!canSubscribe) {
      setStreamStatus('idle');
      setStreamError(null);
      streamRetryRef.current = undefined;
    }
  }, [canSubscribe]);
 
  const handleStreamMeta = useCallback((m: StreamMeta) => {
    setStreamStatus(m.status ?? 'idle');
    setStreamError(m.error ?? null);
    streamRetryRef.current = m.retry;
  }, []);
 
  /* ------------------------------------------------------------
   * 5) Legend toggle (lines only)
   * ------------------------------------------------------------ */
  const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(new Set());
 
  useEffect(() => {
    setHiddenKeys(new Set());
  }, [attrsSig]);
 
  const handleLegendClick = useCallback(
    (e: any) => {
      const idx = e.curveNumber;
      const rawAttr = safeAttributes[idx];
      const key = canonicalAttr(rawAttr);
      setHiddenKeys((prev) => {
        const next = new Set(prev);
        if (next.has(key)) {
          next.delete(key);
        } else {
          next.add(key);
        }
        return next;
      });
      return false;
    },
    [safeAttributes]
  );
 
  const handleLegendDoubleClick = useCallback(
    (e: any) => {
      const idx = e.curveNumber;
      const rawAttr = safeAttributes[idx];
      const key = canonicalAttr(rawAttr);
 
      setHiddenKeys((prev) => {
        const total = safeAttributes.length;
        const isIsolatedToThis = prev.size === total - 1 && !prev.has(key);
        if (isIsolatedToThis) {
          return new Set();
        }
        const next = new Set<string>();
        safeAttributes.forEach((attr) => {
          const k = canonicalAttr(attr);
          if (k !== key) next.add(k);
        });
        return next;
      });
      return false;
    },
    [safeAttributes]
  );
 
  /* ------------------------------------------------------------
   * 6) Traces
   * ------------------------------------------------------------ */
  const lineTraces = useMemo(
    () =>
      buildLineTraces(
        safeAttributes,
        dataMap,
        legendFormat,
        colorScheme,
        hiddenKeys,
        enumDisplay,
        enumLabelsByAttr
      ),
    [safeAttributes, dataMap, legendFormat, colorScheme, hiddenKeys, enumDisplay, enumLabelsByAttr]
  );
 
  const heatmapTrace = useMemo(
    () =>
      buildHeatmap(
        safeAttributes,
        dataMap,
        colorScheme,
        maxPoints,
        legendFormat ?? 'lastname',
        heatmapConnectGaps,
        colorMapPosition,
        enumDisplay,
        enumLabelsByAttr
      ),
    [
      safeAttributes,
      dataMap,
      colorScheme,
      maxPoints,
      legendFormat,
      heatmapConnectGaps,
      colorMapPosition,
      enumDisplay,
      enumLabelsByAttr
    ]
  );
 
  const enumAxisTicks = useMemo(() => {
    if (useHeatmap || enumDisplay !== 'label') return null;
    return buildEnumAxisTicks(safeAttributes, dataMap, enumLabelsByAttr);
  }, [useHeatmap, enumDisplay, safeAttributes, dataMap, enumLabelsByAttr]);
 
  /* ------------------------------------------------------------
   * 7) Layout
   * ------------------------------------------------------------ */
  const { isDark: dark } = { isDark };
  const layout = useMemo<Partial<Plotly.Layout>>(() => {
    const parsedMargins = parseMargins(customMargins);
    const hasTitle = Boolean((plotTitle || '').trim());
    const topMargin = hasTitle ? 60 : 18;
    const mergedMargin = {
      t: topMargin,
      r: 6,
      b: 22,
      l: 32,
      ...extraMargin,
      ...parsedMargins
    };
    if (hasTitle) {
      mergedMargin.t = Math.max(topMargin, mergedMargin.t ?? topMargin);
    }
    if (useHeatmap) {
      if (colorMapPosition === 'left') mergedMargin.l = Math.max(mergedMargin.l ?? 40, 72);
      if (colorMapPosition === 'right') mergedMargin.r = Math.max(mergedMargin.r ?? 10, 68);
      Iif (colorMapPosition === 'top') mergedMargin.t = Math.max(mergedMargin.t ?? topMargin, 76);
      Iif (colorMapPosition === 'bottom') mergedMargin.b = Math.max(mergedMargin.b ?? 30, 70);
    }
 
    const yaxis = useHeatmap
      ? { title: 'Attributes', gridcolor: dark ? '#444' : '#ddd', type: 'category' as const }
      : { title: 'Value', gridcolor: dark ? '#444' : '#ddd' };
    if (!useHeatmap && enumDisplay === 'label' && enumAxisTicks) {
      Object.assign(yaxis, {
        title: 'State',
        tickmode: 'array',
        tickvals: enumAxisTicks.tickvals,
        ticktext: enumAxisTicks.ticktext,
        tickfont: { size: ENUM_AXIS_FONT_SIZE, color: dark ? '#e0e0e0' : '#222' }
      });
    }
 
    const legendCfg = {
      ...legend,
      font: {
        ...(legend.font ?? {}),
        size: LINE_LEGEND_FONT_SIZE,
        color: dark ? '#e0e0e0' : '#222'
      }
    };
 
    const base: Partial<Plotly.Layout> = {
      template: dark ? ('plotly_dark' as any) : undefined,
      autosize: true,
      margin: mergedMargin,
      paper_bgcolor: dark ? '#1e1e1e' : 'transparent',
      plot_bgcolor: dark ? '#1e1e1e' : 'transparent',
      font: { color: dark ? '#e0e0e0' : '#222' },
      xaxis: { title: 'Time', gridcolor: dark ? '#444' : '#ddd', type: 'date' },
      yaxis,
      legend: legendCfg,
      showlegend: showLegend && !useHeatmap
    };
 
    if (hasTitle) {
      (base as any).title = { text: plotTitle, x: 0.5, xanchor: 'center' };
    }
 
    return base;
  }, [
    dark,
    legend,
    extraMargin,
    showLegend,
    useHeatmap,
    colorMapPosition,
    customMargins,
    plotTitle,
    enumDisplay,
    enumAxisTicks
  ]);
 
  const missingDisplayNames = useMemo(
    () => missingAttributes.map((attr) => formatLegendName(attr, legendFormat ?? 'lastname')),
    [missingAttributes, legendFormat]
  );
 
  /* ------------------------------------------------------------
   * 8) Early / error states
   * ------------------------------------------------------------ */
  Iif (histStatus === 'failed' && !hasData)
    return (
      <DataLoadFailed
        message="Failed to load history"
        error={histError as any}
        handleRetry={refetchHistory}
      />
    );
 
  Iif (useLiveData && streamStatus === 'failed' && !hasData)
    return (
      <DataLoadFailed
        message="Subscription failed"
        error={streamError}
        handleRetry={streamRetryRef.current}
      />
    );
 
  /* ------------------------------------------------------------
   * 9) Render
   * ------------------------------------------------------------ */
 
  const refreshing =
    histStatus === 'loading' ||
    histStatus === 'refreshing' ||
    (useLiveData && streamStatus === 'loading');
 
  const plotData = useHeatmap ? [heatmapTrace] : lineTraces;
 
  return (
    <Box className={styles.container}>
      {missingAttributes.length > 0 && (
        <div className={styles.warning} role="status">
          Some attributes failed to load: {missingDisplayNames.join(', ')}
        </div>
      )}
 
      <div className={styles.plotShell}>
        {canSubscribe && (
          <LiveStreamDriver
            attrs={safeAttributes}
            maxPoints={maxPoints}
            setDataMap={setDataMap}
            appendIntervalSec={appendInterval}
            onStatus={handleStreamMeta}
          />
        )}
 
        <Plot
          key={`plot-${attrsSig}-${plotConfigSig}`}
          data={plotData as any}
          layout={layout}
          config={{ responsive: true, displayModeBar: false }}
          useResizeHandler
          className={styles.plot}
          onLegendClick={useHeatmap ? undefined : handleLegendClick}
          onLegendDoubleClick={useHeatmap ? undefined : handleLegendDoubleClick}
        />
 
        {/* Subtle refresh indicator that doesn't replace the chart */}
        <RefreshingBadge active={refreshing} text="Refreshing…" position="top-right" />
      </div>
    </Box>
  );
}