refactor search cpace chats fetching - with tanstack query

This commit is contained in:
thierryverse 2025-11-12 12:32:04 +02:00
parent 93f6056a91
commit b2887543a2
3 changed files with 364 additions and 318 deletions

View file

@ -50,6 +50,8 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useAtomValue } from "jotai";
import { activeSearchSpaceChatsAtom } from "@/stores/chats/active-search-space-chats.atom";
export interface Chat { export interface Chat {
created_at: string; created_at: string;
@ -91,10 +93,10 @@ const MotionCard = motion(Card);
export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps) { export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps) {
const router = useRouter(); const router = useRouter();
const [chats, setChats] = useState<Chat[]>([]); // const [chats, setChats] = useState<Chat[]>([]);
const [filteredChats, setFilteredChats] = useState<Chat[]>([]); const [filteredChats, setFilteredChats] = useState<Chat[]>([]);
const [isLoading, setIsLoading] = useState(true); // const [isFetching, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null); // const [error, setError] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(1); const [totalPages, setTotalPages] = useState(1);
@ -103,6 +105,7 @@ export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps)
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [chatToDelete, setChatToDelete] = useState<{ id: number; title: string } | null>(null); const [chatToDelete, setChatToDelete] = useState<{ id: number; title: string } | null>(null);
const [isDeleting, setIsDeleting] = useState(false); const [isDeleting, setIsDeleting] = useState(false);
const {isFetching , data : chats, error} = useAtomValue(activeSearchSpaceChatsAtom);
const chatsPerPage = 9; const chatsPerPage = 9;
const searchParams = useSearchParams(); const searchParams = useSearchParams();
@ -118,58 +121,67 @@ export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps)
} }
}, [searchParams]); }, [searchParams]);
// Fetch chats from API
useEffect(() => { useEffect(() => {
const fetchChats = async () => { if (error) {
try { console.error("Error fetching chats:", error);
setIsLoading(true); }
}, [error]);
// Get token from localStorage // Fetch chats from API
const token = localStorage.getItem("surfsense_bearer_token"); // useEffect(() => {
// const fetchChats = async () => {
// try {
// setIsLoading(true);
if (!token) { // // Get token from localStorage
setError("Authentication token not found. Please log in again."); // const token = localStorage.getItem("surfsense_bearer_token");
setIsLoading(false);
return;
}
// Fetch all chats for this search space // if (!token) {
const response = await fetch( // setError("Authentication token not found. Please log in again.");
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/chats?search_space_id=${searchSpaceId}`, // setIsLoading(false);
{ // return;
headers: { // }
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
cache: "no-store",
}
);
if (!response.ok) { // // Fetch all chats for this search space
const errorData = await response.json().catch(() => null); // const response = await fetch(
throw new Error(`Failed to fetch chats: ${response.status} ${errorData?.error || ""}`); // `${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/chats?search_space_id=${searchSpaceId}`,
} // {
// headers: {
// Authorization: `Bearer ${token}`,
// "Content-Type": "application/json",
// },
// cache: "no-store",
// }
// );
const data: Chat[] = await response.json(); // if (!response.ok) {
setChats(data); // const errorData = await response.json().catch(() => null);
setFilteredChats(data); // throw new Error(`Failed to fetch chats: ${response.status} ${errorData?.error || ""}`);
setError(null); // }
} catch (error) {
console.error("Error fetching chats:", error);
setError(error instanceof Error ? error.message : "Unknown error occurred");
setChats([]);
setFilteredChats([]);
} finally {
setIsLoading(false);
}
};
fetchChats(); // const data: Chat[] = await response.json();
}, [searchSpaceId]); // setChats(data);
// setFilteredChats(data);
// setError(null);
// } catch (error) {
// console.error("Error fetching chats:", error);
// setError(error instanceof Error ? error.message : "Unknown error occurred");
// setChats([]);
// setFilteredChats([]);
// } finally {
// setIsLoading(false);
// }
// };
// fetchChats();
// }, [searchSpaceId]);
// Filter and sort chats based on search query, type, and sort order // Filter and sort chats based on search query, type, and sort order
useEffect(() => { useEffect(() => {
let result = [...chats]; let result = [...(chats || [])];
console.log("chats", chats);
// Filter by search term // Filter by search term
if (searchQuery) { if (searchQuery) {
@ -201,42 +213,42 @@ export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps)
// Function to handle chat deletion // Function to handle chat deletion
const handleDeleteChat = async () => { const handleDeleteChat = async () => {
if (!chatToDelete) return; // if (!chatToDelete) return;
setIsDeleting(true); // setIsDeleting(true);
try { // try {
const token = localStorage.getItem("surfsense_bearer_token"); // const token = localStorage.getItem("surfsense_bearer_token");
if (!token) { // if (!token) {
setIsDeleting(false); // setIsDeleting(false);
return; // return;
} // }
const response = await fetch( // const response = await fetch(
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/chats/${chatToDelete.id}`, // `${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/chats/${chatToDelete.id}`,
{ // {
method: "DELETE", // method: "DELETE",
headers: { // headers: {
Authorization: `Bearer ${token}`, // Authorization: `Bearer ${token}`,
"Content-Type": "application/json", // "Content-Type": "application/json",
}, // },
} // }
); // );
if (!response.ok) { // if (!response.ok) {
throw new Error(`Failed to delete chat: ${response.statusText}`); // throw new Error(`Failed to delete chat: ${response.statusText}`);
} // }
// Close dialog and refresh chats // // Close dialog and refresh chats
setDeleteDialogOpen(false); // setDeleteDialogOpen(false);
setChatToDelete(null); // setChatToDelete(null);
// Update local state by removing the deleted chat // // Update local state by removing the deleted chat
setChats((prevChats) => prevChats.filter((chat) => chat.id !== chatToDelete.id)); // setChats((prevChats) => prevChats.filter((chat) => chat.id !== chatToDelete.id));
} catch (error) { // } catch (error) {
console.error("Error deleting chat:", error); // console.error("Error deleting chat:", error);
} finally { // } finally {
setIsDeleting(false); // setIsDeleting(false);
} // }
}; };
// Calculate pagination // Calculate pagination
@ -245,7 +257,7 @@ export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps)
const currentChats = filteredChats.slice(indexOfFirstChat, indexOfLastChat); const currentChats = filteredChats.slice(indexOfFirstChat, indexOfLastChat);
// Get unique chat types for filter dropdown // Get unique chat types for filter dropdown
const chatTypes = ["all", ...Array.from(new Set(chats.map((chat) => chat.type)))]; const chatTypes = chats ? ["all", ...Array.from(new Set(chats.map((chat) => chat.type)))] : [];
return ( return (
<motion.div <motion.div
@ -307,7 +319,7 @@ export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps)
</div> </div>
{/* Status Messages */} {/* Status Messages */}
{isLoading && ( {isFetching && (
<div className="flex items-center justify-center h-40"> <div className="flex items-center justify-center h-40">
<div className="flex flex-col items-center gap-2"> <div className="flex flex-col items-center gap-2">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"></div> <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"></div>
@ -316,14 +328,14 @@ export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps)
</div> </div>
)} )}
{error && !isLoading && ( {error && !isFetching && (
<div className="border border-destructive/50 text-destructive p-4 rounded-md"> <div className="border border-destructive/50 text-destructive p-4 rounded-md">
<h3 className="font-medium">Error loading chats</h3> <h3 className="font-medium">Error loading chats</h3>
<p className="text-sm">{error}</p> <p className="text-sm">{error.message}</p>
</div> </div>
)} )}
{!isLoading && !error && filteredChats.length === 0 && ( {!isFetching && !error && filteredChats.length === 0 && (
<div className="flex flex-col items-center justify-center h-40 gap-2 text-center"> <div className="flex flex-col items-center justify-center h-40 gap-2 text-center">
<MessageCircleMore className="h-8 w-8 text-muted-foreground" /> <MessageCircleMore className="h-8 w-8 text-muted-foreground" />
<h3 className="font-medium">No chats found</h3> <h3 className="font-medium">No chats found</h3>
@ -336,7 +348,7 @@ export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps)
)} )}
{/* Chat Grid */} {/* Chat Grid */}
{!isLoading && !error && filteredChats.length > 0 && ( {!isFetching && !error && filteredChats.length > 0 && (
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{currentChats.map((chat, index) => ( {currentChats.map((chat, index) => (
@ -422,7 +434,7 @@ export default function ChatsPageClient({ searchSpaceId }: ChatsPageClientProps)
)} )}
{/* Pagination */} {/* Pagination */}
{!isLoading && !error && totalPages > 1 && ( {!isFetching && !error && totalPages > 1 && (
<Pagination className="mt-8"> <Pagination className="mt-8">
<PaginationContent> <PaginationContent>
<PaginationItem> <PaginationItem>

View file

@ -1,9 +1,9 @@
"use client"; "use client";
import { useAtom, useAtomValue } from "jotai"; import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { Loader2, PanelRight } from "lucide-react"; import { Loader2, PanelRight } from "lucide-react";
import { AnimatePresence, motion } from "motion/react"; import { AnimatePresence, motion } from "motion/react";
import { usePathname, useRouter } from "next/navigation"; import { useParams, usePathname, useRouter } from "next/navigation";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import type React from "react"; import type React from "react";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
@ -12,233 +12,275 @@ import { DashboardBreadcrumb } from "@/components/dashboard-breadcrumb";
import { LanguageSwitcher } from "@/components/LanguageSwitcher"; import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { AppSidebarProvider } from "@/components/sidebar/AppSidebarProvider"; import { AppSidebarProvider } from "@/components/sidebar/AppSidebarProvider";
import { ThemeTogglerComponent } from "@/components/theme/theme-toggle"; import { ThemeTogglerComponent } from "@/components/theme/theme-toggle";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { SidebarInset, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"; import {
SidebarInset,
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar";
import { useLLMPreferences } from "@/hooks/use-llm-configs"; import { useLLMPreferences } from "@/hooks/use-llm-configs";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { activeChatIdAtom } from "@/stores/chats/active-chat.atom"; import { activeChatIdAtom } from "@/stores/chats/active-chat.atom";
import { chatUIAtom } from "@/stores/chats/active-chat-ui.atom"; import { chatUIAtom } from "@/stores/chats/active-chat-ui.atom";
import { activeSearchSpaceIdAtom } from "@/stores/seach-space/active-seach-space.atom";
export function DashboardClientLayout({ export function DashboardClientLayout({
children, children,
searchSpaceId, searchSpaceId,
navSecondary, navSecondary,
navMain, navMain,
}: { }: {
children: React.ReactNode; children: React.ReactNode;
searchSpaceId: string; searchSpaceId: string;
navSecondary: any[]; navSecondary: any[];
navMain: any[]; navMain: any[];
}) { }) {
const t = useTranslations("dashboard"); const t = useTranslations("dashboard");
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
const searchSpaceIdNum = Number(searchSpaceId); const searchSpaceIdNum = Number(searchSpaceId);
const { search_space_id, chat_id } = useParams();
const [chatUIState, setChatUIState] = useAtom(chatUIAtom);
const activeChatId = useAtomValue(activeChatIdAtom);
const setActiveSearchSpaceIdState = useSetAtom(activeSearchSpaceIdAtom);
const setActiveChatIdState = useSetAtom(activeChatIdAtom);
const [showIndicator, setShowIndicator] = useState(false);
const [chatUIState, setChatUIState] = useAtom(chatUIAtom); const { isChatPannelOpen } = chatUIState;
const activeChatId = useAtomValue(activeChatIdAtom);
const [showIndicator, setShowIndicator] = useState(false);
const { isChatPannelOpen } = chatUIState; // Check if we're on the researcher page
const isResearcherPage = pathname?.includes("/researcher");
// Check if we're on the researcher page // Show indicator when chat becomes active and panel is closed
const isResearcherPage = pathname?.includes("/researcher"); useEffect(() => {
if (activeChatId && !isChatPannelOpen) {
setShowIndicator(true);
// Hide indicator after 5 seconds
const timer = setTimeout(() => setShowIndicator(false), 5000);
return () => clearTimeout(timer);
} else {
setShowIndicator(false);
}
}, [activeChatId, isChatPannelOpen]);
// Show indicator when chat becomes active and panel is closed const { loading, error, isOnboardingComplete } =
useEffect(() => { useLLMPreferences(searchSpaceIdNum);
if (activeChatId && !isChatPannelOpen) { const [hasCheckedOnboarding, setHasCheckedOnboarding] = useState(false);
setShowIndicator(true);
// Hide indicator after 5 seconds
const timer = setTimeout(() => setShowIndicator(false), 5000);
return () => clearTimeout(timer);
} else {
setShowIndicator(false);
}
}, [activeChatId, isChatPannelOpen]);
const { loading, error, isOnboardingComplete } = useLLMPreferences(searchSpaceIdNum); // Skip onboarding check if we're already on the onboarding page
const [hasCheckedOnboarding, setHasCheckedOnboarding] = useState(false); const isOnboardingPage = pathname?.includes("/onboard");
// Skip onboarding check if we're already on the onboarding page // Translate navigation items
const isOnboardingPage = pathname?.includes("/onboard"); const tNavMenu = useTranslations("nav_menu");
const translatedNavMain = useMemo(() => {
return navMain.map((item) => ({
...item,
title: tNavMenu(item.title.toLowerCase().replace(/ /g, "_")),
items: item.items?.map((subItem: any) => ({
...subItem,
title: tNavMenu(subItem.title.toLowerCase().replace(/ /g, "_")),
})),
}));
}, [navMain, tNavMenu]);
// Translate navigation items const translatedNavSecondary = useMemo(() => {
const tNavMenu = useTranslations("nav_menu"); return navSecondary.map((item) => ({
const translatedNavMain = useMemo(() => { ...item,
return navMain.map((item) => ({ title:
...item, item.title === "All Search Spaces"
title: tNavMenu(item.title.toLowerCase().replace(/ /g, "_")), ? tNavMenu("all_search_spaces")
items: item.items?.map((subItem: any) => ({ : item.title,
...subItem, }));
title: tNavMenu(subItem.title.toLowerCase().replace(/ /g, "_")), }, [navSecondary, tNavMenu]);
})),
}));
}, [navMain, tNavMenu]);
const translatedNavSecondary = useMemo(() => { const [open, setOpen] = useState<boolean>(() => {
return navSecondary.map((item) => ({ try {
...item, const match = document.cookie.match(/(?:^|; )sidebar_state=([^;]+)/);
title: item.title === "All Search Spaces" ? tNavMenu("all_search_spaces") : item.title, if (match) return match[1] === "true";
})); } catch {
}, [navSecondary, tNavMenu]); // ignore
}
return true;
});
const [open, setOpen] = useState<boolean>(() => { useEffect(() => {
try { // Skip check if already on onboarding page
const match = document.cookie.match(/(?:^|; )sidebar_state=([^;]+)/); if (isOnboardingPage) {
if (match) return match[1] === "true"; setHasCheckedOnboarding(true);
} catch { return;
// ignore }
}
return true;
});
useEffect(() => { // Only check once after preferences have loaded
// Skip check if already on onboarding page if (!loading && !hasCheckedOnboarding) {
if (isOnboardingPage) { const onboardingComplete = isOnboardingComplete();
setHasCheckedOnboarding(true);
return;
}
// Only check once after preferences have loaded if (!onboardingComplete) {
if (!loading && !hasCheckedOnboarding) { router.push(`/dashboard/${searchSpaceId}/onboard`);
const onboardingComplete = isOnboardingComplete(); }
if (!onboardingComplete) { setHasCheckedOnboarding(true);
router.push(`/dashboard/${searchSpaceId}/onboard`); }
} }, [
loading,
isOnboardingComplete,
isOnboardingPage,
router,
searchSpaceId,
hasCheckedOnboarding,
]);
setHasCheckedOnboarding(true); // Synchronize active search space and chat IDs with URL
} useEffect(() => {
}, [ const activeSeacrhSpaceId =
loading, typeof search_space_id === "string"
isOnboardingComplete, ? search_space_id
isOnboardingPage, : Array.isArray(search_space_id) && search_space_id.length > 0
router, ? search_space_id[0]
searchSpaceId, : "";
hasCheckedOnboarding, if (!activeSeacrhSpaceId) return;
]); setActiveSearchSpaceIdState(activeSeacrhSpaceId);
}, [search_space_id]);
// Show loading screen while checking onboarding status (only on first load) useEffect(() => {
if (!hasCheckedOnboarding && loading && !isOnboardingPage) { const activeChatId =
return ( typeof chat_id === "string" ? chat_id : Array.isArray(chat_id) && chat_id.length > 0 ? chat_id[0] : "";
<div className="flex flex-col items-center justify-center min-h-screen space-y-4"> if (!activeChatId) return;
<Card className="w-[350px] bg-background/60 backdrop-blur-sm"> setActiveChatIdState(activeChatId);
<CardHeader className="pb-2"> }, [chat_id, search_space_id]);
<CardTitle className="text-xl font-medium">{t("loading_config")}</CardTitle>
<CardDescription>{t("checking_llm_prefs")}</CardDescription>
</CardHeader>
<CardContent className="flex justify-center py-6">
<Loader2 className="h-12 w-12 text-primary animate-spin" />
</CardContent>
</Card>
</div>
);
}
// Show error screen if there's an error loading preferences (but not on onboarding page) // Show loading screen while checking onboarding status (only on first load)
if (error && !hasCheckedOnboarding && !isOnboardingPage) { if (!hasCheckedOnboarding && loading && !isOnboardingPage) {
return ( return (
<div className="flex flex-col items-center justify-center min-h-screen space-y-4"> <div className="flex flex-col items-center justify-center min-h-screen space-y-4">
<Card className="w-[400px] bg-background/60 backdrop-blur-sm border-destructive/20"> <Card className="w-[350px] bg-background/60 backdrop-blur-sm">
<CardHeader className="pb-2"> <CardHeader className="pb-2">
<CardTitle className="text-xl font-medium text-destructive"> <CardTitle className="text-xl font-medium">
{t("config_error")} {t("loading_config")}
</CardTitle> </CardTitle>
<CardDescription>{t("failed_load_llm_config")}</CardDescription> <CardDescription>{t("checking_llm_prefs")}</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent className="flex justify-center py-6">
<p className="text-sm text-muted-foreground">{error}</p> <Loader2 className="h-12 w-12 text-primary animate-spin" />
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
); );
} }
return ( // Show error screen if there's an error loading preferences (but not on onboarding page)
<SidebarProvider if (error && !hasCheckedOnboarding && !isOnboardingPage) {
className="h-full bg-red-600 overflow-hidden" return (
open={open} <div className="flex flex-col items-center justify-center min-h-screen space-y-4">
onOpenChange={setOpen} <Card className="w-[400px] bg-background/60 backdrop-blur-sm border-destructive/20">
> <CardHeader className="pb-2">
{/* Use AppSidebarProvider which fetches user, search space, and recent chats */} <CardTitle className="text-xl font-medium text-destructive">
<AppSidebarProvider {t("config_error")}
searchSpaceId={searchSpaceId} </CardTitle>
navSecondary={translatedNavSecondary} <CardDescription>{t("failed_load_llm_config")}</CardDescription>
navMain={translatedNavMain} </CardHeader>
/> <CardContent>
<SidebarInset className="h-full "> <p className="text-sm text-muted-foreground">{error}</p>
<main className="flex h-full"> </CardContent>
<div className="flex grow flex-col h-full border-r"> </Card>
<header className="sticky top-0 z-50 flex h-16 shrink-0 items-center gap-2 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-b"> </div>
<div className="flex items-center justify-between w-full gap-2 px-4"> );
<div className="flex items-center gap-2"> }
<SidebarTrigger className="-ml-1" />
<Separator orientation="vertical" className="h-6" /> return (
<DashboardBreadcrumb /> <SidebarProvider
</div> className="h-full bg-red-600 overflow-hidden"
<div className="flex items-center gap-2"> open={open}
<LanguageSwitcher /> onOpenChange={setOpen}
<ThemeTogglerComponent /> >
{/* Only show artifacts toggle on researcher page */} {/* Use AppSidebarProvider which fetches user, search space, and recent chats */}
{isResearcherPage && ( <AppSidebarProvider
<motion.div searchSpaceId={searchSpaceId}
className="relative" navSecondary={translatedNavSecondary}
animate={ navMain={translatedNavMain}
showIndicator />
? { <SidebarInset className="h-full ">
scale: [1, 1.05, 1], <main className="flex h-full">
} <div className="flex grow flex-col h-full border-r">
: {} <header className="sticky top-0 z-50 flex h-16 shrink-0 items-center gap-2 bg-background/95 backdrop-blur supports-backdrop-filter:bg-background/60 border-b">
} <div className="flex items-center justify-between w-full gap-2 px-4">
transition={{ <div className="flex items-center gap-2">
duration: 2, <SidebarTrigger className="-ml-1" />
repeat: showIndicator ? Number.POSITIVE_INFINITY : 0, <Separator orientation="vertical" className="h-6" />
ease: "easeInOut", <DashboardBreadcrumb />
}} </div>
> <div className="flex items-center gap-2">
<motion.button <LanguageSwitcher />
type="button" <ThemeTogglerComponent />
onClick={() => { {/* Only show artifacts toggle on researcher page */}
setChatUIState((prev) => ({ {isResearcherPage && (
...prev, <motion.div
isChatPannelOpen: !isChatPannelOpen, className="relative"
})); animate={
setShowIndicator(false); showIndicator
}} ? {
className={cn( scale: [1, 1.05, 1],
"shrink-0 rounded-full p-2 transition-all duration-300 relative", }
showIndicator : {}
? "bg-primary/20 hover:bg-primary/30 shadow-lg shadow-primary/25" }
: "hover:bg-muted", transition={{
activeChatId && !showIndicator && "hover:bg-primary/10" duration: 2,
)} repeat: showIndicator ? Number.POSITIVE_INFINITY : 0,
title="Toggle Artifacts Panel" ease: "easeInOut",
whileHover={{ scale: 1.05 }} }}
whileTap={{ scale: 0.95 }} >
> <motion.button
<motion.div type="button"
animate={ onClick={() => {
showIndicator setChatUIState((prev) => ({
? { ...prev,
rotate: [0, -10, 10, -10, 0], isChatPannelOpen: !isChatPannelOpen,
} }));
: {} setShowIndicator(false);
} }}
transition={{ className={cn(
duration: 0.5, "shrink-0 rounded-full p-2 transition-all duration-300 relative",
repeat: showIndicator ? Number.POSITIVE_INFINITY : 0, showIndicator
repeatDelay: 2, ? "bg-primary/20 hover:bg-primary/30 shadow-lg shadow-primary/25"
}} : "hover:bg-muted",
> activeChatId &&
<PanelRight !showIndicator &&
className={cn( "hover:bg-primary/10"
"h-4 w-4 transition-colors", )}
showIndicator && "text-primary" title="Toggle Artifacts Panel"
)} whileHover={{ scale: 1.05 }}
/> whileTap={{ scale: 0.95 }}
</motion.div> >
</motion.button> <motion.div
animate={
showIndicator
? {
rotate: [0, -10, 10, -10, 0],
}
: {}
}
transition={{
duration: 0.5,
repeat: showIndicator
? Number.POSITIVE_INFINITY
: 0,
repeatDelay: 2,
}}
>
<PanelRight
className={cn(
"h-4 w-4 transition-colors",
showIndicator && "text-primary"
)}
/>
</motion.div>
</motion.button>
{/* Pulsing indicator badge */} {/* Pulsing indicator badge */}
<AnimatePresence> <AnimatePresence>

View file

@ -1,46 +1,38 @@
"use client"; "use client";
import { type ChatHandler, ChatSection as LlamaIndexChatSection } from "@llamaindex/chat-ui"; import {
import { useSetAtom } from "jotai"; type ChatHandler,
ChatSection as LlamaIndexChatSection,
} from "@llamaindex/chat-ui";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import { useEffect } from "react";
import { ChatInputUI } from "@/components/chat/ChatInputGroup"; import { ChatInputUI } from "@/components/chat/ChatInputGroup";
import { ChatMessagesUI } from "@/components/chat/ChatMessages"; import { ChatMessagesUI } from "@/components/chat/ChatMessages";
import type { Document } from "@/hooks/use-documents"; import type { Document } from "@/hooks/use-documents";
import { activeChatIdAtom } from "@/stores/chats/active-chat.atom";
import { ChatPanelContainer } from "./ChatPanel/ChatPanelContainer";
interface ChatInterfaceProps { interface ChatInterfaceProps {
handler: ChatHandler; handler: ChatHandler;
onDocumentSelectionChange?: (documents: Document[]) => void; onDocumentSelectionChange?: (documents: Document[]) => void;
selectedDocuments?: Document[]; selectedDocuments?: Document[];
onConnectorSelectionChange?: (connectorTypes: string[]) => void; onConnectorSelectionChange?: (connectorTypes: string[]) => void;
selectedConnectors?: string[]; selectedConnectors?: string[];
searchMode?: "DOCUMENTS" | "CHUNKS"; searchMode?: "DOCUMENTS" | "CHUNKS";
onSearchModeChange?: (mode: "DOCUMENTS" | "CHUNKS") => void; onSearchModeChange?: (mode: "DOCUMENTS" | "CHUNKS") => void;
topK?: number; topK?: number;
onTopKChange?: (topK: number) => void; onTopKChange?: (topK: number) => void;
} }
export default function ChatInterface({ export default function ChatInterface({
handler, handler,
onDocumentSelectionChange, onDocumentSelectionChange,
selectedDocuments = [], selectedDocuments = [],
onConnectorSelectionChange, onConnectorSelectionChange,
selectedConnectors = [], selectedConnectors = [],
searchMode, searchMode,
onSearchModeChange, onSearchModeChange,
topK = 10, topK = 10,
onTopKChange, onTopKChange,
}: ChatInterfaceProps) { }: ChatInterfaceProps) {
const { chat_id, search_space_id } = useParams(); const { chat_id, search_space_id } = useParams();
const setActiveChatIdState = useSetAtom(activeChatIdAtom);
useEffect(() => {
const id = typeof chat_id === "string" ? chat_id : chat_id ? chat_id[0] : "";
if (!id) return;
setActiveChatIdState(id);
}, [chat_id, search_space_id]);
return ( return (
<LlamaIndexChatSection handler={handler} className="flex h-full max-w-7xl mx-auto"> <LlamaIndexChatSection handler={handler} className="flex h-full max-w-7xl mx-auto">