Skip to content

Commit 55d243b

Browse files
committed
feat: auto navigate to previous chat after deleting current chat
1 parent 7c48e98 commit 55d243b

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

web/src/components/sidebar.tsx

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { Edit2 } from 'lucide-react';
44
import { Message } from "ai/react";
55
import Image from "next/image";
66
import Link from "next/link";
7+
import { useRouter } from "next/navigation";
78
import Logo from "../../public/logo.png";
89
import { ChatOptions } from "./chat/chat-options";
910
import SidebarTabs from "./sidebar-tabs";
@@ -31,6 +32,7 @@ export function Sidebar({
3132
chatOptions,
3233
setChatOptions,
3334
}: SidebarProps) {
35+
const router = useRouter();
3436
const [localChats, setLocalChats] = useState<Chats>({});
3537
const [isLoading, setIsLoading] = useState(true);
3638

@@ -99,9 +101,35 @@ export function Sidebar({
99101
return groupChatsByDate(chatObjects);
100102
};
101103

102-
const handleDeleteChat = (chatId: string) => {
103-
localStorage.removeItem(chatId);
104+
const handleDeleteChat = (chatIdToDelete: string) => {
105+
const flatChats = Object.values(localChats).flat();
106+
const chatIndex = flatChats.findIndex((c) => c.chatId === chatIdToDelete);
107+
108+
let nextChatId = "";
109+
110+
if (flatChats.length > 1) {
111+
if (chatIndex === flatChats.length - 1) {
112+
nextChatId = flatChats[chatIndex - 1].chatId;
113+
} else {
114+
nextChatId = flatChats[chatIndex + 1].chatId;
115+
}
116+
}
117+
118+
localStorage.removeItem(chatIdToDelete);
104119
setLocalChats(getLocalstorageChats());
120+
121+
// Auto-navigate to previous chat if the deleted chat is currently open
122+
const currentChatKey = `chat_${chatId}`;
123+
if (chatIdToDelete === currentChatKey) {
124+
if (nextChatId) {
125+
const nextUUID = nextChatId.substring(5);
126+
setChatId(nextUUID);
127+
router.push(`/chats/${nextUUID}`);
128+
} else {
129+
setChatId("");
130+
router.push("/");
131+
}
132+
}
105133
};
106134

107135
return (
@@ -116,7 +144,7 @@ export function Sidebar({
116144
onClick={() => setChatId("")}
117145
className={cn(
118146
"flex items-center justify-between px-3 py-2.5 rounded-md text-sm font-medium transition-all duration-200",
119-
"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm", // Primary Button Style
147+
"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm",
120148
"border border-transparent"
121149
)}
122150
>

0 commit comments

Comments
 (0)