All files / src/pages/main-page/components EllipsisMenu.tsx

37.8% Statements 31/82
46.34% Branches 19/41
11.11% Functions 2/18
37.8% Lines 31/82

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                                                                                            103x                                                                                                                                                         633x 633x 633x 633x   633x 633x       633x 633x 633x 633x 633x 633x 633x 633x   633x                                                                                                                                   2x       1x                                                                                                                                         2x 2x   1x 1x                                       633x                             1899x       3144x 3144x                 626x   3x     2515x           3x 3x                                                                                                                                                  
import {
  Copy,
  EllipsisVertical,
  FileXIcon,
  History,
  PenLine,
  SquarePen,
  Star,
  StarOff,
  Trash2,
  Undo2,
} from "lucide-react";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
import {
  api,
  PatchedProject,
  type ScenarioResultCopySummary,
  useCoreProjectsCopyCreateMutation,
  useCoreProjectsDestroyMutation,
  useCoreProjectsPartialUpdateMutation,
  useLazyCoreProjectsCopyPreviewRetrieveQuery,
} from "@/api/apiStore.gen";
import {
  type CloneValidationProblem,
  parseCloneValidationProblem,
} from "@/flowsheet-cloning/cloneValidation";
import { DuplicateWithResultsDialog } from "@/flowsheet-cloning/DuplicateWithResultsDialog";
import { FlowsheetCloneProblemDialog } from "@/flowsheet-cloning/FlowsheetCloneProblemDialog";
import { useRevertTemplate } from "@/hooks/useTemplate";
import { useUserInfo } from "@/hooks/useUserInfo";
import type { ProjectCardData } from "@/pages/main-page/components/projectCardData";
import type { ProjectFolderId } from "@/pages/main-page/project-folders/model";
import { ProjectFolderMoveMenu } from "@/pages/main-page/project-folders/ProjectFolderControls";
import { useAppDispatch } from "@/store/hooks";
import DeleteDialog from "../../../ahuora-design-system/ui/delete-dialog";
import RenameDialog from "../../../ahuora-design-system/ui/rename-dialog";
 
const ellipsisMenuInfo = {
  project: {
    rename: {
      label: "Rename",
      icon: <PenLine />,
      ariaLabel: "Rename Ellipsis Menu Item",
    },
    copy: {
      label: "Copy",
      icon: <Copy />,
      ariaLabel: "Copy Ellipsis Menu Item",
    },
    star: {
      label: "Star",
      icon: <Star />,
      ariaLabel: "Star Ellipsis Menu Item",
      patchedProject: { is_starred: true },
      toastSuccess: "Successfully starred ",
      toastFail: "Failed to star project:",
    },
    unstar: {
      label: "Unstar",
      icon: <StarOff />,
      ariaLabel: "Unstar Ellipsis Menu Item",
      patchedProject: { is_starred: false },
      toastSuccess: "Successfully unstarred ",
      toastFail: "Failed to unstar project:",
    },
    bin: {
      label: "Move to bin",
      icon: <Trash2 />,
      ariaLabel: "Bin Ellipsis Menu Item",
      patchedProject: {
        is_binned: true,
      },
      toastSuccess: "Successfully binned ",
      toastFail: "Failed to bin project:",
    },
  },
  template: {
    edit: {
      label: "Edit template",
      icon: <SquarePen />,
      ariaLabel: "Edit Template Ellipsis Menu Item",
    },
    revert: {
      label: "Revert to project",
      icon: <Undo2 />,
      ariaLabel: "Revert Ellipsis Menu Item",
    },
  },
  binned: {
    restore: {
      label: "Restore",
      icon: <History />,
      ariaLabel: "Restore Ellipsis Menu Item",
      patchedProject: { is_binned: false },
      toastSuccess: "Successfully restored ",
      toastFail: "Failed to restore project:",
    },
    delete: {
      label: "Delete forever",
      icon: <FileXIcon />,
      ariaLabel: "Delete Ellipsis Menu Item",
    },
  },
};
 
