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

59.42% Statements 104/175
46.92% Branches 84/179
30.76% Functions 8/26
62.18% Lines 74/119

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                                                                                                      103x   1687x     1250x   1250x     1250x         437x                   4248x       1250x 437x 2937x   2561x     632x                   632x         632x   1896x     2528x         437x 6x     431x   431x   1293x       1250x             1250x                 866x 1687x 1687x 1250x 1250x 1250x 1250x 437x   1250x 1250x 2124x   1687x 641x               4455x     1687x 632x       3146x 2514x         2124x 1687x 437x   1250x   1687x 2124x 2561x 437x               1687x 2124x 2514x 8774x                                                                                                                                     437x 255x   255x   1250x         1250x 1250x               1250x 1250x               344x   344x           433x   255x 344x 344x   255x   391x     255x 255x         1250x                       255x                       765x          
import { Star, Users } from "lucide-react";
import { motion } from "motion/react";
import { useEffect } from "react";
import { useDrag } from "react-dnd";
import { getEmptyImage } from "react-dnd-html5-backend";
import { Link } from "react-router-dom";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import {
  CardPreview,
  useCoreFlowsheetsCardPreviewsRetrieveQuery,
} from "@/api/apiStore.gen";
import { useUserInfo } from "@/hooks/useUserInfo";
import { cn } from "@/lib/utils";
import EllipsisMenu from "@/pages/main-page/components/EllipsisMenu";
import FlowsheetCardPreview from "@/pages/main-page/components/FlowsheetCardPreview";
import type { ProjectCardData } from "@/pages/main-page/components/projectCardData";
import {
  type MoveProject,
  PROJECT_CARD_DRAG_TYPE,
  type ProjectCardDragItem,
  type ProjectViewMode,
} from "@/pages/main-page/project-folders/model";
import {
  Card,
  CardContent,
  CardFooter,
} from "../../../ahuora-design-system/ui/card";
 
type MainPageGalleryProps = {
  data: ProjectCardData[];
  viewMode: ProjectViewMode;
  onMoveProject?: MoveProject;
  pendingProjectMoveIds?: ReadonlySet<number>;
};
 
type CardInfo = {
  data: ProjectCardData;
  date: string;
  dateText: string;
  isShared: boolean;
};
 
type CardProps = {
  info: CardInfo;
  preview?: CardPreview;
  isPreviewLoading?: boolean;
  onMoveProject?: MoveProject;
  isMovePending?: boolean;
};
 
const MotionCard = motion.create(Card);
 
function useProjectCardDrag(
  project: ProjectCardData,
  onMoveProject: CardProps["onMoveProject"],
  isMovePending = false,
) {
  const canDrag = Boolean(
    onMoveProject && project.type === "project" && !isMovePending,
  );
  const [{ isDragging }, drag, preview] = useDrag<
    ProjectCardDragItem,
    unknown,
    { isDragging: boolean }
  >(
    () => ({
      type: PROJECT_CARD_DRAG_TYPE,
      item: {
        projectId: project.id,
        projectName: project.name,
        folderId: project.folderId ?? null,
      },
      canDrag,
      collect: (monitor) => ({ isDragging: monitor.isDragging() }),
    }),
    [canDrag, project.folderId, project.id, project.name],
  );
 
  // React DnD's custom layer replaces the browser's full-card drag ghost.
  useEffect(() => {
    preview(getEmptyImage(), { captureDraggingState: true });
  }, [preview]);
 
  return { canDrag, drag, isDragging };
}
 
function ProjectCardMenu({
  project,
  onMoveProject,
  isMovePending,
}: {
  project: ProjectCardData;
  onMoveProject?: MoveProject;
  isMovePending?: boolean;
}) {
  return (
    <div className="relative z-10">
      <EllipsisMenu
        projectCardInfo={project}
        isMovePending={isMovePending}
        onMoveToFolder={
          onMoveProject
            ? (folderId) => onMoveProject(project.id, folderId)
            : undefined
        }
      />
    </div>
  );
}
 
/** Provides native browser link behavior without nesting the card menu in a link. */
function ProjectCardLink({ project }: { project: ProjectCardData }) {
  Iif (!project.href) return null;
 
  return (
    <Link
      to={project.href}
      aria-label={`Open project ${project.name}`}
      className="absolute inset-0 z-[1] rounded-[inherit]"
    />
  );
}
 
const GridCard = ({
  info,
  preview,
  isPreviewLoading,
  onMoveProject,
  isMovePending,
}: CardProps) => {
  const { canDrag, drag, isDragging } = useProjectCardDrag(
    info.data,
    onMoveProject,
    isMovePending,
  );
 
  return (
    <MotionCard
      ref={(element) => {
        drag(element);
      }}
      onClick={info.data.href ? undefined : () => info.data.onClick?.()}
      aria-label={"Grid Card " + info.data.name}
      aria-busy={isMovePending || undefined}
      title={canDrag ? "Drag to move to a folder" : undefined}
      whileTap={{ scale: 0.97 }}
      className={cn(
        "relative cursor-pointer transition-[opacity,box-shadow]",
        canDrag && "cursor-grab active:cursor-grabbing",
        isDragging && "opacity-40 shadow-lg ring-1 ring-primary/30",
      )}
    >
      <ProjectCardLink project={info.data} />
      <CardContent>
        <FlowsheetCardPreview
          flowsheetId={info.data.defaultFlowsheetId}
          rootGrouping={info.data.rootGrouping}
          name={info.data.name}
          preview={preview}
          isLoading={isPreviewLoading}
        />
      </CardContent>
      <CardFooter className="flex flex-col gap-3 mt-1">
        <div className="flex flex-row items-center justify-between">
          <p className="line-clamp-2">{info.data.name}</p>
          <ProjectCardMenu
            project={info.data}
            onMoveProject={onMoveProject}
            isMovePending={isMovePending}
          />
        </div>
        <div className="flex flex-col justify-between items-start flex-wrap gap-3">
          <div className="flex flex-row gap-3">
            <p className="font-light text-xs">
              {info.dateText} {info.date}
            </p>
            {info.data.isStarred && <Star />}
            <ToolTipCover
              asChild
              content={`Shared by ${info.data.owner.email}`}
            >
              {info.isShared && <Users />}
            </ToolTipCover>
          </div>
          {info.data.badges?.map((badgeItem) => (
            <Badge
              key={badgeItem}
              variant="secondary"
              className="flex flex-row items-center font-light rounded-xl px-5"
            >
              {badgeItem}
            </Badge>
          ))}
        </div>
      </CardFooter>
    </MotionCard>
  );
};
 
