Skip to content

The platform for continuously improving AI agents.

7.7 KB
Raw Blame
import { useRef, useState } from "react";

import { useNavigate, useRouterState, useSearch } from "@tanstack/react-router";

import { Button } from "@/components/ui/button";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { Icon } from "@/components/ui/icons";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { SidebarMenuButton, useSidebar } from "@/components/ui/sidebar";
import { Spinner } from "@/components/ui/spinner";
import { useAuthContext } from "@/contexts/auth-context";
import { useGuestGate } from "@/hooks/use-guest-gate";
import { selectProject } from "@/hooks/use-project-search-sync";
import { useProjectsList } from "@/hooks/use-projects";
import { notify } from "@/lib/notify";
import { cn } from "@/lib/utils";
import { workspaceSection } from "@/lib/workspace-navigation";

const markTones = [1, 2, 3, 4, 5, 6].map((n) => `bg-cat-${n}/15 text-cat-${n}`);

function ProjectMark({ id, name, compact }: { id: string; name: string; compact?: boolean }) {
  const tone = [...id].reduce((sum, c) => sum + c.charCodeAt(0), 0) % markTones.length;
  return (
    <span
      aria-hidden="true"
      className={cn(
        "flex shrink-0 items-center justify-center rounded-sm font-sans text-xs font-semibold",
        compact ? "size-6" : "size-7",
        markTones[tone]
      )}
    >
      {name.trim().slice(0, 1).toUpperCase() || <Icon.project className="size-4" />}
    </span>
  );
}

export function ProjectSelector({ compact = false }: { compact?: boolean }) {
  const { projectId = "" } = useSearch({ from: "/_auth" });
  const { user } = useAuthContext();
  const { isMobile, setOpenMobile } = useSidebar();
  const guard = useGuestGate();
  const navigate = useNavigate();
  const pathname = useRouterState({ select: (state) => state.location.pathname });
  const projectsQuery = useProjectsList();
  const [open, setOpen] = useState(false);
  const [pendingId, setPendingId] = useState<string>();
  const commandRef = useRef<HTMLDivElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);
  const projects = projectsQuery.data?.projects ?? [];
  const current = projects.find((project) => project.projectId === (pendingId ?? projectId));
  const name = current?.name ?? "Select project";
  const showSearch = projects.length > 7;

  const pick = async (id: string) => {
    if (pendingId) return;
    setOpen(false);
    if (id === projectId) return;
    setPendingId(id);
    try {
      selectProject(id);
      await navigate({ search: { projectId: id }, to: workspaceSection(pathname) });
      if (isMobile) setOpenMobile(false);
    } catch (error) {
      selectProject(projectId);
      notify.error(error, "Couldn't switch projects");
    } finally {
      setPendingId(undefined);
    }
  };

  const close = () => {
    setOpen(false);
    if (isMobile) setOpenMobile(false);
  };

  return (
    <Popover onOpenChange={setOpen} open={open}>
      <PopoverTrigger asChild>
        <SidebarMenuButton
          aria-label={`Switch project, ${name}`}
          className="group/project bg-wash-subtle px-2 font-sans data-[state=open]:bg-wash-raised group-data-[collapsible=icon]:bg-transparent"
          disabled={!!pendingId}
          size="lg"
          tooltip={name}
        >
          <span
            className="flex min-w-0 flex-1 animate-in fade-in-0 slide-in-from-bottom-[3px] items-center gap-2 duration-200 group-data-[collapsible=icon]:justify-center motion-reduce:animate-none"
            key={current?.projectId ?? "empty"}
          >
            <ProjectMark
              compact={compact}
              id={current?.projectId ?? ""}
              name={current?.name ?? ""}
            />
            {!compact && (
              <span className="flex min-w-0 flex-1 flex-col gap-0.5">
                <span className="truncate text-sm font-medium">{name}</span>
                <span className="text-xs text-muted-foreground">
                  {current
                    ? `${current.memberCount} ${current.memberCount === 1 ? "member" : "members"}`
                    : "Projects"}
                </span>
              </span>
            )}
          </span>
          {!compact &&
            (pendingId ? (
              <Spinner size="sm" />
            ) : (
              <Icon.sortable className="!size-3.5 text-muted-foreground transition-transform duration-200 group-data-[state=open]/project:rotate-180 motion-reduce:transition-none" />
            ))}
        </SidebarMenuButton>
      </PopoverTrigger>
      <PopoverContent
        align="start"
        aria-label="Switch project"
        className="w-64 max-w-[calc(100vw-1rem)] origin-(--radix-popover-content-transform-origin) overflow-hidden p-1 duration-200 motion-reduce:animate-none"
        onOpenAutoFocus={(event) => {
          event.preventDefault();
          (searchRef.current ?? commandRef.current)?.focus();
        }}
        side={compact ? "right" : "top"}
        sideOffset={8}
      >
        {user && (
          <p className="truncate px-2 py-2 text-xs text-muted-foreground">
            {user.email || user.name}
          </p>
        )}
        <Command
          className="[&_[data-slot=command-input-wrapper]]:border-0"
          label="Projects"
          ref={commandRef}
          tabIndex={0}
        >
          {showSearch && (
            <CommandInput
              aria-label="Search projects"
              placeholder="Search projects…"
              ref={searchRef}
            />
          )}
          <CommandList className="max-h-64">
            {projectsQuery.isSuccess && <CommandEmpty>No matching projects</CommandEmpty>}
            <CommandGroup className="p-0">
              {projects.map((project) => (
                <CommandItem
                  className="gap-2 px-2 py-2"
                  key={project.projectId}
                  keywords={[project.name]}
                  onSelect={() => void pick(project.projectId)}
                  value={project.projectId}
                >
                  <ProjectMark compact id={project.projectId} name={project.name} />
                  <span className="min-w-0 flex-1 truncate">{project.name}</span>
                  {project.projectId === projectId && (
                    <Icon.success
                      aria-label="Current project"
                      className="size-3.5 text-foreground"
                    />
                  )}
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
        {projectsQuery.isPending && (
          <p
            className="flex items-center gap-2 px-2 py-2 text-xs text-muted-foreground"
            role="status"
          >
            <Spinner size="sm" />
            Loading projects…
          </p>
        )}
        {projectsQuery.isError && (
          <Button
            className="m-1"
            onClick={() => void projectsQuery.refetch()}
            size="sm"
            variant="secondary"
          >
            Retry loading projects
          </Button>
        )}
        <div className="mt-1 space-y-0.5">
          {(
            [
              [Icon.add, "New project", "new"],
              [Icon.settings, "Manage projects", undefined],
            ] as const
          ).map(([Glyph, label, createProject]) => (
            <Button
              className="w-full justify-start"
              key={label}
              onClick={guard(() => {
                close();
                void navigate({ search: { createProject, projectId }, to: "/projects" });
              })}
              size="sm"
              variant="secondary"
            >
              <Glyph /> {label}
            </Button>
          ))}
        </div>
      </PopoverContent>
    </Popover>
  );
}