All files / src/pages/main-page/project-folders ProjectFolderControls.tsx

66.01% Statements 136/206
38.42% Branches 78/203
25.92% Functions 7/27
72.15% Lines 114/158

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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496                                                                                      585x         585x 1108x     31x         31x           31x   62x 31x 31x 31x 58x                                                 1x                   5819x 93x 93x 124x                                                                                     597x       597x   597x 597x 597x 597x   597x 8x 8x 8x 8x 597x   597x 4x 4x           4x 4x   4x 4x         2376x       197x   597x     794x 593x   98x 597x       695x   597x 97x       4x 4x 597x       597x 597x 888x 89x               686x 791x 97x 97x     597x       694x 97x 597x 791x 791x   2969x 2388x                   1x     1x   1x 1x 1x 1x 1x 1x           1x 3x 2x   1x 1x 1x   1x 1x 3x 1x   1x   1x 1x 1x 1x 2x   1x   2x     1x               1x               1x 1x 3x 1x 1x 1x   1x         1x     1x                                         2x             2x 1x 1x                                         3x                             6x 1x                 1x                                                                                                             27x                                                               6x 8x 6x 5x      
import {
  ArrowLeft,
  ChevronRight,
  Folder,
  FolderInput,
  FolderPlus,
  Home,
  Search,
} from "lucide-react";
import { type FormEvent, useEffect, useRef, useState } from "react";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/ahuora-design-system/ui/dialog";
import {
  DropdownMenuItem,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
import { Input } from "@/ahuora-design-system/ui/input";
import { Label } from "@/ahuora-design-system/ui/label";
import { useCoreProjectFoldersDestinationsRetrieveQuery } from "@/api/apiStore.gen";
import {
  getParentProjectFolderId,
  getProjectFolderBreadcrumbs,
  type ProjectFolderId,
  type ProjectFolderIndex,
  ROOT_PROJECT_FOLDER_ID,
} from "@/pages/main-page/project-folders/model";
 
type ProjectFolderNavigationProps = {
  currentFolderId: ProjectFolderId;
  folderIndex: ProjectFolderIndex;
  onNavigate: (folderId: ProjectFolderId) => void;
};
 
export function ProjectFolderNavigation({
  currentFolderId,
  folderIndex,
  onNavigate,
}: ProjectFolderNavigationProps) {
  const breadcrumbs = getProjectFolderBreadcrumbs(folderIndex, currentFolderId);
  Iif (currentFolderId === ROOT_PROJECT_FOLDER_ID) return null;
 
  return (
    <div className="flex min-h-9 flex-wrap items-center gap-2">
      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={() =>
          onNavigate(getParentProjectFolderId(folderIndex, currentFolderId))
        }
        aria-label="Back to parent folder"
        className="px-2"
      >
        <ArrowLeft className="icon-small" aria-hidden="true" />
        Back
      </Button>
      <nav aria-label="Project folder path">
        <ol className="flex flex-wrap items-center gap-1 text-sm text-muted-foreground">
          {breadcrumbs.map((breadcrumb, index) => {
            const isCurrent = index === breadcrumbs.length - 1;
            return (
              <li
                key={breadcrumb.id ?? "root"}
                className="flex items-center gap-1"
              >
                {index > 0 && (
                  <ChevronRight
                    className="h-3.5 w-3.5 text-muted-foreground/70"
                    aria-hidden="true"
                  />
                )}
                {isCurrent ? (
                  <span
                    className="px-2 py-1 font-medium text-foreground"
                    aria-current="page"
                  >
                    {breadcrumb.name}
                  </span>
                ) : (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="h-7 px-2 font-normal text-muted-foreground"
                    onClick={() => onNavigate(breadcrumb.id)}
                  >
                    {index === 0 && (
                      <Home className="h-3.5 w-3.5" aria-hidden="true" />
                    )}
                    {breadcrumb.name}
                  </Button>
                )}
              </li>
            );
          })}
        </ol>
      </nav>
    </div>
  );
}
 
type CreateProjectFolderButtonProps = {
  currentFolderId: ProjectFolderId;
  currentFolderLabel: string;
  onCreate: (parentId: ProjectFolderId, name: string) => Promise<void> | void;
  disabled?: boolean;
};
 
function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null;
}
 
/** Map structured API validation fields to stable product copy. */
function getCreateFolderErrorMessage(error: unknown) {
  if (!isRecord(error) || !isRecord(error.data)) {
    return "Could not create the folder. Try again.";
  }
 
  const nameErrors = Array.isArray(error.data.name)
    ? error.data.name
    : [error.data.name];
  if (
    nameErrors.some(
      (message) =>
        typeof message === "string" &&
        /(already exists|unique|conflict)/i.test(message),
    )
  ) {
    return "A folder with this name already exists here.";
  }
  if (error.data.name !== undefined) {
    return "Check the folder name and try again.";
  }
  if (error.data.parent !== undefined) {
    return "This folder is no longer available. Refresh and try again.";
  }
 
  return "Could not create the folder. Try again.";
}
 
