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.

15.5 KB
Raw Blame
import {
  AnimatedSizeContainer,
  ArrowUpRight2,
  ChevronLeft,
  ClientOnly,
  Icon,
  Lock,
  NavWordmark,
  Tooltip,
  useScrollProgress,
} from "@dub/ui";
import { cn } from "@dub/utils";
import { ChevronDown } from "lucide-react";
import { motion } from "motion/react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  ComponentType,
  CSSProperties,
  isValidElement,
  PropsWithChildren,
  ReactNode,
  Suspense,
  useMemo,
  useRef,
  useState,
} from "react";
import { UserDropdown } from "./user-dropdown";

export type NavItemCommon = {
  name: string;
  href: `/${string}`;
  exact?: boolean;
  isActive?: (pathname: string, href: string) => boolean;
  badge?: ReactNode;
  arrow?: boolean;
  locked?: boolean;
};

export type NavSubItemType = NavItemCommon;

export type NavItemType = NavItemCommon & {
  icon: Icon;
  items?: NavSubItemType[];
};

export type NavGroupType = {
  name: string;
  icon: Icon;
  href: string;
  active: boolean;
  onClick?: () => void;
  popup?: ComponentType<{
    referenceElement: HTMLElement | null;
  }>;
  badge?: ReactNode;
  description: string;
  learnMoreHref?: string;
};

export type SidebarNavGroups<T extends Record<any, any>> = (
  args: T,
) => NavGroupType[];

export type SidebarNavAreas<T extends Record<any, any>> = Record<
  string,
  (args: T) => {
    title?: string | ReactNode;
    backHref?: string;
    hideSwitcherIcons?: boolean; // hide workspace switcher + product icons for this area
    direction?: "left" | "right";
    // can either be a list of items, or a ReactNode
    content:
      | {
          name?: string;
          items: NavItemType[];
        }[]
      | ReactNode;
  }
>;

const SIDEBAR_WIDTH = 304;
const SIDEBAR_GROUPS_WIDTH = 64;
const SIDEBAR_AREAS_WIDTH = SIDEBAR_WIDTH - SIDEBAR_GROUPS_WIDTH;

export function SidebarNav<T extends Record<any, any>>({
  groups,
  areas,
  currentArea,
  data,
  switcher,
  toolContent,
  bottomContent,
  newsContent,
}: {
  groups: SidebarNavGroups<T>;
  areas: SidebarNavAreas<T>;
  currentArea: string | null;
  data: T;
  switcher?: ReactNode;
  toolContent?: ReactNode;
  bottomContent?: ReactNode;
  newsContent?: ReactNode;
}) {
  return (
    <div
      className={cn(
        "h-full w-[var(--sidebar-width)] transition-[width] duration-300",
      )}
      style={
        {
          "--sidebar-width": `${currentArea === null ? SIDEBAR_GROUPS_WIDTH : SIDEBAR_WIDTH}px`,
          "--sidebar-groups-width": `${SIDEBAR_GROUPS_WIDTH}px`,
          "--sidebar-areas-width": `${SIDEBAR_AREAS_WIDTH}px`,
        } as CSSProperties
      }
    >
      <ClientOnly className="size-full">
        <nav className="grid size-full grid-cols-[var(--sidebar-groups-width)_1fr]">
          <div className="flex flex-col items-center justify-between">
            <div className="flex flex-col items-center p-2">
              <div className="pb-1 pt-2">
                <Link
                  href="/"
                  className="block overflow-visible rounded-lg px-1 py-4 outline-none transition-opacity focus-visible:ring-2 focus-visible:ring-black/50"
                >
                  <NavWordmark className="h-5 overflow-visible" isInApp />
                </Link>
              </div>
              {(!currentArea ||
                !areas[currentArea](data).hideSwitcherIcons) && (
                <div className="flex flex-col gap-3">
                  {switcher}
                  {groups(data).map((group) => (
                    <NavGroupItem key={group.name} group={group} />
                  ))}
                </div>
              )}
            </div>
            <div className="flex flex-col items-center gap-3 py-3">
              <Suspense fallback={null}>{toolContent}</Suspense>
              <div className="flex size-12 items-center justify-center">
                <UserDropdown />
              </div>
            </div>
          </div>
          <div
            className={cn(
              "size-full overflow-hidden py-2 pr-2 transition-opacity duration-300",
              currentArea === null && "opacity-0",
            )}
          >
            <SidebarAreasPanel
              areas={areas}
              data={data}
              currentArea={currentArea}
              newsContent={newsContent}
              bottomContent={bottomContent}
            />
          </div>
        </nav>
      </ClientOnly>
    </div>
  );
}