const ListCard = ({ info, onMoveProject, isMovePending }: CardProps) => {
  const { canDrag, drag, isDragging } = useProjectCardDrag(
    info.data,
    onMoveProject,
    isMovePending,
  );
 
  return (
    <MotionCard
      ref={(element) => {
        drag(element);
      }}
      onClick={info.data.href ? undefined : () => info.data.onClick?.()}
      aria-label={"List Card " + info.data.name}
      aria-busy={isMovePending || undefined}
      title={canDrag ? "Drag to move to a folder" : undefined}
      variant="list"
      whileHover={{ scale: 1.01 }}
      whileTap={{ scale: 0.97 }}
      className={cn(
        "relative cursor-pointer transition-[opacity,box-shadow]",
        canDrag && "cursor-grab active:cursor-grabbing",
        isDragging && "opacity-40 shadow-lg ring-1 ring-primary/30",
      )}
    >
      <ProjectCardLink project={info.data} />
      <CardFooter className="flex flex-col gap-3 ml-2 mt-1">
        <div className="flex flex-row items-center justify-between">
          <div>
            <p className="line-clamp-2 mb-3">{info.data.name}</p>
            <div className="flex flex-row gap-5">
              <p className="flex flex-row items-center gap-1 font-light text-xs">
                {info.dateText} {info.date}
              </p>
              {info.data.isStarred && <Star />}
              <ToolTipCover
                asChild
                content={`Shared by ${info.data.owner.email}`}
              >
                {info.isShared && <Users />}
              </ToolTipCover>
              {info.data.badges?.map((badgeItem) => (
                <Badge
                  key={badgeItem}
                  variant="secondary"
                  className="flex flex-row items-center font-light rounded-xl px-5"
                >
                  {badgeItem}
                </Badge>
              ))}
            </div>
          </div>
          <ProjectCardMenu
            project={info.data}
            onMoveProject={onMoveProject}
            isMovePending={isMovePending}
          />
        </div>
      </CardFooter>
    </MotionCard>
  );
};
 
const CardGallery = (props: MainPageGalleryProps) => {
  const { data: userInfo } = useUserInfo();
 
  const cardData: CardInfo[] = props.data.map((info: ProjectCardData) => {
    const dateText =
      info.type === "template"
        ? "Created"
        : info.isBinned
          ? "Binned"
          : "Opened";
    const binnedDate = new Date(info.binnedAt!).getTime();
    const binnedDateAsString = new Date(binnedDate).toLocaleDateString(
      "en-GB",
      {
        year: "numeric",
        month: "short",
        day: "numeric",
      },
    );
    const date = info.isBinned ? binnedDateAsString : info.description;
    const isShared = userInfo?.id !== info.owner.id;
 
    return {
      data: info,
      date: date,
      dateText: dateText,
      isShared: isShared,
    };
  });
  const previewFlowsheetIds =
    props.viewMode === "grid"
      ? props.data
          .map((info) => info.defaultFlowsheetId)
          .filter((id): id is number => typeof id === "number")
          .sort((a, b) => a - b)
          .join(",")
      : "";
  const { data: cardPreviews, isFetching: isPreviewLoading } =
    useCoreFlowsheetsCardPreviewsRetrieveQuery(
      { flowsheets: previewFlowsheetIds },
      { skip: previewFlowsheetIds.length === 0 },
    );
  const previewsByFlowsheet = new Map(
    cardPreviews?.previews.map((preview) => [preview.flowsheet, preview]) ?? [],
  );
 
  return (
    <>
      {props.viewMode === "grid" && (
        <div
          className={`w-full grid grid-cols-1 mb-56 gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 `}
        >
          {cardData.map((info: CardInfo) => (
            <GridCard
              key={info.data.id}
              info={info}
              preview={previewsByFlowsheet.get(info.data.defaultFlowsheetId)}
              isPreviewLoading={isPreviewLoading}
              onMoveProject={props.onMoveProject}
              isMovePending={props.pendingProjectMoveIds?.has(info.data.id)}
            />
          ))}
        </div>
      )}
 
      {props.viewMode === "list" && (
        <div className="grid grid-rows-1">
          {cardData.map((info: CardInfo, index: number) => (
            <ListCard
              key={index}
              info={info}
              onMoveProject={props.onMoveProject}
              isMovePending={props.pendingProjectMoveIds?.has(info.data.id)}
            />
          ))}
        </div>
      )}
    </>
  );
};
 
export default CardGallery;