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

65.95% Statements 31/47
79.31% Branches 23/29
75% Functions 3/4
68.88% Lines 31/45

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                                                                            9091x 9091x 9091x 9091x 9091x 9091x 9091x 9091x   9091x 9091x     9091x   9091x   9091x         9091x 127x         2x     2x                     2x     2x                     2x       2x                             2x         2x           2x                     2x     2x                             9091x   9091x             4x                                                                                                                 1x                                                                                                             4x                                          
// removed Popover usage for IDAES export (now a command/dialog)
import { ArrowLeft, BellMinus, Lock, Redo, Undo } from "lucide-react";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { useLocalStorage } from "usehooks-ts";
import { AhuoraLogo } from "@/ahuora-design-system/componentIcons/AhuoraLogo";
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 { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import {
  api,
  FlowsheetTemplateTypeEnum,
  useCoreFlowsheetsPartialUpdateMutation,
} from "@/api/apiStore.gen";
import { useFlowsheetAccess } from "@/hooks/flowsheetAccess";
import { useProject, useProjectId } from "@/hooks/project";
import { useSearchParam } from "@/hooks/searchParams";
import { useUndoRedoStore } from "@/hooks/useUndoRedoStore";
import { useUserInfo } from "@/hooks/useUserInfo";
import ExportToIDAESCommand from "@/pages/flowsheet-page/export/ExportToIDAESCommand";
import { FeedbackForm } from "@/pages/flowsheet-page/menuBar/FeedbackForm.tsx";
import TemplateCommands from "@/pages/flowsheet-page/menuBar/TemplateCommands";
import { NavTabParams } from "@/pages/main-page/components/MainPageNavTabDefinitions";
import { useAppDispatch } from "@/store/hooks";
import { CommandPalette } from "../../../commands/CommandPalette";
import AddUnitOpButton from "../flowsheet/AddUnitOpButton";
import {
  CONTENT_MAP,
  ContentTypes,
  ViewTypes,
} from "../flowsheet/LeftSideBar/LeftSideBarTabDefinitions";
import Pointers from "./Pointers";
import ShareFlowsheet from "./ShareFlowsheet";
import { SyncIndicator } from "./SyncIndicator";
 
function MenuBar() {
  const nav = useNavigate();
  const project = useProject();
  const access = useFlowsheetAccess();
  const flowsheetId = useProjectId();
  const dispatch = useAppDispatch();
  const [updateProject] = useCoreFlowsheetsPartialUpdateMutation();
  const { data: userInfo } = useUserInfo();
  const [page, setPage] = useSearchParam("content", ContentTypes.unitOps);
  // Removed inline template handlers and createTemplate usage
  const [toastId, setToastId] = useState<string | number | null>(null);
  const [currentPage] = useLocalStorage("current-page", NavTabParams.home);
  // Use new external store-based undo/redo system
  const { executeUndo, executeRedo, canUndo, canRedo, isReady } =
    useUndoRedoStore();
 
  const canEdit = access?.can_edit ?? true;
  const showShareButton =
    access?.can_share ??
    (project?.flowsheet_template_type ==
      FlowsheetTemplateTypeEnum.NotTemplate &&
      project.owner.id === userInfo?.id);
 
  useEffect(() => {
    document.title = `${project?.name || "Untitled"} - Ahuora`;
  }, [project?.name]);
 
  // Handle undo/redo operations with proper error handling
  const handleUndo = async () => {
    Iif (!canUndo) return;
 
    try {
      const success = await executeUndo();
      if (!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();
      if (!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();
 
    if (isNameInvalid(name)) {
      if (toastId) {
        toast.dismiss(toastId);
      }
      const id = toast.error("Invalid name submission.", {
        richColors: true,
        description: "Name cannot be empty.",
      });
      setToastId(id);
      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(() => {
        if (toastId) {
          toast.dismiss(toastId);
        }
        const id = toast.success(
          `Successfully updated project name to ${name}`,
        );
        setToastId(id);
      })
      .catch((error) => {
        if (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);
      });
  };
 
  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("/" + currentPage);
              }}
              size="icon"
              variant="ghost"
              aria-label="Ahuora-Logo"
              className="shadow-none my-auto"
            >
              <AhuoraLogo />
            </Button>
 
            <div className="flex-1 flex items-center">
              {canEdit ? (
                <AutoSelectInput
                  value={project?.name || "Untitled"}
                  onUpdateValue={changeProjectName}
                  aria-label="Project name"
                  textSize="text-sm"
                />
              ) : (
                <div
                  aria-label="Project name"
                  className="flex items-center gap-2 truncate"
                >
                  <span className="truncate font-medium text-sm text-foreground">
                    {project?.name || "Untitled"}
                  </span>
                </div>
              )}
              {access?.read_only && (
                <Badge
                  variant="secondary"
                  size="xs"
                  borderRadius="round"
                  className="ml-4 gap-1"
                  aria-label="flowsheet-read-only-indicator"
                >
                  <Lock size={12} />
                  Read only
                </Badge>
              )}
            </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 && (
              <div className="ml-4 flex items-center">
                <Pointers />
                <div className="flex flex-row items-center">
                  <ToolTipCover asChild content="Undo (⌘Z)">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleUndo}
                      disabled={!canUndo || !isReady || !canEdit}
                      aria-label="Undo"
                    >
                      <Undo className="icon-medium" />
                    </Button>
                  </ToolTipCover>
 
                  <ToolTipCover asChild content="Redo (⌘⇧Z)">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleRedo}
                      disabled={!canRedo || !isReady || !canEdit}
                      aria-label="Redo"
                    >
                      <Redo className="icon-medium" />
                    </Button>
                  </ToolTipCover>
                  <AddUnitOpButton />
                </div>
              </div>
            )}
          </div>
        </div>
        {/* 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">
          <SyncIndicator />
          <ToolTipCover content="Dismiss Notifications" asChild>
            <Button
              size="icon"
              variant="ghost"
              aria-label="Dismiss Notifications"
              onClick={() => {
                toast.dismiss();
              }}
              className="w-fit"
            >
              <BellMinus
                size={18}
                color="primary" // Invisible button - only needed for the playwright tests.
              />
            </Button>
          </ToolTipCover>
 
          <TemplateCommands />
          <ExportToIDAESCommand />
          <FeedbackForm />
          {showShareButton && <ShareFlowsheet />}
        </div>
      </nav>
    </>
  );
}
export { MenuBar };