Skip to content

The platform for continuously improving AI agents.

13.7 KB
Raw Blame
import { type KeyboardEvent, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";

import { useNavigate, useRouterState } from "@tanstack/react-router";
import { AnimatePresence, Reorder, useReducedMotion } from "motion/react";

import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
import { Input } from "@/components/ui/input";
import { useSidebar } from "@/components/ui/sidebar";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useAuthContext } from "@/contexts/auth-context";
import { usePatchDatasetMutation } from "@/hooks/use-datasets";
import { useGuestGate } from "@/hooks/use-guest-gate";
import { acknowledgeLaunchedTab, useLaunchedTabs, withLaunchedTabs } from "@/lib/launched-tabs";
import { sessionStore } from "@/lib/storage";
import { cn } from "@/lib/utils";
import { workspaceTabDestination, workspaceTabId } from "@/lib/workspace-navigation";
import styles from "./workspace.module.css";

export interface WorkspaceTab {
  id: string;
  href: string;
  title: string;
  pinned?: boolean;
  /** Opened in the background for a running job and not yet selected. */
  unseen?: boolean;
}

const MARKS: Record<string, typeof Icon.finetuning> = {
  evaluations: Icon.evaluations,
  inference: Icon.inferenceTitle,
  observability: Icon.observabilityTitle,
  training: Icon.finetuning,
};
const GLYPHS: Record<string, typeof Icon.home> = {
  agent: Icon.agent,
  capabilities: Icon.capability,
  datasets: Icon.dataset,
  experiments: Icon.ai,
  integrations: Icon.integrations,
  projects: Icon.project,
  settings: Icon.settings,
};

function TabIcon({ href }: { href: string }) {
  const section = href.split("?")[0].split("/")[1];
  const Mark = MARKS[section];
  if (Mark)
    return <Mark aria-hidden className="size-4 shrink-0 [image-rendering:pixelated] invert" />;
  const Glyph = GLYPHS[section] ?? Icon.home;
  return <Glyph aria-hidden className="size-4 shrink-0" />;
}

export function visitWorkspaceTab(tabs: WorkspaceTab[], tab: WorkspaceTab) {
  const previous = tabs.find((t) => t.id === tab.id);
  if (previous?.href === tab.href && previous.title === tab.title) return tabs;
  return previous ? tabs.map((t) => (t.id === tab.id ? tab : t)) : [...tabs, tab];
}

/** Restores stored tabs, dropping any whose href is unsafe, mismatched or from another project. */
export function readWorkspaceTabs(raw: string | null, home: WorkspaceTab): WorkspaceTab[] {
  const project = new URL(home.href, "http://workspace.local").searchParams.get("projectId");
  const tabs: WorkspaceTab[] = [];
  try {
    const stored: unknown = JSON.parse(raw ?? "[]");
    for (const item of Array.isArray(stored) ? stored : []) {
      if (
        typeof item?.id !== "string" ||
        typeof item.title !== "string" ||
        typeof item.href !== "string"
      )
        continue;
      if (!item.href.startsWith("/") || item.href.startsWith("//") || item.href.includes("\\"))
        continue;
      const url = new URL(item.href, "http://workspace.local");
      if (workspaceTabId(url.pathname, Object.fromEntries(url.searchParams)) !== item.id) continue;
      if (url.searchParams.get("projectId") !== project || item.id === "home") continue;
      if (!tabs.some((tab) => tab.id === item.id))
        tabs.push({ href: item.href, id: item.id, title: item.title.slice(0, 100) });
    }
  } catch {
    /* A corrupt entry restores Home alone. */
  }
  return [home, ...tabs];
}

export function nextWorkspaceTab(tabs: readonly WorkspaceTab[], id: string) {
  const at = tabs.findIndex((tab) => tab.id === id);
  return at < 0 ? undefined : (tabs[at + 1] ?? tabs[at - 1])?.id;
}

