All files / src/pages/flowsheet-page/flowsheet/PropertiesSidebar/PropertyPanel QuickAddCompoundsModal.tsx

68.69% Statements 147/214
61.93% Branches 96/155
26.66% Functions 8/30
78.76% Lines 115/146

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                                                                                                          233493x 1069x 1069x   1069x 1069x   1069x   1069x 1069x     1069x         1069x 3976x     1069x       1069x   1069x       1069x     1069x   1069x 1249x 1159x       300x         171x   129x     300x               1069x 300x     35482x   300x 300x         35482x       300x 300x 300x 300x   35482x   7314x 1969x 2269x     1069x     1069x   51x 51x         51x 51x             1429x                 1x         1x                         1x       1069x     1069x 1069x   1069x   1069x     2065x     46x 46x 46x     1069x                             3061x   1069x                                       3559x     1069x 1069x 1069x                             1069x                 1069x     3207x   90x 90x                   1x 1x 1x                   40x 40x               1159x 9621x     1069x 1069x 90x   1069x 1069x 1069x 1069x 1069x 1159x 1318x     90x   1069x 1069x 1069x         3207x   7483x 90x       1069x 2138x 3207x     153x         1375x   1069x   2138x 3207x 5345x 4276x     249x 249x 90x           1069x   90x             1249x 249x         1318x 249x   1318x   1816x 1816x 4276x      
// QuickAddCompoundsModal.tsx
 
import {
  AlertDialogDescription,
  AlertDialogTitle,
} from "@radix-ui/react-alert-dialog";
import { Maximize2, Plus, X } from "lucide-react";
import * as React from "react";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogFooter,
  AlertDialogHeader,
} from "@/ahuora-design-system/ui/alert-dialog";
import { Button } from "@/ahuora-design-system/ui/button";
import { Combobox, ComboboxOption } from "@/ahuora-design-system/ui/combobox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import {
  DirectionEnum,
  useCompoundsuggestionsRetrieveQuery,
  useUnitopsSimulationobjectsUpdateCompoundsCreateMutation,
} from "@/api/apiStore.gen";
import { useListCompounds } from "@/hooks/compounds.ts";
import {
  useCurrentGroupId,
  useFlowsheetPorts,
  useFlowsheetUnitOps,
} from "@/hooks/flowsheetObjects";
import { useFlowsheetId } from "@/hooks/project";
import { useSearchParam } from "@/hooks/searchParams";
import { isStream } from "@/lib/isStream";
import CompoundSelectPage from "@/pages/compound-select-page/CompoundSelectPage";
 
