All files / src/pages/flowsheet-page/menuBar MenuBar.tsx

56.98% Statements 53/93
63.82% Branches 30/47
80% Functions 12/15
60.22% Lines 53/88

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 421 422 423 424 425                                                                                                              1853x 1853x 1853x 1853x 1853x 1853x 1853x 1853x       1853x   1853x 1853x 1853x 1853x     1853x     1853x 1853x       1853x         1853x 71x       1853x             1853x 1x 1x       1x                           1853x                             1853x 2x   2x 2x 2x                 1853x 2x   2x 2x 2x                 1853x 2x     1853x 2x   2x                             2x         2x           2x               2x     2x     2x 2x 2x                                 1853x   1853x             4x                                                                   1x                                                                                                             4x                                                                                                                                                                                                    
import { AhuoraLogo } from "@/ahuora-design-system/componentIcons/AhuoraLogo";
import { AutoSelectInput } from "@/ahuora-design-system/ui/auto-select-input";
import { Button } from "@/ahuora-design-system/ui/button";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
import {
  api,
  FlowsheetTemplateTypeEnum,
  useCoreFlowsheetsPartialUpdateMutation,
} from "@/api/apiStore.gen";
import { useProject, useProjectId } from "@/hooks/project";
import { useSearchParam } from "@/hooks/searchParams";
import { useUndoRedoStore } from "@/hooks/useUndoRedoStore";
import { useCreateTemplate } from "@/hooks/useTemplate";
import { useAppDispatch } from "@/store/hooks";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@radix-ui/react-popover";
import {
  ArrowLeft,
  BellMinus,
  BookDown,
  Globe,
  Lock,
  Package,
  Redo,
  Undo,
} from "lucide-react";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { CommandPalette } from "../../../commands/CommandPalette";
import GenerateIDAESPython from "../export/ExportIDAES";
import Pointers from "./Pointers";
import { CircleUserRound } from 'lucide-react';
 
 
import AddUnitOpButton from "../flowsheet/AddUnitOpButton";
import {
  CONTENT_MAP,
  ContentTypes,
  ViewTypes,
} from "../flowsheet/LeftSideBar/LeftSideBarTabDefinitions";
import ShareFlowsheet from "./ShareFlowsheet";
import { useUserInfo } from "@/hooks/useUserInfo";
import {FeedbackForm} from "@/pages/flowsheet-page/menuBar/FeedbackForm.tsx";
 
