All files / src/pages/flowsheet-page/flowsheet/Canvas FloatingPropertyTable.tsx

79.92% Statements 227/284
68.77% Branches 174/253
81.63% Functions 40/49
82.65% Lines 224/271

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 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053                                                                                                        45x 45x 45x 45x   45x 45x   45x                                         45x                                         169x 169x 169x       169x             169x 169x       169x       169x   169x 169x 169x 169x   169x 169x 169x 169x 169x 169x 169x   169x 169x 169x 169x   169x     169x 6x 3x 3x   6x 3x 3x   6x 6x 6x 6x 6x       169x             30x         30x   30x       30x                             169x                                                               169x 37x       37x 37x 36x         169x 9x 9x                                                                     169x 3x 3x 3x 3x           3x     3x 30x 30x 30x 30x 30x   30x       30x     30x       30x       30x 30x 30x       3x 3x 3x 3x 3x     3x 3x 3x 3x     169x 169x 169x   169x         169x 169x 169x 169x 169x           169x   169x 276x 276x 276x 276x                                           169x   169x   169x                                           1x                                       3x                   2x 2x                                                                                                                                                                               45x                 206x 206x   206x         206x 347x     206x     206x       206x 206x 206x     206x   206x 206x                   206x   206x 206x 64x   142x 142x     142x     206x   206x   206x 206x 206x   206x       206x         206x     5x 5x 5x 10x 10x 10x       5x   5x           206x     5x 5x 5x         5x 5x                   206x 1x 1x         1x 1x 1x   1x 1x 1x     1x               206x 2x     2x 2x 2x 3x   2x 2x       2x 2x             2x 2x               2x 3x   2x   2x   2x 2x           2x 2x 3x   2x 2x 2x   2x 2x               206x                                                                                                                 45x                           45x                   228x 228x 228x 228x 228x 228x     228x     228x 228x 228x     228x 3x 3x 3x         3x       228x 1x   1x 1x   1x       228x                       228x 1x             1x       228x     228x                     228x             228x       228x         228x         228x                                     3x 3x                                                                                                                                   1x                                                                                                                          
import { Expand, Minimize, Settings2, X, EllipsisVertical, Replace, SquareFunction, Trash2, Repeat2 } from "lucide-react";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { AutoSelectInput } from "@/ahuora-design-system/ui/auto-select-input";
import DebouncedInput from "@/ahuora-design-system/ui/debounced-input";
import {
  useSimulationObjectPropertySet,
  getPropertyData,
} from "@/hooks/properties";
import { SelectedPropertyInfo } from "../PropertiesSidebar/ObjectDetailsPanel";
import {
  api,
  PropertySetRead,
  PropertyInfoRead,
  PropertyValueRead,
  SimulationObjectRetrieveRead,
  useCorePropertyinfoPartialUpdateMutation,
  useCorePropertyvaluePartialUpdateMutation,
  useCoreControlvaluesCreateMutation,
  useCoreControlvaluesDestroyMutation,
  useCoreRecyclepropertyPartialUpdateMutation,
} from "@/api/apiStore.gen";
import { UnitsDropdown } from "../PropertiesSidebar/PropertyPanel/InputFields/UnitsDropdown";
import { useAppDispatch } from "@/store/hooks";
import { round_to_sf_dp } from "@/functions/roundNumber";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuLabel,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
import { PropertySelector } from "../PropertiesSidebar/PropertyPanel/PropertySelector";
import {
  isStateVariable,
  isFreeVariable,
  hasFreeVariable,
  hasStateVariable,
} from "../PropertiesSidebar/PropertyPanel/ControlTarget";
import { FormulaInputField } from "../LeftSideBar/Formulas/FormulaInputField";
import { useProjectId } from "@/hooks/project";
 
// Table sizing and bounds for drag/resize.
const MIN_WIDTH = 380;
const MIN_HEIGHT = 100;
const HEADER_HEIGHT = 48;
const EDGE_PADDING = 16;
// Virtualization settings
const ROW_HEIGHT = 40; // Keep this equal to the actual row CSS height or virtualization will misalign
const OVERSCAN_COUNT = 10; // number of extra rows to render above/below viewport for smoother scrolling
const iconButtonStyle =
  "inline-flex h-8 w-8 items-center justify-center border bg-background hover:bg-muted";
 
