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

69.11% Statements 94/136
53.65% Branches 88/164
26.31% Functions 5/19
80.21% Lines 73/91

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                                                                103x               7x       6x 6x     96x           96x               192x         18x         14x 14x 14x 14x 14x       14x   14x 14x       14x 14x         14x     14x     14x 14x   21x           14x 35x 21x     14x           21x 14x 1x     1x 1x 1x               28x   10x 6x           17x 10x             17x 10x       18x 1x     22x 34x 14x 6x                       1x   122x 14x 14x 14x     14x     14x     9x 7x 7x   28x 21x   21x   7x       14x       7x 21x     7x       21x 35x 21x 7x                                                 42x 35x 28x                                                                                   122x 41x      
import { Filter, Grid2x2, List } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { useLocalStorage } from "usehooks-ts";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
import { ScrollArea } from "@/ahuora-design-system/ui/scroll-area";
import SortDropdown from "@/ahuora-design-system/ui/sort-dropdown";
import {
  FlowsheetRead,
  FlowsheetTemplateTypeEnum,
  ProjectRead,
  useCoreProjectsListQuery,
} from "@/api/apiStore.gen";
import { useCreateFromTemplate, useTemplates } from "@/hooks/useTemplate";
import { useUserInfo } from "@/hooks/useUserInfo";
import type { ProjectViewMode } from "../project-folders/model";
import { OwnedProjectsWorkspace } from "../project-folders/OwnedProjectsWorkspace";
import CardGallery from "./CardGallery";
import { MainPageContents } from "./MainPageContentDefinitions";
import { PROJECTS_PER_PAGE, ProjectPagination } from "./ProjectPagination";
import { buildProjectCardData, type ProjectCardData } from "./projectCardData";
 
const ORDERING_BY_SORT = {
  "Recently Added": "recently_added",
  "Recently Binned": "recently_binned",
  "Recently Edited": "recently_edited",
  "A-Z": "name",
} as const;
 
function projectQueryForPage(currentPageName: string) {
  if (currentPageName === "sharedWithMe") return { type: "shared" };
  if (currentPageName === "starred") {
    return { type: "all", isStarred: true, isBinned: false };
  }
  Iif (currentPageName === "binned") return { type: "all", isBinned: true };
  return { type: "all" };
}
 
export function MainPageContent({
  currentPageName,
}: {
  currentPageName: string;
}) {
  return (
    <ScrollArea className="w-full h-screen overflow-x-hidden">
      <section className="ml-[20%] h-full flex flex-col px-[5%] py-4 gap-5">
        {currentPageName === "home" ? (
          <OwnedProjectsWorkspace />
        ) : (
          <GeneralMainPageContent currentPageName={currentPageName} />
        )}
      </section>
    </ScrollArea>
  );
}
 