export const QuickAddCompoundsModal: React.FC<{
  schema: object;
  moleFracComp: {
    values: Record<string, number>;
    type: string;
    unit?: string;
  };
  // server truth – used only as initial value for local UI state
  selectedCompounds: string[];
  disabled?: boolean;
}> = ({ selectedCompounds, disabled = false }) => {
  const [id] = useSearchParam("object");
  const parentGroup = useCurrentGroupId();
  const [updateCompounds] =
    useUnitopsSimulationobjectsUpdateCompoundsCreateMutation();
  const compounds = useListCompounds();
 
  const [isDialogOpen, setIsDialogOpen] = React.useState<boolean>(false);
 
  const allStreams = (useFlowsheetUnitOps() || []).filter(isStream);
  const ports = useFlowsheetPorts() || [];
 
  // inlet streams only
  const inletStreamIds = new Set(
    ports
      .filter((p) => p.direction === DirectionEnum.Inlet && p.stream != null)
      .map((p) => p.stream),
  );
  const flowsheetStreams = allStreams.filter((stream) =>
    inletStreamIds.has(stream.id),
  );
 
  const defaultStreamId = id ? +id : flowsheetStreams[0]?.id;
 
  // local, modal-scoped selection (no syncing effects — re-seeded by key remount)
  const [localSelected, setLocalSelected] =
    React.useState<string[]>(selectedCompounds);
 
  const [selectedStreamId, setSelectedStreamId] = React.useState<
    number | undefined
  >(defaultStreamId);
 
  const flowsheetId: number | undefined = parentGroup
    ? +parentGroup
    : undefined;
  const streamId: number | undefined = selectedStreamId;
 
  const { data: suggestionsData } = useCompoundsuggestionsRetrieveQuery(
    { flowsheet: useFlowsheetId(), streamId },
    { skip: !flowsheetId || !streamId },
  );
 
  // normalize suggestions to lowercase (matches our option.value)
  const normalizedSuggestions: string[] = (() => {
    if (Array.isArray(suggestionsData)) {
      return (suggestionsData as string[]).map((v) => v.toLowerCase());
    }
    if (suggestionsData && Array.isArray((suggestionsData as any).data)) {
      return (suggestionsData as any).data.map((v: string) => v.toLowerCase());
    }
    return [];
  })();
 
  const comboBoxItems: ComboboxOption[] = compounds
    .slice() // copy array to avoid mutating read-only original
    .sort((a, b) => a.name.localeCompare(b.name))
    .map((compound) => ({
      value: compound.name,
      label: compound.name.charAt(0).toUpperCase() + compound.name.slice(1),
    }));
 
  const groupedOptions = [
    {
      type: "group" as const,
      label: "Selected compounds",
      options: comboBoxItems.filter((c) => localSelected.includes(c.value)),
    },
    { type: "separator" as const },
    {
      type: "group" as const,
      label: "Recommended",
      options: comboBoxItems.filter(
        (c) =>
          normalizedSuggestions.includes(c.value) &&
          !localSelected.includes(c.value),
      ),
    },
    {
      type: "group" as const,
      label: "Not selected",
      options: comboBoxItems.filter(
        (c) =>
          !localSelected.includes(c.value) &&
          !normalizedSuggestions.includes(c.value),
      ),
    },
  ];
 
  // Keep the combobox open across multiple selections
  const [comboOpen, setComboOpen] = React.useState(false);
 
  // UI-first update; then sync server (no effect needed)
  const handleChange = (newSelected: string[]) => {
    Iif (disabled) return;
    setLocalSelected(newSelected);
    setComboOpen(true); // keep it open after selecting
 
    Iif (!selectedStreamId) return;
 
    // small microtask delay feels smoother; avoids rapid remounts
    requestAnimationFrame(() => {
      updateCompounds({
        updateCompound: {
          simulationObject: selectedStreamId,
          compounds: newSelected,
        },
      });
    });
  };
 
  const handleOK = () => {
    Iif (disabled) return;
    Iif (!selectedStreamId) return;
 
    // Persist the just-confirmed modal state immediately so stream-switch
    // comparisons do not treat the saved selection as an unsaved change while
    // the parent prop is still catching up with the mutation response.
    setSavedByStream((prev) => ({
      ...prev,
      [selectedStreamId]: localSelected,
    }));
 
    updateCompounds({
      updateCompound: {
        simulationObject: selectedStreamId,
        compounds: localSelected,
      },
    });
 
    if (localSelected.length === 0) {
      toast.warning("No compounds selected!", {
        description:
          "Please ensure you have selected appropriate compounds for your process design.",
      });
    }
    setIsDialogOpen(false);
  };
 
  // Unsaved-change guard when switching streams
  const [pendingStreamId, setPendingStreamId] = React.useState<number | null>(
    null,
  );
  const [showUnsavedDialog, setShowUnsavedDialog] = React.useState(false);
  const [savedByStream, setSavedByStream] = React.useState<
    Record<number, string[]>
  >({});
 
  const hasUnsavedChanges = () =>
    selectedStreamId !== undefined &&
    JSON.stringify(localSelected) !==
      JSON.stringify(savedByStream[selectedStreamId] || selectedCompounds);
 
  const openCompoundPicker = () => {
    setSelectedStreamId(defaultStreamId);
    setLocalSelected(selectedCompounds);
    setComboOpen(true);
  };
 
  const handleStreamChange = (newStreamId: number) => {
    Iif (disabled) return;
    if (
      selectedStreamId !== undefined &&
      newStreamId !== selectedStreamId &&
      hasUnsavedChanges()
    ) {
      setPendingStreamId(newStreamId);
      setShowUnsavedDialog(true);
      return;
    }
    setSelectedStreamId(newStreamId);
    // re-seed from last saved snapshot (if any) or from current server truth
    const next = savedByStream[newStreamId] ?? selectedCompounds;
    setLocalSelected(next);
  };
 
  const confirmStreamSwitch = (save: boolean) => {
    if (pendingStreamId !== null) {
      if (save && selectedStreamId !== undefined) {
        setSavedByStream((prev) => ({
          ...prev,
          [selectedStreamId]: localSelected,
        }));
        updateCompounds({
          updateCompound: {
            simulationObject: selectedStreamId,
            compounds: localSelected,
          },
        });
      }
      setSelectedStreamId(pendingStreamId);
      const next = savedByStream[pendingStreamId] ?? selectedCompounds;
      setLocalSelected(next);
      setPendingStreamId(null);
      setShowUnsavedDialog(false);
    }
  };
 
  return (
    <>
      <Combobox
        key={`stream-${selectedStreamId ?? "none"}`} // only remount on stream change (not on selection change)
        options={groupedOptions}
        selectedValues={localSelected}
        onChange={handleChange}
        disabled={disabled}
        open={comboOpen} // controlled visibility
        onOpenChange={setComboOpen}
        closeOnSelect={false}
        searchPlaceholder="Search compounds"
        emptyMessage="No compounds found"
        noGroupItemsMessage="No compounds selected"
        trigger={
          // PopoverTrigger `asChild` requires a concrete DOM element/ref target.
          // Keep the tooltip/button inside a wrapper so the combobox trigger
          // remains clickable and Radix can attach its trigger props safely.
          <div>
            <ToolTipCover content="Add compounds" delay={0} asChild>
              <Button
                size="icon"
                variant="secondary"
                aria-label="Add Compounds"
                onClick={openCompoundPicker}
                disabled={disabled}
              >
                <Plus className="icon-medium" />
              </Button>
            </ToolTipCover>
          </div>
        }
        renderSelectedValues={(setOpen) => (
          <div>
            <div className="flex flex-row justify-between">
              <h3>Compound List</h3>
              <div className="flex flex-row">
                <ToolTipCover content="Maximise" asChild>
                  <Maximize2
                    size={17}
                    className="self-center cursor-pointer mr-2 hover:stroke-zinc-400"
                    onClick={() => {
                      Iif (disabled) return;
                      setIsDialogOpen(true);
                      setOpen?.(false);
                      setComboOpen(false);
                    }}
                    aria-label="Quick Compound Maximise"
                  />
                </ToolTipCover>
                <ToolTipCover content="Close" asChild>
                  <X
                    size={20}
                    className="self-center cursor-pointer hover:stroke-rose-700"
                    onClick={() => {
                      setOpen?.(false);
                      setComboOpen(false);
                    }}
                    aria-label="Quick Compound Close"
                  />
                </ToolTipCover>
              </div>
            </div>
          </div>
        )}
      />
 
      {/* Expanded Modal */}
      <AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <AlertDialogContent className="flex flex-col justify-between p-6">
          <AlertDialogTitle className="text-lg font-semibold mb-4">
            Select Compounds
          </AlertDialogTitle>
          <AlertDialogHeader>
            <div className="pb-4">
              <div className="flex flex-col gap-1 mb-4">
                <Select
                  value={selectedStreamId?.toString()}
                  onValueChange={(val) => handleStreamChange(Number(val))}
                  disabled={disabled}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select stream" />
                  </SelectTrigger>
                  <SelectContent className="max-h-60 overflow-y-auto">
                    {flowsheetStreams.map((stream) => (
                      <SelectItem key={stream.id} value={stream.id.toString()}>
                        {stream.componentName || `Stream ${stream.id}`}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <AlertDialogDescription className="mb-4">
                <p className="text-sm text-muted-foreground mb-2">
                  Choose which compounds you want to add to this stream.
                </p>
              </AlertDialogDescription>
            </div>
          </AlertDialogHeader>
 
          <div className="flex flex-col lg:gap-2 md:gap-2 sm:gap-1">
            <div className="lg:h-[55vh] md:h-[55vh] sm:h-[30vh]">
              <CompoundSelectPage
                selectedCompounds={localSelected}
                setSelectedCompounds={setLocalSelected}
              />
            </div>
            <AlertDialogFooter className="mt-0">
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <AlertDialogAction onClick={handleOK}>Save</AlertDialogAction>
            </AlertDialogFooter>
          </div>
        </AlertDialogContent>
      </AlertDialog>
 
      {/* Unsaved changes confirmation */}
      <AlertDialog open={showUnsavedDialog} onOpenChange={setShowUnsavedDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <h2 className="text-lg font-semibold mb-2">Unsaved Changes</h2>
            <p className="text-sm text-muted-foreground mb-2">
              You have unsaved changes for this stream. Do you want to save
              before switching?
            </p>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel
              onClick={() => {
                setShowUnsavedDialog(false);
                setPendingStreamId(null);
              }}
            >
              Cancel
            </AlertDialogCancel>
            <Button
              variant="secondary"
              onClick={() => confirmStreamSwitch(false)}
            >
              Don't Save
            </Button>
            <AlertDialogAction onClick={() => confirmStreamSwitch(true)}>
              Save
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};