"use client";
import { navigateTask } from "@/lib/workspace-scope";
import Image from "next/image";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
Suspense,
type ReactNode,
type CSSProperties,
} from "react";
import { useAppShell } from "@/context/AppShellContext";
import { ChevronsLeft, ChevronsRight, PanelLeftClose, Search, SquarePen } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useChatWorkspaces } from "@/hooks/useChatWorkspaces";
import { useSidebarDrawer } from "@/components/layout/AppShell";
import { useDevice } from "@/hooks/useDevice";
import type {
SessionOrganizationPatch,
SessionSummary,
} from "@/lib/session-api";
import type { MasteryTopicLabel } from "@/lib/learning-api";
import { isNoteSession } from "@/lib/mastery-session";
import type { ReadingCollectionLabel } from "@/lib/reading-workspace-api";
import { useSidebarResize } from "@/hooks/useSidebarResize";
import { CategoryBody, CategoryTabs, useCategoryNavigation } from "@/components/sidebar/CategoryNavigation";
import { isLearningSession } from "@/lib/navigation";
import Tooltip from "@/shared/ui/Tooltip";
import { WorkspaceMenu } from "@/components/sidebar/WorkspaceMenu";
import { SHORTCUTS, matchesShortcut } from "@/lib/shortcuts";
import { RecordHeader, useRecordView } from "@/components/sidebar/RecordList";
import type { LearningSessions } from "@/components/sidebar/LearningNavigation";
// The fallback history list is needed only by shells without organization.
const SessionList = dynamic(() => import("@/components/SessionList"), { ssr: false });
// Loaded on first ⌘K, with the learning and partner indexes it searches.
const CommandPalette = dynamic(
() => import("@/components/sidebar/CommandPalette").then((module) => module.CommandPalette),
{ ssr: false },
);
// Session data arrives after mount; defer its organization UI with it so
// every workspace route does not download it as part of the initial shell.
const OrganizedSessionList = dynamic(
() => import("@/components/sessions/OrganizedSessionList"),
{
ssr: false,
loading: () => (
{[1, 2, 3].map((i) => (
))}
),
},
);
export interface SidebarShellProps {
/** Reuse the shell's resizing/collapse behavior with embedded navigation. */
homeSlot?: (collapsed: boolean) => ReactNode;
bodySlot?: (collapsed: boolean) => ReactNode;
footerOverride?: (collapsed: boolean) => ReactNode;
brandHref?: string;
initialWidth?: number;
widthStorageKey?: string;
sessions?: SessionSummary[];
activeSessionId?: string | null;
/** Conversations the caller is streaming right now; they sort to the top. */
liveSessionIds?: ReadonlySet;
loadingSessions?: boolean;
showSessions?: boolean;
/** Clicking the Chat nav item resets to a fresh session via this handler. */
onNewChat?: () => void;
onSelectSession?: (sessionId: string) => void | Promise;
onRenameSession?: (sessionId: string, title: string) => void | Promise;
onDeleteSession?: (sessionId: string) => void | Promise;
/** Topic labels for grouping mastery study conversations under their path. */
masteryTopics?: MasteryTopicLabel[];
/** Collection labels for grouping reading conversations under their shelf. */
readingCollections?: ReadingCollectionLabel[];
onOrganizeSession?: (
sessionId: string,
patch: SessionOrganizationPatch,
) => void | Promise;
/**
* Footer content rendered below the nav. Pass a render function to receive
* the current ``collapsed`` state so footer items (e.g. Admin / Sign out) can
* switch to their icon-only variant when the rail is collapsed.
*/
footerSlot?: ReactNode | ((collapsed: boolean) => ReactNode);
}
export function SidebarShell({
homeSlot,
bodySlot,
footerOverride,
brandHref = "/",
initialWidth = 272,
widthStorageKey,
sessions = [],
activeSessionId = null,
liveSessionIds,
loadingSessions = false,
showSessions = false,
onNewChat,
onSelectSession,
onRenameSession,
onDeleteSession,
masteryTopics = [],
readingCollections = [],
onOrganizeSession,
footerSlot,
}: SidebarShellProps) {
const categoryNav = useCategoryNavigation();
const router = useRouter();
const { t } = useTranslation();
const { sidebarCollapsed, setSidebarCollapsed: setCollapsed } = useAppShell();
const { isMobile } = useDevice();
const drawer = useSidebarDrawer();
const recentsScrollRef = useRef(null);
const [paletteOpen, setPaletteOpen] = useState(false);
// The row menus offer these as move destinations.
const { workspaces } = useChatWorkspaces();
// Inside the mobile drawer the icon-only rail is pointless — the panel is
// already hidden when you don't want it, so it always opens fully expanded
// regardless of the persisted desktop preference.
const collapsed = sidebarCollapsed && !isMobile;
const resize = useSidebarResize(collapsed || isMobile, initialWidth, widthStorageKey);
// The account links live in the workspace menu, which always shows them in
// full, open sidebar or rail.
const renderedFooter =
typeof footerSlot === "function" ? footerSlot(false) : footerSlot;
// Conversations read like the learning and partner records: by day, in
// the order the learner picked, searchable in place.
const chatView = useRecordView("deeptutor.navigation.chats.sort");
const startNewChat = () => {
drawer?.close();
onNewChat?.();
navigateTask("/chat", router.push);
};
const handleHomeClick = (event: React.MouseEvent) => {
// Always reset to a fresh session (mirrors the old "New Chat" affordance);
// let modifier-clicks fall through to default Link behavior so middle-click
// open-in-new-tab still works.
if (event.metaKey || event.ctrlKey || event.shiftKey || event.button === 1)
return;
event.preventDefault();
startNewChat();
};
// Shell shortcuts. The handler is re-bound after every render so it always
// sees the current category list; the listener itself is installed once.
const hotkeys = useRef<(event: KeyboardEvent) => void>(() => {});
const handleHotkey = (event: KeyboardEvent) => {
if (matchesShortcut(event, SHORTCUTS.search)) {
event.preventDefault();
setPaletteOpen((open) => !open);
} else if (matchesShortcut(event, SHORTCUTS.newChat)) {
event.preventDefault();
startNewChat();
} else {
const index = categoryNav.categories.findIndex((_, position) =>
matchesShortcut(event, SHORTCUTS.category(position)),
);
if (index < 0) return;
event.preventDefault();
const target = categoryNav.categories[index];
categoryNav.select(target.id);
if (collapsed) navigateTask(target.href, router.push);
}
};
useLayoutEffect(() => {
hotkeys.current = handleHotkey;
});
useEffect(() => {
if (bodySlot) return;
const onKeyDown = (event: KeyboardEvent) => hotkeys.current(event);
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [bodySlot]);
const palette =
!bodySlot && paletteOpen ? (
setPaletteOpen(false)}
categories={categoryNav.categories}
allowedSurfaces={categoryNav.allowedSurfaces}
sessions={sessions}
onSelectSession={onSelectSession}
onNewChat={startNewChat}
/>
) : null;
// Everything the learner has, minus the archived and minus the tutor threads
// that render nested under the conversation that spawned them.
//
// Keep the complete index here. OrganizedSessionList limits the initial
// rendering and exposes older conversations through Show more.
// The product shell files learning conversations under Learning only; an
// embedded body (the /preview demo) brings its own lists.
const listed = sessions.filter(
(session) =>
!session.preferences?.archived &&
!session.preferences?.parent_session_id &&
!isNoteSession(session),
);
const visibleSessions = bodySlot ? listed : listed.filter((session) => !isLearningSession(session));
// Learning conversations are filed under the record they were held in; the
// learning shelf draws them with the same rows and actions as these.
const learningSessions: LearningSessions | undefined =
!bodySlot && showSessions && onSelectSession && onRenameSession && onDeleteSession && onOrganizeSession
? {
rows: listed.filter(isLearningSession),
activeSessionId,
render: (rows) => (
{
drawer?.close();
return onSelectSession(sessionId);
}}
onRename={onRenameSession}
onDelete={onDeleteSession}
onOrganize={onOrganizeSession}
/>
),
}
: undefined;
// Conversation history follows the category's entries in the same scroller.
const sessionContent = (
<>
{showSessions &&
onSelectSession &&
onRenameSession &&
onDeleteSession &&
onOrganizeSession ? (
{loadingSessions ? (
) : (
{
drawer?.close();
return onSelectSession(sessionId);
}}
onRename={onRenameSession}
onDelete={onDeleteSession}
onOrganize={onOrganizeSession}
/>
)}
) : null}
>
);
/* ---- Collapsed state ---- */
if (collapsed) {
return (
);
}
/* ---- Expanded state ---- */
return (
);
}