refactor(ui): build the dashboard and chat shells on the shadcn Sidebar (#51257)

* refactor(ui): build the dashboard and chat shells on the shadcn Sidebar

Replace the hand-rolled shared/Sidebar.tsx, the per-shell collapse state and
the hand-wired mobile Sheet with the base-vega shadcn Sidebar (SidebarProvider,
Sidebar collapsible="icon", SidebarInset, Collapsible nav groups). The primitive
and use-mobile hook come straight from the shadcn CLI's output. The only edits
are the cn import pointing at @/lib/cva.config and its English strings moving
into en.json. Its z-10/z-20 and the hook's setState-in-effect stay as shadcn
ships them, so eslint.config.mjs turns those two rules off for those two files.

Our look (280/72px widths, 34px rows, 13px text, accent bar, scrollable rail)
is carried by className overrides in shared/sidebarStyles.ts. Behaviour the
primitive leaves to the app is kept: per-route collapse on /logs, expanding the
rail when a group is chosen while collapsed, and closing the mobile drawer on
navigation, link clicks and a resize to desktop.

The settings wrapper is renamed AppSidebar so it no longer collides with
shadcn's SidebarProvider.

* fix(ui): close the phone drawer on any link inside it

Main closed the dashboard's mobile drawer whenever an a[href] inside it was
clicked, which covered the version badge and the account menu's release notes
link as well as nav links. One delegated click-capture handler in the nav
restores that and replaces the per-link handlers.

* fix(ui): keep chat search focused when Cmd+K opens the phone drawer

Base UI keeps one pending initial-focus request and lets the last one win. The
search dialog is nested in the drawer, so the drawer queued its focus after the
search box's and the logo won. Main avoided this with initialFocus={false} on
the sheet, which the shadcn Sidebar does not expose. Opening search once the
drawer has taken focus restores main's behavior.

* chore(ui): exempt the stock shadcn sidebar from the inline object arg budget

* chore(ui): exempt shadcn primitives from the inline object arg rule and ratchet its budget

* fix(ui): restore main's phone drawers, rail titles and nav semantics on the shadcn sidebar

* fix(ui): reset phone drawer groups on open and restore the drawer trigger's dialog semantics

* fix(ui): keep the phone drawer closed after a desktop round trip

* test(ui): match the stock sidebar's data-active attribute in the customer portal nav test

* fix(ui): keep the shell sidebars in step with main across the 768px breakpoint

The dashboard nav keeps its scroll position when the window crosses the phone
breakpoint and comes back, like main did when it hid the desktop sidebar with CSS.

The phone drawer now follows the same (min-width: 768px) query as Tailwind's md
variant, so it opens at fractional widths just under 768px under browser zoom.
The stock useIsMobile hook only listens to (max-width: 767px), which never fires
in that band.

Chat search at phone width expands the desktop rail again, so widening after
Cmd+K shows the rail expanded as on main.

* refactor(ui): use the stock shadcn mobile sidebar and lift chat search out of it

Drop the hand-rolled drawer, trigger and scroll memory in favor of the stock
Sidebar mobile Sheet and SidebarTrigger. Render the chat search dialog once in
ChatShell so Cmd+K on a phone opens only the search box instead of racing the
drawer for focus.

* test(ui): cover the phone drawer after the desktop rail is collapsed

The drawer depends on treating the rail as expanded on phones, and no test
failed when that guard was removed in the brand, the nav or the chat shell.
Also point the chat design doc at the stock shadcn Sidebar and the lifted
search dialog.

* refactor(ui): rename leftnav to LeftNav

Brings the sidebar component file in line with the PascalCase filename rule
and drops its now unused filename-pascal-case suppression.
This commit is contained in:
yuneng-jiang 2026-11-16 22:19:54 -08:00 • committed by GitHub
parent 0134008628
commit 9e94c716f8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
39 changed files with 1505 additions and 866 deletions

View file

@ -3,7 +3,7 @@
"no-console": { "max": 12, "target": 0 },
"complexity": { "max": 140, "target": 80 },
"max-depth": { "max": 70, "target": 30 },
"local/no-large-inline-object-arg": { "max": 551, "target": 300 },
"local/no-large-inline-object-arg": { "max": 545, "target": 300 },
"local/no-long-condition-chain": { "max": 194, "target": 120 },
"testing-library/no-container": { "max": 133, "target": 50 },
"testing-library/no-node-access": { "max": 707, "target": 500 },

View file

@ -1607,11 +1607,6 @@
"count": 1
}
},
"src/components/leftnav.tsx": {
"local/filename-pascal-case": {
"count": 1
}
},
"src/components/llm_calls/chat_completion.tsx": {
"local/filename-pascal-case": {
"count": 1

View file

@ -308,6 +308,19 @@ const eslintConfig = [
"jest-dom/prefer-to-have-text-content": "error",
},
},
{
files: ["src/components/ui/**/*.{ts,tsx}"],
ignores: ["src/**/*.test.{ts,tsx}"],
rules: { "local/no-large-inline-object-arg": "off" },
},
{
files: ["src/components/ui/sidebar.tsx"],
rules: { "local/no-ad-hoc-z-index": "off" },
},
{
files: ["src/hooks/use-mobile.ts"],
rules: { "react-hooks/set-state-in-effect": "off" },
},
];
export default eslintConfig;

View file

