All files / src/pages/flowsheet-page/flowsheet/PropertiesSidebar/GeneralInfo GeneralInfo.tsx

68.42% Statements 65/95
58.13% Branches 25/43
36.36% Functions 4/11
71.25% Lines 57/80

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                                        103x       2063x 2063x 2063x   2063x 2063x 2063x 2063x 2291x 2063x 2063x 2063x       2063x 321x 2384x   4x     2059x               45x 404x 404x           45x     3077x     45x       45x                                                           45x         45x           45x                 6x   45x 45x 45x 45x                                               5239x   2059x   2059x 297x   19x           278x     2356x   2059x 16x 16x 2541x     863x       2356x 622x 2059x     3303x 3303x 482x             2059x 2541x 3785x     297x           2059x         2653x   3785x          
import { X } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { ModuleMark } from "@/ahuora-design-system/componentIcons/ModuleMark";
import { AutoSelectInput } from "@/ahuora-design-system/ui/auto-select-input";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  api,
  useUnitopsSimulationobjectsListQuery,
  useUnitopsSimulationobjectsPartialUpdateMutation,
} from "@/api/apiStore.gen";
import { ObjectType } from "@/data/ObjectTypes.gen";
import objs from "@/data/unitOpConfigs";
import { useCurrentObject } from "@/hooks/flowsheetObjects";
import { useFlowsheetId } from "@/hooks/project";
import { useSearchParam } from "@/hooks/searchParams";
import { cn } from "@/lib/utils";
import { useAppDispatch } from "@/store/hooks";
 
const objects = objs as unknown as Record<string, ObjectType>;
 
import { ContentTypes } from "@/pages/flowsheet-page/flowsheet/LeftSideBar/LeftSideBarTabDefinitions";
 
function GeneralInfo() {
  const [, setContent] = useSearchParam("content");
  const simulationObject = useCurrentObject();
  const [updateSimulationObject] =
    useUnitopsSimulationobjectsPartialUpdateMutation();
  const dispatch = useAppDispatch();
  const { data: listObjects } = useUnitopsSimulationobjectsListQuery({
    flowsheet: useFlowsheetId(),
  });
  const [toastId, setToastId] = useState<string | number | null>(null);
  const [prevName, setPrevName] = useState(simulationObject?.componentName);
  const [displayValue, setDisplayValue] = useState(
    simulationObject?.componentName,
  );
 
  useEffect(() => {
    setDisplayValue(simulationObject?.componentName);
  }, [simulationObject?.componentName]);
 
  if (!simulationObject || !listObjects) {
    return null;
  }
  const isNameInvalid = (value: string) => {
    // Check if the string is empty or contains only whitespace
    if (value.trim() === "") {
      return true;
    }
 
    // Check for duplicate names
    const isDuplicated =
      listObjects!.filter((x) => {
        const isSameName = x.componentName === value;
        const isSameObject = x.id && x.id === simulationObject?.id;
        return isSameName && !isSameObject;
      }).length > 0;
 
    if (isDuplicated) {
      return true;
    }
 
    return false;
  };
 
  const handleFinishEditing = (update: string | number) => {
    handleSubmitNameChange(update);
  };
 
  const handleSubmitNameChange = (update: string | number) => {
    const name = (update as string).trim();
 
    if (isNameInvalid(name)) {
      if (toastId) {
        toast.dismiss(toastId);
      }
      const id = toast.error("Invalid name submission.", {
        richColors: true,
        description:
          name === ""
            ? "Name cannot be empty."
            : "This name is already in use. Please choose a unique name.",
      });
      setToastId(id);
 
      // Revert optimistically
      dispatch(
        api.util.updateQueryData(
          "unitopsSimulationobjectsRetrieve",
          { id: simulationObject!.id },
          (draft) => {
            draft.componentName = prevName!;
          },
        ),
      );
      setDisplayValue(prevName);
      return;
    }
 
    // Optimistic update
    dispatch(
      api.util.updateQueryData(
        "unitopsSimulationobjectsRetrieve",
        { id: simulationObject!.id },
        (draft) => {
          draft.componentName = name;
        },
      ),
    );
 
    // Backend update
    updateSimulationObject({
      id: simulationObject!.id,
      patchedSimulationObject: {
        componentName: name,
      },
    })
      .unwrap()
      .then(() => {
        if (toastId) {
          toast.dismiss(toastId);
        }
        const id = toast.success(`Successfully updated name to ${name}`);
        setToastId(id);
        setPrevName(name);
        setDisplayValue(name);
      })
      .catch((error) => {
        if (toastId) {
          toast.dismiss(toastId);
        }
        const id = toast.error("Failed to update name.", {
          richColors: true,
          description: error.data?.message || "An unexpected error occurred.",
        });
        setToastId(id);
 
        // Revert optimistically on error
        dispatch(
          api.util.updateQueryData(
            "unitopsSimulationobjectsRetrieve",
            { id: simulationObject!.id },
            (draft) => {
              draft.componentName = prevName!;
            },
          ),
        );
        setDisplayValue(prevName);
      });
  };
 
  const objectDisplayName = objects[simulationObject.objectType!].displayName;
 
  const getStatusIcon = () => {
    const isModule = simulationObject?.objectType === "group";
 
    if (isModule) {
      return (
        <div className={cn("text-primary-foreground")}>
          <ModuleMark />
        </div>
      );
    }
 
    return null;
  };
 
  const handleCollapse = (e: React.MouseEvent) => {
    e.stopPropagation(); // Prevent event bubbling
    setContent(ContentTypes.objectList);
  };
 
  return (
    <div className="flex flex-col">
      <div className="p-4 py-2 flex flex-col gap-2">
        <div className="flex flex-row items-center justify-between">
          <div className="flex flex-row items-center gap-1 flex-1">
            {getStatusIcon()}
            <AutoSelectInput
              value={displayValue || ""}
              onUpdateValue={handleFinishEditing}
              aria-label="Selected object name"
            />
          </div>
          <Button
            size="icon"
            variant="ghost"
            onClick={handleCollapse}
            className="ml-2 w-max"
            aria-label="Collapse-Right-Sidebar"
          >
            <X />
          </Button>
        </div>
 
        {/* Keep existing badge section */}
        <div className="flex flex-row justify-between items-center w-full">
          <div className="flex flex-row items-center gap-2">
            <Badge
              variant="outline"
              borderRadius="round"
              className="text-muted-foreground"
              aria-label={`selected-${objectDisplayName}`}
            >
              {objectDisplayName}
            </Badge>
          </div>
        </div>
      </div>
    </div>
  );
}
 
export default GeneralInfo;