Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

10.1 KB
Raw Blame
"use client";

import useWorkspaceUsers from "@/lib/swr/use-workspace-users";
import useWorkspaces from "@/lib/swr/use-workspaces";
import { PlanProps, WorkspaceProps } from "@/lib/types";
import { ModalContext } from "@/ui/modals/modal-provider";
import { getUserAvatarUrl } from "@/ui/users/user-avatar";
import { BlurImage, Popover, ScrollContainer, StatusBadge } from "@dub/ui";
import { Check2, Gear, Plus, UserPlus } from "@dub/ui/icons";
import { cn, pluralize } from "@dub/utils";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";

export function WorkspaceDropdown() {
  const { workspaces } = useWorkspaces();
  const { data: session, status } = useSession();
  const { slug: currentSlug } = useParams() as {
    slug?: string;
    key?: string;
  };

  // Prevent slug from changing to empty to avoid UI switching during nav animation
  const [slug, setSlug] = useState(currentSlug);
  useEffect(() => {
    if (currentSlug) setSlug(currentSlug);
  }, [currentSlug]);

  const selected = useMemo(() => {
    const selectedWorkspace = workspaces?.find(
      (workspace) => workspace.slug === slug,
    );

    if (slug && workspaces && selectedWorkspace) {
      return {
        ...selectedWorkspace,
        image:
          selectedWorkspace.logo ||
          `https://avatar.vercel.sh/${selectedWorkspace.id}`,
      };

      // return personal account selector if there's no workspace or error (user doesn't have access to workspace)
    } else {
      return {
        name: session?.user?.name || session?.user?.email,
        image: getUserAvatarUrl(session?.user).then((url) => url),
        plan: "free",
      };
    }
  }, [slug, workspaces, session]) as {
    id?: string;
    name: string;
    slug: string;
    image: string;
    plan: PlanProps;
    disabledAt?: Date | string | null;
  };

  const [openPopover, setOpenPopover] = useState(false);

  if (!workspaces || status === "loading") {
    return <WorkspaceDropdownPlaceholder />;
  }

  return (
    <div>
      <Popover
        content={
          <WorkspaceList
            selected={selected}
            workspaces={workspaces}
            setOpenPopover={setOpenPopover}
          />
        }
        side="right"
        align="start"
        openPopover={openPopover}
        setOpenPopover={setOpenPopover}
      >
        <button
          onClick={() => setOpenPopover(!openPopover)}
          className={cn(
            "flex size-11 items-center justify-center rounded-lg p-1.5 text-left text-sm transition-all duration-75",
            "hover:bg-bg-inverted/5 active:bg-bg-inverted/10 data-[state=open]:bg-bg-inverted/10",
            "outline-none focus-visible:ring-2 focus-visible:ring-black/50",
          )}
        >
          <BlurImage
            src={selected.image}
            referrerPolicy="no-referrer"
            width={28}
            height={28}
            alt={selected.id || selected.name}
            className="size-7 flex-none shrink-0 overflow-hidden rounded-full"
            draggable={false}
          />
        </button>
      </Popover>
    </div>
  );
}

function WorkspaceDropdownPlaceholder() {
  return (
    <div className="flex size-11 animate-pulse items-center gap-x-1.5 rounded-lg bg-neutral-300" />
  );
}