function EllipsisMenu({
  projectCardInfo,
  onMoveToFolder,
  isMovePending = false,
}: {
  projectCardInfo: ProjectCardData;
  onMoveToFolder?: (folderId: ProjectFolderId) => Promise<void> | void;
  isMovePending?: boolean;
}) {
  const nav = useNavigate();
  const dispatch = useAppDispatch();
  const [copyProject, copyProjectResult] = useCoreProjectsCopyCreateMutation();
  const [loadCopyPreview] = useLazyCoreProjectsCopyPreviewRetrieveQuery();
  const [copyConfirmation, setCopyConfirmation] =
    useState<ScenarioResultCopySummary | null>(null);
  const [copyFailure, setCopyFailure] = useState<{
    problem: CloneValidationProblem;
    includeScenarioResults: boolean;
  } | null>(null);
  const [deleteProject] = useCoreProjectsDestroyMutation();
  const [updateProject] = useCoreProjectsPartialUpdateMutation();
  const [toastId, setToastId] = useState<string | number | null>(null);
  const [isRenameDialogOpen, setIsRenameDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const { revertTemplate } = useRevertTemplate();
  const { data: userInfo } = useUserInfo();
  const isShared = userInfo?.id !== projectCardInfo.owner.id;
 
  const menuItemClassName = "w-full gap-3 items-center cursor-pointer p-2";
 
  const handleDeleteProject = () => {
    deleteProject({
      id: projectCardInfo.id.toString(),
    })
      .unwrap()
      .then(() => {
        toast.success(`${projectCardInfo.name} deleted!`);
      })
      .catch((error) => {
        toast.error(
          "Failed to delete project: " + (error.data?.detail || error.message),
        );
      });
    setIsDeleteDialogOpen(false);
  };
 
  const isNameInvalid = (value: string) => {
    return value.trim() === "";
  };
 
  const handleRenameProject = (newProjectName: string) => {
    const name = newProjectName.trim();
 
    if (isNameInvalid(name)) {
      if (toastId) {
        toast.dismiss(toastId);
      }
      const id = toast.error("Invalid name submission.", {
        richColors: true,
        description: "New project name cannot be empty.",
      });
      setToastId(id);
      return;
    }
 
    // Optimistic update
    dispatch(
      api.util.updateQueryData(
        "coreProjectsRetrieve",
        { id: projectCardInfo.id.toString() },
        (prev) => {
          prev.name = name;
        },
      ),
    );
 
    updateProject({
      id: projectCardInfo.id.toString(),
      patchedProject: {
        name: newProjectName,
      },
    })
      .then(() => {
        toast.success(`Successfully renamed project to ${newProjectName}!`);
      })
      .catch((error) => {
        toast.error(
          "Failed to rename project: " + (error.data?.detail || error.message),
        );
      });
    setIsRenameDialogOpen(false);
  };
 
  const handleEditTemplate = () => {
    nav(`/project/${projectCardInfo.id}/flowsheet`);
  };
 
  const handleRevertTemplate = () => {
    revertTemplate(projectCardInfo.id)
      .then(() => {
        toast.success(
          `Successfully reverted ${projectCardInfo.name}  to regular flowsheet!`,
        );
      })
      .catch((error) => {
        toast.error(
          "Failed to revert template: " + (error.data?.detail || error.message),
        );
      });
  };
 
  const handleCopyProject = async (
    repairLegacyFormulaUnits = false,
    includeScenarioResults = false,
  ) => {
    setCopyConfirmation(null);
    try {
      await copyProject({
        id: projectCardInfo.id.toString(),
        cloneRequest: {
          ...(repairLegacyFormulaUnits
            ? { repair_legacy_formula_units: true }
            : {}),
          ...(includeScenarioResults ? { include_scenario_results: true } : {}),
        },
      }).unwrap();
      setCopyFailure(null);
      toast.success(`Successfully copied ${projectCardInfo.name}!`);
    } catch (error) {
      const problem = parseCloneValidationProblem(error);
      if (problem) {
        setCopyFailure({ problem, includeScenarioResults });
        return;
      }
      toast.error("Failed to copy project.");
    }
  };
 
  const requestCopyProject = async () => {
    try {
      const summary = await loadCopyPreview({
        id: projectCardInfo.id.toString(),
      }).unwrap();
      if (summary.has_results) {
        setCopyConfirmation(summary);
        return;
      }
      await handleCopyProject();
    } catch {
      toast.error("Scenario result counts could not be loaded");
    }
  };
 
  const handleOnClick = (
    key: string,
    patchedProject: PatchedProject,
    toastSuccess: string,
    toastFail: string,
  ) => {
    switch (key) {
      case "rename":
        setIsRenameDialogOpen(true);
        break;
      case "delete":
        setIsDeleteDialogOpen(true);
        break;
      case "edit":
        handleEditTemplate?.();
        break;
      case "revert":
        handleRevertTemplate?.();
        break;
      case "copy":
        void requestCopyProject();
        break;
      default:
        // Default involves cases in which the flowsheet data needs to be changed
        updateProject({
          id: projectCardInfo.id.toString(),
          patchedProject,
        })
          .then(() => {
            toast.success(toastSuccess + `${projectCardInfo.name}!`);
          })
          .catch((error) => {
            toast.error(toastFail + (error.data?.detail || error.message));
          });
        break;
    }
  };
 
  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            size="xs"
            variant="ghost"
            aria-label={`${projectCardInfo.name} Ellipsis Menu`}
            onClick={(event) => event.stopPropagation()}
          >
            <EllipsisVertical className="icon-large" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent className="font-normal">
          {Object.entries(ellipsisMenuInfo).map(([group, data], index) => {
            return (
              <React.Fragment key={index}>
                {projectCardInfo.type === group &&
                  Object.keys(data).map((key) => {
                    const groupData = ellipsisMenuInfo[group][key];
                    const skipForSharedProject = [
                      "rename",
                      "star",
                      "bin",
                    ].includes(key);
                    // Instances in which we want to skip certain items in ellipsisMenuInfo depending on conditon
                    if (projectCardInfo.isStarred && key === "star") {
                      return null;
                    } else if (!projectCardInfo.isStarred && key === "unstar") {
                      return null;
                    } else if (isShared && skipForSharedProject) {
                      return null;
                    }
 
                    return (
                      <DropdownMenuItem
                        key={key}
                        aria-label={groupData.ariaLabel}
                        className={menuItemClassName}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleOnClick?.(
                            key,
                            groupData.patchedProject,
                            groupData.toastSuccess,
                            groupData.toastFail,
                          );
                        }}
                      >
                        {groupData.icon} {groupData.label}
                      </DropdownMenuItem>
                    );
                  })}
              </React.Fragment>
            );
          })}
          {projectCardInfo.type === "project" &&
            !isShared &&
            onMoveToFolder && (
              <ProjectFolderMoveMenu
                currentFolderId={projectCardInfo.folderId ?? null}
                onMove={onMoveToFolder}
                disabled={isMovePending}
              />
            )}
        </DropdownMenuContent>
      </DropdownMenu>
 
      <RenameDialog
        projectName={projectCardInfo.name}
        isOpen={isRenameDialogOpen}
        onOpenChange={setIsRenameDialogOpen}
        onRename={handleRenameProject}
        onCancel={() => setIsRenameDialogOpen(false)}
      />
 
      <DeleteDialog
        projectName={projectCardInfo.name}
        isOpen={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        onDelete={handleDeleteProject}
        onCancel={() => setIsDeleteDialogOpen(false)}
      />
 
      <FlowsheetCloneProblemDialog
        problem={copyFailure?.problem ?? null}
        scope="project"
        isRepairingAutomatically={copyProjectResult.isLoading}
        onDismiss={() => setCopyFailure(null)}
        onRepairManually={(affectedFlowsheetId) => {
          setCopyFailure(null);
          nav(`/project/${affectedFlowsheetId}/flowsheet`);
        }}
        onRepairAutomatically={() =>
          handleCopyProject(true, copyFailure?.includeScenarioResults ?? false)
        }
      />
      {copyConfirmation && (
        <DuplicateWithResultsDialog
          name={projectCardInfo.name}
          scope="project"
          summary={copyConfirmation}
          isDuplicating={copyProjectResult.isLoading}
          onCancel={() => setCopyConfirmation(null)}
          onConfirm={(includeScenarioResults) =>
            handleCopyProject(false, includeScenarioResults)
          }
        />
      )}
    </>
  );
}
 
export default EllipsisMenu;