function SidebarAreasPanel<T extends Record<any, any>>({
  areas,
  data,
  currentArea,
  newsContent,
  bottomContent,
}: {
  areas: SidebarNavAreas<T>;
  data: T;
  currentArea: string | null;
  newsContent?: ReactNode;
  bottomContent?: ReactNode;
}) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const { scrollProgress, updateScrollProgress } = useScrollProgress(scrollRef);

  return (
    <div className="flex h-full w-[calc(var(--sidebar-areas-width)-0.5rem)] flex-col rounded-xl bg-neutral-100">
      {/* Scrollable content with gradient overlay */}
      <div className="relative min-h-0 flex-1 overflow-hidden">
        <div
          ref={scrollRef}
          onScroll={updateScrollProgress}
          className="scrollbar-hide max-h-full overflow-y-auto overflow-x-hidden rounded-xl"
        >
          <div className="relative flex flex-col p-3 text-neutral-500">
            <div className="relative w-full overflow-hidden">
              {Object.entries(areas).map(([area, areaConfig]) => {
                const { title, backHref, content, direction } =
                  areaConfig(data);

                const TitleContainer = backHref ? Link : "div";

                return (
                  <Area
                    key={area}
                    visible={area === currentArea}
                    direction={direction ?? "right"}
                  >
                    {title &&
                      (typeof title === "string" ? (
                        <TitleContainer
                          href={backHref ?? "#"}
                          className="group mb-2 flex items-center gap-3 px-3 py-2"
                        >
                          {backHref && (
                            <div
                              className={cn(
                                "text-content-muted bg-bg-emphasis flex size-6 items-center justify-center rounded-lg",
                                "group-hover:bg-bg-inverted/10 group-hover:text-content-subtle transition-[transform,background-color,color] duration-150 group-hover:-translate-x-0.5",
                              )}
                            >
                              <ChevronLeft className="size-3 [&_*]:stroke-2" />
                            </div>
                          )}
                          <span className="text-content-emphasis text-lg font-semibold">
                            {title}
                          </span>
                        </TitleContainer>
                      ) : (
                        title
                      ))}
                    {isValidElement(content) ? (
                      content
                    ) : Array.isArray(content) ? (
                      <div className="flex flex-col gap-8">
                        {content.map(({ name, items }, idx) => (
                          <div key={idx} className="flex flex-col gap-0.5">
                            {name && (
                              <div className="mb-2 pl-3 text-sm text-neutral-500">
                                {name}
                              </div>
                            )}
                            {items.map((item) => (
                              <NavItem key={item.name} item={item} />
                            ))}
                          </div>
                        ))}
                      </div>
                    ) : null}
                  </Area>
                );
              })}
            </div>
          </div>
        </div>
        {/* Bottom scroll fade - shows when content overflows */}
        <div
          className="pointer-events-none absolute bottom-0 left-0 z-10 h-16 w-full rounded-b-lg bg-gradient-to-t from-neutral-100 to-transparent"
          style={{ opacity: 1 - Math.pow(scrollProgress, 2) }}
        />
      </div>

      {/* Fixed bottom sections - always visible */}
      <AnimatedSizeContainer
        height
        className="flex flex-shrink-0 flex-col gap-2 rounded-b-xl"
      >
        {bottomContent ? bottomContent : newsContent}
      </AnimatedSizeContainer>
    </div>
  );
}

export function NavGroupTooltip({
  name,
  description,
  learnMoreHref,
  disabled,
  children,
}: PropsWithChildren<{
  name: string;
  description?: string;
  learnMoreHref?: string;
  disabled?: boolean;
}>) {
  return (
    <Tooltip
      side="right"
      delayDuration={100}
      disabled={disabled}
      className="rounded-lg bg-black px-3 py-1.5 text-sm font-medium text-white"
      content={
        <div>
          <span>{name}</span>
          {description && (
            <motion.div
              initial={{ opacity: 0, width: 0, height: 0 }}
              animate={{ opacity: 1, width: "auto", height: "auto" }}
              transition={{ delay: 0.5, duration: 0.25, type: "spring" }}
              className="overflow-hidden"
            >
              <div className="w-44 py-1 text-xs tracking-tight">
                <p className="text-content-muted">{description}</p>
                {learnMoreHref && (
                  <div className="mt-2.5">
                    <Link
                      href={learnMoreHref}
                      target="_blank"
                      className="font-semibold text-white underline"
                    >
                      Learn more
                    </Link>
                  </div>
                )}
              </div>
            </motion.div>
          )}
        </div>
      }
    >
      {children}
    </Tooltip>
  );
}