export function CreateProjectFolderButton({
  currentFolderId,
  currentFolderLabel,
  onCreate,
  disabled = false,
}: CreateProjectFolderButtonProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [folderName, setFolderName] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
 
  const handleOpenChange = (open: boolean) => {
    setIsOpen(open);
    setFolderName("");
    setError(null);
    setIsSubmitting(false);
  };
 
  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const name = folderName.trim();
    if (!name) {
      setError("Enter a folder name.");
      return;
    }
 
    setError(null);
    setIsSubmitting(true);
    try {
      await onCreate(currentFolderId, name);
      handleOpenChange(false);
    } catch (createError) {
      setError(getCreateFolderErrorMessage(createError));
      setIsSubmitting(false);
    }
  };
 
  return (
    <Dialog open={isOpen} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button type="button" variant="outline" disabled={disabled}>
          <FolderPlus className="icon-small" aria-hidden="true" />
          New Folder
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md" aria-label="Create folder dialog">
        <form onSubmit={handleSubmit} className="space-y-5">
          <DialogHeader>
            <DialogTitle>New Folder</DialogTitle>
            <DialogDescription>
              Create a folder inside {currentFolderLabel}.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-2">
            <Label htmlFor="new-project-folder-name">Folder name</Label>
            <Input
              id="new-project-folder-name"
              value={folderName}
              onChange={(event) => {
                setFolderName(event.target.value);
                setError(null);
              }}
              autoFocus
              autoComplete="off"
              maxLength={64}
              aria-invalid={Boolean(error)}
              aria-describedby={error ? "new-project-folder-error" : undefined}
            />
            {error && (
              <p
                id="new-project-folder-error"
                className="text-sm text-destructive"
                role="alert"
              >
                {error}
              </p>
            )}
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => handleOpenChange(false)}
              disabled={isSubmitting}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Creating..." : "Create Folder"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
 
type ProjectFolderMoveMenuProps = {
  currentFolderId: ProjectFolderId;
  onMove: (folderId: ProjectFolderId) => Promise<void> | void;
  disabled?: boolean;
};
 
