All files / src/pages/flowsheet-page/pinch-analysis/hen-generation HENDiagramsPage.tsx

91.34% Statements 306/335
69.44% Branches 100/144
90.78% Functions 69/76
92.95% Lines 277/298

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 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945                                                                                            76x 76x   76x                                                               98x   98x 98x 98x     98x   98x 98x     98x 98x 98x 98x 98x 98x 98x 98x   98x 16x         98x   775x 775x 647x           98x 20x 91x 20x             98x 38x     20x   20x   20x 20x           98x       44x 128x 128x     128x       44x 44x 44x 128x 128x       44x 128x         44x         44x       44x   44x                     98x 44x 20x 20x 48x         20x     20x   20x         98x 44x 44x 128x 128x 128x 128x   44x           98x 98x               98x   98x 16x 16x 314x 9x 9x 9x       98x   9x                       98x 47x 47x 136x 136x     124x             124x     12x 30x               12x     47x             98x           98x 38x 38x   72x 38x 77x   38x 38x           98x 44x           44x         44x                     98x 38x 38x 38x 108x 208x   108x 54x   38x         98x     98x     98x 98x     98x 98x   98x 98x     98x 9x           30x       98x 47x                           98x   47x     47x             47x               98x 7x             98x 47x 96x 96x   45x 45x     51x 51x   51x 51x   8x 8x                                 98x 47x             98x 25x       98x   26x         98x 38x 108x 38x           98x   1x 1x 1x 1x 1x 1x 1x           98x   6x 6x 6x 6x                     98x   13x 13x 13x       13x           98x   6x 6x 6x 6x 6x 6x                   98x               98x 1x 1x 1x 1x 1x 1x 1x       98x     98x   5x     86x                                                                                   292x   292x   292x     292x     292x 558x   292x 558x       292x         292x 292x 292x     292x 342x 292x 412x     412x   444x 444x           292x 342x   33x 83x   33x 37x 17x     259x       292x 342x             342x 834x               328x   328x           328x           574x 328x   246x           292x     292x 454x     454x 454x   412x 412x   454x         146x 146x   146x 146x   146x     292x 342x             342x 342x 342x   342x 342x     328x       328x 328x 428x       328x 454x     454x       454x     484x             428x                                                       328x 328x 146x 146x 146x 146x               292x   292x   292x       292x                               4x 4x 4x 4x       4x     4x                             4x 4x 4x 4x                                                                                                                              
import * as d3 from "d3";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { ScrollArea } from "@/ahuora-design-system/ui/scroll-area";
import {
  SegmentRead,
  usePinchHenNodePartialUpdateMutation,
  usePinchStreamDataEntryPartialUpdateMutation,
} from "@/api/apiStore.gen";
import {
  useCurrentHenNodes,
  useCurrentStreamDataEntries,
  useElementSize,
} from "@/hooks/henHooks";
import { useCurrentPinchOutputs, useCurrentSegments } from "@/hooks/PinchHooks";
import ExchangerLines from "./HENExchangerLines";
import { useHenHoverCard } from "./HENHoverCard";
import PinchLine from "./HENPinchLine";
import StreamGraphic from "./HENStreamGraphic";
import { Bounds, HenNodeMarker, StreamDragState } from "./henTypes";
import { boundsFor } from "./utils/bounds";
import { buildStreams } from "./utils/buildHENStreams";
import {
  getNodePlacementRegion,
  MARGIN_X,
  MIN_NODE_GAP,
  STREAM_BLOCK_HEIGHT,
} from "./utils/henLayoutUtils";
import {
  buildHxCanonicalIdByKey,
  buildHxStoredXByKey,
  buildHxXsByRowBySdeId,
  collectHxSides,
  computeAlignedHX,
  computeHxColumnBlocks,
  computeHxColumnsByKey,
  computeHxMultiplicityByKey,
  detectHxOrder,
  pairHxRowsForEachKey,
} from "./utils/hxNodes";
import { getUnitopSide } from "./utils/nodeMarkers";
import { computePinchPlacement } from "./utils/pinchLine";
import { collectAllTemps } from "./utils/streams";
 
// --- layout constants ---
// top/bottom whitespace for the SVG canvas (in pixels)
const PADDING_TOP = 100;
const PADDING_BOTTOM = 20;
 
const STREAM_BLOCK_GAP = 10; // vertical gap between strema blocks
 
// types
type RowIdx = number; // row number for all visible stream lines (if collapsed, 0; if expanded, 0..N-1)
type XCoord = number; // pixel X chosen for that row's hx marker
type RowsMap = Map<RowIdx, XCoord>; // All row Xs for a single (hxKey, sde id)
type SdeIdMap = Map<string, RowsMap>; // which sde does this row belong to?
/** resolvedHxMap[hxKey][sdeId][rowIdx] = xCoord */
type ResolvedHxMap = Map<string, SdeIdMap>;
 