export const FloatingPropertyTable: React.FC<{
  tableId?: number;
  handleOpenDialog: () => void;
  title?: string;
  selectedProperties?: SelectedPropertyInfo[];
  setSelectedProperties?: React.Dispatch<
    React.SetStateAction<SelectedPropertyInfo[]>
  >;
  unitOpLookup?: Record<number | string, string>;
  isVisible?: boolean;
  onVisibilityChange?: (visible: boolean) => void;
  onHide?: () => void;
  onRename?: (newName: string) => void;
  position?: { x: number; y: number };
  size?: { width: number; height: number };
  isMinimized?: boolean;
  onPositionChange?: (pos: { x: number; y: number }) => void;
  onSizeChange?: (sz: { width: number; height: number }) => void;
  onMinimizedChange?: (minimized: boolean) => void;
}> = ({
  tableId: _tableId,
  handleOpenDialog,
  selectedProperties = [],
  unitOpLookup = {},
  title,
  setSelectedProperties,
  isVisible: controlledVisible,
  onVisibilityChange,
  onHide,
  onRename,
  position: propPosition,
  size: propSize,
  isMinimized: propMinimized = true,
  onPositionChange,
  onSizeChange,
  onMinimizedChange,
}) => {
  // drag/resize state
  // only used during active pointer interactions.
  // Outside of drag/resize, we render directly from props.
  const [dragPosition, setDragPosition] = useState<{ x: number; y: number } | null>(null);
  const [resizeState, setResizeState] = useState<{ width: number; height: number; x: number; y: number } | null>(null);
  const [isDragging, setIsDragging] = useState(false);
  // Holds the last user committed position/size so the table doesnt snap
  // back to stale props between clearing state and the backend
  // responding with the new values.
  const committedRef = useRef<{
    position: { x: number; y: number } | null;
    size: { width: number; height: number } | null;
  }>({ position: null, size: null });
 
  // During drag/resize, use the interaction state for position/size. 
  // Otherwise, use the last committed values or fallback to props/defaults.
  const activeInteraction = dragPosition ?? resizeState;
  const position = activeInteraction
    ? { x: activeInteraction.x, y: activeInteraction.y }
    : committedRef.current.position
      ?? { x: propPosition?.x ?? 440, y: propPosition?.y ?? 110 };
  const size = resizeState
    ? { width: resizeState.width, height: resizeState.height }
    : committedRef.current.size
      ?? { width: propSize?.width ?? MIN_WIDTH, height: propSize?.height ?? MIN_HEIGHT };
  const isMinimized = propMinimized;
 
  const isVisible = controlledVisible ?? false;
  const dispatch = useAppDispatch();
  const [updateValue] = useCorePropertyvaluePartialUpdateMutation();
  const [updatePropertyInfo] = useCorePropertyinfoPartialUpdateMutation();
 
  const dragOffsetRef = useRef({ x: 0, y: 0 });
  const resizeStartRef = useRef({ x: 0, y: 0, width: 0, height: 0 });
  const rootRef = useRef<HTMLDivElement | null>(null);
  const isDraggingRef = useRef(false);
  const isResizingRef = useRef(false);
  const moveListenerRef = useRef<((event: MouseEvent) => void) | null>(null);
  const upListenerRef = useRef<(() => void) | null>(null);
  // Refs to access latest position/size in event handler closures
  const positionRef = useRef(position);
  positionRef.current = position;
  const sizeRef = useRef(size);
  sizeRef.current = size;
  // virtualisation state
  const [scrollTop, setScrollTop] = useState(0);
 
  // Remove per-interaction listeners and reset drag/resize flags.
  const cleanupPointerTracking = useCallback(() => {
    if (moveListenerRef.current && typeof window !== "undefined") {
      window.removeEventListener("mousemove", moveListenerRef.current);
      moveListenerRef.current = null;
    }
    if (upListenerRef.current && typeof window !== "undefined") {
      window.removeEventListener("mouseup", upListenerRef.current);
      upListenerRef.current = null;
    }
    isDraggingRef.current = false;
    isResizingRef.current = false;
    setIsDragging(false);
    setDragPosition(null);
    setResizeState(null);
  }, []);
 
  // Keep the table inside the viewport during drag and resize
  const clampPosition = useCallback(
    (
      nextX: number,
      nextY: number,
      dims: { width: number; height: number } = size,
      minimized: boolean = isMinimized
    ) => {
      Iif (typeof window === "undefined") {
        return { x: nextX, y: nextY };
      }
 
      // maximum allowed x/y so the box stays on-screen
      const maxX = window.innerWidth - dims.width - EDGE_PADDING;
      const maxY =
        window.innerHeight -
        (minimized ? HEADER_HEIGHT : dims.height) -
        EDGE_PADDING;
 
      return {
        x: Math.min(
          Math.max(EDGE_PADDING, nextX),
          Math.max(EDGE_PADDING, maxX)
        ),
        y: Math.min(
          Math.max(EDGE_PADDING, nextY),
          Math.max(EDGE_PADDING, maxY)
        ),
      };
    },
    [isMinimized, size.height, size.width]
  );
 
  // When the viewport resizes (eg window resize), make sure the table remains visible
  const handleViewportResize = useCallback(() => {
    Iif (typeof window === "undefined" || isDraggingRef.current || isResizingRef.current) {
      return;
    }
 
    const maxWidth = Math.max(MIN_WIDTH, window.innerWidth - EDGE_PADDING * 2);
    const maxHeight = Math.max(
      MIN_HEIGHT,
      window.innerHeight - EDGE_PADDING * 2
    );
 
    const curSize = sizeRef.current;
    const curPos = positionRef.current;
    const nextSize = {
      width: Math.min(curSize.width, maxWidth),
      height: Math.min(curSize.height, maxHeight),
    };
    const nextPos = clampPosition(curPos.x, curPos.y, nextSize, isMinimized);
 
    const sizeChanged = nextSize.width !== curSize.width || nextSize.height !== curSize.height;
    const posChanged = nextPos.x !== curPos.x || nextPos.y !== curPos.y;
    Iif (sizeChanged || posChanged) {
      committedRef.current = {
        position: posChanged ? nextPos : committedRef.current.position,
        size: sizeChanged ? nextSize : committedRef.current.size,
      };
      Iif (sizeChanged) onSizeChange?.(nextSize);
      Iif (posChanged) onPositionChange?.(nextPos);
    }
  }, [clampPosition, isMinimized, onSizeChange, onPositionChange]);
  // keep stored size/position valid on window resize
 
  useEffect(() => {
    Iif (typeof window === "undefined") {
      return;
    }
 
    window.addEventListener("resize", handleViewportResize);
    return () => {
      window.removeEventListener("resize", handleViewportResize);
    };
  }, [handleViewportResize]);
 
  // Start dragging: capture offset and attach temporary move/up listeners
  const handleDragStart = (event: React.MouseEvent<HTMLDivElement>) => {
    if ((event.target as HTMLElement).closest("button")) {
      return;
    }
 
    cleanupPointerTracking();
    event.preventDefault();
    // record pointer offset so movement feels natural
    dragOffsetRef.current = {
      x: event.clientX - position.x,
      y: event.clientY - position.y,
    };
    isDraggingRef.current = true;
    setIsDragging(true);
 
    // Update position with viewport clamping while dragging
    const handleDragMove = (e: MouseEvent) => {
      Iif (!isDraggingRef.current) return;
      const nextX = e.clientX - dragOffsetRef.current.x;
      const nextY = e.clientY - dragOffsetRef.current.y;
      setDragPosition(clampPosition(nextX, nextY));
    };
 
    // Drop listeners and reset flags on release
    const handleDragEnd = () => {
      committedRef.current = { ...committedRef.current, position: positionRef.current };
      onPositionChange?.(positionRef.current);
      cleanupPointerTracking();
    };
 
    moveListenerRef.current = handleDragMove;
    upListenerRef.current = handleDragEnd;
    window.addEventListener("mousemove", handleDragMove);
    window.addEventListener("mouseup", handleDragEnd);
  };
 
  // Start resize: capture start size/pos and attach temporary move/up listeners
  const handleResizeStart = (event: React.MouseEvent<HTMLDivElement>) => {
    event.preventDefault();
    event.stopPropagation();
    cleanupPointerTracking();
    resizeStartRef.current = {
      x: event.clientX,
      y: event.clientY,
      width: size.width,
      height: size.height,
    };
    isResizingRef.current = true;
 
    // Apply bounds and update size/position to keep the handle in view
    const handleResizeMove = (e: MouseEvent) => {
      Iif (!isResizingRef.current) return;
      const deltaX = e.clientX - resizeStartRef.current.x;
      const deltaY = e.clientY - resizeStartRef.current.y;
      const desiredWidth = resizeStartRef.current.width + deltaX;
      const desiredHeight = resizeStartRef.current.height + deltaY;
      const viewportWidth =
        typeof window !== "undefined"
          ? window.innerWidth
          : desiredWidth + EDGE_PADDING * 2;
      const viewportHeight =
        typeof window !== "undefined"
          ? window.innerHeight
          : desiredHeight + EDGE_PADDING * 2;
      const boundedWidth = Math.max(
        MIN_WIDTH,
        Math.min(desiredWidth, viewportWidth - EDGE_PADDING * 2)
      );
      const boundedHeight = Math.max(
        MIN_HEIGHT,
        Math.min(desiredHeight, viewportHeight - EDGE_PADDING * 2)
      );
      const nextDims = { width: boundedWidth, height: boundedHeight };
      const nextPos = clampPosition(positionRef.current.x, positionRef.current.y, nextDims);
      setResizeState({ ...nextDims, ...nextPos });
    };
 
    // Drop listeners and reset flags on release
    const handleResizeEnd = () => {
      committedRef.current = { position: positionRef.current, size: sizeRef.current };
      onSizeChange?.(sizeRef.current);
      onPositionChange?.(positionRef.current);
      cleanupPointerTracking();
    };
 
    moveListenerRef.current = handleResizeMove;
    upListenerRef.current = handleResizeEnd;
    window.addEventListener("mousemove", handleResizeMove);
    window.addEventListener("mouseup", handleResizeEnd);
  };
 
  const totalRows = selectedProperties.length;
  const viewportHeight = Math.max(0, size.height - HEADER_HEIGHT - ROW_HEIGHT);
  const totalHeight = totalRows * ROW_HEIGHT;
  // virtualisation calculations
  const startIndex = Math.max(
    0,
    Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN_COUNT
  );
  const visibleCount =
    Math.ceil(viewportHeight / ROW_HEIGHT) + OVERSCAN_COUNT * 2;
  const endIndex = Math.min(totalRows, startIndex + visibleCount);
  const visibleProperties = selectedProperties.slice(startIndex, endIndex);
  const topSpacerHeight = startIndex * ROW_HEIGHT;
  const bottomSpacerHeight = Math.max(
    0,
    totalHeight - topSpacerHeight - visibleProperties.length * ROW_HEIGHT
  );
 
  // rendered rows
  const rows = useMemo(
    () =>
      visibleProperties.map((p) => {
        const uId = p.unitOpId ?? p.unitOp;
        const propId = p.propertyId ?? p.property;
        const key = `${uId ?? "u"}-${propId ?? "p"}`;
        return (
          <FloatingPropertyTableRow
            key={key}
            p={p}
            unitOpLookup={unitOpLookup}
            setSelectedProperties={setSelectedProperties}
            dispatch={dispatch}
            updateValue={updateValue}
            updatePropertyInfo={updatePropertyInfo}
          />
        );
      }),
    [
      dispatch,
      setSelectedProperties,
      unitOpLookup,
      updatePropertyInfo,
      updateValue,
      visibleProperties,
    ]
  );
 
  const hasRows = selectedProperties.length > 0;
 
  Iif (!isVisible) return null;
 
  return (
    <div
      className="fixed z-50"
      ref={rootRef}
      style={{ top: position.y, left: position.x, width: size.width }}
    >
      <div
        className="flex flex-col overflow-hidden rounded-xl border bg-card shadow-2xl"
        style={{ height: isMinimized ? HEADER_HEIGHT : size.height }}
      >
        <div
          className={`flex shrink-0 items-center justify-between border-b px-3 ${
            isDragging ? "cursor-grabbing" : "cursor-grab"
          }`}
          style={{ height: HEADER_HEIGHT, minHeight: HEADER_HEIGHT }}
          onMouseDown={handleDragStart}
          role="toolbar"
        >
          <div className="text-sm font-semibold text-card-foreground flex items-center gap-2">
            <AutoSelectInput
              value={title ?? "Monitoring Table"}
              onUpdateValue={(v) => {
                onRename?.(v);
              }}
              textSize="text-sm"
              width="max-w-xs"
            />
          </div>
          <div className="flex items-center gap-2">
            <button
              className={iconButtonStyle}
              title="Select properties"
              aria-label="Select properties"
              onClick={handleOpenDialog}
            >
              <Settings2 size={16} />
            </button>
            <button
              className={iconButtonStyle}
              title={isMinimized ? "Expand table" : "Minimise table"}
              aria-label={isMinimized ? "Expand table" : "Minimise table"}
              onClick={() => {
                onMinimizedChange?.(!isMinimized);
              }}
            >
              {isMinimized ? <Expand size={16} /> : <Minimize size={16} />}
            </button>
            <button
              className={iconButtonStyle}
              title="Hide table"
              aria-label="Hide table"
              onClick={() => {
                if (onHide) {
                  onHide();
                IE} else if (onVisibilityChange) {
                  onVisibilityChange(false);
                }
              }}
            >
              <X size={16} />
            </button>
          </div>
        </div>
        {!isMinimized && (
          <div className="flex h-full flex-col min-h-0">
            <div className="flex-1 bg-card min-h-0">
              {hasRows ? (
                <div className="flex h-full flex-col min-h-0">
                  <table className="w-full border-collapse table-fixed">
                    <thead>
                      <tr className="text-left text-xs tracking-wide text-muted-foreground bg-muted/100">
                        <th className="border-b border-border px-3 py-2 border-r border-border/30">
                          UnitOp
                        </th>
                        <th className="border-b border-border px-3 py-2 border-r border-border/30">
                          Property
                        </th>
                        <th className="border-b border-border px-3 py-2 border-r border-border/30">
                          Value
                        </th>
                        <th className="border-b border-border px-3 py-2 border-border/30">
                          Unit
                        </th>
                      </tr>
                    </thead>
                  </table>
                  <div
                    className="flex-1 overflow-auto min-h-0"
                    onScroll={(event) =>
                      setScrollTop(event.currentTarget.scrollTop)
                    }
                  >
                    <table className="w-full border-collapse table-fixed">
                      <tbody>
                        {topSpacerHeight > 0 && (
                          <tr style={{ height: topSpacerHeight }}>
                            <td colSpan={4} />
                          </tr>
                        )}
                        {rows}
                        {bottomSpacerHeight > 0 && (
                          <tr style={{ height: bottomSpacerHeight }}>
                            <td colSpan={4} />
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                </div>
              ) : (
                <div className="flex h-full items-center justify-center px-6 text-center text-sm text-muted-foreground">
                  Select properties to populate this table.
                </div>
              )}
            </div>
            <div
              className="absolute bottom-1 right-1 h-3 w-3 cursor-se-resize border-b-2 border-r-2"
              onMouseDown={handleResizeStart}
            />
          </div>
        )}
      </div>
    </div>
  );
};
 
export default FloatingPropertyTable;
 
type FloatingPropertyTableRowProps = {
  p: SelectedPropertyInfo;
  unitOpLookup: Record<number | string, string>;
  setSelectedProperties?: React.Dispatch<
    React.SetStateAction<SelectedPropertyInfo[]>
  >;
  dispatch: ReturnType<typeof useAppDispatch>;
  updateValue: ReturnType<typeof useCorePropertyvaluePartialUpdateMutation>[0];
  updatePropertyInfo: ReturnType<
    typeof useCorePropertyinfoPartialUpdateMutation
  >[0];
};
 
const FloatingPropertyTableRow = React.memo(
  ({
    p,
    unitOpLookup,
    setSelectedProperties,
    dispatch,
    updateValue,
    updatePropertyInfo,
  }: FloatingPropertyTableRowProps) => {
    const uId = p.unitOpId ?? p.unitOp;
    const propId = p.propertyId ?? p.property;
 
    const propertySet = useSimulationObjectPropertySet(uId) as
      | PropertySetRead
      | undefined;
    // Resolve property info/value for this row from cached simulation object.
    const propInfo = (
      propertySet as PropertySetRead | undefined
    )?.ContainedProperties?.find((pp: PropertyInfoRead) => pp.id === propId) as
      | PropertyInfoRead
      | undefined;
    const propertyValue = propInfo?.values?.[0];
    // Control metadata is used to mirror VariableWithUnit edit rules.
    const propertyMeta =
      propInfo && propertyValue
        ? getPropertyData(propInfo, propertyValue, p.propertyName)
        : { isControlManipulated: false, isControlSetPoint: false, isRecycle: false, displayName: "" };
 
    const unitOpName = unitOpLookup?.[uId ?? ""] ?? `#${uId}`;
    const propertyName = propInfo?.displayName ?? `#${propId}`;
    const unit = propInfo?.unit ?? "";
 
    // Value shaping mirrors VariableWithUnit: fixed detection, Compounds use displayValue, rounded output
    const fixed = ![undefined, null, ""].includes(propertyValue?.value as any);
 
    let baseValue: string | number | null | undefined = propertyValue?.value;
    Iif (
      propInfo?.displayName === "Compounds" &&
      (propertyValue?.enabled ||
        propertyMeta.isControlSetPoint ||
        propertyMeta.isControlManipulated)
    ) {
      baseValue = propertyValue?.displayValue;
    }
 
    const rawValue: string | number | null | undefined =
      baseValue ?? propertyValue?.displayValue ?? undefined;
 
    const roundedValue = (() => {
      if (rawValue === undefined || rawValue === null || rawValue === "") {
        return "";
      }
      const parsed = parseFloat(String(rawValue));
      Iif (Number.isNaN(parsed)) {
        return String(rawValue);
      }
      return round_to_sf_dp(parsed);
    })();
 
    const formattedValue = roundedValue === "" ? "-" : roundedValue;
 
    const simulationObjectId = Number(uId);
    // Match VariableWithUnit editability/recycle/guess rules
    const { isControlManipulated, isControlSetPoint, isRecycle } = propertyMeta;
    const disabled = !propertyValue?.enabled && !isControlSetPoint;
    const isEditable = !disabled || isControlSetPoint || isControlManipulated;
    const canEditValue =
      Boolean(propInfo && propertyValue && (isEditable || isRecycle)) &&
      !Number.isNaN(simulationObjectId) &&
      propId !== undefined;
    const canEditUnit =
      Boolean(propInfo) &&
      !Number.isNaN(simulationObjectId) &&
      propId !== undefined;
 
    // Update local selected property info for this row
    const updateSelectedProperty = (
      updater: (sp: SelectedPropertyInfo) => SelectedPropertyInfo
    ) => {
      Iif (!setSelectedProperties) return;
      setSelectedProperties((prev) =>
        prev.map((sp) => {
          const unitOpKey = sp.unitOpId ?? sp.unitOp;
          const propKey = sp.propertyId ?? sp.property;
          if (
            String(unitOpKey ?? "") === String(uId ?? "") &&
            String(propKey ?? "") === String(propId ?? "")
          ) {
            return updater(sp);
          }
          return sp;
        })
      );
    };
 
    // Update cached simulation object property info/value for this row
    const updateCachedSimulationObject = (
      fn: (draft: SimulationObjectRetrieveRead | undefined) => void
    ) => {
      Iif (!Number.isFinite(simulationObjectId)) return;
      try {
        dispatch(
          api.util.updateQueryData(
            "unitopsSimulationobjectsRetrieve",
            { id: simulationObjectId },
            (draft: SimulationObjectRetrieveRead | undefined) => {
              try {
                fn(draft);
              } catch {}
            }
          )
        );
      } catch {}
    };
 
    // When value changes, optimistically update local selection and cached
    // simulation object, then send to backend
    const handleValueUpdate = (next: string | number) => {
      Iif (!propertyValue?.id || propId == null) return;
      updateSelectedProperty((sp) => ({
        ...sp,
        propertyValue: next as any,
        currentValue: next as any,
      }));
      updateCachedSimulationObject((draft) => {
        const targetProp = draft?.properties?.ContainedProperties?.find(
          (prop: PropertyInfoRead) => prop.id === propId
        );
        if (targetProp?.values?.length) {
          targetProp.values[0].value = next as any;
          targetProp.values[0].displayValue = next as any;
        }
      });
      updateValue({
        id: propertyValue.id,
        patchedPropertyValue: { value: next as any },
      }).catch(() => undefined);
    };
 
    // When units change, update backend then refetch to pull the converted value
    // so the table shows the new-unit value
    const handleUnitUpdate = async (nextUnit: string) => {
      Iif (!propInfo?.id || propId == null) return;
 
      // Optimistically update local selection and cached simulation object
      updateSelectedProperty((sp) => ({ ...sp, propertyUnit: nextUnit }));
      updateCachedSimulationObject((draft) => {
        const targetProp = draft?.properties?.ContainedProperties?.find(
          (prop: PropertyInfoRead) => prop.id === propId
        );
        if (targetProp) {
          targetProp.unit = nextUnit;
        }
      });
 
      try {
        await updatePropertyInfo({
          id: propInfo.id,
          patchedPropertyInfo: { unit: nextUnit },
        }).unwrap();
 
        // Refetch the simulation object to pull the converted value so the
        // table shows the new-unit value
        if (Number.isFinite(simulationObjectId)) {
          const refreshed = await dispatch(
            api.endpoints.unitopsSimulationobjectsRetrieve.initiate(
              { id: simulationObjectId },
              { forceRefetch: true }
            )
          ).unwrap();
 
          const refreshedProp =
            refreshed?.properties?.ContainedProperties?.find(
              (pInfo: PropertyInfoRead) => pInfo.id === propId
            );
          const refreshedVal = refreshedProp?.values?.[0];
          const nextValue =
            refreshedVal?.displayValue ?? refreshedVal?.value ?? undefined;
 
          if (nextValue !== undefined) {
            updateSelectedProperty((sp) => ({
              ...sp,
              propertyValue: nextValue as any,
              currentValue: nextValue as any,
              propertyUnit: refreshedProp?.unit ?? nextUnit,
            }));
            updateCachedSimulationObject((draft) => {
              const targetProp = draft?.properties?.ContainedProperties?.find(
                (prop: PropertyInfoRead) => prop.id === propId
              );
              if (targetProp?.values?.length) {
                targetProp.values[0].value = nextValue as any;
                targetProp.values[0].displayValue = nextValue as any;
              }
              if (targetProp) {
                targetProp.unit = refreshedProp?.unit ?? nextUnit;
              }
            });
          }
        }
      } catch {}
    };
 
    return (
      <tr className="h-10 text-sm text-foreground">
        <td className="border-b border-border/30 px-3 py-2 border-r border-border/30">
          {String(unitOpName)}
        </td>
        <td className="border-b border-border/30 px-3 py-2 border-r border-border/30">
          {String(propertyName)}
        </td>
        <td className="border-b border-border/30 px-3 py-2 border-r border-border/30">
          <div className="flex items-center gap-1">
            <div className="flex-1 min-w-0">
              {canEditValue ? (
                <DebouncedInput
                  value={roundedValue as string | number}
                  onUpdate={handleValueUpdate}
                  isFixed={fixed}
                  className="h-8 w-full bg-transparent"
                  ariaLabel={`monitoring-value-${propId}`}
                  placeholder={
                    (isControlManipulated && isEditable) ||
                    (isRecycle && !isControlSetPoint)
                      ? "Enter a guess..."
                      : "Enter a value..."
                  }
                />
              ) : (
                formattedValue
              )}
            </div>
            {propInfo && propertyValue && (
              <PropertyActionsMenu
                property={propInfo}
                propertyValue={propertyValue}
                isEditable={Boolean(isEditable)}
                isGuess={Boolean(
                  (isEditable && isControlManipulated) ||
                  (isRecycle && !isControlSetPoint)
                )}
                isControlManipulated={Boolean(isControlManipulated)}
                isControlSetPoint={Boolean(isControlSetPoint)}
                isRecycle={Boolean(isRecycle)}
                simulationObjectId={simulationObjectId}
              />
            )}
          </div>
        </td>
        <td className="border-b border-border/30 px-3 py-2 border-border/30">
          {canEditUnit && propInfo ? (
            <UnitsDropdown property={propInfo} onUpdate={handleUnitUpdate} />
          ) : (
            unit || "-"
          )}
        </td>
      </tr>
    );
  }
);
FloatingPropertyTableRow.displayName = "FloatingPropertyTableRow";
 
// Property Actions Menu component for the floating table
interface PropertyActionsMenuProps {
  property: PropertyInfoRead;
  propertyValue: PropertyValueRead;
  isEditable: boolean;
  isGuess: boolean;
  isControlManipulated: boolean;
  isControlSetPoint: boolean;
  isRecycle: boolean;
  simulationObjectId: number;
}
 
const PropertyActionsMenu: React.FC<PropertyActionsMenuProps> = ({
  property,
  propertyValue,
  isEditable,
  isGuess,
  isControlManipulated,
  isControlSetPoint,
  isRecycle,
  simulationObjectId,
}) => {
  const [updateValue] = useCorePropertyvaluePartialUpdateMutation();
  const [createControlvalue] = useCoreControlvaluesCreateMutation();
  const [deleteControlvalue] = useCoreControlvaluesDestroyMutation();
  const [updateRecycleProperty] = useCoreRecyclepropertyPartialUpdateMutation();
  const flowsheetId = useProjectId();
  const [isOpen, setIsOpen] = useState(false);
 
  // Check if this property has a replacement that can be removed
  const hasReplacement = isControlManipulated || isControlSetPoint;
 
  // Recycle connection and fixed state
  const recycleConn = property?.recycleConnection;
  const recycleFixed = recycleConn?.fixed ?? false;
  const canToggleRecycle = isRecycle && !isControlManipulated && !isControlSetPoint;
 
  // Handler to toggle recycle fixed/unfixed
  const handleToggleRecycle = async () => {
    Iif (!recycleConn?.id) return;
    try {
      await updateRecycleProperty({
        id: recycleConn.id,
        patchedRecycleProperty: { fixed: !recycleFixed },
      }).unwrap?.();
    } catch {}
    setIsOpen(false);
  };
 
  // Handler for removing replacement
  const handleRemoveReplacement = async () => {
    Iif (isControlManipulated && propertyValue.controlManipulated) {
      await deleteControlvalue({ id: propertyValue.controlManipulated });
    } else if (isControlSetPoint && propertyValue.controlSetPoint) {
      await deleteControlvalue({ id: propertyValue.controlSetPoint });
    }
    setIsOpen(false);
  };
 
  // Handler for Replace DoF (for editable properties)
  const handleReplaceDoFSelect = async (setpointProperty: PropertyValueRead) => {
    await createControlvalue({
      controlValue: {
        flowsheet: flowsheetId,
        manipulated: propertyValue.id,
        setPoint: setpointProperty.id,
      },
    });
    setIsOpen(false);
  };
 
  // Handler for Control Target (for non-editable properties)
  const handleControlTargetSelect = async (manipulatedProperty: PropertyValueRead) => {
    await createControlvalue({
      controlValue: {
        flowsheet: flowsheetId,
        manipulated: manipulatedProperty.id,
        setPoint: propertyValue.id,
      },
    });
    setIsOpen(false);
  };
 
  // Check if property has a constraint (formula)
  const hasConstraint = Boolean(propertyValue.formula);
 
  // Handler for removing constraint
  const handleRemoveConstraint = () => {
    updateValue({
      id: propertyValue.id,
      patchedPropertyValue: {
        formula: "",
      },
    });
    setIsOpen(false);
  };
 
  // Handler for when constraint is saved
  const handleConstraintSave = () => {
    setIsOpen(false);
  };
 
  // Show Replace DoF for editable properties that are not already controlled
  // Also show for recycle when fixed
  const showReplaceDoF =
    (isEditable && !isControlManipulated && !isControlSetPoint && !isGuess) ||
    (isRecycle && recycleFixed && !isControlManipulated && !isControlSetPoint);
 
  // Show Add Constraint for editable properties that are not guesses
  const showAddConstraint = (isEditable || propertyValue.enabled) && !isGuess;
 
  // Show Control Target for non-editable properties
  // Also show for recycle when not fixed
  // If recycle is fixed, do not show Control Target (only Replace DoF should appear)
  const showControlTarget =
    ((!isEditable && !propertyValue.enabled) ||
      (isRecycle && !recycleFixed && !isControlManipulated && !isControlSetPoint)) &&
    !recycleFixed;
 
  return (
    <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
      <DropdownMenuTrigger asChild>
        <button
          className="flex-shrink-0 p-0.5 rounded hover:bg-muted"
          aria-label={`Property actions for ${property.displayName}`}
        >
          <EllipsisVertical className="h-4 w-4 text-muted-foreground hover:text-foreground" />
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent side="right" align="start" className="w-72 p-2">
        <DropdownMenuLabel className="text-xs font-medium">
          {property.displayName}
        </DropdownMenuLabel>
 
        {/* Recycle fix/unfix toggle */}
        {canToggleRecycle && (
          <DropdownMenuItem
            onSelect={(e) => {
              e.preventDefault();
              handleToggleRecycle();
            }}
            className="cursor-pointer"
          >
            <Repeat2 className="mr-2 h-4 w-4" />
            <span>{recycleFixed ? "Unfix recycle" : "Fix recycle"}</span>
          </DropdownMenuItem>
        )}
 
        {/* Replacement info - show what's replacing what */}
        {isControlManipulated && (
          <div className="px-2 py-1.5 text-xs text-success">
            <span className="font-light">
              Replaced by {propertyValue.controlManipulatedName}
              {propertyValue.controlManipulatedObject && (
                <span className="text-muted-foreground"> at {propertyValue.controlManipulatedObject}</span>
              )}
            </span>
          </div>
        )}
        {isControlSetPoint && (
          <div className="px-2 py-1.5 text-xs text-success">
            <span className="font-light">
              Replacing {propertyValue.controlSetPointName}
              {propertyValue.controlSetPointObject && (
                <span className="text-muted-foreground"> at {propertyValue.controlSetPointObject}</span>
              )}
            </span>
          </div>
        )}
 
        <DropdownMenuSeparator />
 
        {/* Replace DoF option for editable properties */}
        {showReplaceDoF && (
          <PropertySelector
            onSelect={handleReplaceDoFSelect}
            variant="outline"
            title={`Choose a variable to replace ${property.displayName}.`}
            filter={hasFreeVariable}
            filterValue={isFreeVariable}
            header=""
            description=""
          >
            <DropdownMenuItem
              onSelect={(e) => e.preventDefault()}
              className="cursor-pointer"
            >
              <Replace className="mr-2 h-4 w-4" />
              <span>Replace DoF</span>
            </DropdownMenuItem>
          </PropertySelector>
        )}
 
        {/* Control Target option for non-editable properties */}
        {showControlTarget && (
          <PropertySelector
            onSelect={handleControlTargetSelect}
            variant="secondary"
            title={`Choose a parameter for ${property.displayName} to replace.`}
            filter={hasStateVariable}
            filterValue={isStateVariable}
            header=""
            description=""
          >
            <DropdownMenuItem
              onSelect={(e) => e.preventDefault()}
              className="cursor-pointer"
            >
              <Replace className="mr-2 h-4 w-4" />
              <span>Replace Parameter</span>
            </DropdownMenuItem>
          </PropertySelector>
        )}
 
        {/* Constraint submenu which opens to the right */}
        {showAddConstraint && (
          <DropdownMenuSub>
            <DropdownMenuSubTrigger className="cursor-pointer">
              <SquareFunction className="mr-2 h-4 w-4" />
              <span>{hasConstraint ? "Edit Constraint" : "Add Constraint"}</span>
            </DropdownMenuSubTrigger>
            <DropdownMenuSubContent className="w-96 min-h-48 max-h-[500px] overflow-y-auto p-3" sideOffset={8}>
              <div className="space-y-3">
                <div className="text-xs font-medium text-muted-foreground">
                  {hasConstraint ? "Edit formula constraint" : "Add a formula constraint"}
                </div>
                <FormulaInputField
                  property={property}
                  propertyValue={propertyValue}
                  simulationObjectId={simulationObjectId}
                  onSave={handleConstraintSave}
                />
                {hasConstraint && (
                  <>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem
                      onSelect={handleRemoveConstraint}
                      className="cursor-pointer text-destructive focus:text-destructive"
                    >
                      <Trash2 className="mr-2 h-4 w-4" />
                      <span>Remove Constraint</span>
                    </DropdownMenuItem>
                  </>
                )}
              </div>
            </DropdownMenuSubContent>
          </DropdownMenuSub>
        )}
 
        {/* Remove Replacement option for controlled properties */}
        {hasReplacement && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onSelect={handleRemoveReplacement}
              className="cursor-pointer text-destructive focus:text-destructive"
            >
              <Trash2 className="mr-2 h-4 w-4" />
              <span>Remove Replacement</span>
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
};