export function ProjectFolderMoveMenu({
  currentFolderId,
  onMove,
  disabled = false,
}: ProjectFolderMoveMenuProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("");
  const [resultPage, setResultPage] = useState(1);
  const firstDestinationRef = useRef<HTMLDivElement | null>(null);
  const lastDestinationRef = useRef<HTMLDivElement | null>(null);
  const {
    currentData: destinationPage,
    isFetching,
    isError,
    refetch,
  } = useCoreProjectFoldersDestinationsRetrieveQuery(
    { q: debouncedSearchQuery, page: resultPage },
    { skip: !isOpen },
  );
  useEffect(() => {
    const timer = window.setTimeout(
      () => setDebouncedSearchQuery(searchQuery),
      250,
    );
    return () => window.clearTimeout(timer);
  }, [searchQuery]);
  const isSearchSettling = searchQuery !== debouncedSearchQuery;
  const destinations =
    isError || isSearchSettling ? [] : (destinationPage?.results ?? []);
  const rootMatches =
    !isError && !isSearchSettling && (destinationPage?.root_matches ?? false);
  const activeResultPage = Math.min(resultPage, destinationPage?.pages ?? 1);
  const hasMultiplePages = (destinationPage?.pages ?? 1) > 1;
  const firstEnabledDestination = destinations.find(
    (destination) => destination.id !== currentFolderId,
  );
  const lastEnabledDestination = [...destinations]
    .reverse()
    .find((destination) => destination.id !== currentFolderId);
 
  return (
    <DropdownMenuSub
      onOpenChange={(open) => {
        setIsOpen(open);
        setResultPage(1);
        if (!open) {
          setSearchQuery("");
          setDebouncedSearchQuery("");
        }
      }}
    >
      <DropdownMenuSubTrigger
        className="w-full cursor-pointer gap-3 p-2 data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
        aria-label="Move Project to Folder"
        disabled={disabled}
        onClick={(event) => event.stopPropagation()}
      >
        <FolderInput className="h-4 w-4" aria-hidden="true" />
        {disabled ? "Moving project..." : "Move to folder"}
      </DropdownMenuSubTrigger>
      <DropdownMenuSubContent
        aria-label="Project folder destinations"
        className="w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)] overflow-hidden"
      >
        <div
          className="border-b border-border p-2"
          onClick={(event) => event.stopPropagation()}
        >
          <div className="relative">
            <Search
              className="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
              aria-hidden="true"
            />
            <Input
              value={searchQuery}
              onChange={(event) => {
                setSearchQuery(event.target.value);
                setResultPage(1);
              }}
              onKeyDown={(event) => {
                if (["ArrowDown", "Home"].includes(event.key)) {
                  event.preventDefault();
                  event.stopPropagation();
                  firstDestinationRef.current?.focus();
                  return;
                }
                if (["ArrowUp", "End"].includes(event.key)) {
                  event.preventDefault();
                  event.stopPropagation();
                  lastDestinationRef.current?.focus();
                  return;
                }
                Iif (event.key !== "Escape") event.stopPropagation();
              }}
              aria-label="Search folder destinations"
              placeholder="Search folder names"
              className="h-8 pl-8"
              autoComplete="off"
            />
          </div>
        </div>
        <div className="max-h-64 overflow-y-auto p-1">
          {(isFetching || isSearchSettling) &&
            destinations.length === 0 &&
            !isError && (
              <p className="px-2 py-5 text-center text-sm text-muted-foreground">
                Loading folder destinations...
              </p>
            )}
          {isError && (
            <div className="flex items-center justify-between gap-2 px-2 py-3">
              <p className="text-sm text-muted-foreground">
                Folder destinations could not be loaded.
              </p>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={refetch}
              >
                Retry
              </Button>
            </div>
          )}
          {rootMatches && activeResultPage === 1 && (
            <DropdownMenuItem
              data-project-folder-destination=""
              disabled={currentFolderId === ROOT_PROJECT_FOLDER_ID}
              aria-label="Move project to My Projects"
              className="min-w-0 cursor-pointer"
              onClick={(event) => {
                event.stopPropagation();
                Iif (!disabled) void onMove(ROOT_PROJECT_FOLDER_ID);
              }}
            >
              <Home className="mr-2 h-4 w-4 shrink-0" aria-hidden="true" />
              My Projects
            </DropdownMenuItem>
          )}
          {!isFetching &&
            !isSearchSettling &&
            !isError &&
            !rootMatches &&
            destinations.length === 0 && (
              <p className="px-2 py-5 text-center text-sm text-muted-foreground">
                No folders match this search.
              </p>
            )}
          {destinations.map((destination) => (
            <DropdownMenuItem
              key={destination.id ?? "root"}
              ref={(element) => {
                if (destination === firstEnabledDestination) {
                  firstDestinationRef.current = element;
                }
                if (destination === lastEnabledDestination) {
                  lastDestinationRef.current = element;
                }
              }}
              data-project-folder-destination=""
              disabled={destination.id === currentFolderId}
              aria-label={`Move project to ${destination.has_omitted_ancestors ? "ancestor folders omitted, " : ""}${destination.path.join(
                ", inside ",
              )}, search result ${destination.result_position}`}
              className="min-w-0 cursor-pointer"
              onClick={(event) => {
                event.stopPropagation();
                Iif (!disabled) void onMove(destination.id);
              }}
            >
              <Folder className="mr-2 h-4 w-4 shrink-0" aria-hidden="true" />
              <span className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden">
                {destination.has_omitted_ancestors && (
                  <>
                    <span className="shrink-0 text-xs italic text-muted-foreground">
                      Ancestors omitted
                    </span>
                    <ChevronRight
                      className="h-3.5 w-3.5 shrink-0 text-muted-foreground"
                      aria-hidden="true"
                    />
                  </>
                )}
                {destination.path.map((segment, index) => (
                  <span
                    key={`${destination.id}:${index}`}
                    data-project-folder-path-segment=""
                    className="contents"
                  >
                    {index > 0 && (
                      <ChevronRight
                        className="h-3.5 w-3.5 shrink-0 text-muted-foreground"
                        aria-hidden="true"
                      />
                    )}
                    <span className="min-w-0 max-w-32 truncate">{segment}</span>
                  </span>
                ))}
              </span>
              <span className="ml-2 shrink-0 text-xs text-muted-foreground">
                Result {destination.result_position}
              </span>
            </DropdownMenuItem>
          ))}
          {hasMultiplePages && !isSearchSettling && !isError && (
            <div className="mt-1 flex items-center gap-1 border-t border-border pt-1">
              <DropdownMenuItem
                disabled={activeResultPage === 1}
                aria-label="Previous folder destinations"
                className="cursor-pointer"
                onSelect={(event) => {
                  event.preventDefault();
                  setResultPage(Math.max(1, activeResultPage - 1));
                }}
              >
                Previous
              </DropdownMenuItem>
              <p
                role="status"
                className="min-w-0 flex-1 text-center text-xs text-muted-foreground"
              >
                Page {activeResultPage} of {destinationPage?.pages ?? 1}
              </p>
              <DropdownMenuItem
                disabled={activeResultPage === destinationPage?.pages}
                aria-label="Next folder destinations"
                className="cursor-pointer"
                onSelect={(event) => {
                  event.preventDefault();
                  setResultPage(activeResultPage + 1);
                }}
              >
                Next
              </DropdownMenuItem>
            </div>
          )}
        </div>
      </DropdownMenuSubContent>
    </DropdownMenuSub>
  );
}