function NavGroupItem({
  group: {
    name,
    description,
    learnMoreHref,
    icon: Icon,
    href,
    active,
    badge,
    onClick,
    popup: Popup,
  },
}: {
  group: NavGroupType;
}) {
  const [element, setElement] = useState<HTMLAnchorElement | null>(null);
  const [hovered, setHovered] = useState(false);

  return (
    <>
      <NavGroupTooltip
        name={name}
        description={description}
        learnMoreHref={learnMoreHref}
      >
        <div>
          <Link
            ref={Popup ? setElement : undefined}
            href={href}
            aria-label={name}
            onPointerEnter={() => setHovered(true)}
            onPointerLeave={() => setHovered(false)}
            onFocus={(e) =>
              e.currentTarget.matches(":focus-visible") && setHovered(true)
            }
            onBlur={() => setHovered(false)}
            onClick={onClick}
            className={cn(
              "relative flex size-11 items-center justify-center rounded-lg transition-colors duration-150",
              "outline-none focus-visible:ring-2 focus-visible:ring-black/50",
              active
                ? "bg-white"
                : "hover:bg-bg-inverted/5 active:bg-bg-inverted/10",
            )}
          >
            <Icon
              className="text-content-default size-5"
              data-hovered={hovered}
            />
            {badge && (
              <div className="absolute right-0.5 top-0.5 flex size-3.5 items-center justify-center rounded-full bg-blue-600 text-[0.625rem] font-semibold text-white">
                {badge}
              </div>
            )}
          </Link>
        </div>
      </NavGroupTooltip>
      {Popup && element && <Popup referenceElement={element} />}
    </>
  );
}

function NavItem({ item }: { item: NavItemType | NavSubItemType }) {
  const { name, href, exact, isActive: customIsActive, locked } = item;

  const Icon = "icon" in item ? item.icon : undefined;
  const items = "items" in item ? item.items : undefined;

  const [hovered, setHovered] = useState(false);

  const pathname = usePathname();

  const isActive = useMemo(() => {
    if (customIsActive) {
      return customIsActive(pathname, href);
    }

    const hrefWithoutQuery = href.split("?")[0];
    return exact
      ? pathname === hrefWithoutQuery
      : pathname.startsWith(hrefWithoutQuery);
  }, [pathname, href, exact, customIsActive]);

  return (
    <div>
      <Link
        href={locked ? "#" : href}
        data-active={isActive}
        onPointerEnter={() => !locked && setHovered(true)}
        onPointerLeave={() => !locked && setHovered(false)}
        className={cn(
          "text-content-default group flex h-8 items-center justify-between rounded-lg p-2 text-sm leading-none transition-[background-color,color,font-weight] duration-75",
          "outline-none focus-visible:ring-2 focus-visible:ring-black/50",
          isActive && !items
            ? "bg-blue-100/50 font-medium text-blue-600 hover:bg-blue-100/80 active:bg-blue-100"
            : locked
              ? "cursor-not-allowed opacity-75"
              : "hover:bg-bg-inverted/5 active:bg-bg-inverted/10",
        )}
        aria-disabled={locked}
      >
        <span className="flex items-center gap-2.5">
          {locked ? (
            <Lock className="size-4" />
          ) : (
            Icon && (
              <Icon
                className={cn(
                  "size-4",
                  !items && "group-data-[active=true]:text-blue-600",
                )}
                data-hovered={hovered}
              />
            )
          )}
          {name}
        </span>
        <span className="ml-2 flex items-center gap-2">
          {"badge" in item && item.badge && (
            <span
              className={cn(
                "flex items-center justify-center rounded px-1.5 py-0.5 text-xs font-semibold",
                isActive && !items
                  ? "bg-blue-600 text-white"
                  : "bg-blue-100 text-blue-600",
              )}
            >
              {item.badge}
            </span>
          )}
          {items && (
            <ChevronDown className="size-3.5 text-neutral-500 transition-transform duration-75 group-data-[active=true]:rotate-180" />
          )}
          {item.arrow && (
            <ArrowUpRight2 className="text-content-default size-3.5 transition-transform duration-75 group-hover:-translate-y-px group-hover:translate-x-px" />
          )}
        </span>
      </Link>
      {items && (
        <AnimatedSizeContainer
          height
          transition={{ duration: 0.2, ease: "easeInOut" }}
        >
          <div
            className={cn(
              "transition-opacity duration-200",
              isActive ? "h-auto" : "h-0 opacity-0",
            )}
            aria-hidden={!isActive}
          >
            <div className="pl-px pt-1">
              <div className="pl-3.5">
                <div className="flex flex-col gap-0.5 border-l border-neutral-200 pl-2">
                  {items.map((item) => (
                    <NavItem key={item.name} item={item} />
                  ))}
                </div>
              </div>
            </div>
          </div>
        </AnimatedSizeContainer>
      )}
    </div>
  );
}

export function Area({
  visible,
  direction,
  children,
}: PropsWithChildren<{ visible: boolean; direction: "left" | "right" }>) {
  return (
    <div
      className={cn(
        "left-0 top-0 flex flex-col md:transition-[opacity,transform] md:duration-300",
        visible
          ? "relative w-full opacity-100"
          : cn(
              "pointer-events-none absolute inset-0 overflow-hidden opacity-0",
              direction === "left" ? "-translate-x-full" : "translate-x-full",
            ),
      )}
      aria-hidden={!visible ? "true" : undefined}
      inert={!visible}
    >
      {children}
    </div>
  );
}