export function WorkspaceTabs({
  onClosed,
  title,
}: {
  /** A closed tab's id, so a kept-alive Home chat can be dropped. */
  onClosed?: (id: string) => void;
  title: string;
}) {
  const { location } = useRouterState();
  const { user } = useAuthContext();
  const navigate = useNavigate();
  const { toggleSidebar } = useSidebar();
  const reduce = useReducedMotion();
  const strip = useRef<HTMLDivElement>(null);
  const [edges, setEdges] = useState({ left: false, right: false });
  const [renamingId, setRenamingId] = useState<string>();
  const guard = useGuestGate();
  const patchDataset = usePatchDatasetMutation();

  const search = location.search as Record<string, unknown>;
  const projectId = typeof search.projectId === "string" ? search.projectId : undefined;
  const home: WorkspaceTab = {
    href: projectId ? `/?projectId=${encodeURIComponent(projectId)}` : "/",
    id: "home",
    pinned: true,
    title: "Home",
  };
  const active = workspaceTabId(location.pathname, search);
  const current = useMemo<WorkspaceTab>(
    () => ({
      href: location.href,
      id: active,
      pinned: active === "home",
      title: active === "home" ? "Home" : active.startsWith("chat:") ? "New chat" : title,
    }),
    [active, location.href, title]
  );
  const storageKey = `workspace-tabs:${user?.id ?? "guest"}:${projectId ?? "none"}`;
  const [tabs, setTabs] = useState(() =>
    visitWorkspaceTab(readWorkspaceTabs(sessionStore.get(storageKey), home), current)
  );
  const launched = useLaunchedTabs(user?.id, projectId);
  const visible = withLaunchedTabs(visitWorkspaceTab(tabs, current), launched).map((tab) => ({
    ...tab,
    unseen: tab.id !== active && launched.some((item) => item.id === tab.id && item.unseen),
  }));
  const ids = visible.map((tab) => tab.id);

  useEffect(() => setTabs((old) => visitWorkspaceTab(old, current)), [current]);
  useEffect(() => {
    sessionStore.set(storageKey, JSON.stringify(tabs));
  }, [storageKey, tabs]);
  useEffect(() => {
    if (launched.some((tab) => tab.id === active)) acknowledgeLaunchedTab(active);
  }, [active, launched]);

  // Overflow masks, and vertical wheel scrolls the strip sideways.
  useLayoutEffect(() => {
    const el = strip.current;
    if (!el) return;
    const measure = () =>
      setEdges({
        left: el.scrollLeft > 2,
        right: el.scrollLeft + el.clientWidth < el.scrollWidth - 2,
      });
    const wheel = (e: WheelEvent) => {
      if (el.scrollWidth <= el.clientWidth || Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
      e.preventDefault();
      el.scrollLeft += e.deltaY;
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(el);
    el.addEventListener("scroll", measure);
    el.addEventListener("wheel", wheel, { passive: false });
    return () => {
      observer.disconnect();
      el.removeEventListener("scroll", measure);
      el.removeEventListener("wheel", wheel);
    };
  }, []);
  // biome-ignore lint/correctness/useExhaustiveDependencies: selection and insertion move the active tab
  useLayoutEffect(() => {
    // Not scrollIntoView: that would also scroll the clipped shell around the strip.
    const el = strip.current;
    const tab = el?.querySelector<HTMLElement>('[data-active="true"]');
    if (!el || !tab) return;
    const behavior = reduce ? "instant" : "smooth";
    const end = tab.offsetLeft + tab.offsetWidth;
    if (tab.offsetLeft < el.scrollLeft) el.scrollTo({ behavior, left: tab.offsetLeft });
    else if (end > el.scrollLeft + el.clientWidth)
      el.scrollTo({ behavior, left: end - el.clientWidth });
  }, [active, visible.length, reduce]);

  const select = (id: string) => {
    const target = visible.find((tab) => tab.id === id);
    if (target) void navigate(workspaceTabDestination(target.href));
  };
  const close = (id: string) => {
    acknowledgeLaunchedTab(id);
    if (id === active) select(nextWorkspaceTab(visible, id) ?? "home");
    setTabs(visible.filter((tab) => tab.id !== id));
    onClosed?.(id);
  };
  // Only dataset tabs rename: the new title renames the dataset itself.
  const datasetOf = (tab: WorkspaceTab) => /^\/datasets\/([^/?#]+)/.exec(tab.href)?.[1];
  const rename = guard((tab: WorkspaceTab, name: string) => {
    const id = datasetOf(tab);
    if (!id || !name || name === tab.title) return;
    patchDataset.mutate(
      { id, name },
      {
        onSuccess: () =>
          setTabs((old) => old.map((t) => (t.id === tab.id ? { ...t, title: name } : t))),
      }
    );
  });
  const focus = (id: string | undefined) =>
    requestAnimationFrame(() => {
      if (id)
        strip.current?.querySelector<HTMLElement>(`[data-tab-id="${CSS.escape(id)}"]`)?.focus();
    });
  const onKeyDown = (e: KeyboardEvent, tab: WorkspaceTab) => {
    const at = ids.indexOf(tab.id);
    if (e.key === "F2" && datasetOf(tab)) return setRenamingId(tab.id);
    if (e.altKey && (e.key === "ArrowLeft" || e.key === "ArrowRight")) {
      e.preventDefault();
      const to = at + (e.key === "ArrowLeft" ? -1 : 1);
      if (tab.pinned || to < 1 || to >= ids.length) return;
      setTabs(visible.map((_, i) => visible[i === at ? to : i === to ? at : i]));
      return focus(tab.id);
    }
    const target = {
      ArrowLeft: ids[at - 1],
      ArrowRight: ids[at + 1],
      End: ids.at(-1),
      Home: ids[0],
    }[e.key];
    if (target) {
      e.preventDefault();
      select(target);
      focus(target);
    } else if (!tab.pinned && (e.key === "Delete" || e.key === "Backspace")) {
      e.preventDefault();
      focus(nextWorkspaceTab(visible, tab.id));
      close(tab.id);
    }
  };

  return (
    <div className="flex min-w-0 items-end">
      <Button
        aria-label="Open sidebar"
        className="mb-1 shrink-0 md:hidden"
        onClick={toggleSidebar}
        size="icon-sm"
        variant="ghost"
      >
        <Icon.sidebar />
      </Button>
      <Reorder.Group
        aria-label="Workspace tabs"
        as="div"
        axis="x"
        className={styles.strip}
        data-left={edges.left}
        data-right={edges.right}
        layoutScroll
        // Home stays first whatever the drag order.
        onReorder={(order: string[]) =>
          setTabs([
            home,
            ...order
              .filter((id) => id !== "home")
              .map((id) => visible.find((tab) => tab.id === id) as WorkspaceTab),
          ])
        }
        ref={strip}
        role="tablist"
        values={ids}
      >
        <AnimatePresence initial={false} mode="popLayout">
          {visible.map((tab) => (
            <Reorder.Item
              animate={{ opacity: 1, scale: 1 }}
              as="div"
              className={styles.tab}
              data-active={tab.id === active}
              data-unseen={tab.unseen || undefined}
              dragListener={!tab.pinned}
              exit={{ opacity: 0, scale: reduce ? 1 : 0.92 }}
              initial={{ opacity: 0, scale: reduce ? 1 : 0.92 }}
              key={tab.id}
              // Position only: the active tab's height change would otherwise animate
              // as a scale transform and stretch its title.
              layout="position"
              transition={{ duration: reduce ? 0 : 0.2, ease: [0.4, 0, 0.2, 1] }}
              value={tab.id}
            >
              {renamingId === tab.id ? (
                <div className="flex min-w-0 flex-1 items-center gap-2 pr-1 pl-3">
                  <TabIcon href={tab.href} />
                  <Input
                    aria-label={`Rename ${tab.title}`}
                    defaultValue={tab.title}
                    maxLength={255}
                    // Enter and Escape blur too, so blur is the one place a rename commits.
                    onBlur={(e) => {
                      setRenamingId(undefined);
                      rename(tab, e.currentTarget.value.trim());
                    }}
                    onFocus={(e) => e.currentTarget.select()}
                    onKeyDown={(e) => {
                      if (e.key !== "Enter" && e.key !== "Escape") return;
                      e.preventDefault();
                      if (e.key === "Escape") e.currentTarget.value = tab.title;
                      e.currentTarget.blur();
                      focus(tab.id);
                    }}
                    // Reorder.Item starts a drag from any pointer press inside it.
                    onPointerDown={(e) => e.stopPropagation()}
                    ref={(input) => input?.focus()}
                    size="xs"
                  />
                </div>
              ) : (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <button
                      aria-controls="workspace-panel"
                      aria-selected={tab.id === active}
                      className={styles.select}
                      data-tab-id={tab.id}
                      onAuxClick={(e) => {
                        if (e.button !== 1 || tab.pinned) return;
                        e.preventDefault();
                        close(tab.id);
                      }}
                      onClick={() => select(tab.id)}
                      onDoubleClick={() => datasetOf(tab) && setRenamingId(tab.id)}
                      onKeyDown={(e) => onKeyDown(e, tab)}
                      role="tab"
                      tabIndex={tab.id === active ? 0 : -1}
                      type="button"
                    >
                      <TabIcon href={tab.href} />
                      <span className="truncate">{tab.title}</span>
                    </button>
                  </TooltipTrigger>
                  <TooltipContent>{tab.title}</TooltipContent>
                </Tooltip>
              )}
              {!tab.pinned && (
                <Button
                  aria-label={`Close ${tab.title}`}
                  className={cn(styles.close, "shrink-0")}
                  onClick={() => close(tab.id)}
                  onPointerDown={(e) => e.stopPropagation()}
                  size="icon-xs"
                  variant="ghost"
                >
                  <Icon.close />
                </Button>
              )}
            </Reorder.Item>
          ))}
        </AnimatePresence>
      </Reorder.Group>
    </div>
  );
}