/**
 * immutable update: wriote a resolved X for HX nodes (hxKey, sdeid, rowIdx)
 * children, (e.g. StreamGraphics) can commit a row-specific X when alignement is ambiguous.
 * returns a new nested map so react state updates properly
 */
function setRowX(
  map: ResolvedHxMap,
  hxKey: string,
  sdeId: string,
  rowIdx: number,
  x: number,
): ResolvedHxMap {
  const next = new Map(map);
  const bySdeId = new Map(next.get(hxKey) ?? []);
  const rows = new Map(bySdeId.get(sdeId) ?? []);
  rows.set(rowIdx, x);
  bySdeId.set(sdeId, rows);
  next.set(hxKey, bySdeId);
  return next;
}
 
export default function HenDiagramsPage() {
  const [_, setSearchParams] = useSearchParams();
  const [containerRef, { width: svgWidth, height: svgHeight }] =
    useElementSize<HTMLDivElement>();
  const [streamPositions, setStreamPositions] = useState<any[]>([]);
  const [optimisticExpandedBySde, setOptimisticExpandedBySde] = useState<
    Map<string, boolean>
  >(new Map()); // state for optimistic expanding
  const [togglingSdes, setTogglingSdes] = useState<Set<string>>(new Set()); // state for "loading" optimistic expansion.
 
  const [dragState, setDragState] = useState<StreamDragState>(null);
  const [resolvedHxRowsByKey, setResolvedHxRowsByKey] = useState<ResolvedHxMap>(
    new Map(),
  );
  const { streams: segments, isLoading, isError } = useCurrentSegments();
  const { streams: sdes } = useCurrentStreamDataEntries();
  const { outputs } = useCurrentPinchOutputs();
  const { data: henNodes, isLoading: henNodesIsLoading } = useCurrentHenNodes();
  const [updateHenNode] = usePinchHenNodePartialUpdateMutation();
  const [updateSDE] = usePinchStreamDataEntryPartialUpdateMutation();
  const { HoverLayer, show, hide, buildContent } = useHenHoverCard();
  const pendingPersistedHxXs = useRef<Map<string, number>>(new Map());
 
  const { allStreams, expandedBySde, aggregatedStreams } = useMemo(
    () => buildStreams(segments, sdes, henNodes, streamPositions),
    [segments, sdes, henNodes, streamPositions],
  );
 
  // is this sde expanded right now?
  const isExpanded = useCallback(
    (sdeId: string) => {
      const local = optimisticExpandedBySde.get(sdeId);
      if (local != null) return local;
      return expandedBySde.get(sdeId) ?? false;
    },
    [optimisticExpandedBySde, expandedBySde],
  );
 
  // optimisitc update expand
  const effectiveExpandedBySde = useMemo(() => {
    const m = new Map<string, boolean>();
    (sdes ?? []).forEach((s) => m.set(String(s.id), isExpanded(String(s.id))));
    return m;
  }, [sdes, isExpanded]);
 
  // -------------------------------------------------
  // What stuff are we actually rendering
  // -------------------------------------------------
  // Which list should we render: preview (while dragging) or current?
  const renderStreams = useMemo(() => {
    if (!dragState?.active) return allStreams;
 
    // copy array of all streams (depending on whether user has reordered or not)
    const arr = [...allStreams];
    // remove the stream being dragged from array
    const [moved] = arr.splice(dragState.draggedIndex, 1);
    // add it back to the array in a new index.
    arr.splice(dragState.overIndex, 0, moved);
    return arr;
  }, [dragState, allStreams]);
 
  // -------------------------------------------------
  // vertical layouts  (heights, Y's, svg height)
  // -------------------------------------------------
  const verticalLayouts = useMemo(() => {
    // block heights + gap (in pixels)
    // if a stream is EXPANDED, you should see multiple lines in the same BLOCK
    // hence the stream block height will grow to fit them.
    const streamBlockHeights = renderStreams.map((s) => {
      const expanded = isExpanded(String(s.stream_data_entry));
      const h = expanded
        ? STREAM_BLOCK_HEIGHT * s.rawSegments.length
        : STREAM_BLOCK_HEIGHT;
      return h + STREAM_BLOCK_GAP;
    });
 
    // top-edge Y position (pixels) for each stream block.
    const streamBlockYPositions: number[] = [];
    let cur = PADDING_TOP;
    streamBlockHeights.forEach((h) => {
      streamBlockYPositions.push(cur);
      cur += h;
    });
 
    // centre of a VISIBLE streamBlock (i.e. not/expanded), for landing slot for drag drop.
    const streamBlockCentres = streamBlockYPositions.map(
      (y, i) => y + (streamBlockHeights[i] - STREAM_BLOCK_GAP) / 2,
    );
 
    // get the sum of all stream block heights which is used to calculate total svgheight.
    const allStreamBlocksHeight =
      d3.sum(streamBlockHeights) -
      (streamBlockHeights.length ? STREAM_BLOCK_GAP : 0);
 
    // calculate svg height
    const calculatedSvgHeight =
      PADDING_TOP + allStreamBlocksHeight + PADDING_BOTTOM;
 
    //final svg height should be at least 200px.
    const finalSvgHeight =
      calculatedSvgHeight < 300 ? 300 : calculatedSvgHeight;
 
    return {
      streamBlockHeights,
      streamBlockYPositions,
      streamBlockCentres,
      allStreamBlocksHeight,
      calculatedSvgHeight,
      finalSvgHeight,
    };
  }, [renderStreams, isExpanded]);
 
  // FOR HX LINES: when dragging, show the lines follow the stream.
  const streamYPositionsForHXLines = useMemo(() => {
    if (!dragState?.active) return verticalLayouts.streamBlockYPositions;
    const arr = [...verticalLayouts.streamBlockYPositions];
    const idx = renderStreams.findIndex(
      (s) => String(s.stream_data_entry) === dragState.draggedStreamId,
    );
    if (idx >= 0) {
      // get current stream block height
      const blockHeight =
        verticalLayouts.streamBlockHeights[idx] - STREAM_BLOCK_GAP;
      // convert current drag centre Y to a top-edge Y so lines attach correctly
      // topY = currentY (centre) - visible streamblockheight /2
      arr[idx] = dragState.currentY - blockHeight / 2;
    }
    return arr;
  }, [dragState, verticalLayouts, renderStreams]);
 
  //quick lookup table to show visible (rows) per SDE in the diageram.
  // e.g. there will be more visible rows for expanded segments.
  const visibleCountBySdeId = useMemo(() => {
    const m = new Map<string, number>();
    renderStreams.forEach((s) => {
      const sdeId = String(s.stream_data_entry);
      const expanded = isExpanded(sdeId);
      const k = expanded ? (s.rawSegments?.length ?? 1) : 1;
      m.set(sdeId, Math.max(1, k));
    });
    return m;
  }, [renderStreams, isExpanded]);
 
  // -------------------------------------------------
  // pinch stuff, and per-row horizontal bounds (depending on pinch and svg width)
  // -------------------------------------------------
  const pinchTempRead = outputs?.[0]?.targets?.[0]?.temp_pinch;
  const pinchTemps = pinchTempRead
    ? {
        coldPinch: pinchTempRead.cold_temp,
        hotPinch: pinchTempRead.hot_temp,
      }
    : undefined;
 
  // Single scalar pinch we'll use for side decisions, but this will have to be refactored to CHOOSE if there is BOTH hot and COLD pinch.
  const pinch = pinchTemps?.coldPinch ?? pinchTemps?.hotPinch;
 
  const { minT, maxT } = useMemo(() => {
    const temps = collectAllTemps(aggregatedStreams);
    if (!temps.length) return { minT: 0, maxT: 1 };
    const s = temps.slice().sort((a, b) => a - b);
    const lo = d3.quantileSorted(s, 0.05)!; // 5th percentile cut out outliers
    const hi = d3.quantileSorted(s, 0.95)!; // 95th percentile
    return { minT: lo, maxT: Math.max(hi, lo + 1e-6) };
  }, [aggregatedStreams]);
 
  // get pinch line X position.
  const { pinchX } = useMemo(
    () =>
      computePinchPlacement({
        pinch,
        minT,
        maxT,
        svgWidth,
        marginX: MARGIN_X,
      }),
    [pinch, minT, maxT, svgWidth],
  );
 
  // gets the horix=zontal bounds of each stream/segment
  // i.e. between which X pixels are we allowed to place stuff for this row?
  const rowBoundsAlignBySdeId = useMemo(() => {
    const m = new Map<string, Bounds[]>();
    renderStreams.forEach((s) => {
      const sdeId = String(s.stream_data_entry);
      const expanded = isExpanded(sdeId);
      if (!expanded) {
        // collpased: exactly one row -> one Bounds
        const b = boundsFor(
          Number(s.t_supply),
          Number(s.t_target),
          pinch,
          svgWidth || 0,
          pinchX,
        );
        m.set(sdeId, [b]);
      } else {
        // expanded: one Bounds per segment row.
        const rows: Bounds[] = (s.rawSegments ?? []).map((seg: SegmentRead) =>
          boundsFor(
            Number(seg.t_supply),
            Number(seg.t_target),
            pinch,
            svgWidth || 0,
            pinchX,
          ),
        );
        m.set(sdeId, rows);
      }
    });
    return m;
  }, [renderStreams, isExpanded, pinch, svgWidth, pinchX]);
 
  // -------------------------------------------------
  // GLOBAL columns for nodes (stable order, per-hx columns, )
  // -------------------------------------------------
  // Sticky HX order and width (so columns don't jump around on reorder)
  const hxStickyOrderRef = useRef<string[]>([]);
 
  // stable left-to-right HX order across reorders within the session so columns dont reshuffle
  // Prevents HX columns from reshuffling during drag/expand/collapse:
  // - Start from the previous sticky list, drop keys not detected now.
  // - Append newly detected keys (preserve their detected order).
  const hxOrder: string[] = useMemo(() => {
    const detectedOrder = detectHxOrder(renderStreams);
    const seen = new Set(detectedOrder);
    // start from the *previous sticky order* (the ref). Keep only keys that still exist in "detected".
    const existing = hxStickyOrderRef.current.filter((k) => seen.has(k));
    detectedOrder.forEach((k) => {
      if (!existing.includes(k)) existing.push(k);
    });
    hxStickyOrderRef.current = existing;
    return existing;
  }, [renderStreams]);
 
  // build a global hx column plan to determine where each hx block begins (start column index),
  // bhow many columns it spans (its multiplicity)
  // and the total number of HX columns across ALL hx keys.
  const { hxStartColByKey, hxColumnSpanByKey, hxTotalCols } = useMemo(() => {
    const multiplicityByKey = computeHxMultiplicityByKey(
      renderStreams,
      hxOrder,
      effectiveExpandedBySde,
    );
 
    const { startByKey, widthByKey, totalWidth } = computeHxColumnBlocks(
      hxOrder,
      multiplicityByKey,
    );
 
    return {
      hxStartColByKey: startByKey,
      hxColumnSpanByKey: widthByKey,
      hxTotalCols: totalWidth,
    };
  }, [renderStreams, hxOrder, effectiveExpandedBySde]);
 
  // left/right pads for heaters/coolers (non-HX)
  // to make room for nonHX nodes. We will make OVERALL global columns using this.
  // left pad is for heaters (cold streams target side is on the left)
  // right pad is for coolers (hot streams target is on right)
  const { leftPad, rightPad } = useMemo(() => {
    let maxHotnonHxNodes = 0;
    let maxColdnonHxNodes = 0;
    renderStreams.forEach((s) => {
      const nonHxNodes = (s.markers ?? []).filter(
        (m: HenNodeMarker) => !m.label?.startsWith("E") && m.henNode,
      ).length;
      if (s.isHot) maxHotnonHxNodes = Math.max(maxHotnonHxNodes, nonHxNodes);
      else maxColdnonHxNodes = Math.max(maxColdnonHxNodes, nonHxNodes);
    });
    return { leftPad: maxColdnonHxNodes, rightPad: maxHotnonHxNodes };
  }, [renderStreams]);
 
  // set the minimum spacing you want between grid columns (px)
  // use >= MIN_NODE_GAP so circles can fit;
  const desiredSpacingPx = Math.max(MIN_NODE_GAP, 120);
 
  // base columns = what HX needs + left/right pads
  const baseCols = Math.max(1, leftPad + hxTotalCols + rightPad);
 
  // how many columns do we need to achieve desired spacing across the drawable width?
  const usableW = Math.max(0, (svgWidth || 0) - 2 * MARGIN_X);
  const denseCols = Math.max(1, Math.floor(usableW / desiredSpacingPx) + 1);
 
  // add slack columns into pads so HX block stays centered/stable
  const extra = Math.max(0, denseCols - baseCols);
  const addLeft = Math.floor(extra / 2);
 
  const effectiveLeftPad = leftPad + addLeft;
  const totalCols = baseCols + extra;
 
  // build the actual Xs
  const columnXs = useMemo(() => {
    const sp = d3
      .scalePoint<number>()
      .domain(d3.range(totalCols))
      .range([MARGIN_X, (svgWidth || 0) - MARGIN_X])
      .align(0.5)
      .padding(1);
    return d3.range(totalCols).map((i) => sp(i)!);
  }, [totalCols, svgWidth]);
 
  // when mapping HX -> column centers, use *effectiveLeftPad*
  const hxColumnsByKey = useMemo(() => {
    return computeHxColumnsByKey(
      hxOrder,
      hxStartColByKey,
      hxColumnSpanByKey,
      columnXs,
      effectiveLeftPad,
    );
  }, [hxOrder, hxStartColByKey, hxColumnSpanByKey, columnXs, effectiveLeftPad]);
 
  // -------------------------------------------------
  // stuff for setting up layout LATER
  // -------------------------------------------------
  // authoritative HX X's and rows, computed by projecting global columns into each row-pair region
  const { alignedHXByKey, alignedHXRowsByKey, candidateSharedXByKey } =
    useMemo(() => {
      // get hot/cold sides and rows for each HX
      const hxSides = collectHxSides(renderStreams, effectiveExpandedBySde);
 
      // 2) pair rows per HX with overlap-aware pairing
      const hxPairs = pairHxRowsForEachKey(
        hxSides,
        rowBoundsAlignBySdeId,
        // matchRowsByOverlap
      );
 
      // 3) compute shared (aligned) X for each hot/cold row pair using global columns
      return computeAlignedHX(hxPairs, rowBoundsAlignBySdeId, hxColumnsByKey);
    }, [
      renderStreams,
      effectiveExpandedBySde,
      rowBoundsAlignBySdeId,
      hxColumnsByKey,
    ]);
 
  const { hxExistingXByKey, hxCanonicalIdByKey } = useMemo(() => {
    return {
      hxExistingXByKey: buildHxStoredXByKey(henNodes ?? []), // stored X for HX persistence. Does an X position already exist for this HX?
      hxCanonicalIdByKey: buildHxCanonicalIdByKey(henNodes ?? []), // Canonical node. For each HX key, if there is no X yet, assign the hx node with the smallest ID to be the "canonical" node for the HX
    };
  }, [henNodes]);
 
  // Persist shared X per hxKey only if missing (write to canonical node)
  useEffect(() => {
    candidateSharedXByKey?.forEach((x, hxKey) => {
      Iif (!Number.isFinite(x)) return;
      const already = hxExistingXByKey.get(hxKey);
      if (Number.isFinite(already)) {
        pendingPersistedHxXs.current.delete(hxKey);
        return;
      }
 
      const canonicalId = hxCanonicalIdByKey.get(hxKey);
      Iif (!canonicalId) return;
 
      const pendingX = pendingPersistedHxXs.current.get(hxKey);
      if (Number.isFinite(pendingX) && Math.abs(pendingX! - x) < 0.5) return;
 
      pendingPersistedHxXs.current.set(hxKey, x);
      updateHenNode({
        id: canonicalId,
        patchedHenNode: { x_position: x },
      })
        .unwrap()
        .catch(() => {
          pendingPersistedHxXs.current.delete(hxKey);
        });
    });
  }, [
    candidateSharedXByKey,
    hxExistingXByKey,
    hxCanonicalIdByKey,
    updateHenNode,
  ]);
 
  // "must-pass" HX X's per row (segment expansion)
  const hxXsByRowBySdeId = useMemo(() => {
    return buildHxXsByRowBySdeId(alignedHXByKey, alignedHXRowsByKey);
  }, [alignedHXByKey, alignedHXRowsByKey]);
 
  // -------------------------------------------------
  // fast lookups and indices
  // -------------------------------------------------
  // for fast lookups for streamgraphics and unitopcircle
  const sdeById = useMemo(
    () => d3.index(sdes ?? [], (s: any) => +s.id),
    [sdes],
  );
 
  const segmentsBySdeId = useMemo(
    () =>
      d3.group(segments?.children ?? [], (seg: any) => +seg.stream_data_entry),
    [segments],
  );
 
  // SdeId -> current stream index (needed by ExchangerLines)
  const streamIndexBySdeId = useMemo(() => {
    const m = new Map<string, number>();
    renderStreams.forEach((s, idx) => m.set(String(s.stream_data_entry), idx));
    return m;
  }, [renderStreams]);
 
  // -------------------------------------------------
  // drag handlers
  // -------------------------------------------------
  const handleReorder = useCallback(
    (oldIndex: number, newIndex: number) => {
      setStreamPositions((prev) => {
        const base = prev.length > 0 ? prev : allStreams;
        Iif (!base[oldIndex]) return base;
        const updated = [...base];
        const [moved] = updated.splice(oldIndex, 1);
        updated.splice(newIndex, 0, moved);
        return updated;
      });
    },
    [allStreams],
  );
 
  const handleDragStart = useCallback(
    (idx: number, startY: number) => {
      const base = allStreams;
      const dragged = base[idx];
      const draggedStreamId = String(dragged.stream_data_entry);
      setDragState({
        active: true,
        draggedIndex: idx,
        draggedStreamId,
        currentY: startY,
        overIndex: idx,
      });
    },
    [allStreams],
  );
 
  const handleDragMove = useCallback(
    (idx: number, yCenter: number) => {
      setDragState((prev) => {
        Iif (!prev || !prev.active || prev.draggedIndex !== idx) return prev;
        const over = d3.bisectCenter(
          verticalLayouts.streamBlockCentres,
          yCenter,
        );
        return { ...prev, currentY: yCenter, overIndex: over };
      });
    },
    [verticalLayouts.streamBlockCentres],
  );
 
  const handleDragEnd = useCallback(
    (idx: number) => {
      setDragState((prev) => {
        Iif (!prev) return null;
        const from = prev.draggedIndex;
        const to = prev.overIndex;
        if (from !== to) handleReorder(from, to);
        return null;
      });
    },
    [handleReorder],
  );
 
  // -------------------------------------------------
  // final resolved HX map for shared x positions per HX pair
  // -------------------------------------------------
  // write one resolved X for hx nodes using the initial render index (0 for collapsed stream, 0..N-1 for expanded segments)
  const setResolvedHxX = useCallback(
    (hxKey: string, sdeId: string, rowIdx: number, x: number) =>
      setResolvedHxRowsByKey((prev) => setRowX(prev, hxKey, sdeId, rowIdx, x)),
    [],
  );
 
  // clicking node or stream sets params (for hen sidebar)
  // SO clicking on the SVG background CLEARS these params (to show overview sidetab)
  const handleBackgroundClick = useCallback((): void => {
    setSearchParams((prev) => {
      const newParams = new URLSearchParams(prev);
      newParams.delete("henStream");
      newParams.delete("henNode");
      newParams.delete("selType");
      newParams.delete("hxGroup");
      return newParams;
    });
  }, [setSearchParams]);
 
  Iif (isError) return <p>Error... Please try refresh the page.</p>;
  // if (!segments || segments.length === 0) // idk why this doesnt work
  //   return <p>No stream data found... Please click "Extract" button.</p>;
  if (isLoading || henNodesIsLoading) return <p>Loading HEN diagram...</p>;
  if (!allStreams.length) {
    return <p>No stream data found... Please click "Extract" button.</p>;
  }
 
  return (
    <ScrollArea>
      {/* container for entire svg */}
      <div ref={containerRef} className="w-full">
        <svg
          width={svgWidth}
          height={verticalLayouts.finalSvgHeight}
          aria-label="hen-diagram"
        >
          {/* arrow head shape that is appended to target end of StreamGraphics stream/segment lines */}
          <defs>
            <marker
              id="arrow"
              viewBox="-10 -10 25 25"
              refX={-10}
              refY={0}
              markerWidth={2}
              markerHeight={2}
              orient="auto"
            >
              <path
                d="M -10 0 L 50 0 M 15 0 L 7 -6 M 15 0 L 7 6"
                fill="hsl(var(--hen-diagram-foreground))"
                stroke="hsl(var(--hen-diagram-foreground))"
                strokeWidth={2}
              />
            </marker>
          </defs>
 
          {/* background of svg */}
          <rect
            x={0}
            y={0}
            className="w-full"
            height={verticalLayouts.calculatedSvgHeight}
            fill="hsl(var(--hen-diagram))"
            onClick={handleBackgroundClick}
          />
 
          {/* stuff for rendering STREAM/SEGMENT lines with their HenNodes */}
          <g>
            {renderStreams.map((stream, i) => {
              const y = verticalLayouts.streamBlockYPositions[i]; // get y pixel for top of streamblock
              const blockHeight =
                verticalLayouts.streamBlockHeights[i] - STREAM_BLOCK_GAP;
              const isDraggingThis =
                !!dragState?.active &&
                String(stream.stream_data_entry) === dragState.draggedStreamId;
 
              const expanded = isExpanded(String(stream.stream_data_entry));
 
              // split markers
              const hxMarkers = (stream.markers ?? []).filter(
                (m: HenNodeMarker) => m.label?.startsWith("E") && m.henNode,
              );
              const extraMarkers = (stream.markers ?? []).filter(
                (m: HenNodeMarker) => !m.label?.startsWith("E") && m.henNode,
              );
 
              // choose side for ALL nodes based on TARGET temperature
              const streamUnitOpSide = getUnitopSide(
                Number(stream.t_target),
                pinch,
              );
 
              const sdeId = String(stream.stream_data_entry);
              const rowAlignBounds = rowBoundsAlignBySdeId.get(sdeId) ?? [];
              const rowCount = visibleCountBySdeId.get(sdeId) ?? 1;
 
              // Map "row -> HX keys (dedup) that actually participate on this row (for this sdeId)"
              const hxKeysByRow = new Map<number, string[]>();
              for (let r = 0; r < rowCount; r++) hxKeysByRow.set(r, []);
              hxMarkers.forEach((m) => {
                const rows = m.hxKey
                  ? (alignedHXRowsByKey.get(m.hxKey)?.get(sdeId) ?? [])
                  : [];
                rows.forEach((rowIdx) => {
                  if (rowIdx != null && rowIdx >= 0 && rowIdx < rowCount) {
                    const arr = hxKeysByRow.get(rowIdx)!;
                    if (m.hxKey && !arr.includes(m.hxKey)) arr.push(m.hxKey);
                  }
                });
              });
 
              // Map "row -> non-HX markers present on that row"
              const nonHxNodesByRow = new Map<number, HenNodeMarker[]>();
              for (let r = 0; r < rowCount; r++) nonHxNodesByRow.set(r, []);
              if (expanded) {
                const rowSdeIds: string[] = (stream.rawSegments ?? []).map(
                  (seg) => String(seg.stream_data_entry),
                );
                extraMarkers.forEach((m) => {
                  const idx = rowSdeIds.findIndex((sdeId) => sdeId === m.sdeId);
                  if (idx >= 0) nonHxNodesByRow.get(idx)!.push(m);
                });
              } else {
                extraMarkers.forEach((m) => nonHxNodesByRow.get(0)!.push(m));
              }
 
              // Deterministic secondary order for nonHxNodes
              for (let r = 0; r < rowCount; r++) {
                nonHxNodesByRow
                  .get(r)!
                  .sort((a, b) => a.henNode!.id - b.henNode!.id);
              }
 
              // For HX: inside each row, honor sticky hxOrder. Only include hxKeys that appear on THIS row.
              function orderedHxKeysForRow(row: number): string[] {
                const present = new Set(hxKeysByRow.get(row) ?? []);
                return hxOrder.filter((k) => present.has(k));
              }
 
              // Compute slot centers for a row, inside the stream's side region (pinch-aware)
              function makeSlotsForRow(
                rowBounds: Bounds,
                slotCount: number,
              ): number[] {
                Iif (slotCount <= 0) return [];
                // Region biased by the chosen side relative to the pinch
                const region = getNodePlacementRegion(
                  rowBounds,
                  pinchX,
                  svgWidth || 0,
                  streamUnitOpSide,
                );
                const sp = d3
                  .scalePoint<number>()
                  .domain(d3.range(slotCount))
                  .range([region.left, region.right])
                  .align(0.5)
                  .padding(0);
                const centers = d3.range(slotCount).map((i) => sp(i)!);
                return centers.sort(
                  (a, b) =>
                    Math.abs(a - pinchX) - Math.abs(b - pinchX) || a - b,
                );
              }
 
              // Assign X-positions for all markers via unified slots
              // Use a map so each HX appears once (with xPositions filled across rows)
              const markersByKey = new Map<string, HenNodeMarker>();
 
              // helpers to get/create unique entries
              const hxKeyFor = (m: HenNodeMarker) =>
                String(m.henNode?.id ?? `${m.hxKey}|${sdeId}`);
 
              const ensureHX = (m: HenNodeMarker) => {
                const key = hxKeyFor(m);
                let acc = markersByKey.get(key);
                if (!acc) {
                  acc = { ...m, xPositions: Array(rowCount).fill(NaN) };
                  markersByKey.set(key, acc);
                }
                return acc;
              };
 
              const ensureExtra = (m: HenNodeMarker, row: number) => {
                // nonHxNodes are truly per-row, so key by (nodeId,row) to avoid repeats
                const key = `${m.henNode?.id ?? m.label}:${row}`;
                let acc = markersByKey.get(key);
                if (!acc) {
                  acc = { ...m, xPositions: Array(rowCount).fill(NaN) };
                  markersByKey.set(key, acc);
                }
                return acc;
              };
 
              for (let row = 0; row < rowCount; row++) {
                const rowBounds = rowAlignBounds[row] ??
                  rowAlignBounds[0] ?? {
                    left: MARGIN_X,
                    right: (svgWidth || 0) - MARGIN_X,
                  };
 
                // 1) Count HX pairs and nonHxNodes on this row
                const hxKeysRowOrdered = orderedHxKeysForRow(row); // honors sticky hxOrder but filtered to present keys
                const hxPairsOnRow = hxKeysRowOrdered.length;
                const nonHxNodesOnRow = (nonHxNodesByRow.get(row) ?? []).length;
 
                const totalSlots = hxPairsOnRow + nonHxNodesOnRow;
                if (totalSlots <= 0) continue;
 
                // 2) Make slots (pinch-biased)
                const slotXs = makeSlotsForRow(rowBounds, totalSlots);
 
                // 3) Build a slot-index map for HX on this row:
                //    Allocate the first hxPairsOnRow slots to HX (in hxOrder), then the rest to nonHxNodes.
                const hxSlotIndexByKey = new Map<string, number>();
                for (let j = 0; j < hxPairsOnRow; j++) {
                  hxSlotIndexByKey.set(hxKeysRowOrdered[j], j);
                }
 
                // 4) Place HX markers that actually live on this row (for THIS sdeId)
                hxMarkers.forEach((m) => {
                  const rows = m.hxKey
                    ? (alignedHXRowsByKey.get(m.hxKey)?.get(sdeId) ?? [])
                    : [];
                  const alignedXsForSdeId = m.hxKey
                    ? (alignedHXByKey.get(m.hxKey)?.get(sdeId) ?? [])
                    : [];
 
                  const acc = ensureHX(m); // single marker object for this HX across rows
 
                  // does this HX participate on this row?
                  const idxInRows = rows.findIndex((r) => r === row);
 
                  if (
                    idxInRows >= 0 &&
                    Number.isFinite(alignedXsForSdeId[idxInRows])
                  ) {
                    // use the shared, cross-side aligned X
                    acc.xPositions[row] = alignedXsForSdeId[
                      idxInRows
                    ] as number;
                  } else if (!expanded && row === 0 && rows.length > 0) {
                    // collapsed: show HX on row 0 if it exists anywhere on this sdeId
                    const firstAligned = alignedXsForSdeId.find((v) =>
                      Number.isFinite(v),
                    );
                    if (Number.isFinite(firstAligned)) {
                      acc.xPositions[row] = firstAligned as number;
                    } else if (m.hxKey && hxSlotIndexByKey.has(m.hxKey)) {
                      const slotIdx = hxSlotIndexByKey.get(m.hxKey)!;
                      acc.xPositions[row] = slotXs[slotIdx];
                    }
                  } else if (
                    !expanded &&
                    m.hxKey &&
                    hxSlotIndexByKey.has(m.hxKey)
                  ) {
                    // collapsed-only: local slot fallback
                    const slotIdx = hxSlotIndexByKey.get(m.hxKey)!;
                    // acc[row] = slotXs[slotIdx];
                    acc.xPositions[row] = slotXs[slotIdx];
                  }
                  // when expanded and we didn't get an aligned X, leave xs[row] as NaN
                });
 
                // 5) Place nonHxNodes into the remaining slots, deterministically
                const nonHxNodes = nonHxNodesByRow.get(row) ?? [];
                nonHxNodes.forEach((m, k) => {
                  const acc = ensureExtra(m, row);
                  const slotIdx = hxPairsOnRow + k;
                  if (slotIdx < slotXs.length)
                    acc.xPositions[row] = slotXs[slotIdx];
 
                  // collapsed: nonHxNodes appear only on row 0 (keep others NaN)
                  // nothing else to do — xPositions for other rows remain NaN
                });
              }
 
              // Final array sent to StreamGraphic
              const markersWithXs = Array.from(markersByKey.values());
 
              const hxXsByRow = hxXsByRowBySdeId.get(sdeId);
 
              const yForRow = isDraggingThis
                ? dragState!.currentY - blockHeight / 2
                : y;
 
              return (
                <StreamGraphic
                  key={stream.stream_data_entry}
                  stream={stream}
                  isHot={stream.isHot}
                  index={i}
                  y={yForRow}
                  dragging={isDraggingThis}
                  onDragStart={handleDragStart}
                  onDragMove={handleDragMove}
                  onDragEnd={handleDragEnd}
                  width={svgWidth}
                  height={blockHeight}
                  expanded={expanded}
                  onToggleExpanded={(sdeId, next) => {
                    // optimistic flip
                    setOptimisticExpandedBySde((prev) => {
                      const m = new Map(prev);
                      m.set(sdeId, next);
                      return m;
                    });
 
                    // mark busy
                    setTogglingSdes((prev) => new Set(prev).add(sdeId));
 
                    // persust
                    updateSDE({
                      id: +sdeId,
                      patchedStreamDataEntry: { expanded: next },
                    })
                      .unwrap()
                      .catch(() => {
                        //rollback on fail
                        setOptimisticExpandedBySde((prev) => {
                          const m = new Map(prev);
                          m.set(sdeId, !next);
                          return m;
                        });
                      })
                      .finally(() => {
                        // clear busy
                        setTogglingSdes((prev) => {
                          const n = new Set(prev);
                          n.delete(sdeId);
                          return n;
                        });
                      });
                  }}
                  isToggling={togglingSdes.has(
                    String(stream.stream_data_entry),
                  )}
                  pinchX={pinchX}
                  pinchTemps={pinchTemps}
                  markers={markersWithXs}
                  alignedHxByKey={alignedHXByKey}
                  alignedHxRowsByKey={alignedHXRowsByKey}
                  resolvedHxRowsByKey={resolvedHxRowsByKey}
                  onResolveHxX={setResolvedHxX}
                  hxXsByRow={hxXsByRow}
                  globalColumns={columnXs}
                  unitOpSide={streamUnitOpSide}
                  unitOpLayout="EVEN"
                  onShowHover={show}
                  onHideHover={hide}
                  hoverBuilders={buildContent}
                  lookup={{ sdeById, segmentsBySdeId }}
                />
              );
            })}
          </g>
 
          {/* Hx lines and pinch line rendered OVER the stream lines. */}
          <g>
            <ExchangerLines
              streamYPositions={streamYPositionsForHXLines}
              streamIndexBySdeId={streamIndexBySdeId}
              alignedHXByKey={alignedHXByKey}
              alignedHXRowsByKey={alignedHXRowsByKey}
              streamBlockHeight={STREAM_BLOCK_HEIGHT}
            />
 
            {/* CURENTLY: if there is pinch temp info, show pinch line, otherwise don't.
                  BUT: maybe we want to change this so that pinch temp MUST be claculated before diagram even renders?
              */}
            {pinchTemps && (
              <PinchLine
                x={pinchX}
                height={verticalLayouts.calculatedSvgHeight}
                onShowHover={show}
                onHideHover={hide}
                hoverBuilders={buildContent}
                hotPinch={pinchTemps?.hotPinch}
                coldPinch={pinchTemps?.coldPinch}
              />
            )}
          </g>
 
          {/* Allow svg elements to show hover cards. */}
          <HoverLayer
            svgWidth={svgWidth || 0}
            svgHeight={verticalLayouts.finalSvgHeight || 0}
          />
        </svg>
      </div>
    </ScrollArea>
  );
}