function WorkspaceList({
  selected,
  workspaces,
  setOpenPopover,
}: {
  selected: {
    name: string;
    slug?: string; // undefined if the user is on the personal account
    image: string;
    plan: PlanProps;
    disabledAt?: Date | string | null;
  };
  workspaces: WorkspaceProps[];
  setOpenPopover: (open: boolean) => void;
}) {
  const { setShowAddWorkspaceModal } = useContext(ModalContext);
  const { link } = useParams() as {
    link: string | string[];
  };
  const pathname = usePathname();

  const { users } = useWorkspaceUsers();
  const membersCount = users?.filter((user) => !user.isMachine).length ?? 0;

  const href = useCallback(
    (slug: string) => {
      if (link) {
        // if we're on a link page, navigate back to the workspace root
        return `/${slug}/links`;
      } else if (selected.slug) {
        // else, we keep the path but remove all query params
        return pathname.replace(selected.slug, slug).split("?")[0] || "/";
      } else {
        return "/";
      }
    },
    [link, pathname, selected.slug],
  );

  return (
    <div className="w-xs relative w-full rounded-xl bg-white text-base sm:w-72 sm:text-sm">
      {/* Current workspace section */}
      <div className="flex flex-col gap-2.5 border-b border-neutral-200 px-3 pb-3 sm:p-3">
        <div className="flex items-center gap-x-2.5">
          <BlurImage
            src={selected.image}
            width={28}
            height={28}
            alt={selected.name}
            className="size-9 shrink-0 overflow-hidden rounded-full sm:size-8"
            draggable={false}
          />
          <div className="min-w-0">
            <div className="flex min-w-0 items-center gap-1.5">
              <div className="min-w-0 truncate text-base font-medium leading-5 text-neutral-900 sm:text-sm">
                {selected.name}
              </div>
              {selected.disabledAt && (
                <StatusBadge
                  variant="neutral"
                  size="sm"
                  icon={null}
                  className="shrink-0"
                >
                  Disabled
                </StatusBadge>
              )}
            </div>
            {selected.slug && (
              <div
                className={cn(
                  "truncate text-sm capitalize leading-tight sm:text-xs",
                  getPlanColor(selected.plan),
                )}
              >
                {selected.plan}
                {membersCount > 0
                  ? ` · ${membersCount} ${pluralize("member", membersCount)}`
                  : ""}
              </div>
            )}
          </div>
        </div>

        {/* Settings and Invite members options */}
        <div className="flex flex-row gap-1">
          <Link
            href={`/${selected.slug ? selected.slug : "account"}/settings`}
            className="flex flex-1 items-center justify-center gap-x-2 rounded-lg border border-neutral-200 px-2 py-1 text-neutral-700 outline-none transition-all duration-75 hover:bg-neutral-100/50 focus-visible:ring-2 focus-visible:ring-black/50 active:bg-neutral-200/80"
            onClick={() => setOpenPopover(false)}
          >
            <Gear className="size-4 text-neutral-800" />
            <span className="block truncate text-sm">Settings</span>
          </Link>
          {selected.slug && (
            <Link
              href={`/${selected.slug}/settings/people`}
              className="flex flex-1 items-center justify-center gap-x-2 rounded-lg border border-neutral-200 px-2 py-1 text-neutral-700 outline-none transition-all duration-75 hover:bg-neutral-100/50 focus-visible:ring-2 focus-visible:ring-black/50 active:bg-neutral-200/80"
              onClick={() => setOpenPopover(false)}
            >
              <UserPlus className="size-4 text-neutral-800" />
              <span className="block truncate text-sm">Invite members</span>
            </Link>
          )}
        </div>
      </div>

      {/* Workspaces section */}
      <ScrollContainer className="max-h-[min(260px,calc(100vh-300px))]">
        <div className="p-1">
          <p className="px-2 py-2 text-xs font-medium text-neutral-500">
            Workspaces
          </p>
          <div className="flex flex-col gap-0.5">
            {workspaces.map(({ id, name, slug, logo, disabledAt }) => {
              const isActive = selected.slug === slug;
              return (
                <Link
                  key={slug}
                  className={cn(
                    "flex w-full items-center gap-x-2 rounded-md px-2 py-2 transition-all duration-75",
                    "hover:bg-neutral-200/50 active:bg-neutral-200/80",
                    "outline-none focus-visible:ring-2 focus-visible:ring-black/50",
                    isActive && "bg-neutral-200/50",
                  )}
                  href={href(slug)}
                  shallow={false}
                  onClick={() => setOpenPopover(false)}
                >
                  <BlurImage
                    src={logo || `https://avatar.vercel.sh/${id}`}
                    width={28}
                    height={28}
                    alt={id}
                    className="size-5 shrink-0 overflow-hidden rounded-full"
                    draggable={false}
                  />
                  <span className="min-w-0 flex-1 truncate text-base leading-5 text-neutral-900 sm:text-sm">
                    {name}
                  </span>
                  {disabledAt && (
                    <StatusBadge
                      variant="neutral"
                      size="sm"
                      icon={null}
                      className="shrink-0"
                    >
                      Disabled
                    </StatusBadge>
                  )}
                  {isActive ? (
                    <Check2
                      className="size-4 shrink-0 text-black"
                      aria-hidden="true"
                    />
                  ) : null}
                </Link>
              );
            })}
            <button
              key="add"
              onClick={() => {
                setOpenPopover(false);
                setShowAddWorkspaceModal(true);
              }}
              className="group flex w-full cursor-pointer items-center gap-x-2.5 rounded-md p-2 text-neutral-700 transition-all duration-75 hover:bg-neutral-200/50 active:bg-neutral-200/80"
            >
              <Plus className="ml-0.5 size-4 text-neutral-500" />
              <span className="block truncate">Create workspace</span>
            </button>
          </div>
        </div>
      </ScrollContainer>
    </div>
  );
}

const getPlanColor = (plan: string) =>
  plan === "enterprise"
    ? "text-purple-700"
    : plan === "advanced"
      ? "text-amber-800"
      : plan.startsWith("business")
        ? "text-blue-900"
        : plan === "pro"
          ? "text-cyan-900"
          : "text-neutral-500";