function MenuBar() {
  const nav = useNavigate();
  const project = useProject();
  const flowsheetId = useProjectId();
  const dispatch = useAppDispatch();
  const [updateProject] = useCoreFlowsheetsPartialUpdateMutation();
  const { data: userInfo } = useUserInfo();
  const [page, setPage] = useSearchParam("content", ContentTypes.unitOps);
  const { createTemplate } = useCreateTemplate();
 
  // Use new external store-based undo/redo system
  const { executeUndo, executeRedo, canUndo, canRedo, isReady } =
    useUndoRedoStore();
 
  const [isEditing, setIsEditing] = useState(false);
  const [prevName, setPrevName] = useState(project?.name);
  const [displayValue, setDisplayValue] = useState(project?.name);
  const [toastId, setToastId] = useState<string | number | null>(null);
 
  const showShareButton =
    project?.flowsheet_template_type == FlowsheetTemplateTypeEnum.NotTemplate &&
    project?.owner === userInfo?.id;
 
  const templateType = project?.flowsheet_template_type;
  const isAdmin = !!userInfo?.is_admin;
 
  // Show template options to everyone for NotTemplate, only to admins otherwise
  const showTemplateOptions =
    templateType === FlowsheetTemplateTypeEnum.NotTemplate ||
    (isAdmin &&
      (templateType === FlowsheetTemplateTypeEnum.PublicTemplate ||
        templateType === FlowsheetTemplateTypeEnum.PrivateTemplate));
 
  useEffect(() => {
    document.title = `${project?.name || "Untitled"} - Ahuora`;
  }, [project?.name]);
 
  // Template handlers
  const getErrorMessage = (error: any, defaultMessage: string): string => {
    Iif (error?.data?.error) return error.data.error;
    Iif (error?.message) return error.message;
    Iif (typeof error === 'string') return error;
    return defaultMessage;
  };
 
  const handleCreatePublicTemplate = async () => {
    try {
      await createTemplate(
        flowsheetId,
        FlowsheetTemplateTypeEnum.PublicTemplate,
      );
      toast.success("Successfully converted to public template!");
    } catch (error: any) {
      const message = getErrorMessage(error, "Failed to create public template");
      
      // Special handling for permission errors
      if (error?.status === 403) {
        toast.error("You do not have permission to create public templates");
      } else {
        toast.error(message);
      }
      console.error("Template creation error:", error);
    }
  };
 
  const handleCreatePrivateTemplate = async () => {
    try {
      await createTemplate(
        flowsheetId,
        FlowsheetTemplateTypeEnum.PrivateTemplate,
      );
      toast.success("Successfully converted to private template!");
    } catch (error: any) {
      const message = getErrorMessage(error, "Failed to create private template");
      toast.error(message);
      console.error("Template creation error:", error);
    }
  };
 
  // Handle undo/redo operations with proper error handling
  const handleUndo = async () => {
    Iif (!canUndo) return;
 
    try {
      const success = await executeUndo();
      Iif (!success) {
        toast.error("Failed to undo operation");
      }
    } catch (error) {
      console.error("[MenuBar] Undo failed:", error);
      toast.error("Failed to undo operation");
    }
  };
 
  const handleRedo = async () => {
    Iif (!canRedo) return;
 
    try {
      const success = await executeRedo();
      Iif (!success) {
        toast.error("Failed to redo operation");
      }
    } catch (error) {
      console.error("[MenuBar] Redo failed:", error);
      toast.error("Failed to redo operation");
    }
  };
 
  const isNameInvalid = (value: string) => {
    return value.trim() === "";
  };
 
  const changeProjectName = (update: string) => {
    const name = update.trim();
 
    Iif (isNameInvalid(name)) {
      Iif (toastId) {
        toast.dismiss(toastId);
      }
      const id = toast.error("Invalid name submission.", {
        richColors: true,
        description: "Name cannot be empty.",
      });
      setToastId(id);
      setDisplayValue(prevName);
      setIsEditing(false);
      return;
    }
 
    // Optimistic update
    dispatch(
      api.util.updateQueryData(
        "coreFlowsheetsRetrieve",
        { id: String(flowsheetId) },
        (prev) => {
          prev.name = name;
        },
      ),
    );
 
    // Backend update
    updateProject({
      id: flowsheetId,
      patchedFlowsheet: {
        name: name,
      },
    })
      .unwrap()
      .then(() => {
        Iif (toastId) {
          toast.dismiss(toastId);
        }
        const id = toast.success(
          `Successfully updated project name to ${name}`,
        );
        setToastId(id);
        setPrevName(name);
        setDisplayValue(name);
      })
      .catch((error) => {
        Iif (toastId) {
          toast.dismiss(toastId);
        }
        const id = toast.error("Failed to update project name.", {
          richColors: true,
          description: error.data?.message || "An unexpected error occurred.",
        });
        setToastId(id);
        setDisplayValue(prevName);
        setIsEditing(false);
      });
  };
 
  const isFlowsheetPage =
    CONTENT_MAP[page as ContentTypes] == ViewTypes.flowsheet;
 
  return (
    <>
      <nav className="flex flex-row justify-center items-center min-h-[40px] px-1 w-full bg-card">
        <div className="flex-1 flex justify-center items-center h-full">
          <div className="mr-auto flex flex-row gap-1 items-center h-full pl-2">
            <Button
              onClick={() => {
                nav("/");
              }}
              size="icon"
              variant="ghost"
              aria-label="Ahuora-Logo"
              className="shadow-none my-auto"
            >
              <AhuoraLogo />
            </Button>
 
            <div className="flex-1 flex items-center">
              <AutoSelectInput
                value={project?.name || "Untitled"}
                onUpdateValue={changeProjectName}
                aria-label="Project name"
                textSize="text-sm"
              />
            </div>
            {/* <div className="flex flex-row">
                            <ToolTipCover content="Settings" asChild>
                                <Button size="icon" variant="disabled">
                                    <Settings className="icon-medium" />
                                </Button>
                            </ToolTipCover>
                            <ToolTipCover content="Comments" asChild>
                                <Button size="icon" variant="disabled">
                                    <MessageSquare className="icon-medium" />
                                </Button>
                            </ToolTipCover>
                        </div> */}
            {!isFlowsheetPage && (
              <Button
                variant="ghost"
                onClick={() => {
                  setPage(ContentTypes.flowsheet);
                }}
              >
                {" "}
                <ArrowLeft />
                Back to Flowsheet
              </Button>
            )}
            {isFlowsheetPage && (
              <>
                <Pointers />
                <div className="flex flex-row items-center">
                  <ToolTipCover asChild content="Undo (⌘Z)">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleUndo}
                      disabled={!canUndo || !isReady}
                      aria-label="Undo"
                    >
                      <Undo className="icon-medium" />
                    </Button>
                  </ToolTipCover>
 
                  <ToolTipCover asChild content="Redo (⌘⇧Z)">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleRedo}
                      disabled={!canRedo || !isReady}
                      aria-label="Redo"
                    >
                      <Redo className="icon-medium" />
                    </Button>
                  </ToolTipCover>
                  <AddUnitOpButton />
                </div>
              </>
            )}
          </div>
        </div>
        {/* TODO: add search bar functionality. Hidden for now */}
        {/* center the search in the center of the navbar regardless of lhs or rhs width */}
        <div className="flex-1 flex justify-center items-center">
          <div className="flex justify-center w-full max-w-[860px]">
            <CommandPalette />
          </div>
        </div>
        <div className="flex-1 flex justify-end items-center gap-5 mr-1">
          <ToolTipCover content="Dismiss Notifications" asChild>
            <Button
              size="icon"
              variant="ghost"
              aria-label="Dismiss Notifications"
              onClick={() => {
                toast.dismiss();
              }}
              className="w-fit"
            >
              <BellMinus size={18} />
            </Button>
          </ToolTipCover>
          {showTemplateOptions && (
            <DropdownMenu>
              <ToolTipCover content="Template Options" asChild>
                <DropdownMenuTrigger asChild>
                  <Button
                    size="icon"
                    variant="ghost"
                    aria-label="Template Options"
                    className="w-fit"
                  >
                    <Package size={18} />
                  </Button>
                </DropdownMenuTrigger>
              </ToolTipCover>
              <DropdownMenuContent align="end">
                {templateType === FlowsheetTemplateTypeEnum.NotTemplate && (
                  <>
                    {isAdmin && (
                      <DropdownMenuItem
                        onClick={handleCreatePublicTemplate}
                        className="flex items-center gap-2"
                      >
                        <Globe size={16} />
                        Make Public Template
                      </DropdownMenuItem>
                    )}
                    <DropdownMenuItem
                      onClick={handleCreatePrivateTemplate}
                      className="flex items-center gap-2"
                    >
                      <Lock size={16} />
                      Make Private Template
                    </DropdownMenuItem>
                  </>
                )}
                {templateType === FlowsheetTemplateTypeEnum.PublicTemplate && isAdmin && (
                  <DropdownMenuItem
                    onClick={handleCreatePrivateTemplate}
                    className="flex items-center gap-2"
                  >
                    <Lock size={16} />
                    Make Private Template
                  </DropdownMenuItem>
                )}
                {templateType === FlowsheetTemplateTypeEnum.PrivateTemplate && isAdmin && (
                  <DropdownMenuItem
                    onClick={handleCreatePublicTemplate}
                    className="flex items-center gap-2"
                  >
                    <Globe size={16} />
                    Make Public Template
                  </DropdownMenuItem>
                )}
              </DropdownMenuContent>
            </DropdownMenu>
          )}
          <Popover>
            <ToolTipCover
              content="Export the project to IDAES Python code"
              asChild
            >
              <PopoverTrigger asChild>
                <Button
                  size="icon"
                  variant="ghost"
                  aria-label="Export-to-IDAES"
                  className="w-fit"
                >
                  <BookDown size={18} />
                </Button>
              </PopoverTrigger>
            </ToolTipCover>
 
            <PopoverContent
              className="w-[800px] z-50 bg-background border rounded-md"
              align="end"
              sideOffset={5}
              aria-label="Export to IDAES"
            >
              <GenerateIDAESPython />
            </PopoverContent>
          </Popover>
          {showShareButton && <ShareFlowsheet />}
          <FeedbackForm/>
         
        </div>
      </nav>
    </>
  );
}
export { MenuBar };