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

62.9% Statements 78/124
65.51% Branches 57/87
27.27% Functions 6/22
71.59% Lines 63/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                                                                          415x         367x 367x 367x 367x 444x 367x 367x 367x 367x 367x   367x   367x         367x         367x   444x   367x 63x         63x   521x   367x 1x     1x 1x 1x               521x   228x       228x 10x                             6x   1x               222x     3x           415x 415x             5x     5x 415x                                 4x               228x                     222x 222x               228x       2786x   228x   141x 141x   790x 508x   444x   77x                           521x   444x 444x 598x 444x 77x                                                       598x 675x 521x 228x               1279x   1051x      
import { Filter, Grid2x2, List, Plus } from "lucide-react";
import { motion } from "motion/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 {
  FlowsheetRead,
  FlowsheetTemplateTypeEnum,
  useCoreFlowsheetsCreateMutation,
  useCoreFlowsheetsListQuery,
} from "@/api/apiStore.gen";
import { useCreateFromTemplate, useTemplates } from "@/hooks/useTemplate";
import { useUserInfo } from "@/hooks/useUserInfo";
import CardGallery, {
  FlowsheetCardData,
} from "@/pages/main-page/components/CardGallery";
import SortDropdown from "../../../ahuora-design-system/ui/sort-dropdown";
import { MainPageContents } from "./MainPageContentDefinitions";
 
type FlowsheetsData = {
  timestamp: number; // used to sort the flowsheets
  createdAt: number; // used to sort the flowsheets by creation date
  flowsheetCardData: FlowsheetCardData;
};
 