/** Render non-folder collections against the paginated project API. */
function GeneralMainPageContent({
  currentPageName,
}: {
  currentPageName: string;
}) {
  const nav = useNavigate();
  const { data: userInfo } = useUserInfo();
  const { templates } = useTemplates();
  const { createFromTemplate } = useCreateFromTemplate();
  const [viewMode, setViewMode] = useLocalStorage<ProjectViewMode>(
    "page-view-mode",
    "grid",
  );
  const [pageByCollection, setPageByCollection] = useState<
    Record<string, number>
  >({});
  const [templateFilter, setTemplateFilter] = useLocalStorage(
    "template-current-filter",
    "All",
  );
  const config = MainPageContents[currentPageName];
  const [sortOrder] = useLocalStorage(
    config.sortStorageKey,
    config.sortStorageValue,
  );
  const ordering =
    ORDERING_BY_SORT[sortOrder as keyof typeof ORDERING_BY_SORT] ??
    "recently_edited";
  const pageKey =
    currentPageName === "templates"
      ? `${currentPageName}:${ordering}:${templateFilter}`
      : `${currentPageName}:${ordering}`;
  const currentPage = pageByCollection[pageKey] ?? 1;
  const setCurrentPage = (page: number) => {
    setPageByCollection((pages) => ({ ...pages, [pageKey]: page }));
  };
  const {
    currentData: projectResponse,
    isError: isProjectError,
    isFetching: isProjectFetching,
    refetch: refetchProjects,
  } = useCoreProjectsListQuery(
    { ...projectQueryForPage(currentPageName), ordering, page: currentPage },
    { skip: currentPageName === "templates" },
  );
 
  const openProject = (project: ProjectRead) => {
    if (project.active_flowsheet) {
      nav(`/project/${project.active_flowsheet}/flowsheet`);
    } else {
      toast.error("Project has no default flowsheet.");
    }
  };
  const createFromSelectedTemplate = (templateId: number) => {
    createFromTemplate(templateId)
      .unwrap()
      .then((result) => {
        const created = result as FlowsheetRead;
        toast.success("Project created from template successfully!");
        nav(`/project/${created.id}/flowsheet`);
      })
      .catch((error) => {
        toast.error(
          "Failed to create project from template: " +
            (error.data?.detail || error.message),
        );
      });
  };
 
  const filteredTemplates = (templates ?? []).filter((template) => {
    Iif (templateFilter === "All") return true;
    const expectedType =
      templateFilter === "Public"
        ? FlowsheetTemplateTypeEnum.PublicTemplate
        : FlowsheetTemplateTypeEnum.PrivateTemplate;
    return template.flowsheet_template_type === expectedType;
  });
  const sortedTemplates = [...filteredTemplates].sort((left, right) => {
    Iif (sortOrder === "A-Z")
      return (left.name ?? "").localeCompare(right.name ?? "");
    return (
      new Date(right.created_at ?? 0).getTime() -
      new Date(left.created_at ?? 0).getTime()
    );
  });
  const templatePage = sortedTemplates.slice(
    (currentPage - 1) * PROJECTS_PER_PAGE,
    currentPage * PROJECTS_PER_PAGE,
  );
  const projectCards = (projectResponse?.results ?? []).map((project) =>
    buildProjectCardData(project, {
      type: config.type,
      onMissingFlowsheet: () => openProject(project),
    }),
  );
  const templateCards = templatePage.map<ProjectCardData>((template) => {
    const timestamp = new Date(template.created_at!).getTime();
    return {
      id: template.id,
      defaultFlowsheetId: template.id,
      owner: template.owner,
      name: template.name!,
      type: config.type,
      description: new Date(timestamp).toLocaleDateString("en-GB", {
        year: "numeric",
        month: "short",
        day: "numeric",
      }),
      onClick: () => createFromSelectedTemplate(template.id),
    } as ProjectCardData;
  });
  const isTemplatePage = currentPageName === "templates";
  const cards = isTemplatePage ? templateCards : projectCards;
  const total = isTemplatePage
    ? filteredTemplates.length
    : (projectResponse?.count ?? 0);
  const pageCount = isTemplatePage
    ? Math.max(1, Math.ceil(total / PROJECTS_PER_PAGE))
    : (projectResponse?.pages ?? 1);
  const activePage = Math.min(currentPage, pageCount);
 
  return (
    <>
      <h1 className="text-3xl mt-16">
        {typeof config.mainTitle === "function"
          ? config.mainTitle(userInfo?.name)
          : config.mainTitle}
      </h1>
      <div className="sticky top-0 z-20 -mx-[5%] flex items-center justify-between bg-background px-[5%] py-4">
        <h1 className="text-xl">{config.subTitle}</h1>
        <div className="flex gap-3">
          <Button
            variant="tertiary"
            size="navIcon"
            aria-label={
              viewMode === "grid"
                ? "Switch to list view"
                : "Switch to grid view"
            }
            onClick={() =>
              setViewMode((mode) => (mode === "grid" ? "list" : "grid"))
            }
          >
            {viewMode === "grid" ? (
              <List className="icon-large" />
            ) : (
              <Grid2x2 className="icon-large" />
            )}
          </Button>
          <SortDropdown currentContent={config} />
          {isTemplatePage && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild aria-label="main-content-sort">
                <Button variant="tertiary" size="navIcon">
                  <Filter className="icon-large" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
                <DropdownMenuLabel>Filter by</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuRadioGroup
                  value={templateFilter}
                  onValueChange={(value) => {
                    setCurrentPage(1);
                    setTemplateFilter(value);
                  }}
                >
                  {["All", "Public", "Private"].map((filter) => (
                    <DropdownMenuRadioItem key={filter} value={filter}>
                      <span className="capitalize">{filter}</span>
                    </DropdownMenuRadioItem>
                  ))}
                </DropdownMenuRadioGroup>
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>
      </div>
      {!isTemplatePage && isProjectError ? (
        <div
          role="alert"
          className="flex items-center justify-between gap-4 rounded-md border border-border bg-muted/30 px-4 py-3"
        >
          <p className="text-sm text-muted-foreground">
            Projects could not be loaded.
          </p>
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={refetchProjects}
          >
            Retry
          </Button>
        </div>
      ) : !isTemplatePage && isProjectFetching && !projectResponse ? (
        <p role="status" className="text-sm text-muted-foreground">
          Loading projects...
        </p>
      ) : cards.length === 0 ? (
        <p className="mt-5 italic text-muted-foreground">
          {config.emptyString}
        </p>
      ) : (
        <div className="mt-5 flex flex-col gap-5">
          <CardGallery data={cards} viewMode={viewMode} />
          <ProjectPagination
            currentPage={activePage}
            pageCount={pageCount}
            totalProjects={total}
            currentPageSize={cards.length}
            pageSize={
              isTemplatePage
                ? PROJECTS_PER_PAGE
                : (projectResponse?.page_size ?? PROJECTS_PER_PAGE)
            }
            onPageChange={setCurrentPage}
          />
        </div>
      )}
    </>
  );
}