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

68.18% Statements 60/88
39.53% Branches 17/43
68.96% Functions 20/29
71.08% Lines 59/83

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                                                                                              33x 456x 456x   456x 456x   456x   456x 456x     456x   2093x 838x   456x 1826x     456x     456x       456x       456x 456x   456x           456x 83x     83x 47x   36x     456x   99x   195435x 25020x             456x       223512x               223512x                 223512x             456x     456x 24x 24x   24x     24x 24x                 456x 1x   1x             1x           1x       456x     456x 456x       456x         456x                               456x                                           456x                                       21x               461x                 1x 1x 1x                   16x 16x                                                     838x                                                                                                                    
// QuickAddCompoundsModal.tsx
import * as React from "react";
import {
  useCompoundsuggestionsRetrieveQuery,
  useUnitopsSimulationobjectsUpdateCompoundsCreateMutation,
  DirectionEnum
} from "@/api/apiStore.gen";
import { useSearchParam } from "@/hooks/searchParams";
import { Combobox, ComboboxOption } from "@/ahuora-design-system/ui/combobox";
import { Button } from "@/ahuora-design-system/ui/button";
import { Maximize2, Plus, X } from "lucide-react";
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogFooter,
  AlertDialogAction,
  AlertDialogCancel,
} from "@/ahuora-design-system/ui/alert-dialog";
import CompoundSelectPage from "@/pages/compound-select-page/CompoundSelectPage";
import { toast } from "sonner";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import { useProjectId } from "@/hooks/project";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import { isStream } from "@/lib/isStream";
import {
  useFlowsheetUnitOps,
  useFlowsheetPorts,
} from "@/hooks/flowsheetObjects";
import { AlertDialogTitle } from "@radix-ui/react-alert-dialog";
import { useListCompounds } from "@/hooks/compounds.ts";
 
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[];
}> = ({ selectedCompounds }) => {
  const [id] = useSearchParam("object");
  const [parentGroup] = useSearchParam("parentGroup");
  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: useProjectId(), streamId },
    { skip: !flowsheetId || !streamId },
  );
 
  // normalize suggestions to lowercase (matches our option.value)
  const normalizedSuggestions: string[] = React.useMemo(() => {
    Iif (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 [];
  }, [suggestionsData]);
 
  const comboBoxItems: ComboboxOption[] = React.useMemo(
    () =>
      compounds
        .slice() // copy array to avoid mutating read-only original
        .sort((a, b) => a.name.localeCompare(b.name))
        .map((compound) => ({
          value: compound.name.toLowerCase(),
          label: compound.name.charAt(0).toUpperCase() + compound.name.slice(1),
        })),
    [compounds],
  );
 
  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[]) => {
    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 (!selectedStreamId) return;
 
    updateCompounds({
      updateCompound: {
        simulationObject: selectedStreamId,
        compounds: localSelected,
      },
    });
 
    Iif (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 handleStreamChange = (newStreamId: number) => {
    Iif (
      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) => {
    Iif (pendingStreamId !== null) {
      Iif (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}
        open={comboOpen} // controlled visibility
        onOpenChange={setComboOpen}
        closeOnSelect={false}
        searchPlaceholder="Search compounds"
        emptyMessage="No compounds found"
        noGroupItemsMessage="No compounds selected"
        trigger={
          <div>
            <ToolTipCover content="Add compounds" delay={0} asChild>
              <Button
                size="icon"
                variant="secondary"
                aria-label="Add Compounds"
                onClick={() => setComboOpen(true)}
              >
                <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={() => {
                      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))}
                >
                  <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>
              <p className="text-sm text-muted-foreground mb-2">
                Choose which compounds you want to add to this stream.
              </p>
            </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>
    </>
  );
};