export function MainPageContent({
  currentPageName,
}: {
  currentPageName: string;
}) {
  const nav = useNavigate();
  const [createFlowsheet] = useCoreFlowsheetsCreateMutation();
  const [type, setType] = useState("all");
  const { data: userInfo } = useUserInfo();
  const { data: flowsheets } = useCoreFlowsheetsListQuery({ type: type });
  const { templates, isLoading, error } = useTemplates();
  const { createFromTemplate, isLoading: isCreating } = useCreateFromTemplate();
  const [searchFilter, setSearchFilter] = useState("");
  const [viewMode, setViewMode] = useLocalStorage("page-view-mode", "grid");
  const filterByData = ["All", "Public", "Private"];
 
  const mainPageCurrentContent = MainPageContents[currentPageName];
 
  const [sortOrder, setSortOrder] = useLocalStorage(
    mainPageCurrentContent.sortStorageKey,
    mainPageCurrentContent.sortStorageValue,
  );
 
  const [templateFilter, setTemplateFilter] = useLocalStorage(
    "template-current-filter",
    "All",
  );
 
  const toggleViewMode = () => {
    setViewMode((prevMode) => (prevMode === "grid" ? "list" : "grid"));
  };
 
  const handleCreateNewProject = () => {
    createFlowsheet({
      flowsheet: {},
    })
      .unwrap()
      .then((flowsheet: FlowsheetRead) => {
        nav(`/project/${flowsheet.id}/flowsheet`);
      });
  };
 
  const handleCreateFromTemplate = (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 currentContentData: FlowsheetsData[] = (() => {
    let data, onClick, isPublic, isPublicLabel;
 
    const filteredTemplates =
      templates?.filter((t) => {
        Iif (templateFilter === "All") return true;
        Iif (templateFilter === "Public")
          return (
            t.flowsheet_template_type ===
            FlowsheetTemplateTypeEnum.PublicTemplate
          );
        Iif (templateFilter === "Private")
          return (
            t.flowsheet_template_type ===
            FlowsheetTemplateTypeEnum.PrivateTemplate
          );
        return true;
      }) || [];
 
    if (currentPageName === "templates") {
      data = filteredTemplates;
      onClick = (id: number) => {
        handleCreateFromTemplate(id);
      };
    } else {
      if (currentPageName === "sharedWithMe") {
        data = flowsheets?.filter((flowsheet) =>
          mainPageCurrentContent.filter?.(userInfo, flowsheet),
        );
      } else {
        data = flowsheets?.filter(mainPageCurrentContent.filter);
      }
      onClick = (id: number) => {
        nav(`/project/${id.toString()}/flowsheet`);
      };
    }
 
    return (
      data?.map((flowsheet: FlowsheetRead) => {
        const timestamp = new Date(flowsheet.savedDate!).getTime();
        const displayDate = new Date(timestamp).toLocaleDateString("en-GB", {
          year: "numeric",
          month: "short",
          day: "numeric",
        });
 
        if (currentPageName === "templates") {
          isPublic =
            flowsheet.flowsheet_template_type ===
            FlowsheetTemplateTypeEnum.PublicTemplate;
          isPublicLabel = isPublic ? "Public" : "Private";
        }
 
        return {
          timestamp: timestamp,
          createdAt: new Date(flowsheet.created_at!).getTime(),
          flowsheetCardData: {
            id: flowsheet.id,
            owner: flowsheet.owner,
            name: flowsheet.name!,
            type: mainPageCurrentContent.type,
            imgUrl: "/assets/example-flowsheet.png",
            description: displayDate,
            badges: isPublicLabel ? [isPublicLabel] : [],
            editDate: timestamp,
            binnedAt: flowsheet.binned_at,
            isStarred: flowsheet.is_starred,
            isBinned: flowsheet.is_binned,
            onClick: () => onClick?.(flowsheet.id),
          },
        };
      }) ?? []
    );
  })();
 
  const getSortedData = () => {
    const sortedData = [...currentContentData];
    switch (sortOrder) {
      case "Recently Added":
        sortedData.sort((a, b) => b.createdAt - a.createdAt);
        break;
      case "Recently Binned":
        sortedData.sort(
          (a, b) => b.flowsheetCardData.binnedAt - a.flowsheetCardData.binnedAt,
        );
        break;
      case "Recently Edited":
        sortedData.sort((a, b) => b.timestamp - a.timestamp);
        break;
      case "A-Z":
        sortedData.sort((a, b) =>
          a.flowsheetCardData.name.localeCompare(b.flowsheetCardData.name),
        );
        break;
      default:
        break;
    }
    return sortedData.map((flowsheet) => flowsheet.flowsheetCardData);
  };
 
  const sortedData = getSortedData();
  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">
        <h1 className="text-3xl mt-16">
          {currentPageName === "home"
            ? mainPageCurrentContent.mainTitle?.(userInfo?.name)
            : mainPageCurrentContent.mainTitle}
        </h1>
        <div className="sticky bg-background flex top-0 justify-between items-center w-full py-4">
          <h1 className="text-xl">{mainPageCurrentContent.subTitle}</h1>
          <div className="flex gap-3">
            {currentPageName === "home" && (
              <Button asChild>
                <motion.button
                  type="button"
                  onClick={handleCreateNewProject}
                  aria-label="Create a new Project"
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  className="gap-2"
                >
                  <Plus className="icon-small" />
                  New Project
                </motion.button>
              </Button>
            )}
            <Button variant="tertiary" size="navIcon" onClick={toggleViewMode}>
              {viewMode === "grid" && <List className="icon-large" />}
              {viewMode === "list" && <Grid2x2 className="icon-large" />}
            </Button>
            <SortDropdown currentContent={mainPageCurrentContent} />
            {currentPageName === "templates" && (
              <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) => {
                      setTemplateFilter(value);
                    }}
                  >
                    {filterByData?.map((filterData) => (
                      <DropdownMenuRadioItem
                        key={filterData}
                        value={filterData}
                        className=""
                      >
                        <span className="capitalize">{filterData}</span>
                      </DropdownMenuRadioItem>
                    ))}
                  </DropdownMenuRadioGroup>
                </DropdownMenuContent>
              </DropdownMenu>
            )}
          </div>
        </div>
        <div className="">
          {currentContentData.length === 0 ? (
            <p className="italic text-foreground">
              {mainPageCurrentContent.emptyString}
            </p>
          ) : (
            <CardGallery data={sortedData} viewMode={viewMode} />
          )}
        </div>
      </section>
    </ScrollArea>
  );
}