@ -2,15 +2,15 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen, within } from "@testing-library/react";
import type { ComponentProps } from "react";
import { expect, it, vi } from "vitest";
import Sidebar from "@/components/leftnav";
import SidebarProvider from "./SidebarProvider";
import Sidebar from "@/components/LeftNav";
import AppSidebar from "./AppSidebar";
const { getSettings } = vi.hoisted(() => ({
getSettings: vi.fn().mockResolvedValue({ values: { enable_projects_ui: true } }),
}));
vi.mock("@/components/networking", () => ({ getUiSettings: getSettings, getProxyBaseUrl: () => "http://localhost" }));
vi.mock("@/components/leftnav", () => ({
vi.mock("@/components/LeftNav", () => ({
default: ({ enableProjectsUI }: ComponentProps<typeof Sidebar>) => (
<nav>{enableProjectsUI && <a href="/projects">Projects</a>}</nav>
),
@ -21,11 +21,11 @@ it("reuses loaded navigation settings immediately when the mobile sidebar mounts
const shell = (mobileOpen: boolean) => (
<QueryClientProvider client={client}>
<section aria-label="Desktop navigation">
<SidebarProvider sidebarCollapsed={false} />
<AppSidebar />
</section>
{mobileOpen && (
<section aria-label="Mobile navigation">
<SidebarProvider sidebarCollapsed={false} />
<AppSidebar />
</section>
)}
</QueryClientProvider>

View file

@ -1,21 +1,14 @@
"use client";
import Sidebar from "@/components/leftnav";
import Sidebar from "@/components/LeftNav";
import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings";
interface SidebarProviderProps {
sidebarCollapsed: boolean;
onToggleCollapsed?: () => void;
}
const SidebarProvider = ({ sidebarCollapsed, onToggleCollapsed }: SidebarProviderProps) => {
const AppSidebar = () => {
const { data: settings } = useUISettings();
const values = settings?.values;
return (
<Sidebar
collapsed={sidebarCollapsed}
onToggleCollapsed={onToggleCollapsed}
enabledPagesInternalUsers={values?.enabled_ui_pages_internal_users ?? null}
enableProjectsUI={Boolean(values?.enable_projects_ui)}
disableAgentsForInternalUsers={Boolean(values?.disable_agents_for_internal_users)}
@ -26,4 +19,4 @@ const SidebarProvider = ({ sidebarCollapsed, onToggleCollapsed }: SidebarProvide
);
};
export default SidebarProvider;
export default AppSidebar;

View file

@ -25,6 +25,7 @@ vi.mock("next/navigation", () => ({
}));
beforeEach(() => {
vi.stubGlobal("innerWidth", 390);
testQueryClient.clear();
localStorage.clear();
deploymentWarnings = { warnings: [], ignore_available: true };
@ -118,8 +119,8 @@ describe("dashboard overlay boundaries", () => {
);
expect(await screen.findByRole("heading", { name: "Gateway page" })).toBeVisible();
expect(screen.getByRole("button", { name: "Open navigation" })).toBeVisible();
expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Toggle Sidebar" })).toBeVisible();
expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument();
});
it.each([
@ -191,9 +192,9 @@ describe("dashboard overlay boundaries", () => {
</AuthProvider>,
);
const trigger = await screen.findByRole("button", { name: "Open navigation" });
const trigger = await screen.findByRole("button", { name: "Toggle Sidebar" });
await user.click(trigger);
const navigation = await screen.findByRole("dialog", { name: "Navigation" });
const navigation = await screen.findByRole("dialog", { name: "Sidebar" });
expect(within(navigation).getByRole("link", { name: "Virtual Keys" })).toBeVisible();
await user.keyboard("{Escape}");
await waitFor(() => expect(trigger).toHaveFocus());

View file

@ -42,14 +42,21 @@ vi.mock("@/components/DashboardHeader", () => ({
),
}));
vi.mock("@/app/(dashboard)/components/SidebarProvider", () => ({
default: ({ sidebarCollapsed, onToggleCollapsed }: { sidebarCollapsed: boolean; onToggleCollapsed: () => void }) => (
<div data-testid="sidebar" data-collapsed={String(sidebarCollapsed)}>
<button onClick={onToggleCollapsed}>Close navigation</button>
<a href="#settings">Settings</a>
</div>
),
}));
vi.mock("@/app/(dashboard)/components/AppSidebar", async () => {
const { Sidebar, useSidebar } = await import("@/components/ui/sidebar");
return {
default: function FakeAppSidebar() {
const { state, toggleSidebar } = useSidebar();
return (
<Sidebar collapsible="icon">
<div data-testid="sidebar" data-collapsed={String(state === "collapsed")}>
<button onClick={toggleSidebar}>Close navigation</button>
</div>
</Sidebar>
);
},
};
});
vi.mock("@/components/UserBanner", () => ({
UserBanner: () => null,
@ -103,7 +110,8 @@ describe("(dashboard) Layout", () => {
vi.unstubAllGlobals();
});
it("starts mobile navigation closed, opens a modal drawer and closes it after choosing a page", async () => {
it("starts mobile navigation closed, opens a modal drawer and closes it from inside", async () => {
vi.stubGlobal("innerWidth", 390);
render(
<AuthProvider>
<Layout>
@ -113,14 +121,13 @@ describe("(dashboard) Layout", () => {
);
pendingUiConfig.resolve();
const trigger = await screen.findByRole("button", { name: "Open navigation" });
expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument();
const trigger = await screen.findByRole("button", { name: "Toggle Sidebar" });
expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument();
fireEvent.click(trigger);
const navigation = await screen.findByRole("dialog", { name: "Navigation" });
expect(within(navigation).getByRole("button", { name: "Close navigation" })).toBeInTheDocument();
fireEvent.click(within(navigation).getByRole("link", { name: "Settings" }));
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument());
const navigation = await screen.findByRole("dialog", { name: "Sidebar" });
fireEvent.click(within(navigation).getByRole("button", { name: "Close navigation" }));
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument());
});
it("records one page view per route segment, not per query change", async () => {
@ -133,7 +140,7 @@ describe("(dashboard) Layout", () => {
);
const { rerender } = render(dashboard());
pendingUiConfig.resolve();
await screen.findByRole("button", { name: "Open navigation" });
await screen.findByRole("button", { name: "Toggle Sidebar" });
searchParamsValue = new URLSearchParams("tab=members");
rerender(dashboard());
vi.mocked(usePathname).mockReturnValue("/ui/teams/abc-123");
@ -150,6 +157,7 @@ describe("(dashboard) Layout", () => {
});
it("closes the mobile drawer when navigation changes outside the drawer", async () => {
vi.stubGlobal("innerWidth", 390);
const dashboard = () => (
<AuthProvider>
<Layout>
@ -159,15 +167,15 @@ describe("(dashboard) Layout", () => {
);
const { rerender } = render(dashboard());
pendingUiConfig.resolve();
fireEvent.click(await screen.findByRole("button", { name: "Open navigation" }));
expect(await screen.findByRole("dialog", { name: "Navigation" })).toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "Toggle Sidebar" }));
expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument();
vi.mocked(usePathname).mockReturnValue("/ui/api-keys");
rerender(dashboard());
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument());
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument());
vi.mocked(usePathname).mockReturnValue("/ui/guardrails");
rerender(dashboard());
expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument();
expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument();
});
it("collapses the sidebar on Logs for a full-screen view and expands it again after leaving", async () => {

View file

@ -2,7 +2,6 @@
import React, { Suspense, useState, useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
import { DashboardHeader } from "@/components/DashboardHeader";
import Navbar from "@/components/navbar";
import LoadingScreen from "@/components/common_components/LoadingScreen";
@ -12,7 +11,7 @@ import { useCurrentUser } from "@/app/(dashboard)/hooks/currentUser/useCurrentUs
import { redirectToLogin } from "@/app/(dashboard)/hooks/redirectToLogin";
import { clearTokenCookies } from "@/utils/cookieUtils";
import { decodeToken } from "@/utils/jwtUtils";
import SidebarProvider from "@/app/(dashboard)/components/SidebarProvider";
import AppSidebar from "@/app/(dashboard)/components/AppSidebar";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
createDeploymentHealthHandle,
@ -27,10 +26,10 @@ import { routeSegmentForPathname, uiHref } from "@/utils/uiHref";
import { PluginModeProvider, usePluginMode } from "@/contexts/PluginModeContext";
import { createApiClient } from "@/lib/http/client";
import { getProxyBaseUrl } from "@/components/networking";
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Menu } from "lucide-react";
import { useMediaQuery } from "usehooks-ts";
import { SidebarInset, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { useCloseMobileSidebarOn } from "@/components/shared/MobileSidebar";
import { sidebarProviderClassName, sidebarWidthStyle } from "@/components/shared/sidebarStyles";
import { cn } from "@/lib/cva.config";
import { CommandPaletteProvider } from "@/components/CommandPalette/CommandPaletteProvider";
import { recordUiEvent } from "@/lib/telemetry/uiEvents";
import TelemetryEnvBanner from "@/app/(dashboard)/telemetry/_components/TelemetryEnvBanner";
@ -116,6 +115,11 @@ export function AgentControlPlaneView() {
}
const FULL_BLEED_SEGMENTS = new Set(["logs"]);
function CloseMobileSidebarOnNavigation({ navigationKey }: { navigationKey: string }) {
useCloseMobileSidebarOn(navigationKey);
return null;
}
const CUSTOMER_PORTAL_SEGMENTS = new Set(["customers"]);
function DashboardShell({ children }: { children: React.ReactNode }) {
@ -134,19 +138,12 @@ function DashboardShell({ children }: { children: React.ReactNode }) {
}, [routeSegment]);
const searchParams = useSearchParams();
const navigationKey = `${pathname}?${searchParams.toString()}`;
const isDesktop = useMediaQuery("(min-width: 768px)", { initializeWithValue: false });
const [mobileNavigationKey, setMobileNavigationKey] = useState<string | null>(null);
const [mobileNavigationHandle] = useState(() => DialogPrimitive.createHandle());
const [deploymentHealthHandle] = useState(createDeploymentHealthHandle);
if (mobileNavigationKey !== null && (isDesktop || mobileNavigationKey !== navigationKey)) {
setMobileNavigationKey(null);
}
const mobileNavigationOpen = !isDesktop && mobileNavigationKey === navigationKey;
const isFullBleed = FULL_BLEED_SEGMENTS.has(routeSegment);
// A manual toggle holds only for the route it was made on; full-bleed routes default to collapsed.
const [sidebarOverride, setSidebarOverride] = useState<{ segment: string; collapsed: boolean } | null>(null);
const sidebarCollapsed = sidebarOverride?.segment === routeSegment ? sidebarOverride.collapsed : isFullBleed;
const toggleSidebar = () => setSidebarOverride({ segment: routeSegment, collapsed: !sidebarCollapsed });
const setSidebarOpen = (open: boolean) => setSidebarOverride({ segment: routeSegment, collapsed: !open });
const isGateway = mode === "ai-gateway" || mode === "customer-portal";
@ -178,53 +175,26 @@ function DashboardShell({ children }: { children: React.ReactNode }) {
// so the page can't be dragged past the end of the nav.
return (
<LiteAdminFrame>
<div className="flex h-screen overflow-hidden bg-background max-md:h-dvh">
<div className="hidden h-full md:flex">
<SidebarProvider sidebarCollapsed={sidebarCollapsed} onToggleCollapsed={toggleSidebar} />
</div>
<Sheet
handle={mobileNavigationHandle}
open={mobileNavigationOpen}
onOpenChange={(open) => setMobileNavigationKey(open ? navigationKey : null)}
>
<SheetContent
side="left"
showCloseButton={false}
className="gap-0 p-0 data-[side=left]:w-[min(280px,calc(100vw-3rem))] [&_[data-slot=sidebar]]:w-full"
onClickCapture={(event) => {
if (event.target instanceof Element && event.target.closest("a[href]")) setMobileNavigationKey(null);
}}
>
<SheetTitle className="sr-only">{t("shell.dashboardShell.navigation")}</SheetTitle>
<SidebarProvider sidebarCollapsed={false} onToggleCollapsed={() => setMobileNavigationKey(null)} />
</SheetContent>
</Sheet>
<SidebarProvider
open={!sidebarCollapsed}
onOpenChange={setSidebarOpen}
style={sidebarWidthStyle}
className={cn("h-screen overflow-hidden bg-background max-md:h-dvh", sidebarProviderClassName)}
>
<CloseMobileSidebarOnNavigation navigationKey={navigationKey} />
<AppSidebar />
<CommandPaletteProvider>
<div className="flex min-w-0 flex-1 flex-col overflow-hidden">
<SidebarInset className="min-w-0 overflow-hidden">
<DashboardHeader
accessToken={accessToken}
navigationTrigger={
<SheetTrigger
handle={mobileNavigationHandle}
render={
<Button
variant="ghost"
size="icon"
className="size-11 md:hidden"
aria-label={t("shell.dashboardShell.openNavigation")}
/>
}
>
<Menu />
</SheetTrigger>
}
navigationTrigger={<SidebarTrigger className="size-11 md:hidden" />}
deploymentHealth={<DeploymentHealthIcon handle={deploymentHealthHandle} />}
deploymentHealthLink={<DeploymentHealthLink handle={deploymentHealthHandle} />}
/>
<DeploymentHealthBanner handle={deploymentHealthHandle} />
<DeploymentHealthPanel handle={deploymentHealthHandle} />
<UserBanner accessToken={accessToken} />
<main
<div
className={
routeSegment === "aria"
? "flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden"
@ -233,10 +203,10 @@ function DashboardShell({ children }: { children: React.ReactNode }) {
>
<TelemetryEnvBanner />
{children}
</main>
</div>
</div>
</SidebarInset>
</CommandPaletteProvider>
</div>
</SidebarProvider>
</LiteAdminFrame>
);
}

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { menuGroups } from "@/components/leftnav";
import { menuGroups } from "@/components/LeftNav";
import { legacyPageRedirectHref } from "./legacyPageRoutes";
const redirect = (query: string) => legacyPageRedirectHref(new URLSearchParams(query));

View file

@ -64,7 +64,7 @@ interface PromptItem {
The component is fully integrated into the main application:
1. **Left Navigation**: Added to `leftnav.tsx` with `FileTextOutlined` icon
1. **Left Navigation**: Added to `LeftNav.tsx` with `FileTextOutlined` icon
2. **Main Routing**: Added to `page.tsx` with proper routing logic
3. **Permissions**: Restricted to admin roles (same as guardrails)

View file

@ -41,6 +41,7 @@ let themeResponse: unknown = { values: {} };
describe("Chat layout product navigation", () => {
beforeEach(() => {
vi.stubGlobal("innerWidth", 390);
themeResponse = { values: {} };
route.pathname = "/ui/chat";
localStorage.clear();
@ -106,7 +107,7 @@ describe("Chat layout product navigation", () => {
</ChatLayout>,
);
await user.click(screen.getByRole("button", { name: "Open chat navigation" }));
await user.click(screen.getByRole("button", { name: "Toggle Sidebar" }));
const logo = await screen.findByRole("link", { name: "Chat home" });
const light = within(logo).getByAltText("LiteLLM");
const dark = within(logo).getByAltText("");
@ -126,8 +127,8 @@ describe("Chat layout product navigation", () => {
</ChatLayout>,
);
await user.click(screen.getByRole("button", { name: "Open chat navigation" }));
expect(await screen.findByRole("dialog", { name: "LiteLLM Chat" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Toggle Sidebar" }));
expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument();
expect(screen.getByAltText("LiteLLM")).toHaveAttribute("src", `${getProxyBaseUrl()}/get_image`);
});
@ -147,7 +148,7 @@ describe("Chat layout product navigation", () => {
);
expect(screen.getByRole("heading", { name: "Chat content" })).toBeVisible();
await user.click(screen.getByRole("button", { name: "Open chat navigation" }));
await user.click(screen.getByRole("button", { name: "Toggle Sidebar" }));
await user.click(screen.getByRole("button", { name: "Switch workspace, current: Chat" }));
expect(await screen.findByRole("menuitem", { name: "Observability" })).toBeInTheDocument();
expect(localStorage.getItem("litellm_plugin_mode")).toBe(plugin.name);
@ -181,7 +182,7 @@ describe("Chat layout product navigation", () => {
);
expect(screen.getByRole("heading", { name: "Chat content" })).toBeVisible();
await user.click(screen.getByRole("button", { name: "Open chat navigation" }));
await user.click(screen.getByRole("button", { name: "Toggle Sidebar" }));
await user.click(screen.getByRole("button", { name: "Switch workspace, current: Chat" }));
expect(await screen.findByRole("menuitem", { name: "Observability" })).toBeInTheDocument();
await user.click(screen.getByRole("menuitem", { name: "AI Gateway", exact: true }));

View file

@ -6,7 +6,7 @@ import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings";
import useIsOrgAdmin from "@/app/(dashboard)/hooks/useIsOrgAdmin";
import { isUserTeamAdminForAnyTeam } from "@/utils/roles";
import { menuGroups, visibleMenuGroups, type MenuVisibilityContext } from "@/components/leftnav";
import { menuGroups, visibleMenuGroups, type MenuVisibilityContext } from "@/components/LeftNav";
export const useVisibleMenuGroups = () => {
const { userId, userRole, isViewOnly } = useAuthorized();

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { visibleMenuGroups, type MenuGroup, menuGroups } from "@/components/leftnav";
import { visibleMenuGroups, type MenuGroup, menuGroups } from "@/components/LeftNav";
import { toSiTerminology } from "@/lib/terminology";
import { effectiveSessionRole, isViewOnlySessionRole } from "@/utils/roles";
import { flattenNavItems, matchNavItems, paletteScopeForRoute, shortcutLabel, type PaletteNavItem } from "./utils";

View file

@ -1,5 +1,5 @@
import type { ReactNode } from "react";
import { labelText, routeOf, sectionText, type MenuGroup } from "@/components/leftnav";
import { labelText, routeOf, sectionText, type MenuGroup } from "@/components/LeftNav";
import { keepTerminology, type Term } from "@/lib/terminology";
import i18n from "@/i18n/i18n";

View file

@ -4,7 +4,7 @@ import type { ReactNode } from "react";
import ThemeToggle from "@/components/ThemeToggle/ThemeToggle";
import { usePathname } from "next/navigation";
import { useTerminology } from "@/contexts/TerminologyContext";
import { getBreadcrumb } from "@/components/leftnav";
import { getBreadcrumb } from "@/components/LeftNav";
import { CommandPaletteTrigger } from "@/components/CommandPalette/CommandPaletteTrigger";
import { DashboardCommunityLinks } from "@/components/Navbar/DashboardResources";
import { NotificationsBell } from "@/components/Navbar/NotificationsBell/NotificationsBell";

View file

@ -1,10 +1,32 @@
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { ComponentProps } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../../tests/test-utils";
import { TerminologyProvider } from "@/contexts/TerminologyContext";
import { PluginModeProvider } from "@/contexts/PluginModeContext";
import Sidebar, { menuGroups, getBreadcrumb } from "./leftnav";
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { useCloseMobileSidebarOn } from "@/components/shared/MobileSidebar";
import LeftNav, { menuGroups, getBreadcrumb } from "./LeftNav";
const Sidebar = ({ collapsed = false, ...props }: ComponentProps<typeof LeftNav> & { collapsed?: boolean }) => (
<SidebarProvider defaultOpen={!collapsed}>
<LeftNav {...props} />
</SidebarProvider>
);
const CloseOnBreakpointChange = () => {
useCloseMobileSidebarOn();
return null;
};
const PhoneShell = ({ railCollapsed = false }: { railCollapsed?: boolean }) => (
<SidebarProvider defaultOpen={!railCollapsed}>
<CloseOnBreakpointChange />
<SidebarTrigger />
<LeftNav />
</SidebarProvider>
);
vi.mock("../utils/roles", async (importOriginal) => {
const actual = await importOriginal<typeof import("../utils/roles")>();
@ -22,6 +44,7 @@ vi.mock("../utils/roles", async (importOriginal) => {
});
const navState = vi.hoisted(() => ({ pathname: "/ui/api-keys" }));
const health = vi.hoisted(() => ({ version: undefined as string | undefined }));
vi.mock("next/navigation", () => ({
usePathname: () => navState.pathname,
@ -96,7 +119,7 @@ vi.mock("@/contexts/ThemeContext", () => ({
// Version tag + logout target come from network hooks; keep them inert in unit tests.
vi.mock("@/app/(dashboard)/hooks/healthReadiness/useHealthReadinessDetails", () => ({
useHealthReadinessDetails: () => ({ data: undefined }),
useHealthReadinessDetails: () => ({ data: health.version ? { litellm_version: health.version } : undefined }),
}));
vi.mock("@/app/(dashboard)/hooks/useLogout", () => ({
useLogout: () => vi.fn(),
@ -145,6 +168,7 @@ describe("Sidebar (leftnav)", () => {
};
afterEach(() => {
vi.unstubAllGlobals();
mockUseAuthorized.mockReset();
mockUseOrganizations.mockReset();
mockUseTeams.mockReset();
@ -155,6 +179,7 @@ describe("Sidebar (leftnav)", () => {
});
mockUseThemeImpl = unbrandedTheme;
navState.pathname = "/ui/api-keys";
health.version = undefined;
uiConfig.data = { admin_ui_disabled: false, use_si_terminology: false };
localStorage.removeItem("litellm_plugin_mode");
});
@ -187,7 +212,7 @@ describe("Sidebar (leftnav)", () => {
</PluginModeProvider>,
);
expect(screen.getByRole("link", { name: "Customer organizations" })).toHaveAttribute("href", "/ui/customers");
expect(screen.getByRole("link", { name: "Customer organizations" })).toHaveAttribute("data-active", "true");
expect(screen.getByRole("link", { name: "Customer organizations" })).toHaveAttribute("data-active");
expect(screen.queryByRole("link", { name: "End users" })).not.toBeInTheDocument();
});
@ -680,14 +705,64 @@ describe("Sidebar (leftnav)", () => {
it("marks the nav item for the current route active", () => {
navState.pathname = "/ui/logs";
renderWithProviders(<Sidebar {...defaultProps} />);
expect(screen.getByRole("link", { name: "Logs" })).toHaveAttribute("data-active", "true");
expect(screen.getByRole("link", { name: "Logs" })).toHaveAttribute("data-active");
expect(screen.getByRole("link", { name: "Virtual Keys" })).not.toHaveAttribute("data-active");
});
it("closes the mobile drawer after following any link in it, including the page already open", async () => {
vi.stubGlobal("innerWidth", 390);
navState.pathname = "/ui/api-keys";
health.version = "1.2.3";
renderWithProviders(<PhoneShell />);
for (const page of ["Virtual Keys", "Playground", "v1.2.3"]) {
fireEvent.click(await screen.findByRole("button", { name: "Toggle Sidebar" }));
fireEvent.click(within(await screen.findByRole("dialog", { name: "Sidebar" })).getByRole("link", { name: page }));
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument());
}
});
it("shows the full nav in the phone drawer when the desktop rail was left collapsed", async () => {
vi.stubGlobal("innerWidth", 390);
navState.pathname = "/ui/search-tools";
renderWithProviders(<PhoneShell railCollapsed />);
fireEvent.click(await screen.findByRole("button", { name: "Toggle Sidebar" }));
const drawer = await screen.findByRole("dialog", { name: "Sidebar" });
expect(within(drawer).getByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true");
const tools = within(drawer).getByRole("button", { name: "Tools" });
expect(tools).toHaveAttribute("aria-expanded", "true");
fireEvent.click(tools);
expect(tools).toHaveAttribute("aria-expanded", "false");
});
it("keeps the phone drawer closed after the window widens to desktop and narrows again", async () => {
const breakpointListeners = new Set<() => void>();
vi.stubGlobal("matchMedia", (media: string) => ({
matches: false,
media,
addEventListener: (_: string, listener: () => void) => breakpointListeners.add(listener),
removeEventListener: (_: string, listener: () => void) => breakpointListeners.delete(listener),
}));
const resizeTo = async (width: number) => {
vi.stubGlobal("innerWidth", width);
await act(async () => breakpointListeners.forEach((listener) => listener()));
};
vi.stubGlobal("innerWidth", 390);
renderWithProviders(<PhoneShell />);
fireEvent.click(await screen.findByRole("button", { name: "Toggle Sidebar" }));
expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument();
await resizeTo(1200);
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument());
await resizeTo(390);
await act(async () => new Promise((resolve) => setTimeout(resolve, 300)));
expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Toggle Sidebar" })).toBeInTheDocument();
});
it("marks Home active at the dashboard root", () => {
navState.pathname = "/ui/";
renderWithProviders(<Sidebar {...defaultProps} />);
expect(screen.getByRole("link", { name: "Home" })).toHaveAttribute("data-active", "true");
expect(screen.getByRole("link", { name: "Home" })).toHaveAttribute("data-active");
});
it("does not highlight Home when the Aria workspace is active", () => {
@ -699,7 +774,7 @@ describe("Sidebar (leftnav)", () => {
it("expands the parent group of the current nested route and marks the child active", () => {
navState.pathname = "/ui/search-tools";
renderWithProviders(<Sidebar {...defaultProps} />);
expect(screen.getByRole("link", { name: "Search Tools" })).toHaveAttribute("data-active", "true");
expect(screen.getByRole("link", { name: "Search Tools" })).toHaveAttribute("data-active");
expect(screen.getByRole("button", { name: "Tools" })).toHaveAttribute("aria-expanded", "true");
});
@ -730,17 +805,23 @@ describe("Sidebar (leftnav)", () => {
expect(hrefs.filter((href) => href.startsWith("/ui/")).length).toBeGreaterThan(30);
});
it("hides labels but keeps items reachable (icon + link) when collapsed to the rail", () => {
it("exposes the sidebar as a complementary landmark", () => {
renderWithProviders(<Sidebar {...defaultProps} />);
expect(within(screen.getByRole("complementary")).getByRole("link", { name: "Virtual Keys" })).toBeInTheDocument();
});
it("expands the rail and opens the group when a group is chosen while collapsed", async () => {
renderWithProviders(<Sidebar {...defaultProps} collapsed />);
fireEvent.click(screen.getByRole("button", { name: "Tools" }));
expect(await screen.findByRole("link", { name: "Search Tools" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true");
});
it("keeps items reachable by name and icon when collapsed to the rail", () => {
const { container } = renderWithProviders(<Sidebar {...defaultProps} collapsed />);
expect(container.querySelector('[data-slot="sidebar"]')).toHaveAttribute("data-collapsed", "true");
// The item stays navigable in the icon-only rail: its link still renders with
// an icon (asserting the <a> + svg, not the text, so a removed icon would
// fail here), while the label is present but CSS-hidden.
const label = screen.getByText("Virtual Keys");
const link = label.closest("a");
expect(link).not.toBeNull();
expect(link!.querySelector("svg")).not.toBeNull();
expect(label).toHaveClass("group-data-[collapsed=true]/sidebar:hidden");
expect(container.querySelector('[data-slot="sidebar"]')).toHaveAttribute("data-collapsible", "icon");
const link = screen.getByRole("link", { name: "Virtual Keys" });
expect(link.querySelector("svg")).not.toBeNull();
});
it("shows Cost Optimization without a Beta badge and no feature-flag gate", () => {
@ -754,11 +835,17 @@ describe("Sidebar (leftnav)", () => {
expect(container.querySelector('a[href*="projects"]')).toBeNull();
});
it("keeps a readable collapsed-rail tooltip for items whose label carries a badge", () => {
const { container } = renderWithProviders(<Sidebar {...defaultProps} enableProjectsUI collapsed />);
it.each([
["Cost Optimization", "/ui/cost-optimization"],
["Projects", "/ui/projects"],
])("titles the collapsed-rail link for %s without its badge text", (name, href) => {
renderWithProviders(<Sidebar {...defaultProps} enableProjectsUI collapsed />);
expect(screen.getByTitle(name)).toHaveAttribute("href", href);
});
expect(container.querySelector('a[href*="cost-optimization"]')).toHaveAttribute("title", "Cost Optimization");
expect(container.querySelector('a[href*="projects"]')).toHaveAttribute("title", "Projects");
it("leaves expanded-rail links untitled", () => {
renderWithProviders(<Sidebar {...defaultProps} enableProjectsUI />);
expect(screen.queryByTitle("Cost Optimization")).not.toBeInTheDocument();
});
});

View file

@ -8,6 +8,7 @@ import { useTerminology } from "@/contexts/TerminologyContext";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupLabel,
@ -15,9 +16,19 @@ import {
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarSeparator,
sidebarMenuButtonVariants,
} from "@/components/shared/Sidebar";
useSidebar,
} from "@/components/ui/sidebar";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
navMenuButtonClassName,
navMenuClassName,
navMenuSubButtonClassName,
navMenuSubClassName,
shellSidebarClassName,
} from "@/components/shared/sidebarStyles";
import {
Activity,
Aperture,
@ -61,7 +72,7 @@ import ViewSwitcher from "@/components/Navbar/ViewSwitcher";
import { usePluginMode } from "@/contexts/PluginModeContext";
import { AriaSidebarLink } from "@/components/liteadmin/LiteAdmin";
import { usePathname } from "next/navigation";
import { useMemo, useState } from "react";
import { type MouseEvent, useMemo, useState } from "react";
import { Trans, useTranslation } from "react-i18next";
import type { ParseKeys } from "i18next";
import i18n from "@/i18n/i18n";
@ -86,8 +97,6 @@ import { routeSegmentForPathname, uiHref } from "@/utils/uiHref";
const ICON = { strokeWidth: 1.75 } as const;
interface SidebarProps {
collapsed?: boolean;
onToggleCollapsed?: () => void;
enabledPagesInternalUsers?: string[] | null;
enableProjectsUI?: boolean;
disableAgentsForInternalUsers?: boolean;
@ -577,9 +586,12 @@ export const getBreadcrumb = (pathname: string): { section: string | null; title
return { section: null, title: prettify(route) };
};
const groupsOpenFor = (route: string) => {
const parent = findParentKey(route);
return new Set(parent ? [parent] : []);
};
const Sidebar_: React.FC<SidebarProps> = ({
collapsed = false,
onToggleCollapsed,
enabledPagesInternalUsers,
enableProjectsUI,
disableAgentsForInternalUsers,
@ -595,14 +607,16 @@ const Sidebar_: React.FC<SidebarProps> = ({
const isOrgAdmin = useIsOrgAdmin();
const { data: teams } = useTeams();
const logout = useLogout(accessToken);
const { state, isMobile, setOpen, setOpenMobile } = useSidebar();
const collapsed = state === "collapsed" && !isMobile;
const closeMobileSidebarOnLinkClick = (event: MouseEvent) => {
if (event.target instanceof Element && event.target.closest("a[href]")) setOpenMobile(false);
};
const currentRoute = routeForPathname(usePathname());
const selectedKey = currentRoute === "aria" ? null : findMenuItemKey(currentRoute);
const [openGroups, setOpenGroups] = useState<Set<string>>(() => {
const parent = findParentKey(currentRoute);
return new Set(parent ? [parent] : []);
});
const [openGroups, setOpenGroups] = useState<Set<string>>(() => groupsOpenFor(currentRoute));
// Keep the active page's parent group expanded as the user navigates, using the
// "adjust state during render" pattern rather than an effect (avoids a
@ -646,128 +660,129 @@ const Sidebar_: React.FC<SidebarProps> = ({
userRole,
]);
const toggleGroup = (key: string) => {
const setGroupOpen = (key: string, open: boolean) => {
if (collapsed) {
onToggleCollapsed?.();
setOpen(true);
setOpenGroups((prev) => new Set(prev).add(key));
return;
}
setOpenGroups((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
if (open) next.add(key);
else next.delete(key);
return next;
});
};
const renderLeaf = (item: MenuItem, isChild: boolean) => {
const active = selectedKey === item.key;
const size = isChild ? "sub" : "default";
const label = <span className="flex-1 truncate group-data-[collapsed=true]/sidebar:hidden">{labelOf(item)}</span>;
const leafLink = (item: MenuItem) =>
item.external_url ? (
<a href={item.external_url} target="_blank" rel="noopener noreferrer" />
) : (
<Link href={uiHref(routeOf(item))} />
);
if (item.external_url) {
const leafContent = (item: MenuItem) => (
<>
{item.icon}
<span className="flex-1 truncate group-data-[collapsible=icon]:hidden">{labelOf(item)}</span>
{item.external_url && (
<ExternalLink className="size-3.5 shrink-0 opacity-70 group-data-[collapsible=icon]:hidden" />
)}
</>
);
const renderItem = (item: MenuItem) => {
const active = selectedKey === item.key;
const title = collapsed ? term(labelText(item)) : undefined;
if (!item.children?.length) {
return (
<a
key={item.key}
href={item.external_url}
target="_blank"
rel="noopener noreferrer"
title={collapsed ? term(labelText(item)) : undefined}
data-active={active || undefined}
className={cn(sidebarMenuButtonVariants({ isActive: active, size }))}
>
{item.icon}
{label}
<ExternalLink className="size-3.5 shrink-0 opacity-70 group-data-[collapsed=true]/sidebar:hidden" />
</a>
<SidebarMenuItem key={item.key}>
<SidebarMenuButton isActive={active} title={title} className={navMenuButtonClassName} render={leafLink(item)}>
{leafContent(item)}
</SidebarMenuButton>
</SidebarMenuItem>
);
}
return (
<Link
key={item.key}
href={uiHref(routeOf(item))}
title={collapsed ? term(labelText(item)) : undefined}
data-active={active || undefined}
className={cn(sidebarMenuButtonVariants({ isActive: active, size }))}
>
{item.icon}
{label}
</Link>
);
};
const renderItem = (item: MenuItem) => {
const isGroup = !!item.children && item.children.length > 0;
if (!isGroup) {
return <SidebarMenuItem key={item.key}>{renderLeaf(item, false)}</SidebarMenuItem>;
}
const active = selectedKey === item.key;
const open = openGroups.has(item.key);
return (
<SidebarMenuItem key={item.key}>
<SidebarMenuButton
isActive={active}
aria-expanded={open}
onClick={() => toggleGroup(item.key)}
title={collapsed ? term(labelText(item)) : undefined}
<Collapsible
key={item.key}
open={open}
onOpenChange={(next) => setGroupOpen(item.key, next)}
render={<SidebarMenuItem />}
>
<CollapsibleTrigger
render={<SidebarMenuButton isActive={active} title={title} className={navMenuButtonClassName} />}
>
{item.icon}
<span className="flex-1 truncate group-data-[collapsed=true]/sidebar:hidden">{labelOf(item)}</span>
<span className="flex-1 truncate group-data-[collapsible=icon]:hidden">{labelOf(item)}</span>
<ChevronRight
className={cn(
"size-4 shrink-0 transition-transform group-data-[collapsed=true]/sidebar:hidden",
"size-4 shrink-0 transition-transform group-data-[collapsible=icon]:hidden",
open && "rotate-90",
)}
/>
</SidebarMenuButton>
{open && (
<SidebarMenuSub>
{item.children!.map((child) => (
<SidebarMenuItem key={child.key}>{renderLeaf(child, true)}</SidebarMenuItem>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub className={navMenuSubClassName}>
{item.children.map((child) => (
<SidebarMenuSubItem key={child.key}>
<SidebarMenuSubButton
isActive={selectedKey === child.key}
className={navMenuSubButtonClassName}
render={leafLink(child)}
>
{leafContent(child)}
</SidebarMenuSubButton>
</SidebarMenuSubItem>
))}
</SidebarMenuSub>
)}
</SidebarMenuItem>
</CollapsibleContent>
</Collapsible>
);
};
return (
<Sidebar collapsed={collapsed}>
<SidebarBrand
accessToken={accessToken}
homeLabel={t("shell.nav.homeLink")}
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
/>
<Sidebar collapsible="icon" role="complementary" className={shellSidebarClassName}>
<div className="contents" onClickCapture={closeMobileSidebarOnLinkClick}>
<SidebarBrand accessToken={accessToken} homeLabel={t("shell.nav.homeLink")} />
<div className="space-y-1 px-3 pt-3 pb-1">
<ViewSwitcher className="h-9 w-full max-w-none justify-start shadow-none group-data-[collapsed=true]/sidebar:size-9 group-data-[collapsed=true]/sidebar:justify-center group-data-[collapsed=true]/sidebar:p-0 [&_[data-slot=workspace-label]]:flex-1 [&_[data-slot=workspace-label]]:text-left group-data-[collapsed=true]/sidebar:[&_[data-slot=workspace-label]]:hidden" />
<AriaSidebarLink active={currentRoute === "aria"} />
</div>
<ScrollArea className="min-h-0 flex-1">
<nav className="flex flex-col gap-0.5 px-3 pb-3">
{visibleGroups.map((group, gi) => (
<SidebarGroup key={group.groupLabel}>
{gi > 0 && <SidebarSeparator className="hidden group-data-[collapsed=true]/sidebar:block" />}
<SidebarGroupLabel>{term(groupText(group.groupLabel))}</SidebarGroupLabel>
<SidebarMenu>{group.items.map((item) => renderItem(item))}</SidebarMenu>
</SidebarGroup>
))}
</nav>
</ScrollArea>
<SidebarFooter>
{isAdminRole(userRole) && (
<SidebarUsageCard
accessToken={accessToken}
<SidebarGroup className="gap-1 px-3 pt-3 pb-1">
<ViewSwitcher
collapsed={collapsed}
onExpandRail={() => onToggleCollapsed?.()}
className="h-9 w-full max-w-none justify-start shadow-none group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:p-0 [&_[data-slot=workspace-label]]:flex-1 [&_[data-slot=workspace-label]]:text-left group-data-[collapsible=icon]:[&_[data-slot=workspace-label]]:hidden"
/>
)}
<SidebarAccountMenu onLogout={logout} collapsed={collapsed} />
</SidebarFooter>
<AriaSidebarLink active={currentRoute === "aria"} />
</SidebarGroup>
<SidebarContent>
<ScrollArea className="min-h-0 flex-1">
<nav className="flex flex-col gap-0.5 px-3 pb-3">
{visibleGroups.map((group, gi) => (
<SidebarGroup key={group.groupLabel} className="gap-0.5 px-0 py-1">
{gi > 0 && (
<SidebarSeparator
aria-hidden
className="my-2 hidden data-horizontal:w-auto group-data-[collapsible=icon]:block"
/>
)}
<SidebarGroupLabel className="block h-auto pt-3 pb-1.5 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase group-data-[collapsible=icon]:hidden">
{term(groupText(group.groupLabel))}
</SidebarGroupLabel>
<SidebarMenu className={navMenuClassName}>{group.items.map((item) => renderItem(item))}</SidebarMenu>
</SidebarGroup>
))}
</nav>
</ScrollArea>
</SidebarContent>
<SidebarFooter className="flex-none gap-2.5 border-t border-sidebar-border p-3">
{isAdminRole(userRole) && (
<SidebarUsageCard accessToken={accessToken} collapsed={collapsed} onExpandRail={() => setOpen(true)} />
)}
<SidebarAccountMenu onLogout={logout} collapsed={collapsed} />
</SidebarFooter>
</div>
</Sidebar>
);
};

View file

@ -10,7 +10,6 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Check, ChevronDown, ChevronsUpDown } from "lucide-react";
import { useSidebar } from "@/components/shared/Sidebar";
import BetaBadge from "@/components/BetaBadge";
import { usePluginMode } from "@/contexts/PluginModeContext";
import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings";
@ -51,15 +50,15 @@ interface ViewSwitcherItem {
interface ViewSwitcherProps {
className?: string;
contentClassName?: string;
collapsed?: boolean;
}
const pluginLabel = (mode: string, plugins: readonly { name: string; display_name: string }[], portalLabel: string) =>
mode === CUSTOMER_PORTAL ? portalLabel : plugins.find((p) => p.name === mode)?.display_name;
export default function ViewSwitcher({ className, contentClassName }: ViewSwitcherProps) {
export default function ViewSwitcher({ className, contentClassName, collapsed = false }: ViewSwitcherProps) {
const { t } = useTranslation();
const term = useTerminology();
const { collapsed } = useSidebar();
const { mode, setMode, plugins } = usePluginMode();
const { data: uiSettings } = useUISettings();
const pathname = usePathname();

View file

@ -1,18 +1,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { screen, waitFor, fireEvent } from "@testing-library/react";
import { screen, waitFor, fireEvent, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderWithProviders } from "@/../tests/test-utils";
import { stubViewportMatchMedia } from "@/../tests/viewport";
import type { ReactElement } from "react";
import { ThemeProvider } from "@/contexts/ThemeContext";
import ChatShell from "./ChatShell";
const render = (ui: ReactElement) => renderWithProviders(<ThemeProvider>{ui}</ThemeProvider>);
const { mockPush, mockUsePathname, mockUseChatShell, mockUseMediaQuery, mockLogout } = vi.hoisted(() => ({
const { mockPush, mockUsePathname, mockUseChatShell, mockLogout } = vi.hoisted(() => ({
mockPush: vi.fn(),
mockLogout: vi.fn(),
mockUsePathname: vi.fn(() => "/ui/chat"),
mockUseMediaQuery: vi.fn(() => true),
mockUseChatShell: vi.fn(() => ({
accessToken: "test-token",
userEmail: "developer@example.com",
@ -39,7 +39,6 @@ vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({
useUISettings: () => ({ data: { values: { enable_chat_ui: true } } }),
}));
vi.mock("@/app/(dashboard)/hooks/useLogout", () => ({ useLogout: () => mockLogout }));
vi.mock("usehooks-ts", () => ({ useMediaQuery: mockUseMediaQuery }));
describe("ChatShell", () => {
beforeEach(() => {
@ -53,7 +52,6 @@ describe("ChatShell", () => {
vi.unstubAllGlobals();
mockPush.mockClear();
mockUsePathname.mockReturnValue("/ui/chat");
mockUseMediaQuery.mockReturnValue(true);
});
it("should render the chat workspace with a single New Chat action", () => {
@ -147,7 +145,7 @@ describe("ChatShell", () => {
});
it("should open mobile navigation and close it after selecting Models", async () => {
mockUseMediaQuery.mockReturnValue(false);
vi.stubGlobal("innerWidth", 390);
const user = userEvent.setup();
render(
<ChatShell>
@ -156,8 +154,8 @@ describe("ChatShell", () => {
);
expect(screen.queryByRole("navigation", { name: "Chat workspace" })).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Open chat navigation" }));
expect(await screen.findByRole("dialog", { name: "LiteLLM Chat" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Toggle Sidebar" }));
expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Models" }));
expect(mockPush).toHaveBeenCalledWith("/ui/chat/models");
@ -166,7 +164,7 @@ describe("ChatShell", () => {
});
it("should dismiss mobile navigation when the Chat home logo is selected", async () => {
mockUseMediaQuery.mockReturnValue(false);
vi.stubGlobal("innerWidth", 390);
const user = userEvent.setup();
render(
<ChatShell>
@ -174,7 +172,7 @@ describe("ChatShell", () => {
</ChatShell>,
);
await user.click(screen.getByRole("button", { name: "Open chat navigation" }));
await user.click(screen.getByRole("button", { name: "Toggle Sidebar" }));
const home = await screen.findByRole("link", { name: "Chat home" });
expect(home).toHaveAttribute("href", "/ui/chat");
await user.click(home);
@ -185,7 +183,7 @@ describe("ChatShell", () => {
});
it("should close mobile navigation with Escape and restore trigger focus", async () => {
mockUseMediaQuery.mockReturnValue(false);
vi.stubGlobal("innerWidth", 390);
const user = userEvent.setup();
render(
<ChatShell>
@ -193,9 +191,9 @@ describe("ChatShell", () => {
</ChatShell>,
);
const trigger = screen.getByRole("button", { name: "Open chat navigation" });
const trigger = screen.getByRole("button", { name: "Toggle Sidebar" });
await user.click(trigger);
expect(await screen.findByRole("dialog", { name: "LiteLLM Chat" })).toBeInTheDocument();
expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument();
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
@ -216,8 +214,43 @@ describe("ChatShell", () => {
expect(await screen.findByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true");
});
it("should focus conversation search when the mobile sidebar starts closed", async () => {
mockUseMediaQuery.mockReturnValue(false);
it("should expand the desktop rail when search was opened at phone width", async () => {
const resizeTo = stubViewportMatchMedia();
const user = userEvent.setup();
render(
<ChatShell>
<div />
</ChatShell>,
);
await user.click(screen.getByRole("button", { name: "Collapse sidebar" }));
await resizeTo(390);
fireEvent.keyDown(document, { key: "k", code: "KeyK", ctrlKey: true });
expect(await screen.findByRole("dialog", { name: "Search conversations" })).toBeInTheDocument();
await resizeTo(1280);
expect(await screen.findByRole("button", { name: "Collapse sidebar", hidden: true })).toHaveAttribute(
"aria-expanded",
"true",
);
});
it("should show the full sidebar in the phone drawer after the desktop rail was collapsed", async () => {
const resizeTo = stubViewportMatchMedia();
const user = userEvent.setup();
render(
<ChatShell>
<div />
</ChatShell>,
);
await user.click(screen.getByRole("button", { name: "Collapse sidebar" }));
await resizeTo(390);
await user.click(await screen.findByRole("button", { name: "Toggle Sidebar" }));
const drawer = await screen.findByRole("dialog", { name: "Sidebar" });
expect(within(drawer).getByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true");
expect(within(drawer).getByRole("button", { name: /^Account menu/ })).toHaveTextContent("developer@example.com");
});
it("should open only conversation search at phone width and focus it", async () => {
vi.stubGlobal("innerWidth", 390);
const user = userEvent.setup();
render(
<ChatShell>
@ -227,6 +260,7 @@ describe("ChatShell", () => {
fireEvent.keyDown(document, { key: "k", code: "KeyK", ctrlKey: true });
const search = await screen.findByRole("textbox", { name: "Search conversations" });
await waitFor(() => expect(search).toHaveFocus());
expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument();
await user.type(search, "release notes");
expect(search).toHaveValue("release notes");
});

View file

@ -3,7 +3,6 @@
import React, { useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import {
Menu,
Plus,
Network,
LayoutGrid,
@ -16,10 +15,7 @@ import {
ChevronDown,
Info,
} from "lucide-react";
import { useMediaQuery } from "usehooks-ts";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import {
DropdownMenu,
DropdownMenuContent,
@ -27,19 +23,39 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Sidebar, SidebarContent, SidebarFooter, SidebarMenuButton } from "@/components/shared/Sidebar";
import {
Sidebar,
SidebarFooter,
SidebarGroup,
SidebarInset,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarProvider,
SidebarTrigger,
useSidebar,
} from "@/components/ui/sidebar";
import { useCloseMobileSidebarOn } from "@/components/shared/MobileSidebar";
import {
navMenuButtonClassName,
navMenuClassName,
shellSidebarClassName,
sidebarProviderClassName,
sidebarWidthStyle,
} from "@/components/shared/sidebarStyles";
import { cn } from "@/lib/cva.config";
import { SidebarBrand } from "@/components/shared/SidebarBrand";
import ChatAccountMenu from "./ChatAccountMenu";
import { Kbd } from "@/components/ui/kbd";
import { useShortcutLabel } from "@/components/CommandPalette/useShortcutLabel";
import { useHotkeys } from "react-hotkeys-hook";
import { DashboardHeader } from "@/components/DashboardHeader";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
import { useLogout } from "@/app/(dashboard)/hooks/useLogout";
import { uiHref } from "@/utils/uiHref";
import { useChatShell } from "@/contexts/ChatShellContext";
import ViewSwitcher from "@/components/Navbar/ViewSwitcher";
import ConversationList from "./ConversationList";
import ConversationSearchDialog from "./ConversationSearchDialog";
const conversationUrl = (chatsRoute: string, id: string) => `${chatsRoute}?id=${encodeURIComponent(id)}`;
@ -70,41 +86,47 @@ interface NavItemProps {
function NavItem({ icon, label, onClick, active = false, shortcut }: NavItemProps) {
return (
<SidebarMenuButton
onClick={onClick}
isActive={active}
aria-label={label}
title={label}
aria-current={active ? "page" : undefined}
>
{icon}
<span className="flex-1 truncate group-data-[collapsed=true]/sidebar:hidden">{label}</span>
{shortcut && (
<Kbd className="bg-transparent text-muted-foreground group-data-[collapsed=true]/sidebar:hidden">
{shortcut}
</Kbd>
)}
</SidebarMenuButton>
<SidebarMenuItem role="none">
<SidebarMenuButton
onClick={onClick}
isActive={active}
aria-label={label}
title={label}
aria-current={active ? "page" : undefined}
className={navMenuButtonClassName}
>
{icon}
<span className="flex-1 truncate">{label}</span>
{shortcut && (
<Kbd className="bg-transparent text-muted-foreground group-data-[collapsible=icon]:hidden">{shortcut}</Kbd>
)}
</SidebarMenuButton>
</SidebarMenuItem>
);
}
const ChatShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const ChatShell: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<SidebarProvider
style={sidebarWidthStyle}
className={cn("chat-theme h-full min-h-0 overflow-hidden bg-background text-foreground", sidebarProviderClassName)}
>
<ChatShellLayout>{children}</ChatShellLayout>
</SidebarProvider>
);
function ChatShellLayout({ children }: { children: React.ReactNode }) {
const { t } = useTranslation();
const router = useRouter();
const pathname = stripTrailingSlash(usePathname() ?? "");
const { accessToken, conversations, activeConversationId, deleteConversation, renameConversation } = useChatShell();
const handleLogout = useLogout(accessToken);
const isDesktop = useMediaQuery("(min-width: 768px)", { initializeWithValue: false });
const [sidebarOpen, setSidebarOpen] = useState(false);
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const { state, isMobile, setOpen, setOpenMobile } = useSidebar();
const collapsed = state === "collapsed" && !isMobile;
useCloseMobileSidebarOn();
const [searchOpen, setSearchOpen] = useState(false);
if (isDesktop && sidebarOpen) setSidebarOpen(false);
const collapsed = isDesktop && sidebarCollapsed;
const [mobileNavigationHandle] = useState(() => DialogPrimitive.createHandle());
const shortcut = useShortcutLabel();
const openSearch = () => {
setSidebarCollapsed(false);
if (!isDesktop) setSidebarOpen(true);
setOpen(true);
setSearchOpen(true);
};
useHotkeys("mod+k", openSearch, { enableOnFormTags: true, preventDefault: true, useKey: true });
@ -118,80 +140,81 @@ const ChatShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
];
const workspaceActive = workspaceItems.some((item) => item.route === pathname);
const navigate = (href: string) => {
setSidebarOpen(false);
setOpenMobile(false);
setSearchOpen(false);
router.push(href);
};
const sidebar = (
<>
<SidebarBrand
accessToken={accessToken}
homeHref={routes.chats}
homeLabel={t("chat.shell.home")}
onHomeClick={() => setSidebarOpen(false)}
collapsed={collapsed}
onToggleCollapsed={() => (isDesktop ? setSidebarCollapsed(!sidebarCollapsed) : setSidebarOpen(false))}
/>
<div className="space-y-1 px-3 pt-3 pb-2">
<ViewSwitcher className="h-9 w-full max-w-none justify-start shadow-none group-data-[collapsed=true]/sidebar:size-9 group-data-[collapsed=true]/sidebar:justify-center group-data-[collapsed=true]/sidebar:p-0 [&_[data-slot=workspace-label]]:flex-1 [&_[data-slot=workspace-label]]:text-left group-data-[collapsed=true]/sidebar:[&_[data-slot=workspace-label]]:hidden" />
<NavItem icon={<Plus />} label={t("chat.shell.newChat")} onClick={() => navigate(routes.chats)} />
</div>
<SidebarContent aria-label={t("chat.shell.workspaceNav")} className="flex-none">
<NavItem
icon={<Network className="size-4" />}
label={t("chat.shell.models")}
onClick={() => navigate(routes.models)}
active={pathname === routes.models}
<SidebarBrand accessToken={accessToken} homeHref={routes.chats} homeLabel={t("chat.shell.home")} />
<SidebarGroup className="gap-1 px-3 pt-3 pb-2">
<ViewSwitcher
collapsed={collapsed}
className="h-9 w-full max-w-none justify-start shadow-none group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:p-0 [&_[data-slot=workspace-label]]:flex-1 [&_[data-slot=workspace-label]]:text-left group-data-[collapsible=icon]:[&_[data-slot=workspace-label]]:hidden"
/>
<NavItem
icon={<LayoutGrid className="size-4" />}
label={t("chat.shell.integrations")}
onClick={() => navigate(routes.integrations)}
active={pathname === routes.integrations}
/>
<DropdownMenu>
<DropdownMenuTrigger
render={
<SidebarMenuButton
isActive={workspaceActive}
aria-label={t("chat.shell.workspace")}
title={t("chat.shell.workspace")}
aria-current={workspaceActive ? "page" : undefined}
/>
}
>
<Settings2 className="size-4" />
<span className="flex-1 text-left group-data-[collapsed=true]/sidebar:hidden">
{t("chat.shell.workspace")}
</span>
<ChevronDown className="size-3.5 group-data-[collapsed=true]/sidebar:hidden" />
</DropdownMenuTrigger>
<DropdownMenuContent side="right" align="start" className="min-w-44">
{workspaceItems.map(({ label, route, Icon }) => (
<DropdownMenuItem
key={route}
aria-current={pathname === route ? "page" : undefined}
onClick={() => navigate(route)}
<SidebarMenu role="none" className={navMenuClassName}>
<NavItem icon={<Plus />} label={t("chat.shell.newChat")} onClick={() => navigate(routes.chats)} />
</SidebarMenu>
</SidebarGroup>
<nav aria-label={t("chat.shell.workspaceNav")} className="flex flex-none flex-col px-3 pb-3">
<SidebarMenu role="none" className={navMenuClassName}>
<NavItem
icon={<Network className="size-4" />}
label={t("chat.shell.models")}
onClick={() => navigate(routes.models)}
active={pathname === routes.models}
/>
<NavItem
icon={<LayoutGrid className="size-4" />}
label={t("chat.shell.integrations")}
onClick={() => navigate(routes.integrations)}
active={pathname === routes.integrations}
/>
<SidebarMenuItem role="none">
<DropdownMenu>
<DropdownMenuTrigger
render={
<SidebarMenuButton
isActive={workspaceActive}
aria-label={t("chat.shell.workspace")}
title={t("chat.shell.workspace")}
aria-current={workspaceActive ? "page" : undefined}
className={navMenuButtonClassName}
/>
}
>
<Icon className="size-4" />
{label}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem
render={
<a href="https://github.com/BerriAI/litellm/discussions/32085" target="_blank" rel="noreferrer" />
}
>
<Info className="size-4" />
{t("chat.shell.shareFeedback")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<NavItem icon={<Search />} label={t("chat.shell.searchChats")} shortcut={shortcut} onClick={openSearch} />
</SidebarContent>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden px-3 pb-3 group-data-[collapsed=true]/sidebar:hidden">
<Settings2 className="size-4" />
<span className="flex-1 truncate text-left">{t("chat.shell.workspace")}</span>
<ChevronDown className="size-3.5 group-data-[collapsible=icon]:hidden" />
</DropdownMenuTrigger>
<DropdownMenuContent side="right" align="start" className="min-w-44">
{workspaceItems.map(({ label, route, Icon }) => (
<DropdownMenuItem
key={route}
aria-current={pathname === route ? "page" : undefined}
onClick={() => navigate(route)}
>
<Icon className="size-4" />
{label}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem
render={
<a href="https://github.com/BerriAI/litellm/discussions/32085" target="_blank" rel="noreferrer" />
}
>
<Info className="size-4" />
{t("chat.shell.shareFeedback")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
<NavItem icon={<Search />} label={t("chat.shell.searchChats")} shortcut={shortcut} onClick={openSearch} />
</SidebarMenu>
</nav>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden px-3 pb-3 group-data-[collapsible=icon]:hidden">
<ConversationList
conversations={conversations}
activeConversationId={activeConversationId}
@ -201,13 +224,9 @@ const ChatShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
if (id === activeConversationId) navigate(routes.chats);
}}
onRename={renameConversation}
searchOpen={searchOpen}
onSearchOpenChange={setSearchOpen}
hideSearchButton
enableSearchShortcut={false}
/>
</div>
<SidebarFooter className="mt-auto">
<SidebarFooter className="mt-auto flex-none gap-2.5 border-t border-sidebar-border p-3">
<ChatAccountMenu
onLogout={handleLogout}
collapsed={collapsed}
@ -230,51 +249,32 @@ const ChatShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
: titles.find((item) => item.route === pathname)?.label ?? t("shell.viewSwitcher.chat");
return (
<div className="chat-theme flex h-full w-full overflow-hidden bg-background text-foreground">
{isDesktop && (
<Sidebar aria-label={t("chat.shell.chatNavigation")} collapsed={collapsed}>
{sidebar}
</Sidebar>
)}
<Sheet handle={mobileNavigationHandle} open={sidebarOpen} onOpenChange={setSidebarOpen}>
<SheetContent
side="left"
initialFocus={searchOpen ? false : undefined}
showCloseButton={false}
className="gap-0 p-0 data-[side=left]:w-[min(280px,calc(100vw-3rem))] [&_[data-slot=sidebar]]:w-full"
>
<SheetHeader className="sr-only">
<SheetTitle>{t("chat.shell.sheetTitle")}</SheetTitle>
<SheetDescription>{t("chat.shell.sheetDescription")}</SheetDescription>
</SheetHeader>
<Sidebar>{sidebar}</Sidebar>
</SheetContent>
</Sheet>
<div className="flex min-w-0 flex-1 flex-col overflow-hidden">
<>
<Sidebar
collapsible="icon"
role="complementary"
aria-label={t("chat.shell.chatNavigation")}
className={shellSidebarClassName}
>
{sidebar}
</Sidebar>
<ConversationSearchDialog
open={searchOpen}
conversations={conversations}
onSelect={(id) => navigate(conversationUrl(routes.chats, id))}
onClose={() => setSearchOpen(false)}
/>
<SidebarInset className="min-w-0 overflow-hidden">
<DashboardHeader
accessToken={accessToken}
title={title}
workspace="chat"
navigationTrigger={
<SheetTrigger
handle={mobileNavigationHandle}
render={
<Button
variant="ghost"
size="icon"
className="size-11 md:hidden"
aria-label={t("chat.shell.openChatNavigation")}
/>
}
>
<Menu />
</SheetTrigger>
}
navigationTrigger={<SidebarTrigger className="size-11 md:hidden" />}
/>
<main className="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">{children}</main>
</div>
</div>
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">{children}</div>
</SidebarInset>
</>
);
};
}
export default ChatShell;

View file

@ -1,4 +1,4 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import ConversationList from "./ConversationList";
@ -55,35 +55,9 @@ describe("ConversationList navigation", () => {
/>,
);
await user.tab();
expect(screen.getByRole("button", { name: "Search chats" })).toHaveFocus();
await user.tab();
expect(screen.getByRole("button", { name: "Design review", exact: true })).toHaveFocus();
await user.keyboard("{Enter}");
expect(onSelect).toHaveBeenCalledWith("design");
});
it("should filter chats from visible search and select a result", async () => {
const onSelect = vi.fn();
const user = userEvent.setup();
render(
<ConversationList
conversations={conversations}
activeConversationId={null}
onSelect={onSelect}
onDelete={vi.fn()}
onRename={vi.fn()}
/>,
);
await user.click(screen.getByRole("button", { name: "Search chats" }));
const dialog = await screen.findByRole("dialog", { name: "Search conversations" });
act(() =>
fireEvent.change(screen.getByRole("textbox", { name: "Search conversations" }), { target: { value: "photo" } }),
);
expect(within(dialog).queryByRole("button", { name: /Design review/ })).not.toBeInTheDocument();
await user.click(within(dialog).getByRole("button", { name: /Photo ideas/ }));
expect(onSelect).toHaveBeenCalledWith("photos");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
});

View file

@ -1,10 +1,9 @@
"use client";
import React, { useState, useEffect, useRef, useCallback } from "react";
import { Pencil, Trash2, Search, MessageSquare, Clock3 } from "lucide-react";
import React, { useState, useEffect, useRef } from "react";
import { Pencil, Trash2, Clock3 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
@ -29,10 +28,6 @@ interface Props {
onSelect: (id: string) => void;
onDelete: (id: string) => void;
onRename: (id: string, newTitle: string) => void;
searchOpen?: boolean;
onSearchOpenChange?: (open: boolean) => void;
hideSearchButton?: boolean;
enableSearchShortcut?: boolean;
}
type DateGroup = "Recents" | "Yesterday" | "Last 7 Days" | "Older";
@ -234,154 +229,33 @@ const ConversationRow: React.FC<ConversationRowProps> = ({ conv, isActive, onSel
);
};
interface SearchModalProps {
open: boolean;
conversations: Conversation[];
onSelect: (id: string) => void;
onClose: () => void;
}
const SearchModal: React.FC<SearchModalProps> = ({ open, conversations, onSelect, onClose }) => {
const ConversationList: React.FC<Props> = ({ conversations, activeConversationId, onSelect, onDelete, onRename }) => {
const { t } = useTranslation();
const [query, setQuery] = useState("");
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
if (!open) setQuery("");
}
const filtered = query.trim()
? conversations.filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase()))
: conversations;
const handleSelect = (id: string) => {
onSelect(id);
onClose();
};
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="chat-theme sm:max-w-[480px] p-4 gap-0">
<DialogTitle className="sr-only">{t("chat.conversationList.searchTitle")}</DialogTitle>
<div className="relative mb-3">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
autoFocus
aria-label={t("chat.conversationList.searchLabel")}
placeholder={t("chat.conversationList.searchPlaceholder")}
value={query}
onChange={(e) => setQuery(e.target.value)}
className="pl-9"
/>
</div>
<ScrollArea className="h-[320px]">
{filtered.length === 0 ? (
<div className="text-center py-6 text-muted-foreground text-sm">{t("chat.conversationList.noResults")}</div>
) : (
filtered.map((conv) => {
return (
<Button
key={conv.id}
variant="ghost"
onClick={() => handleSelect(conv.id)}
className="w-full justify-start gap-2 px-2.5"
>
<MessageSquare className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="text-left text-[13px] flex-1 truncate">{conv.title}</span>
<span className="text-[11px] text-muted-foreground shrink-0 ml-auto">
{dayjs(conv.updatedAt).format("MMM D")}
</span>
</Button>
);
})
)}
</ScrollArea>
</DialogContent>
</Dialog>
);
};
const ConversationList: React.FC<Props> = ({
conversations,
activeConversationId,
onSelect,
onDelete,
onRename,
searchOpen,
onSearchOpenChange,
hideSearchButton = false,
enableSearchShortcut = true,
}) => {
const { t } = useTranslation();
const [localSearchOpen, setLocalSearchOpen] = useState(false);
const searchModalOpen = searchOpen ?? localSearchOpen;
const setSearchModalOpen = onSearchOpenChange ?? setLocalSearchOpen;
const handleGlobalKeyDown = useCallback(
(e: KeyboardEvent) => {
const isSearchShortcut = e.key.toLowerCase() === "k" && (e.metaKey || e.ctrlKey);
if (isSearchShortcut && !e.shiftKey) {
e.preventDefault();
setSearchModalOpen(!searchModalOpen);
}
},
[searchModalOpen, setSearchModalOpen],
);
useEffect(() => {
if (!enableSearchShortcut) return;
document.addEventListener("keydown", handleGlobalKeyDown);
return () => document.removeEventListener("keydown", handleGlobalKeyDown);
}, [handleGlobalKeyDown, enableSearchShortcut]);
const grouped = groupConversations(conversations);
return (
<>
<div className="flex flex-col h-full w-full overflow-hidden">
{!hideSearchButton && (
<div className="px-2 pt-2">
<Button
variant="ghost"
onClick={() => setSearchModalOpen(true)}
className="chat-nav-item w-full justify-start gap-2.5 text-muted-foreground hover:bg-sidebar-accent"
>
<Search className="size-4" />
{t("chat.conversationList.searchChats")}
</Button>
</div>
)}
<ScrollArea className="flex-1 h-0 px-1.5 pt-2">
{grouped.map(({ group, items }) => (
<div key={group} className="mb-2">
<div className="moyai-chat-history-heading flex items-center gap-2 px-2 pt-2 pb-1 text-xs font-normal text-sidebar-foreground">
<Clock3 className="size-3.5" aria-hidden="true" />
{t(DATE_GROUP_LABEL_KEYS[group])}
</div>
{items.map((conv) => (
<ConversationRow
key={conv.id}
conv={conv}
isActive={conv.id === activeConversationId}
onSelect={onSelect}
onDelete={onDelete}
onRename={onRename}
/>
))}
<div className="flex flex-col h-full w-full overflow-hidden">
<ScrollArea className="flex-1 h-0 px-1.5 pt-2">
{grouped.map(({ group, items }) => (
<div key={group} className="mb-2">
<div className="moyai-chat-history-heading flex items-center gap-2 px-2 pt-2 pb-1 text-xs font-normal text-sidebar-foreground">
<Clock3 className="size-3.5" aria-hidden="true" />
{t(DATE_GROUP_LABEL_KEYS[group])}
</div>
))}
</ScrollArea>
</div>
<SearchModal
open={searchModalOpen}
conversations={conversations}
onSelect={onSelect}
onClose={() => setSearchModalOpen(false)}
/>
</>
{items.map((conv) => (
<ConversationRow
key={conv.id}
conv={conv}
isActive={conv.id === activeConversationId}
onSelect={onSelect}
onDelete={onDelete}
onRename={onRename}
/>
))}
</div>
))}
</ScrollArea>
</div>
);
};

View file

@ -0,0 +1,44 @@
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import ConversationSearchDialog from "./ConversationSearchDialog";
import type { Conversation } from "./types";
const conversations: Conversation[] = [
{
id: "design",
title: "Design review",
model: "test-model",
messages: [],
mcpServerNames: [],
createdAt: 1,
updatedAt: 1,
},
{
id: "photos",
title: "Photo ideas",
model: "test-model",
messages: [],
mcpServerNames: [],
createdAt: 2,
updatedAt: 2,
},
];
describe("ConversationSearchDialog", () => {
it("should filter chats by title and select a result", async () => {
const onSelect = vi.fn();
const user = userEvent.setup();
const onClose = vi.fn();
render(<ConversationSearchDialog open conversations={conversations} onSelect={onSelect} onClose={onClose} />);
const dialog = await screen.findByRole("dialog", { name: "Search conversations" });
act(() =>
fireEvent.change(screen.getByRole("textbox", { name: "Search conversations" }), { target: { value: "photo" } }),
);
expect(within(dialog).queryByRole("button", { name: /Design review/ })).not.toBeInTheDocument();
await user.click(within(dialog).getByRole("button", { name: /Photo ideas/ }));
expect(onSelect).toHaveBeenCalledWith("photos");
expect(onClose).toHaveBeenCalled();
});
});

View file

@ -0,0 +1,87 @@
"use client";
import React, { useState } from "react";
import { MessageSquare, Search } from "lucide-react";
import dayjs from "dayjs";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Conversation } from "./types";
interface ConversationSearchDialogProps {
open: boolean;
conversations: Conversation[];
onSelect: (id: string) => void;
onClose: () => void;
}
const ConversationSearchDialog: React.FC<ConversationSearchDialogProps> = ({
open,
conversations,
onSelect,
onClose,
}) => {
const { t } = useTranslation();
const [query, setQuery] = useState("");
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
if (!open) setQuery("");
}
const filtered = query.trim()
? conversations.filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase()))
: conversations;
const handleSelect = (id: string) => {
onSelect(id);
onClose();
};
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="chat-theme sm:max-w-[480px] p-4 gap-0">
<DialogTitle className="sr-only">{t("chat.conversationList.searchTitle")}</DialogTitle>
<div className="relative mb-3">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
autoFocus
aria-label={t("chat.conversationList.searchLabel")}
placeholder={t("chat.conversationList.searchPlaceholder")}
value={query}
onChange={(e) => setQuery(e.target.value)}
className="pl-9"
/>
</div>
<ScrollArea className="h-[320px]">
{filtered.length === 0 ? (
<div className="text-center py-6 text-muted-foreground text-sm">{t("chat.conversationList.noResults")}</div>
) : (
filtered.map((conv) => {
return (
<Button
key={conv.id}
variant="ghost"
onClick={() => handleSelect(conv.id)}
className="w-full justify-start gap-2 px-2.5"
>
<MessageSquare className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="text-left text-[13px] flex-1 truncate">{conv.title}</span>
<span className="text-[11px] text-muted-foreground shrink-0 ml-auto">
{dayjs(conv.updatedAt).format("MMM D")}
</span>
</Button>
);
})
)}
</ScrollArea>
</DialogContent>
</Dialog>
);
};
export default ConversationSearchDialog;

View file

@ -157,9 +157,9 @@ Sizes: `default` (h-9), `sm` (h-8), `xs` (h-6), `lg` (h-10), `icon` (size-9), `i
### Sidebar nav item
Use `Sidebar`, `SidebarContent`, `SidebarFooter` and `SidebarMenuButton` from `components/shared/Sidebar`. Both workspaces use `SidebarBrand`, `ViewSwitcher` and `DashboardHeader`. Chat has a compact account menu with its existing identity, Settings and Sign out actions. Theme lives in the shared top bar. Gateway account preferences and admin controls stay in the gateway. Keep the shared 280px expanded and 72px collapsed widths, 56px header and 768px mobile breakpoint
Use `Sidebar`, `SidebarContent`, `SidebarFooter` and `SidebarMenuButton` from the stock shadcn block in `components/ui/sidebar`, with our look in the className overrides from `components/shared/sidebarStyles`. Both workspaces use `SidebarBrand`, `ViewSwitcher` and `DashboardHeader`. Chat has a compact account menu with its existing identity, Settings and Sign out actions. Theme lives in the shared top bar. Gateway account preferences and admin controls stay in the gateway. Keep the shared 280px expanded and 72px collapsed widths, 56px header and 768px mobile breakpoint
Use one New Chat action for the blank composer; do not duplicate it with a Chats destination. Chat retains Models, Integrations, Workspace and conversation history. Chat has no gateway-wide header search or worker selector. Search chats in the sidebar owns Cmd/Ctrl+K, including when the sidebar is collapsed or on mobile. Mobile navigation uses the same Sheet treatment as the dashboard
Use one New Chat action for the blank composer; do not duplicate it with a Chats destination. Chat retains Models, Integrations, Workspace and conversation history. Chat has no gateway-wide header search or worker selector. Cmd/Ctrl+K and Search chats open one conversation search that `ChatShell` renders outside the sidebar, so the shortcut also works with the sidebar collapsed and on phones opens only the search. Mobile navigation is the stock shadcn Sidebar sheet, the same as the dashboard
The conversation title appears in the shared header. Do not repeat it in a second content header. Routed pages keep their content-specific headings and actions
@ -200,14 +200,15 @@ No max-width cap on panel content — matches the rest of the dashboard's own pa
Card, Textarea and sonner are installed. Earlier versions of this document listed them as missing and encouraged parallel implementations; use the shared owners above
Shared sidebar primitives are available in `components/shared/Sidebar`. Use them instead of hand-writing a separate rail
The stock shadcn Sidebar is installed in `components/ui/sidebar`. Use it instead of hand-writing a separate rail
## File Structure
```
src/components/chat/
ChatShell.tsx # Desktop navigation / mobile Sheet, shared across all /chat/* routes
ConversationList.tsx # Date-grouped chat list and conversation search
ChatShell.tsx # Sidebar, header and conversation search, shared across all /chat/* routes
ConversationList.tsx # Date-grouped chat list
ConversationSearchDialog.tsx # Cmd/Ctrl+K conversation search
ChatMessages.tsx # Shared list and single-message rendering (user, assistant, tool)
MCPAppsPanel.tsx # Integrations grid + detail view
MCPConnectPicker.tsx # MCP server toggle popover

View file

@ -11,6 +11,7 @@ import userEvent from "@testing-library/user-event";
import { Fragment, useEffect, type ComponentType } from "react";
import SidebarAccountMenu from "@/components/SidebarAccountMenu/SidebarAccountMenu";
import UserDropdown from "@/components/Navbar/UserDropdown/UserDropdown";
import { SidebarProvider } from "@/components/ui/sidebar";
import { AriaUsageTrigger, LiteAdminFrame, LiteAdminPage, AriaSidebarLink } from "./LiteAdmin";
import { MAX_INPUT_LENGTH } from "./agent";
import type { ModelGroup } from "@/components/llm_calls/fetch_models";
@ -122,7 +123,9 @@ function renderWidget(
{Menu && <Menu onLogout={() => undefined} />}
<LiteAdminFrame>
<Page />
<AriaSidebarLink active={page} />
<SidebarProvider>
<AriaSidebarLink active={page} />
</SidebarProvider>
{page && <LiteAdminPage />}
{usage && (
<>

View file

@ -17,7 +17,8 @@ import { useTranslation } from "react-i18next";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { uiHref } from "@/utils/uiHref";
import { sidebarMenuButtonVariants } from "@/components/shared/Sidebar";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "@/components/ui/sidebar";
import { navMenuButtonClassName } from "@/components/shared/sidebarStyles";
import { RotateCcw } from "lucide-react";
import { z } from "zod";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
@ -151,20 +152,22 @@ export function AriaSidebarLink({ active }: { active: boolean }) {
const state = useContext(LiteAdminContext);
if (!state) return null;
return (
<Link
href={uiHref("aria")}
aria-current={active ? "page" : undefined}
aria-label={ARIA_AGENT_LABEL}
title={ARIA_AGENT_LABEL}
className={cn(
sidebarMenuButtonVariants({ isActive: active }),
"group-data-[collapsed=true]/sidebar:justify-center",
)}
>
<AriaAvatar size={18} />
<span className="flex-1 group-data-[collapsed=true]/sidebar:hidden">{ARIA_AGENT_LABEL}</span>
<Kbd className="bg-transparent text-[10px] group-data-[collapsed=true]/sidebar:hidden">⌘J</Kbd>
</Link>
<SidebarMenu role="none">
<SidebarMenuItem role="none">
<SidebarMenuButton
isActive={active}
title={ARIA_AGENT_LABEL}
className={navMenuButtonClassName}
render={
<Link href={uiHref("aria")} aria-current={active ? "page" : undefined} aria-label={ARIA_AGENT_LABEL} />
}
>
<AriaAvatar size={18} />
<span className="flex-1 group-data-[collapsible=icon]:hidden">{ARIA_AGENT_LABEL}</span>
<Kbd className="bg-transparent text-[10px] group-data-[collapsible=icon]:hidden">⌘J</Kbd>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
);
}

View file

@ -5,7 +5,7 @@
import { describe, it, expect } from "vitest";
import { getAvailablePages } from "./page_utils";
import { menuGroups } from "./leftnav";
import { menuGroups } from "./LeftNav";
import { pageDescriptions } from "./page_metadata";
import { internalUserRoles } from "@/utils/roles";
@ -162,7 +162,7 @@ describe("Page Utils - LeftNav Sync", () => {
expect(
orphanedDescriptions,
`These descriptions don't match any page in menuGroups: ${orphanedDescriptions.join(", ")}. Remove them or add the pages to leftnav.`,
`These descriptions don't match any page in menuGroups: ${orphanedDescriptions.join(", ")}. Remove them or add the pages to LeftNav.`,
).toHaveLength(0);
});

View file

@ -3,7 +3,7 @@
*/
import i18n from "@/i18n/i18n";
import { groupText, labelText, menuGroups } from "./leftnav";
import { groupText, labelText, menuGroups } from "./LeftNav";
import { pageDescriptions, PageMetadata } from "./page_metadata";
import { internalUserRoles } from "@/utils/roles";

View file

@ -0,0 +1,11 @@
"use client";
import { useEffect } from "react";
import { useSidebar } from "@/components/ui/sidebar";
export function useCloseMobileSidebarOn(navigationKey?: string) {
const { isMobile, setOpenMobile } = useSidebar();
useEffect(() => {
setOpenMobile(false);
}, [navigationKey, isMobile, setOpenMobile]);
}

View file

@ -1,36 +0,0 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { SidebarMenuButton, sidebarMenuButtonVariants } from "./Sidebar";
const CVA_CONFIG_KEYS = ["base", "variants", "defaultVariants"];
describe("sidebarMenuButtonVariants", () => {
it("emits its base classes rather than the names of its own config keys", () => {
const emitted = sidebarMenuButtonVariants({}).split(" ");
expect(emitted).toContain("rounded-md");
expect(emitted).toContain("text-sidebar-foreground/70");
expect(CVA_CONFIG_KEYS.filter((key) => emitted.includes(key))).toEqual([]);
});
it("applies the isActive variant on top of the base classes", () => {
const active = sidebarMenuButtonVariants({ isActive: true }).split(" ");
expect(active).toContain("bg-sidebar-accent");
expect(active).toContain("rounded-md");
expect(sidebarMenuButtonVariants({ isActive: false }).split(" ")).not.toContain("bg-sidebar-accent");
});
});
describe("SidebarMenuButton", () => {
it("renders the variant classes onto the button", () => {
render(<SidebarMenuButton isActive>Keys</SidebarMenuButton>);
const button = screen.getByRole("button", { name: "Keys" });
expect(button).toHaveClass("bg-sidebar-accent", "rounded-md");
for (const key of CVA_CONFIG_KEYS) {
expect(button).not.toHaveClass(key);
}
});
});

View file

@ -1,206 +0,0 @@
"use client";
import * as React from "react";
import { Button as ButtonPrimitive } from "@base-ui/react/button";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/cva.config";
type SidebarContextValue = { collapsed: boolean };
const SidebarContext = React.createContext<SidebarContextValue>({ collapsed: false });
export function useSidebar(): SidebarContextValue {
return React.useContext(SidebarContext);
}
const Sidebar = React.forwardRef<HTMLElement, React.ComponentPropsWithoutRef<"aside"> & { collapsed?: boolean }>(
({ className, collapsed = false, children, ...props }, ref) => (
<SidebarContext.Provider value={{ collapsed }}>
<aside
ref={ref}
data-slot="sidebar"
data-collapsed={collapsed}
className={cn(
"group/sidebar flex h-full flex-none flex-col overflow-hidden border-r border-sidebar-border bg-sidebar text-sidebar-foreground transition-[width] duration-200 ease-in-out",
collapsed ? "w-[72px]" : "w-[280px]",
className,
)}
{...props}
>
{children}
</aside>
</SidebarContext.Provider>
),
);
Sidebar.displayName = "Sidebar";
const SidebarHeader = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
({ className, ...props }, ref) => (
<div
ref={ref}
data-slot="sidebar-header"
className={cn("flex flex-none flex-col gap-2 p-3", className)}
{...props}
/>
),
);
SidebarHeader.displayName = "SidebarHeader";
const SidebarContent = React.forwardRef<HTMLElement, React.ComponentPropsWithoutRef<"nav">>(
({ className, ...props }, ref) => (
<nav
ref={ref}
data-slot="sidebar-content"
className={cn("flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto px-3 pb-3", className)}
{...props}
/>
),
);
SidebarContent.displayName = "SidebarContent";
const SidebarFooter = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
({ className, ...props }, ref) => (
<div
ref={ref}
data-slot="sidebar-footer"
className={cn("flex flex-none flex-col gap-2.5 border-t border-sidebar-border p-3", className)}
{...props}
/>
),
);
SidebarFooter.displayName = "SidebarFooter";
const SidebarGroup = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
({ className, ...props }, ref) => (
<div ref={ref} data-slot="sidebar-group" className={cn("flex flex-col gap-0.5 py-1", className)} {...props} />
),
);
SidebarGroup.displayName = "SidebarGroup";
const SidebarGroupLabel = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
({ className, ...props }, ref) => (
<div
ref={ref}
data-slot="sidebar-group-label"
className={cn(
"px-2 pt-3 pb-1.5 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase group-data-[collapsed=true]/sidebar:hidden",
className,
)}
{...props}
/>
),
);
SidebarGroupLabel.displayName = "SidebarGroupLabel";
const SidebarMenu = React.forwardRef<HTMLUListElement, React.ComponentPropsWithoutRef<"ul">>(
({ className, ...props }, ref) => (
<ul ref={ref} data-slot="sidebar-menu" className={cn("flex w-full flex-col gap-0.5", className)} {...props} />
),
);
SidebarMenu.displayName = "SidebarMenu";
const SidebarMenuItem = React.forwardRef<HTMLLIElement, React.ComponentPropsWithoutRef<"li">>(
({ className, ...props }, ref) => (
<li ref={ref} data-slot="sidebar-menu-item" className={cn("relative", className)} {...props} />
),
);
SidebarMenuItem.displayName = "SidebarMenuItem";
const SidebarMenuSub = React.forwardRef<HTMLUListElement, React.ComponentPropsWithoutRef<"ul">>(
({ className, ...props }, ref) => (
<ul
ref={ref}
data-slot="sidebar-menu-sub"
className={cn(
"mx-3.5 my-0.5 flex min-w-0 flex-col gap-0.5 border-l border-sidebar-border py-0.5 pl-3 group-data-[collapsed=true]/sidebar:hidden",
className,
)}
{...props}
/>
),
);
SidebarMenuSub.displayName = "SidebarMenuSub";
const SidebarMenuBadge = React.forwardRef<HTMLSpanElement, React.ComponentPropsWithoutRef<"span">>(
({ className, ...props }, ref) => (
<span
ref={ref}
data-slot="sidebar-menu-badge"
className={cn(
"ml-auto flex-none rounded-full bg-sidebar-primary/10 px-1.5 py-px text-[10px] font-semibold text-sidebar-primary tabular-nums group-data-[collapsed=true]/sidebar:hidden",
className,
)}
{...props}
/>
),
);
SidebarMenuBadge.displayName = "SidebarMenuBadge";
const sidebarMenuButtonVariants = cva(
[
"group/menu-btn relative flex w-full items-center gap-2.5 overflow-hidden rounded-md px-2.5 text-left text-[13px] font-medium no-underline max-md:min-h-11",
"text-sidebar-foreground/70 outline-none transition-colors",
"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
"focus-visible:ring-2 focus-visible:ring-sidebar-ring",
"disabled:pointer-events-none disabled:opacity-50",
"[&>svg]:size-[18px] [&>svg]:shrink-0",
"group-data-[collapsed=true]/sidebar:mx-auto group-data-[collapsed=true]/sidebar:size-9 group-data-[collapsed=true]/sidebar:justify-center group-data-[collapsed=true]/sidebar:gap-0 group-data-[collapsed=true]/sidebar:px-0",
],
{
variants: {
isActive: {
true: "bg-sidebar-accent text-sidebar-accent-foreground before:absolute before:inset-y-1.5 before:left-0 before:w-[3px] before:rounded-r-full before:bg-sidebar-primary group-data-[collapsed=true]/sidebar:before:hidden",
false: "",
},
size: {
default: "h-[34px]",
sub: "h-[34px]",
},
},
defaultVariants: { isActive: false, size: "default" },
},
);
type SidebarMenuButtonProps = ButtonPrimitive.Props & VariantProps<typeof sidebarMenuButtonVariants>;
const SidebarMenuButton = React.forwardRef<HTMLButtonElement, SidebarMenuButtonProps>(
({ className, isActive, size, ...props }, ref) => (
<ButtonPrimitive
ref={ref}
data-slot="sidebar-menu-button"
data-active={isActive || undefined}
className={cn(sidebarMenuButtonVariants({ isActive, size, className }))}
{...props}
/>
),
);
SidebarMenuButton.displayName = "SidebarMenuButton";
const SidebarSeparator = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
({ className, ...props }, ref) => (
<div
ref={ref}
data-slot="sidebar-separator"
className={cn("mx-2 my-2 h-px bg-sidebar-border", className)}
{...props}
/>
),
);
SidebarSeparator.displayName = "SidebarSeparator";
export {
Sidebar,
SidebarHeader,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuItem,
SidebarMenuButton,
SidebarMenuSub,
SidebarMenuBadge,
SidebarSeparator,
sidebarMenuButtonVariants,
};

View file

@ -9,13 +9,13 @@ import { useHealthReadinessDetails } from "@/app/(dashboard)/hooks/healthReadine
import { getProxyBaseUrl } from "@/components/networking";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { SidebarHeader } from "@/components/shared/Sidebar";
import { SidebarHeader, useSidebar } from "@/components/ui/sidebar";
import { uiHref } from "@/utils/uiHref";
import { cn } from "@/lib/cva.config";
import { productNames } from "@/i18n/untranslated/productNames";
const LOGO_CLASS_NAME =
"h-5 w-auto max-w-[150px] object-contain group-data-[collapsed=true]/sidebar:h-6 group-data-[collapsed=true]/sidebar:w-6";
"h-5 w-auto max-w-[150px] object-contain group-data-[collapsible=icon]:h-6 group-data-[collapsible=icon]:w-6";
function bundledLogoSrc(baseUrl: string, { dark, monogram }: { dark: boolean; monogram: boolean }): string {
const query = [dark && "theme=dark", monogram && "variant=monogram"].filter(Boolean).join("&");
@ -26,18 +26,14 @@ export function SidebarBrand({
accessToken,
homeHref = uiHref(""),
homeLabel = "LiteLLM home",
collapsed = false,
onToggleCollapsed,
onHomeClick,
}: {
accessToken: string | null;
homeHref?: string;
homeLabel?: string;
collapsed?: boolean;
onToggleCollapsed?: () => void;
onHomeClick?: () => void;
}) {
const { t } = useTranslation();
const { state, isMobile, toggleSidebar, setOpenMobile } = useSidebar();
const collapsed = state === "collapsed" && !isMobile;
const { logoUrl, logoUrlDark } = useTheme();
const [erroredDarkLogo, setErroredDarkLogo] = useState<string | null>(null);
const { data: healthData } = useHealthReadinessDetails(accessToken);
@ -47,10 +43,15 @@ export function SidebarBrand({
const reachableDarkLogo = logoUrlDark === erroredDarkLogo ? null : logoUrlDark;
const darkLogoSrc = reachableDarkLogo || logoUrl || bundledLogoSrc(baseUrl, { dark: true, monogram: collapsed });
return (
<SidebarHeader className="h-14 border-b border-border group-data-[collapsed=true]/sidebar:h-auto group-data-[collapsed=true]/sidebar:py-2">
<div className="flex items-center justify-between gap-2 group-data-[collapsed=true]/sidebar:flex-col group-data-[collapsed=true]/sidebar:gap-1">
<SidebarHeader className="h-14 flex-none border-b border-border p-3 group-data-[collapsible=icon]:h-auto group-data-[collapsible=icon]:py-2">
<div className="flex items-center justify-between gap-2 group-data-[collapsible=icon]:flex-col group-data-[collapsible=icon]:gap-1">
<div className="flex min-w-0 items-center gap-2">
<Link href={homeHref} onClick={onHomeClick} className="flex min-w-0 items-center" aria-label={homeLabel}>
<Link
href={homeHref}
onClick={() => setOpenMobile(false)}
className="flex min-w-0 items-center"
aria-label={homeLabel}
>
<img src={logoSrc} alt={productNames.liteLLM} className={cn(LOGO_CLASS_NAME, "dark:hidden")} />
<img
src={darkLogoSrc}
@ -64,24 +65,22 @@ export function SidebarBrand({
<Badge
variant="outline"
render={<a href="https://docs.litellm.ai/release_notes" target="_blank" rel="noopener noreferrer" />}
className="px-1.5 py-0 font-mono text-[10px] font-medium text-muted-foreground group-data-[collapsed=true]/sidebar:hidden"
className="px-1.5 py-0 font-mono text-[10px] font-medium text-muted-foreground group-data-[collapsible=icon]:hidden"
>
v{version}
</Badge>
)}
</div>
{onToggleCollapsed && (
<Button
variant="ghost"
size="icon-sm"
onClick={onToggleCollapsed}
aria-expanded={!collapsed}
aria-label={collapsed ? t("shell.navbar.expandSidebar") : t("shell.navbar.collapseSidebar")}
className="flex-none text-muted-foreground group-data-[collapsed=true]/sidebar:size-9"
>
{collapsed ? <PanelLeftOpen /> : <PanelLeftClose />}
</Button>
)}
<Button
variant="ghost"
size="icon-sm"
onClick={toggleSidebar}
aria-expanded={!collapsed}
aria-label={collapsed ? t("shell.navbar.expandSidebar") : t("shell.navbar.collapseSidebar")}
className="flex-none text-muted-foreground group-data-[collapsible=icon]:size-9"
>
{collapsed ? <PanelLeftOpen /> : <PanelLeftClose />}
</Button>
</div>
</SidebarHeader>
);

View file

@ -0,0 +1,27 @@
import type { CSSProperties } from "react";
const navButtonLook = [
"relative h-[34px] gap-2.5 px-2.5 py-0 text-[13px] font-medium text-sidebar-foreground/70 no-underline transition-colors",
"max-md:min-h-11 [&_svg]:size-[18px]",
"data-active:before:absolute data-active:before:inset-y-1.5 data-active:before:left-0 data-active:before:w-[3px] data-active:before:rounded-r-full data-active:before:bg-sidebar-primary",
].join(" ");
export const navMenuButtonClassName = [
navButtonLook,
"group-data-[collapsible=icon]:mx-auto group-data-[collapsible=icon]:size-9! group-data-[collapsible=icon]:gap-0 group-data-[collapsible=icon]:p-[9px]! group-data-[collapsible=icon]:before:hidden",
].join(" ");
export const navMenuSubButtonClassName = [
navButtonLook,
"w-full translate-x-0 data-[size=md]:text-[13px] [&>svg]:size-[18px] [&>svg]:text-current",
].join(" ");
export const navMenuSubClassName = "my-0.5 translate-x-0 gap-0.5 px-0 pl-3";
export const navMenuClassName = "gap-0.5";
export const shellSidebarClassName = "border-sidebar-border ease-in-out";
export const sidebarProviderClassName = "[&_[data-slot=sidebar-gap]]:ease-in-out";
export const sidebarWidthStyle = { "--sidebar-width": "280px", "--sidebar-width-icon": "72px" } as CSSProperties;

View file

@ -0,0 +1,679 @@
"use client";
import * as React from "react";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { cva, type VariantProps } from "class-variance-authority";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/cva.config";
import { useIsMobile } from "@/hooks/use-mobile";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { PanelLeftIcon } from "lucide-react";
const SIDEBAR_COOKIE_NAME = "sidebar_state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
type SidebarContextProps = {
state: "expanded" | "collapsed";
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen);
const open = openProp ?? _open;
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value;
if (setOpenProp) {
setOpenProp(openState);
} else {
_setOpen(openState);
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
},
[setOpenProp, open],
);
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
toggleSidebar();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed";
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
);
return (
<SidebarContext.Provider value={contextValue}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar", className)}
{...props}
>
{children}
</div>
</SidebarContext.Provider>
);
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
dir,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
}) {
const { t } = useTranslation();
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn("flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground", className)}
{...props}
>
{children}
</div>
);
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
dir={dir}
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>{t("ui.sidebar.title")}</SheetTitle>
<SheetDescription>{t("ui.sidebar.description")}</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
);
}
return (
<div
className="group peer hidden text-sidebar-foreground md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
)}
/>
<div
data-slot="sidebar-container"
data-side={side}
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className,
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="flex size-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border"
>
{children}
</div>
</div>
</div>
);
}
function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
const { t } = useTranslation();
const { toggleSidebar } = useSidebar();
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon-sm"
className={cn(className)}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">{t("ui.sidebar.toggle")}</span>
</Button>
);
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { t } = useTranslation();
const { toggleSidebar } = useSidebar();
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label={t("ui.sidebar.toggle")}
tabIndex={-1}
onClick={toggleSidebar}
title={t("ui.sidebar.toggle")}
className={cn(
"absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className,
)}
{...props}
/>
);
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className,
)}
{...props}
/>
);
}
function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("h-8 w-full bg-background shadow-none", className)}
{...props}
/>
);
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
);
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"no-scrollbar flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className,
)}
{...props}
/>
);
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
);
}
function SidebarGroupLabel({
className,
render,
...props
}: useRender.ComponentProps<"div"> & React.ComponentProps<"div">) {
return useRender({
defaultTagName: "div",
props: mergeProps<"div">(
{
className: cn(
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
className,
),
},
props,
),
render,
state: {
slot: "sidebar-group-label",
sidebar: "group-label",
},
});
}
function SidebarGroupAction({
className,
render,
...props
}: useRender.ComponentProps<"button"> & React.ComponentProps<"button">) {
return useRender({
defaultTagName: "button",
props: mergeProps<"button">(
{
className: cn(
"absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
className,
),
},
props,
),
render,
state: {
slot: "sidebar-group-action",
sidebar: "group-action",
},
});
}
function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
);
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
);
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
);
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function SidebarMenuButton({
render,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: useRender.ComponentProps<"button"> &
React.ComponentProps<"button"> & {
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const { isMobile, state } = useSidebar();
const comp = useRender({
defaultTagName: "button",
props: mergeProps<"button">(
{
className: cn(sidebarMenuButtonVariants({ variant, size }), className),
},
props,
),
render: !tooltip ? render : <TooltipTrigger render={render} />,
state: {
slot: "sidebar-menu-button",
sidebar: "menu-button",
size,
active: isActive,
},
});
if (!tooltip) {
return comp;
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
};
}
return (
<Tooltip>
{comp}
<TooltipContent side="right" align="center" hidden={state !== "collapsed" || isMobile} {...tooltip} />
</Tooltip>
);
}
function SidebarMenuAction({
className,
render,
showOnHover = false,
...props
}: useRender.ComponentProps<"button"> &
React.ComponentProps<"button"> & {
showOnHover?: boolean;
}) {
return useRender({
defaultTagName: "button",
props: mergeProps<"button">(
{
className: cn(
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
showOnHover &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground aria-expanded:opacity-100 md:opacity-0",
className,
),
},
props,
),
render,
state: {
slot: "sidebar-menu-action",
sidebar: "menu-action",
},
});
}
function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 peer-data-active/menu-button:text-sidebar-accent-foreground",
className,
)}
{...props}
/>
);
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean;
}) {
// Random width between 50 to 90%.
const [width] = React.useState(() => {
return `${Math.floor(Math.random() * 40) + 50}%`;
});
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && <Skeleton className="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
);
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5 group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
);
}
function SidebarMenuSubButton({
render,
size = "md",
isActive = false,
className,
...props
}: useRender.ComponentProps<"a"> &
React.ComponentProps<"a"> & {
size?: "sm" | "md";
isActive?: boolean;
}) {
return useRender({
defaultTagName: "a",
props: mergeProps<"a">(
{
className: cn(
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground ring-sidebar-ring outline-hidden group-data-[collapsible=icon]:hidden hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-sm data-[size=sm]:text-xs data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
className,
),
},
props,
),
render,
state: {
slot: "sidebar-menu-sub-button",
sidebar: "menu-sub-button",
size,
active: isActive,
},
});
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
};

View file

@ -0,0 +1,19 @@
import * as React from "react";
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile;
}

View file

@ -8698,10 +8698,6 @@
"plugin": "Plugin",
"configure": "Configure the plugin URL in settings"
},
"dashboardShell": {
"navigation": "Navigation",
"openNavigation": "Open navigation"
},
"telemetryEnvNotice": {
"vetoed": "Telemetry is turned off by an environment variable",
"set": "Telemetry environment variables are set",
@ -8902,6 +8898,11 @@
"sheet": {
"close": "Close"
},
"sidebar": {
"title": "Sidebar",
"description": "Displays the mobile sidebar.",
"toggle": "Toggle Sidebar"
},
"spinner": {
"loading": "Loading"
}
@ -9412,10 +9413,7 @@
"organizationLogo": "Organization logo",
"settings": "Settings",
"signOut": "Sign out",
"chatNavigation": "Chat navigation",
"openChatNavigation": "Open chat navigation",
"sheetTitle": "LiteLLM Chat",
"sheetDescription": "Conversations and chat workspace navigation"
"chatNavigation": "Chat navigation"
},
"conversationList": {
"yesterday": "Yesterday",

View file

@ -126,7 +126,7 @@ vi.mock("@/components/model_hub_table", () => ({ default: stub("model-hub-table"
vi.mock("@/components/new_usage", () => ({ default: stub("new-usage") }));
vi.mock("@/components/api_ref", () => ({ default: stub("api-ref") }));
vi.mock("@/components/chat_ui/ChatUI", () => ({ default: stub("chat-ui") }));
vi.mock("@/components/leftnav", () => ({ default: stub("sidebar") }));
vi.mock("@/components/LeftNav", () => ({ default: stub("sidebar") }));
vi.mock("@/components/cache_dashboard", () => ({ default: stub("cache-dashboard") }));
vi.mock("@/app/(dashboard)/guardrails/_components", () => ({ default: stub("guardrails") }));
vi.mock("@/components/prompts", () => ({ default: stub("prompts") }));

View file

@ -0,0 +1,46 @@
import { act } from "@testing-library/react";
import { vi } from "vitest";
type Subscription = { media: string; listener: () => void };
const pxBound = (media: string, feature: "min-width" | "max-width") => {
const match = new RegExp(`${feature}:\\s*([\\d.]+)px`).exec(media);
return match ? Number(match[1]) : undefined;
};
const matchesWidth = (media: string, width: number) => {
const min = pxBound(media, "min-width");
const max = pxBound(media, "max-width");
if (min === undefined && max === undefined) return false;
const aboveMin = min === undefined || width >= min;
const belowMax = max === undefined || width <= max;
return aboveMin && belowMax;
};
export function stubViewportMatchMedia() {
const viewport: { cssWidth?: number } = {};
const subscriptions = new Set<Subscription>();
const currentWidth = () => viewport.cssWidth ?? window.innerWidth;
vi.stubGlobal("matchMedia", (media: string) => ({
media,
get matches() {
return matchesWidth(media, currentWidth());
},
addEventListener: (_type: string, listener: () => void) => subscriptions.add({ media, listener }),
removeEventListener: (_type: string, listener: () => void) =>
subscriptions.forEach((subscription) => {
if (subscription.media === media && subscription.listener === listener) subscriptions.delete(subscription);
}),
}));
return async function resizeTo(cssWidth: number) {
const previousWidth = currentWidth();
const flipped = [...subscriptions].filter(
({ media }) => matchesWidth(media, previousWidth) !== matchesWidth(media, cssWidth),
);
viewport.cssWidth = cssWidth;
vi.stubGlobal("innerWidth", Math.floor(cssWidth));
await act(async () => flipped.forEach(({ listener }) => listener()));
};
}