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

69.69% Statements 46/66
40% Branches 8/20
76.92% Functions 10/13
69.69% Lines 46/66

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                                      33x       1121x 1121x   1121x 1121x 1121x     1121x 1121x 1121x 1121x       1121x 213x     1121x     1121x   42x           42x 376x 376x 376x     42x       42x     1121x 42x 42x     1121x 42x   42x                                                         42x         42x           42x               42x 8x   42x 42x 42x 42x                                                     1121x   1121x 1121x   1121x 52x               1069x     1121x 6x 6x     1121x                                                                                    
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 objs from "@/data/objects.json";
import { ObjectType } from "@/data/ObjectTypes.gen";
import { useCurrentObject } from "@/hooks/flowsheetObjects";
import { useProjectId } from "@/hooks/project";
import { useSearchParam } from "@/hooks/searchParams";
import { cn } from "@/lib/utils";
import { useAppDispatch } from "@/store/hooks";
import { ArrowLeft } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
const objects = objs as unknown as Record<string, ObjectType>;
import { ContentTypes } from "@/pages/flowsheet-page/flowsheet/LeftSideBar/LeftSideBarTabDefinitions";
 
function GeneralInfo() {
  const [content, setContent] = useSearchParam("content");
  const simulationObject = useCurrentObject();
  const [updateSimulationObject] =
    useUnitopsSimulationobjectsPartialUpdateMutation();
  const dispatch = useAppDispatch();
  const { data: listObjects } = useUnitopsSimulationobjectsListQuery({
    flowsheet: useProjectId(),
  });
  const [toastId, setToastId] = useState<string | number | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [prevName, setPrevName] = useState(simulationObject?.componentName);
  const [displayValue, setDisplayValue] = useState(
    simulationObject?.componentName,
  );
 
  useEffect(() => {
    setDisplayValue(simulationObject?.componentName);
  }, [simulationObject?.componentName]);
 
  Iif (!simulationObject || !listObjects) {
    return null;
  }
  const isNameInvalid = (value: string) => {
    // Check if the string is empty or contains only whitespace
    Iif (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;
 
    Iif (isDuplicated) {
      return true;
    }
 
    return false;
  };
 
  const handleFinishEditing = (update: string | number) => {
    setIsEditing(false);
    handleSubmitNameChange(update);
  };
 
  const handleSubmitNameChange = (update: string | number) => {
    const name = (update as string).trim();
 
    Iif (isNameInvalid(name)) {
      Iif (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);
      setIsEditing(false);
      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) => {
        Iif (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);
        setIsEditing(false);
      });
  };
 
  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"
          >
            <ArrowLeft />
          </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;