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 946 947 948 949 950 951 | 648x 1721x 162x 37x 453x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 787x 787x 787x 787x 714x 32x 32x 682x 102x 375x 120x 120x 120x 120x 120x 10x 10x 6x 6x 6x 13x 13x 13x 6x 6x 6x 120x 120x 114x 114x 375x 362x 354x 354x 673x 673x 177x 177x 177x 13x 375x 362x 362x 362x 102x 362x 362x 79x 79x 375x 129x 129x 129x 129x 129x 129x 129x 129x 129x 375x 129x 228x 129x 129x 129x 81x 129x 129x 81x 129x 129x 129x 81x 81x 81x 81x 81x 81x 129x 129x 48x 48x 48x 48x 129x 129x 102x 129x 375x 129x 129x 129x 228x 129x 129x 129x 183x 129x 81x 81x 81x 150x 81x 81x 81x 81x 81x 81x 81x 81x 21x 81x 81x 81x 21x 81x 129x 375x 129x 81x 48x 48x 48x 48x 48x 375x 51x 51x 51x 51x 129x 129x 129x 48x 48x 81x 81x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 2x 2x 150x 375x 324x 324x 324x 324x 634x 467x 467x 467x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 634x 634x 634x 324x 467x 467x 467x 467x 470x 467x 467x 467x 467x 470x 324x 324x 167x 241x 167x 167x 167x 167x 167x 324x 324x 324x 324x 324x 324x 324x 3x 3x 637x 375x | import { useEffect, useLayoutEffect, useRef, useState } from "react";
import * as d3 from "d3";
import UnitOpCircle from "./HENUnitOpCircle";
import { useSearchParams } from "react-router-dom";
import { SegmentRead, usePinchHenNodePartialUpdateMutation } from "@/api/apiStore.gen";
import { Button } from "@/ahuora-design-system/ui/button";
import { ChevronDown, ChevronUp, X } from "lucide-react";
import {
clampSegmentToPinchSide,
ensureRegionCapacityForHx,
MARGIN_X,
MIN_NODE_GAP,
toCanvasX,
placeNonHxXs,
getNodePlacementRegion,
spreadAwayFromReserved,
pickColumnsForNonHxNodes,
STREAM_BLOCK_HEIGHT,
} from "./utils/henLayoutUtils";
import { HenNodeMarker, StreamGraphicProps } from "./henTypes";
import { boundsFor, canvasBounds } from "./utils/bounds";
// ----------------------------------------
// helpers (mabe we can refactor out?)
// ----------------------------------------
// get stream name from segment, so clean the segment name to get rid of the brackets from segments Stream 1 (1)
function cleanStreamName(name: string) {
return String(name).replace(/ \((\d+)\)/g, "");
}
// is the node marker for a HX or not?
const isHX = (label?: string) => !!label?.startsWith("E");
//
function isHxOnSegmentRow(segment: SegmentRead, marker: HenNodeMarker) {
return Number(segment?.hen_node) === Number(marker?.henNode?.id);
}
// get the absolute difference between two numbers
const absDelta = (a?: number, b?: number) =>
Number.isFinite(Number(a)) && Number.isFinite(Number(b))
? Math.abs(Number(a) - Number(b))
: undefined;
export default function StreamGraphic(props: StreamGraphicProps) {
const {
stream,
index,
isHot,
y,
dragging,
onDragStart,
onDragMove,
onDragEnd,
width,
height,
expanded,
onToggleExpanded,
isToggling,
pinchX,
pinchTemps,
markers,
alignedHxByKey,
alignedHxRowsByKey,
resolvedHxRowsByKey,
onResolveHxX,
hxXsByRow,
globalColumns,
unitOpSide = "MIDDLE",
unitOpLayout = "EVEN",
onShowHover,
onHideHover,
hoverBuilders,
lookup,
} = props;
const [updateHenNode] = usePinchHenNodePartialUpdateMutation();
const [searchParams, setSearchParams] = useSearchParams();
const groupRef = useRef<SVGGElement>(null); // used for d3 dragging
const [optimisticExpanded, setOptimisticExpanded] =
useState<boolean>(expanded);
useEffect(() => setOptimisticExpanded(expanded), [expanded]);
// for batching resolves to parent (HENDiagramsPage)
// when we find a per-row HX X we want to save into parent state, push it here, and flush in layout effect.
const pendingResolves = useRef<
Array<{ hxKey: string; sdeId: string; rowIdx: number; x: number }>
>([]);
// ----------------------------------------
// values derived from props
// ----------------------------------------
// const colour = isHot ? "#C93232" : "#42A5F5";
const colour = isHot ? "#ef4444" : "#0ea5e9";
const pinch = pinchTemps?.coldPinch ?? pinchTemps?.hotPinch;
const sdeIdStr = String(stream.stream_data_entry); //?
const segmentCount = stream.rawSegments.length ?? 1;
const isExpandable = segmentCount > 1;
// check url params to see if this stream is currently selected (for HENsidebar, and circle highlight)
const selectedStream = (() => {
const sel = searchParams.get("henStream");
return sel != null && String(stream.stream_data_entry) === sel;
})();
// ----------------------------------------
// event handlers
// ----------------------------------------
// set/remove search params for HEN sidebar content.
function handleClick() {
setSearchParams((prev) => {
const p = new URLSearchParams(prev);
p.delete("henNode");
p.delete("selType");
p.delete("hxGroup");
p.set("henStream", stream.stream_data_entry);
return p;
});
}
function handleToggleExpanded(e?: React.MouseEvent) {
e?.stopPropagation?.();
const next = !optimisticExpanded;
setOptimisticExpanded(next);
onToggleExpanded?.(String(stream.stream_data_entry), next);
}
// returns true if marker was selected, and gets url params
function isMarkerSelected(m: HenNodeMarker): boolean {
const selType = searchParams.get("selType");
const selectedId = Number(searchParams.get("henNode"));
const hxGroup = searchParams.get("hxGroup");
if (Number(m.henNode?.id) === selectedId) return true;
if (selType === "HX" && isHX(m.label)) {
const myGroup = m.hxKey ?? m.label;
return hxGroup != null && myGroup === hxGroup;
}
return false;
}
// push a "store this HX X for this row" to the batch queue.
function enqueueResolve(
hxKey: string,
sdeId: string,
rowIdx: number,
x: number
) {
pendingResolves.current.push({ hxKey, sdeId, rowIdx, x });
}
// ----------------------------------------
// side effects (drag, persisting node positions)
// ----------------------------------------
// D3 drag binding
useEffect(() => {
Iif (!groupRef.current) return;
const self = d3.select<SVGGElement, unknown>(groupRef.current);
let localOffset = 0;
let blockCenterAtStart = y + height / 2;
const drag = d3
.drag<SVGGElement, unknown>()
.filter((event: any) => {
// don't drag from chevron buttons for expanding/collapsing
const el = event.target as HTMLElement;
return !el.closest('button,[role="button"],.no-drag');
})
.on("start", function () {
self.select("rect").attr("fill", "#a1a1a1ff");
blockCenterAtStart = y + height / 2;
onDragStart?.(index, blockCenterAtStart); // tell parent to look at dragpreview mode list
})
.on("drag", function (event: any) {
localOffset += event.dy;
const currentCenter = blockCenterAtStart + localOffset;
onDragMove?.(index, currentCenter); // give parent current Y
})
.on("end", function () {
self.select("rect").attr("fill", "hsl(var(--hen-diagram))");
localOffset = 0;
onDragEnd?.(index); // tell parent to finalise the final reorder.
});
self.call(drag as any);
return () => {
try {
self.on(".drag", null); // remove old drag listeners
} catch {}
};
}, [index, y, height, onDragStart, onDragMove, onDragEnd]);
// for NON-HX nodes, if we have a good X on screen, but not in db, save it to db.
useEffect(() => {
if (!width || width === 0) return;
Iif (!markers?.length) return;
markers.forEach((m) => {
Iif (!m.henNode) return;
if (m.hxKey) return; // hx persistence is handled in onResolveHxX
const candidate = m.xPositions?.[0];
const stored = m.henNode?.x_position as number | undefined;
if (m.henNode && !Number.isFinite(stored) && Number.isFinite(candidate)) {
updateHenNode({
id: m.henNode!.id,
patchedHenNode: { x_position: candidate! },
});
}
});
}, [markers, updateHenNode, width]);
// flush the resolveHX X queue
useLayoutEffect(() => {
Iif (!onResolveHxX) return;
// Dedup by (hxKey|sdeId|rowIdx), keep latest
const latest = new Map<
string,
{ hxKey: string; sdeId: string; rowIdx: number; x: number }
>();
for (const r of pendingResolves.current) {
latest.set(`${r.hxKey}|${r.sdeId}|${r.rowIdx}`, r);
}
// Clear BEFORE notifying parent to prevent re-entrancy issues
pendingResolves.current = [];
// Only send if parent doesn't already have it
for (const { hxKey, sdeId, rowIdx, x } of latest.values()) {
const cached = resolvedHxRowsByKey?.get(hxKey)?.get(sdeId)?.get(rowIdx);
if (!Number.isFinite(cached)) onResolveHxX(hxKey, sdeId, rowIdx, x);
}
}, [onResolveHxX, resolvedHxRowsByKey]);
// ----------------------------------------
// render helpers (EXPANDED SEGMENTS)
// ----------------------------------------
const layoutExpandedRow = (
segment: SegmentRead,
segIdx: number,
parent: { left: number; right: number },
startX: number
) => {
// split parent span into N sectiosn, pick the one for THIS segment index
const N = Math.max(1, stream.rawSegments.length ?? 0);
const xBand = d3
.scaleLinear<number, number>()
.domain([0, N])
.range([parent.left, parent.right]);
const pos = isHot ? segIdx : N - 1 - segIdx; //reversed order for cold
const chunkLeftRaw = xBand(pos);
const chunkRightRaw = xBand(pos + 1);
let left = Math.min(chunkRightRaw, chunkLeftRaw);
let right = Math.max(chunkLeftRaw, chunkRightRaw);
// keep on correct side of pinch line, min width, and respect the startX
({ left, right } = clampSegmentToPinchSide({
isHot,
tSupply: Number(segment.t_supply),
tTarget: Number(segment.t_target),
pinch,
pinchX,
parent,
left,
right,
MIN_SEG_W: 60,
startX,
}));
return { left, right };
};
// decide which X a HX circle should use on this row.
const placeExpandedMarkers = (
segment: SegmentRead,
segIdx: number,
span: { left: number; right: number }
) => {
// get all markers that belong to this segment's sde.
const inThisRow = (markers ?? []).filter(
(m) => m.henNode && String(segment.stream_data_entry) === String(m.sdeId)
) as HenNodeMarker[];
// separate into two groups of HX or nonHX markers for this row.
const hxsCollapsed = inThisRow.filter((m) => isHX(m.label));
const nonHxsCollapsed = inThisRow.filter((m) => !isHX(m.label));
// of all the HX in this row, which HX ACTUALLY participate in THIS segment?
const hxOnThisRow = hxsCollapsed.filter((m) =>
isHxOnSegmentRow(segment, m)
);
// The row needs to grow to make sure it includes space for ALL hx nodes for this row (from the parent)
let mustIncludeXs: number[] = [];
if (hxOnThisRow.length) {
mustIncludeXs = (hxXsByRow?.get(segIdx) ?? []).filter(Number.isFinite);
}
// start with provided span, but widen if HX node requires more room.
let { left, right } = span;
let clampBounds = canvasBounds(width);
// widen to include HX with padding.
if (mustIncludeXs.length) {
const NODE_PAD = 35; // different so that expanded mode doesnt push HX nodes to edge of segment line.
const minHx = Math.min(...mustIncludeXs);
const maxHx = Math.max(...mustIncludeXs);
left = Math.max(clampBounds.left, Math.min(left, minHx - NODE_PAD));
right = Math.min(clampBounds.right, Math.max(right, maxHx + NODE_PAD));
// ensure minimum visual width
Iif (right - left < 60) {
if (isHot) right = Math.min(clampBounds.right, left + 60);
else left = Math.max(clampBounds.left, right - 60);
}
}
// if no HX to include on this row, start from target temp side with minwidth.
const parent = clampBounds; // keep everything within drawable region for streams/segments
if (!mustIncludeXs.length) {
const w = Math.max(60, right - left);
Iif (isHot) {
left = span.left;
right = Math.min(parent.right, left + w);
} else {
right = span.right;
left = Math.max(parent.left, right - w);
}
}
// place all HEN nodes.
const placedHx = placeExpandedHx(segment, segIdx, left, right);
const placedNonHx = placeExpandedNonHx(
nonHxsCollapsed,
{ left, right },
placedHx.map((p) => p.x)
);
return { placedHx, placedNonHx, left, right };
};
const placeExpandedHx = (
segment: SegmentRead,
segIdx: number,
left: number,
right: number
) => {
// anchor the first occurrence of each HX key on this stream (so repeated occurrences don't duplicate in the same spot)
const primaryXByHxKey = new Map<string, { x: number }>();
const midX = (left + right) / 2; // safe fallback
// get nodes that are actually in this row.
const markersInThisRow = (markers ?? []).filter(
(m) => m.henNode && String(segment.stream_data_entry) === String(m.sdeId)
) as HenNodeMarker[];
// get all HX nodes on this row.
const hxOnThisRow = markersInThisRow.filter(
(m) => isHX(m.label) && isHxOnSegmentRow(segment, m)
);
// put final placements here
const placements: Array<{ key: string; x: number; m: HenNodeMarker }> = [];
const clampCanvas = (x: number) => toCanvasX(x, width);
// for each HX node marker on this row, decide an x position.
hxOnThisRow.forEach((m) => {
// aligned Xs for THIS row (if any)
// i.e. for this HX key, and this SDE id, get the aligned Xs and whichrow indices they belong to.
const xsForSde = m.hxKey
? (alignedHxByKey?.get(m.hxKey)?.get(sdeIdStr) ?? [])
: [];
const rowsForSde = m.hxKey
? (alignedHxRowsByKey?.get(m.hxKey)?.get(sdeIdStr) ?? [])
: [];
// keep only the aligned xs that are for THIS row.
const alignedXsForThisRow = rowsForSde
.map((r, i) =>
r === segIdx && Number.isFinite(xsForSde[i])
? clampCanvas(xsForSde[i]!)
: undefined
)
.filter(Number.isFinite) as number[];
// fallback for when alignement X is missing
const fallbackCandidate =
m.xPositions?.[segIdx] ??
m.xPositions?.[0] ??
m.henNode?.x_position ??
midX;
const fallbackX = clampCanvas(
Number.isFinite(fallbackCandidate)
? (fallbackCandidate as number)
: midX
);
// if this marker is an HX key (and therefor is an HX node),
// check if it is the first occurence in that row.
const hasPrimaryXForHxKey = primaryXByHxKey.has(m.hxKey); // is this the first occurence of this hx node in this row?
// if the hxNode we're looking at is NOT the first that occurs in this row,
if (!hasPrimaryXForHxKey) {
const firstAligned = alignedXsForThisRow[0];
const firstX = Number.isFinite(firstAligned)
? firstAligned!
: fallbackX;
enqueueResolve(m.hxKey, sdeIdStr, segIdx, firstX);
// if there are multiple other aligned Xs, record the others too.
for (let k = 1; k < alignedXsForThisRow.length; k++)
enqueueResolve(m.hxKey, sdeIdStr, segIdx, alignedXsForThisRow[k]);
primaryXByHxKey.set(m.hxKey!, { x: firstX });
placements.push({
key: `${m.henNode!.id}-seg-${segment.id}-hx-primary`,
x: firstX,
m,
});
// any remaining alignedXs on this row.
alignedXsForThisRow.slice(1).forEach((x, i) =>
placements.push({
key: `${m.henNode!.id}-seg-${segment.id}-hx-a${i}`,
x,
m,
})
);
return;
}
// subsequent occurences for the same HX key on this stream
const primaryX = primaryXByHxKey.get(m.hxKey!)?.x;
const nonPrimaryAligned = alignedXsForThisRow.filter(
(x) =>
!Number.isFinite(primaryX) || Math.abs(x - (primaryX as number)) > 1
);
Iif (nonPrimaryAligned.length) {
nonPrimaryAligned.forEach((x, i) => {
Iif (m.hxKey) enqueueResolve(m.hxKey, sdeIdStr, segIdx, x);
placements.push({
key: `${m.henNode!.id}-seg-${segment.id}-hx-b${i}`,
x,
m,
});
});
return;
}
// final fallback to distribute evenly across the row span.
const rowHx = hxOnThisRow;
const orderOnRow = rowHx.findIndex((mm) => mm === m);
const countOnRow = Math.max(1, rowHx.length);
const frac = (orderOnRow + 1) / (countOnRow + 1);
const cached = m.hxKey
? resolvedHxRowsByKey?.get(m.hxKey)?.get(sdeIdStr)?.get(segIdx)
: undefined;
const localX = Number.isFinite(cached)
? (cached as number)
: left + frac * (right - left);
Iif (m.hxKey) enqueueResolve(m.hxKey, sdeIdStr, segIdx, localX);
placements.push({
key: `${m.henNode!.id}-seg-${segment.id}-hx-secondary`,
x: localX,
m,
});
});
return placements;
};
// place the NON-hx nodes present in a row.
const placeExpandedNonHx = (
nonHxNodes: HenNodeMarker[],
rowSpan: { left: number; right: number },
reservedHX: number[]
) => {
if (!nonHxNodes.length)
return [] as Array<{ key: string; x: number; m: HenNodeMarker }>;
// Build a side-biased region and ensure capacity for both HX and nonHx
let region = getNodePlacementRegion(rowSpan, pinchX, width, unitOpSide);
region = ensureRegionCapacityForHx(
region,
rowSpan,
reservedHX.length,
nonHxNodes.length,
MIN_NODE_GAP
);
// get evenly spaced Xs and nudge away from HX nodes so nodes dont overlap.
const xsRaw = placeNonHxXs(nonHxNodes.length, region, isHot, unitOpLayout);
const xs = spreadAwayFromReserved(xsRaw, region, reservedHX, MIN_NODE_GAP);
// return an array {kehy, x, m} for rendering
return nonHxNodes.map((m, idx) => ({
key: `${m.henNode!.id}-seg-${stream.id}-hc-${idx}`,
x: xs[idx],
m,
}));
};
const renderExpanded = () => {
// find the horizontal span for this whoole stream based on temps and pinch.
// each segment row will start inside this span and may widen it to include hx nodes if necessary.
const parent = boundsFor(
Number(stream.t_supply),
Number(stream.t_target),
pinch,
width,
pinchX
);
// layout the rows sequentially from inlet -> outlet to avoid overlaps where possible
// start at the inlet side and move to the outlet side
let startX = isHot ? parent.left : parent.right;
const GAP = 2; // tiny separation so consecutive rows dont flicker.
return stream.rawSegments.map((segment: SegmentRead, segIdx: number) => {
// layout the row using the current startX
const { left: segLeftInit, right: segRightInit } = layoutExpandedRow(
segment,
segIdx,
parent,
startX
);
// place markers, which may widen the span
let { placedHx, placedNonHx, left, right } = placeExpandedMarkers(
segment,
segIdx,
{ left: segLeftInit, right: segRightInit }
);
// re-anchor to prevent any backward movement after widening relative to startX.
if (isHot) {
left = Math.max(left, startX);
right = Math.max(right, left + 60);
} else {
right = Math.min(right, startX);
left = Math.min(left, right - 60);
}
// advance startX to the outlet end we just grew toward so next row starts after this one.
startX = isHot ? right + GAP : left - GAP;
// final line startX and endX for rendering
const xStart = isHot ? left : right;
const xEnd = isHot ? right : left;
// SDE temps/hover payload per row
const sdeId = Number(segment.stream_data_entry);
const sde = lookup?.sdeById?.get(sdeId);
const inlet =
sde?.temperatures?.inlet ??
Number(isHot ? segment.t_supply : segment.t_target);
const outlet =
sde?.temperatures?.outlet ??
Number(isHot ? segment.t_target : segment.t_supply);
const dH =
Number.isFinite(Number(sde?.enthalpies?.inlet)) &&
Number.isFinite(Number(sde?.enthalpies?.outlet))
? (Number(sde!.enthalpies!.inlet) - Number(sde!.enthalpies!.outlet)) *
-1
: undefined;
const payload = {
label: `${segment.name} - ${isHot ? "Hot" : "Cold"} segment`,
temps: { inlet, outlet, delta: absDelta(inlet, outlet) },
dH,
heatFlow: sde?.heat_flow,
};
// return expanded segments visuals
return (
<g
key={segment.id}
transform={`translate(0, ${segIdx * STREAM_BLOCK_HEIGHT})`}
onMouseEnter={(e) => {
e.stopPropagation();
onShowHover?.(e, hoverBuilders?.stream(payload), { width: 320 });
}}
onMouseLeave={onHideHover}
>
<line
x1={xStart}
x2={xEnd}
y1={0}
y2={0}
stroke={colour}
strokeWidth={10}
markerEnd={"url(#arrow)"}
className="cursor-pointer"
aria-label="segment-line"
/>
<text
x={left + 20}
y={-10}
textAnchor="end"
fill="hsl(var(--hen-diagram-foreground))"
style={{ fontSize: 15 }}
className="cursor-pointer"
>
{isHot
? Number(segment.t_supply).toFixed(2)
: Number(segment.t_target).toFixed(2)}
°C
</text>
<text
x={right - 20}
y={-10}
textAnchor="start"
fill="hsl(var(--hen-diagram-foreground))"
style={{ fontSize: 15 }}
className="cursor-pointer"
>
{isHot
? Number(segment.t_target).toFixed(2)
: Number(segment.t_supply).toFixed(2)}
°C
</text>
<text
x={(left + right) / 2}
y={27}
textAnchor="middle"
style={{ fontSize: 15, fill: colour, fontWeight: 500 }}
className="cursor-pointer"
>
{segment.name}
</text>
{[...placedHx, ...placedNonHx].map(({ key, x, m }) => (
<UnitOpCircle
key={key}
midX={x}
colour={m.colour}
text={m.label}
henNode={m.henNode!}
stream={segment}
onShowHover={onShowHover}
onHideHover={onHideHover}
hoverBuilders={hoverBuilders}
hxKey={m.hxKey}
selected={isMarkerSelected(m)}
lookup={lookup}
/>
))}
</g>
);
});
};
// ----------------------------------------
// Render helpers (collapsed)
// ----------------------------------------
// base span (pinch aware), and a relaxed full-canvas span (for when we need to widen).
const renderCollapsed = () => {
const base = boundsFor(
Number(stream.t_supply),
Number(stream.t_target),
pinch,
width,
pinchX
);
const baseRelaxed = canvasBounds(width);
// gather all HX Xs we should respect in collapsed mode
// in collapsed mode, there's only one visible line, but we still want to show
// all HX occurrences that would exist across its expanded rows.
const allRowHX: number[] = Array.from(hxXsByRow?.values() ?? [])
.flat()
.filter(Number.isFinite) as number[];
// include Xs aligned for the same HX across ALL SDEs (both sides)
// to ensure multiplicity is visible even when the other side is the one
// that actually has multiple occurrences
const allAlignedFromAllSdeIds: number[] = (markers ?? [])
.filter((m) => m.hxKey)
.flatMap((m) => {
const bySdeId = m.hxKey ? alignedHxByKey?.get(m.hxKey) : undefined;
Iif (!bySdeId) return [];
return Array.from(bySdeId.values())
.flat()
.filter(Number.isFinite) as number[];
});
const allHX = [...allRowHX, ...allAlignedFromAllSdeIds];
// start from the default collapsed span. If we have HX Xs,
// widen the span (but stay within canvas margins) to include them plus a pad.
let left = base.left;
let right = base.right;
if (allHX.length) {
const NODE_PAD = 12; // small breathing room around nodes so circles don't sit on the line edge
left = Math.max(
baseRelaxed.left,
Math.min(left, Math.min(...allHX) - NODE_PAD)
);
right = Math.min(
baseRelaxed.right,
Math.max(right, Math.max(...allHX) + NODE_PAD)
);
}
// Compute the actual line endpoints for a single collapsed line.
// Hot streams draw left->right; cold streams draw right->left (arrow follows target side).
const xStart = isHot ? left : right;
const xEnd = isHot ? right : left;
const midX = (left + right) / 2;
// Split markers into HX / non-HX fo collapsed plcement
const inCollapsed = (markers ?? []).filter(
(m) => m.henNode
) as HenNodeMarker[];
const hxCollapsed = inCollapsed.filter((m) => isHX(m.label));
const nonHxNodesCollapsed = inCollapsed.filter((m) => !isHX(m.label));
// Collapsed HX placement
const hxPlacedCollapsed = hxCollapsed.flatMap((m, orderIdx) => {
// get all aligned Xs for THIS hxKey across sdeIds,
// then pull the ones for THIS sdeId.
const bySdeId = m.hxKey ? alignedHxByKey?.get(m.hxKey) : undefined;
const xsThisSid = (bySdeId?.get(sdeIdStr) ?? []).filter(
Number.isFinite
) as number[];
// fallback to per-marker xPositions or its stored x_position, then mid.
const storedX = Number.isFinite(m.henNode?.x_position as number)
? (m.henNode!.x_position as number)
: undefined;
const xsRaw = xsThisSid.length
? xsThisSid // aligned for this sde
: m.xPositions?.length
? m.xPositions //marker local xpositions
: storedX != null
? [storedX] //perssited x in db
: [midX]; // fallback to centre
// clamp every X to the drawable area for streams/segments
const xsClamped = xsRaw.map((x) => toCanvasX(Number(x) || midX, width));
// if HX nodes were placed outside the initial span, widen collapsed line to include these Xs
if (xsClamped.length) {
const NODE_PAD = 12;
left = Math.max(
MARGIN_X,
Math.min(left, Math.min(...xsClamped) - NODE_PAD)
);
right = Math.min(
(width ?? 0) - MARGIN_X,
Math.max(right, Math.max(...xsClamped) + NODE_PAD)
);
}
return xsClamped.map((x, i) => ({
key: `${m.henNode!.id}-col-hx-${orderIdx}-${i}`,
x,
m,
}));
});
// Collapsed non hx nodes: snap to global columns within a side band (near target temp); avoid HX with min gap
let nonHxNodesPlacedCollapsed: Array<{
key: string;
x: number;
m: HenNodeMarker;
}> = [];
if (nonHxNodesCollapsed.length) {
const rowSpan = { left, right };
const reservedHX = hxPlacedCollapsed.map((p) => p.x);
// build a side-anchored band near the target side so extras cluster near the arrow
const span = Math.max(0, rowSpan.right - rowSpan.left);
const desired = Math.min(Math.max(180, span * 0.35), span);
const region = isHot
? {
left: Math.max(rowSpan.right - desired, rowSpan.left),
right: rowSpan.right,
}
: {
left: rowSpan.left,
right: Math.min(rowSpan.left + desired, rowSpan.right),
};
// Snap nonHX nodes to the precomputed global columns within the band,
// skipping columns that would violate the min gap to HX.
const xs = pickColumnsForNonHxNodes(
nonHxNodesCollapsed.length,
region,
isHot,
globalColumns ?? [],
reservedHX,
MIN_NODE_GAP
);
nonHxNodesPlacedCollapsed = nonHxNodesCollapsed.map((m, idx) => ({
key: `${m.henNode!.id}-col-hc-${idx}`,
x: xs[idx],
m,
}));
}
// Hover payload for hovercards.
const sdeId = Number(stream.stream_data_entry);
const sde = lookup?.sdeById?.get(sdeId);
const inlet = sde?.temperatures?.inlet ?? Number(stream.t_supply);
const outlet = sde?.temperatures?.outlet ?? Number(stream.t_target);
const dH =
Number.isFinite(Number(sde?.enthalpies?.inlet)) &&
Number.isFinite(Number(sde?.enthalpies?.outlet))
? (Number(sde!.enthalpies!.inlet) - Number(sde!.enthalpies!.outlet)) *
-1
: undefined;
const collapsedPayload = {
label: cleanStreamName(stream.name),
temps: { inlet, outlet, delta: absDelta(inlet, outlet) },
dH,
heatFlow: sde?.heat_flow,
};
// return collapsed stream visuals.
return (
<>
<line
x1={xStart}
x2={xEnd}
y1={0}
y2={0}
stroke={colour}
strokeWidth={10}
markerEnd={"url(#arrow)"}
onMouseEnter={(e) => {
e.stopPropagation();
onShowHover?.(e, hoverBuilders?.stream(collapsedPayload), {
width: 320,
});
}}
onMouseLeave={onHideHover}
className="cursor-pointer"
aria-label="stream-line"
/>
<text
x={left + 30}
y={-10}
textAnchor="end"
fill="hsl(var(--hen-diagram-foreground))"
style={{ fontSize: 15 }}
className="cursor-pointer"
>
{isHot
? Number(stream.t_supply).toFixed(2)
: Number(stream.t_target).toFixed(2)}
°C
</text>
<text
x={right - 30}
y={-10}
textAnchor="start"
fill="hsl(var(--hen-diagram-foreground))"
style={{ fontSize: 15 }}
className="cursor-pointer"
>
{isHot
? Number(stream.t_target).toFixed(2)
: Number(stream.t_supply).toFixed(2)}
°C
</text>
<text
x={(left + right) / 2}
y={27}
textAnchor="middle"
style={{ fontSize: 15, fill: colour, fontWeight: 500 }}
className="cursor-pointer"
>
{cleanStreamName(stream.name)}
</text>
{[...hxPlacedCollapsed, ...nonHxNodesPlacedCollapsed].map(
({ key, x, m }) => (
<UnitOpCircle
key={key}
midX={x}
colour={m.colour}
text={m.label}
henNode={m.henNode!}
stream={stream}
onShowHover={onShowHover}
onHideHover={onHideHover}
hoverBuilders={hoverBuilders}
hxKey={m.hxKey}
selected={isMarkerSelected(m)}
lookup={lookup}
/>
)
)}
</>
);
};
// ----------------------------------------
// RENDER what should be rendered (collapsed/expanded view)
// ----------------------------------------
return (
<g
ref={groupRef}
className="stream"
aria-label="stream-group"
data-stream-id={stream.stream_data_entry}
transform={`translate(0, ${y})`}
onClick={handleClick}
style={{
cursor: dragging ? "grabbing" : "grab",
transition: dragging ? "none" : "transform 140ms ease",
}}
>
<rect
x={0}
y={-30}
height={height}
fill={selectedStream ? "#9c9c9c7f" : "hsl(var(--hen-diagram))"}
stroke="hsl(var(--hen-diagram))"
className="w-full"
aria-label="group-rect"
/>
{optimisticExpanded ? renderExpanded() : renderCollapsed()}
{isExpandable && (
<foreignObject
x={(width ?? 0) - MARGIN_X + 30}
y={-20}
width={50}
height={50}
>
<Button
variant="ghost"
size="icon"
onClick={handleToggleExpanded}
title={optimisticExpanded ? "Collapse stream" : "Expand stream"}
disabled={isToggling}
aria-busy={isToggling ? "true" : "false"}
>
{optimisticExpanded ? (
<ChevronUp stroke="hsl(var(--hen-diagram-foreground))" />
) : (
<ChevronDown stroke="hsl(var(--hen-diagram-foreground))" />
)}
</Button>
</foreignObject>
)}
</g>
);
}
|