Initial commit: EGBE chatbot template

Stripped from vercel/chatbot (Apache 2.0):
- Dropped @vercel/* packages and AI Gateway
- Removed artifacts feature (code/text/sheet/image side panel)
- Switched AI provider to @ai-sdk/openai-compatible -> EGBE LiteLLM
- Replaced Vercel Blob upload with data URLs
- Dropped Redis resumable streams and rate limiter (in-memory now)
- Added Dockerfile (Next.js standalone) + entrypoint that runs migrations
- Wired DATABASE_URL, EGBE_AI_API_URL/KEY, NEXT_PUBLIC_BASE_URL for app-deploy.sh
This commit is contained in:
dmitry.galkin 2026-05-25 14:54:04 +04:00
commit 3e21c2334c
129 changed files with 21913 additions and 0 deletions

View file

@ -0,0 +1,165 @@
"use client";
import {
MessageSquareIcon,
PanelLeftIcon,
PenSquareIcon,
TrashIcon,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import type { User } from "next-auth";
import { useState } from "react";
import { toast } from "sonner";
import { useSWRConfig } from "swr";
import { unstable_serialize } from "swr/infinite";
import {
getChatHistoryPaginationKey,
SidebarHistory,
} from "@/components/chat/sidebar-history";
import { SidebarUserNav } from "@/components/chat/sidebar-user-nav";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
SidebarTrigger,
useSidebar,
} from "@/components/ui/sidebar";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "../ui/alert-dialog";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
export function AppSidebar({ user }: { user: User | undefined }) {
const router = useRouter();
const { setOpenMobile, toggleSidebar } = useSidebar();
const { mutate } = useSWRConfig();
const [showDeleteAllDialog, setShowDeleteAllDialog] = useState(false);
const handleDeleteAll = () => {
setShowDeleteAllDialog(false);
router.replace("/");
mutate(unstable_serialize(getChatHistoryPaginationKey), [], {
revalidate: false,
});
fetch(`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/history`, {
method: "DELETE",
});
toast.success("All chats deleted");
};
return (
<>
<Sidebar collapsible="icon">
<SidebarHeader className="pb-0 pt-3">
<SidebarMenu>
<SidebarMenuItem className="flex flex-row items-center justify-between">
<div className="group/logo relative flex items-center justify-center">
<SidebarMenuButton
asChild
className="size-8 !px-0 items-center justify-center group-data-[collapsible=icon]:group-hover/logo:opacity-0"
tooltip="Chatbot"
>
<Link href="/" onClick={() => setOpenMobile(false)}>
<MessageSquareIcon className="size-4 text-sidebar-foreground/50" />
</Link>
</SidebarMenuButton>
<Tooltip>
<TooltipTrigger asChild>
<SidebarMenuButton
className="pointer-events-none absolute inset-0 size-8 opacity-0 group-data-[collapsible=icon]:pointer-events-auto group-data-[collapsible=icon]:group-hover/logo:opacity-100"
onClick={() => toggleSidebar()}
>
<PanelLeftIcon className="size-4" />
</SidebarMenuButton>
</TooltipTrigger>
<TooltipContent className="hidden md:block" side="right">
Open sidebar
</TooltipContent>
</Tooltip>
</div>
<div className="group-data-[collapsible=icon]:hidden">
<SidebarTrigger className="text-sidebar-foreground/60 transition-colors duration-150 hover:text-sidebar-foreground" />
</div>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<SidebarGroup className="pt-1">
<SidebarGroupContent>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
className="h-8 rounded-lg border border-sidebar-border text-[13px] text-sidebar-foreground/70 transition-colors duration-150 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
onClick={() => {
setOpenMobile(false);
router.push("/");
}}
tooltip="New Chat"
>
<PenSquareIcon className="size-4" />
<span className="font-medium">New chat</span>
</SidebarMenuButton>
</SidebarMenuItem>
{user && (
<SidebarMenuItem>
<SidebarMenuButton
className="rounded-lg text-sidebar-foreground/40 transition-colors duration-150 hover:bg-destructive/10 hover:text-destructive"
onClick={() => setShowDeleteAllDialog(true)}
tooltip="Delete All Chats"
>
<TrashIcon className="size-4" />
<span className="text-[13px]">Delete all</span>
</SidebarMenuButton>
</SidebarMenuItem>
)}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
<SidebarHistory user={user} />
</SidebarContent>
<SidebarFooter className="border-t border-sidebar-border pt-2 pb-3">
{user && <SidebarUserNav user={user} />}
</SidebarFooter>
<SidebarRail />
</Sidebar>
<AlertDialog
onOpenChange={setShowDeleteAllDialog}
open={showDeleteAllDialog}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete all chats?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete all
your chats and remove them from our servers.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDeleteAll}>
Delete All
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}

View file

@ -0,0 +1,53 @@
import Form from "next/form";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
export function AuthForm({
action,
children,
defaultEmail = "",
}: {
action: NonNullable<
string | ((formData: FormData) => void | Promise<void>) | undefined
>;
children: React.ReactNode;
defaultEmail?: string;
}) {
return (
<Form action={action} className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label className="font-normal text-muted-foreground" htmlFor="email">
Email
</Label>
<Input
autoComplete="email"
autoFocus
className="h-10 rounded-lg border-border/50 bg-muted/50 text-sm transition-colors focus:border-foreground/20 focus:bg-muted"
defaultValue={defaultEmail}
id="email"
name="email"
placeholder="you@someo.ne"
required
type="email"
/>
</div>
<div className="flex flex-col gap-2">
<Label className="font-normal text-muted-foreground" htmlFor="password">
Password
</Label>
<Input
className="h-10 rounded-lg border-border/50 bg-muted/50 text-sm transition-colors focus:border-foreground/20 focus:bg-muted"
id="password"
name="password"
placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;"
required
type="password"
/>
</div>
{children}
</Form>
);
}

View file

@ -0,0 +1,76 @@
"use client";
import { PanelLeftIcon } from "lucide-react";
import Link from "next/link";
import { memo } from "react";
import { Button } from "@/components/ui/button";
import { useSidebar } from "@/components/ui/sidebar";
import { VercelIcon } from "./icons";
import { VisibilitySelector, type VisibilityType } from "./visibility-selector";
function PureChatHeader({
chatId,
selectedVisibilityType,
isReadonly,
}: {
chatId: string;
selectedVisibilityType: VisibilityType;
isReadonly: boolean;
}) {
const { state, toggleSidebar, isMobile } = useSidebar();
if (state === "collapsed" && !isMobile) {
return null;
}
return (
<header className="sticky top-0 flex h-14 items-center gap-2 bg-sidebar px-3">
<Button
className="md:hidden"
onClick={toggleSidebar}
size="icon-sm"
variant="ghost"
>
<PanelLeftIcon className="size-4" />
</Button>
<Link
className="flex size-8 items-center justify-center rounded-lg md:hidden"
href="https://vercel.com/templates/next.js/chatbot"
rel="noopener noreferrer"
target="_blank"
>
<VercelIcon size={14} />
</Link>
{!isReadonly && (
<VisibilitySelector
chatId={chatId}
selectedVisibilityType={selectedVisibilityType}
/>
)}
<Button
asChild
className="hidden rounded-lg bg-foreground px-4 text-background hover:bg-foreground/90 md:ml-auto md:flex"
>
<Link
href="https://vercel.com/templates/next.js/chatbot"
rel="noopener noreferrer"
target="_blank"
>
<VercelIcon size={16} />
Deploy with Vercel
</Link>
</Button>
</header>
);
}
export const ChatHeader = memo(PureChatHeader, (prevProps, nextProps) => {
return (
prevProps.chatId === nextProps.chatId &&
prevProps.selectedVisibilityType === nextProps.selectedVisibilityType &&
prevProps.isReadonly === nextProps.isReadonly
);
});

View file

@ -0,0 +1,29 @@
"use client";
import { useEffect } from "react";
import { useSWRConfig } from "swr";
import { unstable_serialize } from "swr/infinite";
import { useDataStream } from "./data-stream-provider";
import { getChatHistoryPaginationKey } from "./sidebar-history";
export function DataStreamHandler() {
const { dataStream, setDataStream } = useDataStream();
const { mutate } = useSWRConfig();
useEffect(() => {
if (!dataStream?.length) {
return;
}
const newDeltas = dataStream.slice();
setDataStream([]);
for (const delta of newDeltas) {
if (delta.type === "data-chat-title") {
mutate(unstable_serialize(getChatHistoryPaginationKey));
}
}
}, [dataStream, setDataStream, mutate]);
return null;
}

View file

@ -0,0 +1,41 @@
"use client";
import type { DataUIPart } from "ai";
import type React from "react";
import { createContext, useContext, useMemo, useState } from "react";
import type { CustomUIDataTypes } from "@/lib/types";
type DataStreamContextValue = {
dataStream: DataUIPart<CustomUIDataTypes>[];
setDataStream: React.Dispatch<
React.SetStateAction<DataUIPart<CustomUIDataTypes>[]>
>;
};
const DataStreamContext = createContext<DataStreamContextValue | null>(null);
export function DataStreamProvider({
children,
}: {
children: React.ReactNode;
}) {
const [dataStream, setDataStream] = useState<DataUIPart<CustomUIDataTypes>[]>(
[]
);
const value = useMemo(() => ({ dataStream, setDataStream }), [dataStream]);
return (
<DataStreamContext.Provider value={value}>
{children}
</DataStreamContext.Provider>
);
}
export function useDataStream() {
const context = useContext(DataStreamContext);
if (!context) {
throw new Error("useDataStream must be used within a DataStreamProvider");
}
return context;
}

View file

@ -0,0 +1,24 @@
import { motion } from "framer-motion";
export const Greeting = () => {
return (
<div className="flex flex-col items-center px-4" key="overview">
<motion.div
animate={{ opacity: 1, y: 0 }}
className="text-center font-semibold text-2xl tracking-tight text-foreground md:text-3xl"
initial={{ opacity: 0, y: 10 }}
transition={{ delay: 0.35, duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
>
What can I help with?
</motion.div>
<motion.div
animate={{ opacity: 1, y: 0 }}
className="mt-3 text-center text-muted-foreground/80 text-sm"
initial={{ opacity: 0, y: 10 }}
transition={{ delay: 0.5, duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
>
Ask a question, write code, or explore ideas.
</motion.div>
</div>
);
};

1213
components/chat/icons.tsx Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,207 @@
import equal from "fast-deep-equal";
import { memo } from "react";
import { toast } from "sonner";
import { useSWRConfig } from "swr";
import { useCopyToClipboard } from "usehooks-ts";
import type { Vote } from "@/lib/db/schema";
import type { ChatMessage } from "@/lib/types";
import {
MessageAction as Action,
MessageActions as Actions,
} from "../ai-elements/message";
import { CopyIcon, PencilEditIcon, ThumbDownIcon, ThumbUpIcon } from "./icons";
export function PureMessageActions({
chatId,
message,
vote,
isLoading,
onEdit,
}: {
chatId: string;
message: ChatMessage;
vote: Vote | undefined;
isLoading: boolean;
onEdit?: () => void;
}) {
const { mutate } = useSWRConfig();
const [_, copyToClipboard] = useCopyToClipboard();
if (isLoading) {
return null;
}
const textFromParts = message.parts
?.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n")
.trim();
const handleCopy = async () => {
if (!textFromParts) {
toast.error("There's no text to copy!");
return;
}
await copyToClipboard(textFromParts);
toast.success("Copied to clipboard!");
};
if (message.role === "user") {
return (
<Actions className="-mr-0.5 justify-end opacity-0 transition-opacity duration-150 group-hover/message:opacity-100">
<div className="flex items-center gap-0.5">
{onEdit && (
<Action
className="size-7 text-muted-foreground/50 hover:text-foreground"
data-testid="message-edit-button"
onClick={onEdit}
tooltip="Edit"
>
<PencilEditIcon />
</Action>
)}
<Action
className="size-7 text-muted-foreground/50 hover:text-foreground"
onClick={handleCopy}
tooltip="Copy"
>
<CopyIcon />
</Action>
</div>
</Actions>
);
}
return (
<Actions className="-ml-0.5 opacity-0 transition-opacity duration-150 group-hover/message:opacity-100">
<Action
className="text-muted-foreground/50 hover:text-foreground"
onClick={handleCopy}
tooltip="Copy"
>
<CopyIcon />
</Action>
<Action
className="text-muted-foreground/50 hover:text-foreground"
data-testid="message-upvote"
disabled={vote?.isUpvoted}
onClick={() => {
const upvote = fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/vote`,
{
method: "PATCH",
body: JSON.stringify({
chatId,
messageId: message.id,
type: "up",
}),
}
);
toast.promise(upvote, {
loading: "Upvoting Response...",
success: () => {
mutate<Vote[]>(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/vote?chatId=${chatId}`,
(currentVotes) => {
if (!currentVotes) {
return [];
}
const votesWithoutCurrent = currentVotes.filter(
(currentVote) => currentVote.messageId !== message.id
);
return [
...votesWithoutCurrent,
{
chatId,
messageId: message.id,
isUpvoted: true,
},
];
},
{ revalidate: false }
);
return "Upvoted Response!";
},
error: "Failed to upvote response.",
});
}}
tooltip="Upvote Response"
>
<ThumbUpIcon />
</Action>
<Action
className="text-muted-foreground/50 hover:text-foreground"
data-testid="message-downvote"
disabled={vote && !vote.isUpvoted}
onClick={() => {
const downvote = fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/vote`,
{
method: "PATCH",
body: JSON.stringify({
chatId,
messageId: message.id,
type: "down",
}),
}
);
toast.promise(downvote, {
loading: "Downvoting Response...",
success: () => {
mutate<Vote[]>(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/vote?chatId=${chatId}`,
(currentVotes) => {
if (!currentVotes) {
return [];
}
const votesWithoutCurrent = currentVotes.filter(
(currentVote) => currentVote.messageId !== message.id
);
return [
...votesWithoutCurrent,
{
chatId,
messageId: message.id,
isUpvoted: false,
},
];
},
{ revalidate: false }
);
return "Downvoted Response!";
},
error: "Failed to downvote response.",
});
}}
tooltip="Downvote Response"
>
<ThumbDownIcon />
</Action>
</Actions>
);
}
export const MessageActions = memo(
PureMessageActions,
(prevProps, nextProps) => {
if (!equal(prevProps.vote, nextProps.vote)) {
return false;
}
if (prevProps.isLoading !== nextProps.isLoading) {
return false;
}
return true;
}
);

View file

@ -0,0 +1,33 @@
"use client";
import type { UseChatHelpers } from "@ai-sdk/react";
import { deleteTrailingMessages } from "@/app/(chat)/actions";
import type { ChatMessage } from "@/lib/types";
export async function submitEditedMessage({
message,
text,
setMessages,
regenerate,
}: {
message: ChatMessage;
text: string;
setMessages: UseChatHelpers<ChatMessage>["setMessages"];
regenerate: UseChatHelpers<ChatMessage>["regenerate"];
}) {
await deleteTrailingMessages({ id: message.id });
setMessages((messages) => {
const index = messages.findIndex((m) => m.id === message.id);
if (index === -1) {
return messages;
}
return [
...messages.slice(0, index),
{ ...message, parts: [{ type: "text" as const, text }] },
];
});
regenerate();
}

View file

@ -0,0 +1,37 @@
"use client";
import { useEffect, useState } from "react";
import {
Reasoning,
ReasoningContent,
ReasoningTrigger,
} from "../ai-elements/reasoning";
type MessageReasoningProps = {
isLoading: boolean;
reasoning: string;
};
export function MessageReasoning({
isLoading,
reasoning,
}: MessageReasoningProps) {
const [hasBeenStreaming, setHasBeenStreaming] = useState(isLoading);
useEffect(() => {
if (isLoading) {
setHasBeenStreaming(true);
}
}, [isLoading]);
return (
<Reasoning
data-testid="message-reasoning"
defaultOpen={hasBeenStreaming}
isStreaming={isLoading}
>
<ReasoningTrigger />
<ReasoningContent>{reasoning}</ReasoningContent>
</Reasoning>
);
}

301
components/chat/message.tsx Normal file
View file

@ -0,0 +1,301 @@
"use client";
import type { UseChatHelpers } from "@ai-sdk/react";
import type { Vote } from "@/lib/db/schema";
import type { ChatMessage } from "@/lib/types";
import { cn, sanitizeText } from "@/lib/utils";
import { MessageContent, MessageResponse } from "../ai-elements/message";
import { Shimmer } from "../ai-elements/shimmer";
import {
Tool,
ToolContent,
ToolHeader,
ToolInput,
} from "../ai-elements/tool";
import { useDataStream } from "./data-stream-provider";
import { SparklesIcon } from "./icons";
import { MessageActions } from "./message-actions";
import { MessageReasoning } from "./message-reasoning";
import { PreviewAttachment } from "./preview-attachment";
import { Weather } from "./weather";
const PurePreviewMessage = ({
addToolApprovalResponse,
chatId,
message,
vote,
isLoading,
setMessages: _setMessages,
regenerate: _regenerate,
isReadonly,
requiresScrollPadding: _requiresScrollPadding,
onEdit,
}: {
addToolApprovalResponse: UseChatHelpers<ChatMessage>["addToolApprovalResponse"];
chatId: string;
message: ChatMessage;
vote: Vote | undefined;
isLoading: boolean;
setMessages: UseChatHelpers<ChatMessage>["setMessages"];
regenerate: UseChatHelpers<ChatMessage>["regenerate"];
isReadonly: boolean;
requiresScrollPadding: boolean;
onEdit?: (message: ChatMessage) => void;
}) => {
const attachmentsFromMessage = message.parts.filter(
(part) => part.type === "file"
);
useDataStream();
const isUser = message.role === "user";
const isAssistant = message.role === "assistant";
const hasAnyContent = message.parts?.some(
(part) =>
(part.type === "text" && part.text?.trim().length > 0) ||
(part.type === "reasoning" &&
"text" in part &&
part.text?.trim().length > 0) ||
part.type.startsWith("tool-")
);
const isThinking = isAssistant && isLoading && !hasAnyContent;
const attachments = attachmentsFromMessage.length > 0 && (
<div
className="flex flex-row justify-end gap-2"
data-testid={"message-attachments"}
>
{attachmentsFromMessage.map((attachment) => (
<PreviewAttachment
attachment={{
name: attachment.filename ?? "file",
contentType: attachment.mediaType,
url: attachment.url,
}}
key={attachment.url}
/>
))}
</div>
);
const mergedReasoning = message.parts?.reduce(
(acc, part) => {
if (part.type === "reasoning" && part.text?.trim().length > 0) {
return {
text: acc.text ? `${acc.text}\n\n${part.text}` : part.text,
isStreaming: "state" in part ? part.state === "streaming" : false,
rendered: false,
};
}
return acc;
},
{ text: "", isStreaming: false, rendered: false }
) ?? { text: "", isStreaming: false, rendered: false };
const parts = message.parts?.map((part, index) => {
const { type } = part;
const key = `message-${message.id}-part-${index}`;
if (type === "reasoning") {
if (!mergedReasoning.rendered && mergedReasoning.text) {
mergedReasoning.rendered = true;
return (
<MessageReasoning
isLoading={isLoading || mergedReasoning.isStreaming}
key={key}
reasoning={mergedReasoning.text}
/>
);
}
return null;
}
if (type === "text") {
return (
<MessageContent
className={cn("text-[13px] leading-[1.65]", {
"w-fit max-w-[min(80%,56ch)] overflow-hidden break-words rounded-2xl rounded-br-lg border border-border/30 bg-gradient-to-br from-secondary to-muted px-3.5 py-2 shadow-[var(--shadow-card)]":
message.role === "user",
})}
data-testid="message-content"
key={key}
>
<MessageResponse>{sanitizeText(part.text)}</MessageResponse>
</MessageContent>
);
}
if (type === "tool-getWeather") {
const { toolCallId, state } = part;
const approvalId = (part as { approval?: { id: string } }).approval?.id;
const isDenied =
state === "output-denied" ||
(state === "approval-responded" &&
(part as { approval?: { approved?: boolean } }).approval?.approved ===
false);
const widthClass = "w-[min(100%,450px)]";
if (state === "output-available") {
return (
<div className={widthClass} key={toolCallId}>
<Weather weatherAtLocation={part.output} />
</div>
);
}
if (isDenied) {
return (
<div className={widthClass} key={toolCallId}>
<Tool className="w-full" defaultOpen={true}>
<ToolHeader state="output-denied" type="tool-getWeather" />
<ToolContent>
<div className="px-4 py-3 text-muted-foreground text-sm">
Weather lookup was denied.
</div>
</ToolContent>
</Tool>
</div>
);
}
if (state === "approval-responded") {
return (
<div className={widthClass} key={toolCallId}>
<Tool className="w-full" defaultOpen={true}>
<ToolHeader state={state} type="tool-getWeather" />
<ToolContent>
<ToolInput input={part.input} />
</ToolContent>
</Tool>
</div>
);
}
return (
<div className={widthClass} key={toolCallId}>
<Tool className="w-full" defaultOpen={true}>
<ToolHeader state={state} type="tool-getWeather" />
<ToolContent>
{(state === "input-available" ||
state === "approval-requested") && (
<ToolInput input={part.input} />
)}
{state === "approval-requested" && approvalId && (
<div className="flex items-center justify-end gap-2 border-t px-4 py-3">
<button
className="rounded-md px-3 py-1.5 text-muted-foreground text-sm transition-colors hover:bg-muted hover:text-foreground"
onClick={() => {
addToolApprovalResponse({
id: approvalId,
approved: false,
reason: "User denied weather lookup",
});
}}
type="button"
>
Deny
</button>
<button
className="rounded-md bg-primary px-3 py-1.5 text-primary-foreground text-sm transition-colors hover:bg-primary/90"
onClick={() => {
addToolApprovalResponse({
id: approvalId,
approved: true,
});
}}
type="button"
>
Allow
</button>
</div>
)}
</ToolContent>
</Tool>
</div>
);
}
return null;
});
const actions = !isReadonly && (
<MessageActions
chatId={chatId}
isLoading={isLoading}
key={`action-${message.id}`}
message={message}
onEdit={onEdit ? () => onEdit(message) : undefined}
vote={vote}
/>
);
const content = isThinking ? (
<div className="flex h-[calc(13px*1.65)] items-center text-[13px] leading-[1.65]">
<Shimmer className="font-medium" duration={1}>
Thinking...
</Shimmer>
</div>
) : (
<>
{attachments}
{parts}
{actions}
</>
);
return (
<div
className={cn(
"group/message w-full",
!isAssistant && "animate-[fade-up_0.25s_cubic-bezier(0.22,1,0.36,1)]"
)}
data-role={message.role}
data-testid={`message-${message.role}`}
>
<div
className={cn(
isUser ? "flex flex-col items-end gap-2" : "flex items-start gap-3"
)}
>
{isAssistant && (
<div className="flex h-[calc(13px*1.65)] shrink-0 items-center">
<div className="flex size-7 items-center justify-center rounded-lg bg-muted/60 text-muted-foreground ring-1 ring-border/50">
<SparklesIcon size={13} />
</div>
</div>
)}
{isAssistant ? (
<div className="flex min-w-0 flex-1 flex-col gap-2">{content}</div>
) : (
content
)}
</div>
</div>
);
};
export const PreviewMessage = PurePreviewMessage;
export const ThinkingMessage = () => {
return (
<div
className="group/message w-full"
data-role="assistant"
data-testid="message-assistant-loading"
>
<div className="flex items-start gap-3">
<div className="flex h-[calc(13px*1.65)] shrink-0 items-center">
<div className="flex size-7 items-center justify-center rounded-lg bg-muted/60 text-muted-foreground ring-1 ring-border/50">
<SparklesIcon size={13} />
</div>
</div>
<div className="flex h-[calc(13px*1.65)] items-center text-[13px] leading-[1.65]">
<Shimmer className="font-medium" duration={1}>
Thinking...
</Shimmer>
</div>
</div>
</div>
);
};

View file

@ -0,0 +1,126 @@
import type { UseChatHelpers } from "@ai-sdk/react";
import { ArrowDownIcon } from "lucide-react";
import { useEffect, useRef } from "react";
import { useMessages } from "@/hooks/use-messages";
import type { Vote } from "@/lib/db/schema";
import type { ChatMessage } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useDataStream } from "./data-stream-provider";
import { Greeting } from "./greeting";
import { PreviewMessage, ThinkingMessage } from "./message";
type MessagesProps = {
addToolApprovalResponse: UseChatHelpers<ChatMessage>["addToolApprovalResponse"];
chatId: string;
status: UseChatHelpers<ChatMessage>["status"];
votes: Vote[] | undefined;
messages: ChatMessage[];
setMessages: UseChatHelpers<ChatMessage>["setMessages"];
regenerate: UseChatHelpers<ChatMessage>["regenerate"];
isReadonly: boolean;
isLoading?: boolean;
selectedModelId: string;
onEditMessage?: (message: ChatMessage) => void;
};
function PureMessages({
addToolApprovalResponse,
chatId,
status,
votes,
messages,
setMessages,
regenerate,
isReadonly,
isLoading,
selectedModelId: _selectedModelId,
onEditMessage,
}: MessagesProps) {
const {
containerRef: messagesContainerRef,
endRef: messagesEndRef,
isAtBottom,
scrollToBottom,
hasSentMessage,
reset,
} = useMessages({
status,
});
useDataStream();
const prevChatIdRef = useRef(chatId);
useEffect(() => {
if (prevChatIdRef.current !== chatId) {
prevChatIdRef.current = chatId;
reset();
}
}, [chatId, reset]);
return (
<div className="relative flex-1 bg-background">
{messages.length === 0 && !isLoading && (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center">
<Greeting />
</div>
)}
<div
className={cn(
"absolute inset-0 touch-pan-y overflow-y-auto",
messages.length > 0 ? "bg-background" : "bg-transparent"
)}
ref={messagesContainerRef}
>
<div className="mx-auto flex min-h-full min-w-0 max-w-4xl flex-col gap-5 px-2 py-6 md:gap-7 md:px-4">
{messages.map((message, index) => (
<PreviewMessage
addToolApprovalResponse={addToolApprovalResponse}
chatId={chatId}
isLoading={
status === "streaming" && messages.length - 1 === index
}
isReadonly={isReadonly}
key={message.id}
message={message}
onEdit={onEditMessage}
regenerate={regenerate}
requiresScrollPadding={
hasSentMessage && index === messages.length - 1
}
setMessages={setMessages}
vote={
votes
? votes.find((vote) => vote.messageId === message.id)
: undefined
}
/>
))}
{status === "submitted" && messages.at(-1)?.role !== "assistant" && (
<ThinkingMessage />
)}
<div
className="min-h-[24px] min-w-[24px] shrink-0"
ref={messagesEndRef}
/>
</div>
</div>
<button
aria-label="Scroll to bottom"
className={`absolute bottom-4 left-1/2 z-10 flex -translate-x-1/2 items-center rounded-full border border-border/50 bg-card/90 px-3.5 shadow-[var(--shadow-float)] backdrop-blur-lg transition-all duration-200 h-7 text-[10px] ${
isAtBottom
? "pointer-events-none scale-90 opacity-0"
: "pointer-events-auto scale-100 opacity-100"
}`}
onClick={() => scrollToBottom("smooth")}
type="button"
>
<ArrowDownIcon className="size-3 text-muted-foreground" />
</button>
</div>
);
}
export const Messages = PureMessages;

View file

@ -0,0 +1,816 @@
"use client";
import type { UseChatHelpers } from "@ai-sdk/react";
import type { UIMessage } from "ai";
import equal from "fast-deep-equal";
import {
ArrowUpIcon,
BrainIcon,
EyeIcon,
LockIcon,
WrenchIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import {
type ChangeEvent,
type Dispatch,
memo,
type SetStateAction,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { toast } from "sonner";
import useSWR from "swr";
import { useLocalStorage, useWindowSize } from "usehooks-ts";
import {
ModelSelector,
ModelSelectorContent,
ModelSelectorGroup,
ModelSelectorInput,
ModelSelectorItem,
ModelSelectorList,
ModelSelectorLogo,
ModelSelectorName,
ModelSelectorTrigger,
} from "@/components/ai-elements/model-selector";
import {
type ChatModel,
chatModels,
DEFAULT_CHAT_MODEL,
type ModelCapabilities,
} from "@/lib/ai/models";
import type { Attachment, ChatMessage } from "@/lib/types";
import { cn } from "@/lib/utils";
import {
PromptInput,
PromptInputFooter,
PromptInputSubmit,
PromptInputTextarea,
PromptInputTools,
} from "../ai-elements/prompt-input";
import { Button } from "../ui/button";
import { PaperclipIcon, StopIcon } from "./icons";
import { PreviewAttachment } from "./preview-attachment";
import {
type SlashCommand,
SlashCommandMenu,
slashCommands,
} from "./slash-commands";
import { SuggestedActions } from "./suggested-actions";
import type { VisibilityType } from "./visibility-selector";
function setCookie(name: string, value: string) {
const maxAge = 60 * 60 * 24 * 365;
// biome-ignore lint/suspicious/noDocumentCookie: needed for client-side cookie setting
document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}`;
}
function PureMultimodalInput({
chatId,
input,
setInput,
status,
stop,
attachments,
setAttachments,
messages,
setMessages,
sendMessage,
className,
selectedVisibilityType,
selectedModelId,
onModelChange,
editingMessage,
onCancelEdit,
isLoading,
}: {
chatId: string;
input: string;
setInput: Dispatch<SetStateAction<string>>;
status: UseChatHelpers<ChatMessage>["status"];
stop: () => void;
attachments: Attachment[];
setAttachments: Dispatch<SetStateAction<Attachment[]>>;
messages: UIMessage[];
setMessages: UseChatHelpers<ChatMessage>["setMessages"];
sendMessage:
| UseChatHelpers<ChatMessage>["sendMessage"]
| (() => Promise<void>);
className?: string;
selectedVisibilityType: VisibilityType;
selectedModelId: string;
onModelChange?: (modelId: string) => void;
editingMessage?: ChatMessage | null;
onCancelEdit?: () => void;
isLoading?: boolean;
}) {
const router = useRouter();
const { setTheme, resolvedTheme } = useTheme();
const textareaRef = useRef<HTMLTextAreaElement>(null);
const { width } = useWindowSize();
const hasAutoFocused = useRef(false);
useEffect(() => {
if (!hasAutoFocused.current && width) {
const timer = setTimeout(() => {
textareaRef.current?.focus();
hasAutoFocused.current = true;
}, 100);
return () => clearTimeout(timer);
}
}, [width]);
const [localStorageInput, setLocalStorageInput] = useLocalStorage(
"input",
""
);
useEffect(() => {
if (textareaRef.current) {
const domValue = textareaRef.current.value;
const finalValue = domValue || localStorageInput || "";
setInput(finalValue);
}
}, [localStorageInput, setInput]);
useEffect(() => {
setLocalStorageInput(input);
}, [input, setLocalStorageInput]);
const handleInput = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
const val = event.target.value;
setInput(val);
if (val.startsWith("/") && !val.includes(" ")) {
setSlashOpen(true);
setSlashQuery(val.slice(1));
setSlashIndex(0);
} else {
setSlashOpen(false);
}
};
const handleSlashSelect = (cmd: SlashCommand) => {
setSlashOpen(false);
setInput("");
switch (cmd.action) {
case "new":
router.push("/");
break;
case "clear":
setMessages(() => []);
break;
case "rename":
toast("Rename is available from the sidebar chat menu.");
break;
case "model": {
const modelBtn = document.querySelector<HTMLButtonElement>(
"[data-testid='model-selector']"
);
modelBtn?.click();
break;
}
case "theme":
setTheme(resolvedTheme === "dark" ? "light" : "dark");
break;
case "delete":
toast("Delete this chat?", {
action: {
label: "Delete",
onClick: () => {
fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chat?id=${chatId}`,
{ method: "DELETE" }
);
router.push("/");
toast.success("Chat deleted");
},
},
});
break;
case "purge":
toast("Delete all chats?", {
action: {
label: "Delete all",
onClick: () => {
fetch(`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/history`, {
method: "DELETE",
});
router.push("/");
toast.success("All chats deleted");
},
},
});
break;
default:
break;
}
};
const fileInputRef = useRef<HTMLInputElement>(null);
const [uploadQueue, setUploadQueue] = useState<string[]>([]);
const [slashOpen, setSlashOpen] = useState(false);
const [slashQuery, setSlashQuery] = useState("");
const [slashIndex, setSlashIndex] = useState(0);
const submitForm = useCallback(() => {
window.history.pushState(
{},
"",
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/chat/${chatId}`
);
sendMessage({
role: "user",
parts: [
...attachments.map((attachment) => ({
type: "file" as const,
url: attachment.url,
name: attachment.name,
mediaType: attachment.contentType,
})),
{
type: "text",
text: input,
},
],
});
setAttachments([]);
setLocalStorageInput("");
setInput("");
if (width && width > 768) {
textareaRef.current?.focus();
}
}, [
input,
setInput,
attachments,
sendMessage,
setAttachments,
setLocalStorageInput,
width,
chatId,
]);
const uploadFile = useCallback(async (file: File) => {
const formData = new FormData();
formData.append("file", file);
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/files/upload`,
{
method: "POST",
body: formData,
}
);
if (response.ok) {
const data = await response.json();
const { url, pathname, contentType } = data;
return {
url,
name: pathname,
contentType,
};
}
const { error } = await response.json();
toast.error(error);
} catch (_error) {
toast.error("Failed to upload file, please try again!");
}
}, []);
const handleFileChange = useCallback(
async (event: ChangeEvent<HTMLInputElement>) => {
const files = Array.from(event.target.files || []);
setUploadQueue(files.map((file) => file.name));
try {
const uploadPromises = files.map((file) => uploadFile(file));
const uploadedAttachments = await Promise.all(uploadPromises);
const successfullyUploadedAttachments = uploadedAttachments.filter(
(attachment) => attachment !== undefined
);
setAttachments((currentAttachments) => [
...currentAttachments,
...successfullyUploadedAttachments,
]);
} catch (_error) {
toast.error("Failed to upload files");
} finally {
setUploadQueue([]);
}
},
[setAttachments, uploadFile]
);
const handlePaste = useCallback(
async (event: ClipboardEvent) => {
const items = event.clipboardData?.items;
if (!items) {
return;
}
const imageItems = Array.from(items).filter((item) =>
item.type.startsWith("image/")
);
if (imageItems.length === 0) {
return;
}
event.preventDefault();
setUploadQueue((prev) => [...prev, "Pasted image"]);
try {
const uploadPromises = imageItems
.map((item) => item.getAsFile())
.filter((file): file is File => file !== null)
.map((file) => uploadFile(file));
const uploadedAttachments = await Promise.all(uploadPromises);
const successfullyUploadedAttachments = uploadedAttachments.filter(
(attachment) =>
attachment !== undefined &&
attachment.url !== undefined &&
attachment.contentType !== undefined
);
setAttachments((curr) => [
...curr,
...(successfullyUploadedAttachments as Attachment[]),
]);
} catch (_error) {
toast.error("Failed to upload pasted image(s)");
} finally {
setUploadQueue([]);
}
},
[setAttachments, uploadFile]
);
useEffect(() => {
const textarea = textareaRef.current;
if (!textarea) {
return;
}
textarea.addEventListener("paste", handlePaste);
return () => textarea.removeEventListener("paste", handlePaste);
}, [handlePaste]);
return (
<div className={cn("relative flex w-full flex-col gap-4", className)}>
{editingMessage && onCancelEdit && (
<div className="flex items-center gap-2 text-[12px] text-muted-foreground">
<span>Editing message</span>
<button
className="rounded px-1.5 py-0.5 text-muted-foreground/50 transition-colors hover:bg-muted hover:text-foreground"
onMouseDown={(e) => {
e.preventDefault();
onCancelEdit();
}}
type="button"
>
Cancel
</button>
</div>
)}
{!editingMessage &&
!isLoading &&
messages.length === 0 &&
attachments.length === 0 &&
uploadQueue.length === 0 && (
<SuggestedActions
chatId={chatId}
selectedVisibilityType={selectedVisibilityType}
sendMessage={sendMessage}
/>
)}
<input
className="pointer-events-none fixed -top-4 -left-4 size-0.5 opacity-0"
multiple
onChange={handleFileChange}
ref={fileInputRef}
tabIndex={-1}
type="file"
/>
<div className="relative">
{slashOpen && (
<SlashCommandMenu
onClose={() => setSlashOpen(false)}
onSelect={handleSlashSelect}
query={slashQuery}
selectedIndex={slashIndex}
/>
)}
</div>
<PromptInput
className="[&>div]:rounded-2xl [&>div]:border [&>div]:border-border/30 [&>div]:bg-card/70 [&>div]:shadow-[var(--shadow-composer)] [&>div]:transition-shadow [&>div]:duration-300 [&>div]:focus-within:shadow-[var(--shadow-composer-focus)]"
onSubmit={() => {
if (input.startsWith("/")) {
const query = input.slice(1).trim();
const cmd = slashCommands.find((c) => c.name === query);
if (cmd) {
handleSlashSelect(cmd);
}
return;
}
if (!input.trim() && attachments.length === 0) {
return;
}
if (status === "ready" || status === "error") {
submitForm();
} else {
toast.error("Please wait for the model to finish its response!");
}
}}
>
{(attachments.length > 0 || uploadQueue.length > 0) && (
<div
className="flex w-full self-start flex-row gap-2 overflow-x-auto px-3 pt-3 no-scrollbar"
data-testid="attachments-preview"
>
{attachments.map((attachment) => (
<PreviewAttachment
attachment={attachment}
key={attachment.url}
onRemove={() => {
setAttachments((currentAttachments) =>
currentAttachments.filter((a) => a.url !== attachment.url)
);
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
}}
/>
))}
{uploadQueue.map((filename) => (
<PreviewAttachment
attachment={{
url: "",
name: filename,
contentType: "",
}}
isUploading={true}
key={filename}
/>
))}
</div>
)}
<PromptInputTextarea
className="min-h-24 text-[13px] leading-relaxed px-4 pt-3.5 pb-1.5 placeholder:text-muted-foreground/35"
data-testid="multimodal-input"
onChange={handleInput}
onKeyDown={(e) => {
if (slashOpen) {
const filtered = slashCommands.filter((cmd) =>
cmd.name.startsWith(slashQuery.toLowerCase())
);
if (e.key === "ArrowDown") {
e.preventDefault();
setSlashIndex((i) => Math.min(i + 1, filtered.length - 1));
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setSlashIndex((i) => Math.max(i - 1, 0));
return;
}
if (e.key === "Enter" || e.key === "Tab") {
e.preventDefault();
if (filtered[slashIndex]) {
handleSlashSelect(filtered[slashIndex]);
}
return;
}
if (e.key === "Escape") {
e.preventDefault();
setSlashOpen(false);
return;
}
}
if (e.key === "Escape" && editingMessage && onCancelEdit) {
e.preventDefault();
onCancelEdit();
}
}}
placeholder={
editingMessage ? "Edit your message..." : "Ask anything..."
}
ref={textareaRef}
value={input}
/>
<PromptInputFooter className="px-3 pb-3">
<PromptInputTools>
<AttachmentsButton
fileInputRef={fileInputRef}
selectedModelId={selectedModelId}
status={status}
/>
<ModelSelectorCompact
onModelChange={onModelChange}
selectedModelId={selectedModelId}
/>
</PromptInputTools>
{status === "submitted" ? (
<StopButton setMessages={setMessages} stop={stop} />
) : (
<PromptInputSubmit
className={cn(
"h-7 w-7 rounded-xl transition-all duration-200",
input.trim()
? "bg-foreground text-background hover:opacity-85 active:scale-95"
: "bg-muted text-muted-foreground/25 cursor-not-allowed"
)}
data-testid="send-button"
disabled={!input.trim() || uploadQueue.length > 0}
status={status}
variant="secondary"
>
<ArrowUpIcon className="size-4" />
</PromptInputSubmit>
)}
</PromptInputFooter>
</PromptInput>
</div>
);
}
export const MultimodalInput = memo(
PureMultimodalInput,
(prevProps, nextProps) => {
if (prevProps.input !== nextProps.input) {
return false;
}
if (prevProps.status !== nextProps.status) {
return false;
}
if (!equal(prevProps.attachments, nextProps.attachments)) {
return false;
}
if (prevProps.selectedVisibilityType !== nextProps.selectedVisibilityType) {
return false;
}
if (prevProps.selectedModelId !== nextProps.selectedModelId) {
return false;
}
if (prevProps.editingMessage !== nextProps.editingMessage) {
return false;
}
if (prevProps.isLoading !== nextProps.isLoading) {
return false;
}
if (prevProps.messages.length !== nextProps.messages.length) {
return false;
}
return true;
}
);
function PureAttachmentsButton({
fileInputRef,
status,
selectedModelId,
}: {
fileInputRef: React.MutableRefObject<HTMLInputElement | null>;
status: UseChatHelpers<ChatMessage>["status"];
selectedModelId: string;
}) {
const { data: modelsResponse } = useSWR(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/models`,
(url: string) => fetch(url).then((r) => r.json()),
{ revalidateOnFocus: false, dedupingInterval: 3_600_000 }
);
const caps: Record<string, ModelCapabilities> | undefined =
modelsResponse?.capabilities ?? modelsResponse;
const hasVision = caps?.[selectedModelId]?.vision ?? false;
return (
<Button
className={cn(
"h-7 w-7 rounded-lg border border-border/40 p-1 transition-colors",
hasVision
? "text-foreground hover:border-border hover:text-foreground"
: "text-muted-foreground/30 cursor-not-allowed"
)}
data-testid="attachments-button"
disabled={status !== "ready" || !hasVision}
onClick={(event) => {
event.preventDefault();
fileInputRef.current?.click();
}}
variant="ghost"
>
<PaperclipIcon size={14} style={{ width: 14, height: 14 }} />
</Button>
);
}
const AttachmentsButton = memo(PureAttachmentsButton);
function PureModelSelectorCompact({
selectedModelId,
onModelChange,
}: {
selectedModelId: string;
onModelChange?: (modelId: string) => void;
}) {
const [open, setOpen] = useState(false);
const { data: modelsData } = useSWR(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/models`,
(url: string) => fetch(url).then((r) => r.json()),
{ revalidateOnFocus: false, dedupingInterval: 3_600_000 }
);
const capabilities: Record<string, ModelCapabilities> | undefined =
modelsData?.capabilities ?? modelsData;
const dynamicModels: ChatModel[] | undefined = modelsData?.models;
const activeModels = dynamicModels ?? chatModels;
const selectedModel =
activeModels.find((m: ChatModel) => m.id === selectedModelId) ??
activeModels.find((m: ChatModel) => m.id === DEFAULT_CHAT_MODEL) ??
activeModels[0];
const [provider] = selectedModel.id.split("/");
return (
<ModelSelector onOpenChange={setOpen} open={open}>
<ModelSelectorTrigger asChild>
<Button
className="h-7 max-w-[200px] justify-between gap-1.5 rounded-lg px-2 text-[12px] text-muted-foreground transition-colors hover:text-foreground"
data-testid="model-selector"
variant="ghost"
>
{provider && <ModelSelectorLogo provider={provider} />}
<ModelSelectorName>{selectedModel.name}</ModelSelectorName>
</Button>
</ModelSelectorTrigger>
<ModelSelectorContent>
<ModelSelectorInput placeholder="Search models..." />
<ModelSelectorList>
{(() => {
const curatedIds = new Set(chatModels.map((m) => m.id));
const allModels = dynamicModels
? [
...chatModels,
...dynamicModels.filter((m) => !curatedIds.has(m.id)),
]
: chatModels;
const grouped: Record<
string,
{ model: ChatModel; curated: boolean }[]
> = {};
for (const model of allModels) {
const key = curatedIds.has(model.id)
? "_available"
: model.provider;
if (!grouped[key]) {
grouped[key] = [];
}
grouped[key].push({ model, curated: curatedIds.has(model.id) });
}
const sortedKeys = Object.keys(grouped).sort((a, b) => {
if (a === "_available") {
return -1;
}
if (b === "_available") {
return 1;
}
return a.localeCompare(b);
});
const providerNames: Record<string, string> = {
alibaba: "Alibaba",
anthropic: "Anthropic",
"arcee-ai": "Arcee AI",
bytedance: "ByteDance",
cohere: "Cohere",
deepseek: "DeepSeek",
google: "Google",
inception: "Inception",
kwaipilot: "Kwaipilot",
meituan: "Meituan",
meta: "Meta",
minimax: "MiniMax",
mistral: "Mistral",
moonshotai: "Moonshot",
morph: "Morph",
nvidia: "Nvidia",
openai: "OpenAI",
perplexity: "Perplexity",
"prime-intellect": "Prime Intellect",
xiaomi: "Xiaomi",
xai: "xAI",
zai: "Zai",
};
return sortedKeys.map((key) => (
<ModelSelectorGroup
heading={
key === "_available"
? "Available"
: (providerNames[key] ?? key)
}
key={key}
>
{grouped[key].map(({ model, curated }) => {
const logoProvider = model.id.split("/")[0];
return (
<ModelSelectorItem
className={cn(
"flex w-full",
model.id === selectedModel.id &&
"border-b border-dashed border-foreground/50",
!curated && "opacity-40 cursor-default"
)}
key={model.id}
onSelect={() => {
if (!curated) {
return;
}
onModelChange?.(model.id);
setCookie("chat-model", model.id);
setOpen(false);
setTimeout(() => {
document
.querySelector<HTMLTextAreaElement>(
"[data-testid='multimodal-input']"
)
?.focus();
}, 50);
}}
value={model.id}
>
<ModelSelectorLogo provider={logoProvider} />
<ModelSelectorName>{model.name}</ModelSelectorName>
<div className="ml-auto flex items-center gap-2 text-foreground/70">
{capabilities?.[model.id]?.tools && (
<WrenchIcon className="size-3.5" />
)}
{capabilities?.[model.id]?.vision && (
<EyeIcon className="size-3.5" />
)}
{capabilities?.[model.id]?.reasoning && (
<BrainIcon className="size-3.5" />
)}
{!curated && (
<LockIcon className="size-3 text-muted-foreground/50" />
)}
</div>
</ModelSelectorItem>
);
})}
</ModelSelectorGroup>
));
})()}
</ModelSelectorList>
</ModelSelectorContent>
</ModelSelector>
);
}
const ModelSelectorCompact = memo(PureModelSelectorCompact);
function PureStopButton({
stop,
setMessages,
}: {
stop: () => void;
setMessages: UseChatHelpers<ChatMessage>["setMessages"];
}) {
return (
<Button
className="h-7 w-7 rounded-xl bg-foreground p-1 text-background transition-all duration-200 hover:opacity-85 active:scale-95 disabled:bg-muted disabled:text-muted-foreground/25 disabled:cursor-not-allowed"
data-testid="stop-button"
onClick={(event) => {
event.preventDefault();
stop();
setMessages((messages) => messages);
}}
>
<StopIcon size={14} />
</Button>
);
}
const StopButton = memo(PureStopButton);

View file

@ -0,0 +1,54 @@
import type { Attachment } from "@/lib/types";
import { Spinner } from "../ui/spinner";
import { CrossSmallIcon } from "./icons";
export const PreviewAttachment = ({
attachment,
isUploading = false,
onRemove,
}: {
attachment: Attachment;
isUploading?: boolean;
onRemove?: () => void;
}) => {
const { name, url, contentType } = attachment;
return (
<div
className="group relative h-24 w-24 shrink-0 overflow-hidden rounded-xl border border-border/40 bg-muted"
data-testid="input-attachment-preview"
>
{contentType?.startsWith("image") ? (
// eslint-disable-next-line @next/next/no-img-element
<img
alt={name ?? "attachment"}
className="size-full object-cover"
src={url}
/>
) : (
<div className="flex size-full items-center justify-center text-muted-foreground text-xs">
File
</div>
)}
{isUploading && (
<div
className="absolute inset-0 flex items-center justify-center rounded-xl bg-black/40 backdrop-blur-sm"
data-testid="input-attachment-loader"
>
<Spinner className="size-5" />
</div>
)}
{onRemove && !isUploading && (
<button
className="absolute top-1.5 right-1.5 flex size-5 items-center justify-center rounded-full bg-black/60 text-white opacity-0 backdrop-blur-sm transition-opacity hover:bg-black/80 group-hover:opacity-100"
onClick={onRemove}
type="button"
>
<CrossSmallIcon size={10} />
</button>
)}
</div>
);
};

View file

@ -0,0 +1,59 @@
"use client";
import { useRouter } from "next/navigation";
import { suggestions } from "@/lib/constants";
import { SparklesIcon } from "./icons";
export function Preview() {
const router = useRouter();
const handleAction = (query?: string) => {
const url = query ? `/?query=${encodeURIComponent(query)}` : "/";
router.push(url);
};
return (
<div className="flex h-full flex-col overflow-hidden rounded-tl-2xl bg-background">
<div className="flex h-14 shrink-0 items-center gap-3 border-b border-border/20 px-5">
<div className="flex size-5 items-center justify-center rounded bg-muted/60 ring-1 ring-border/50">
<SparklesIcon size={10} />
</div>
<span className="text-[13px] text-muted-foreground">Chatbot</span>
</div>
<div className="flex flex-1 flex-col items-center justify-center gap-8 px-8">
<div className="text-center">
<h2 className="text-xl font-semibold tracking-tight">
What can I help with?
</h2>
<p className="mt-1.5 text-sm text-muted-foreground">
Ask a question, write code, or explore ideas.
</p>
</div>
<div className="grid w-full max-w-md grid-cols-2 gap-2">
{suggestions.map((suggestion) => (
<button
className="rounded-xl border border-border/30 bg-card/20 px-3 py-2.5 text-left text-[11px] leading-relaxed text-muted-foreground/70 transition-all duration-200 hover:border-border/60 hover:bg-card/40 hover:text-muted-foreground"
key={suggestion}
onClick={() => handleAction(suggestion)}
type="button"
>
{suggestion}
</button>
))}
</div>
</div>
<div className="shrink-0 px-5 pb-5">
<button
className="flex w-full items-center rounded-2xl border border-border/30 bg-card/30 px-4 py-3 text-left text-[13px] text-muted-foreground/40 transition-colors hover:border-border/50 hover:text-muted-foreground/60"
onClick={() => handleAction()}
type="button"
>
Ask anything...
</button>
</div>
</div>
);
}

128
components/chat/shell.tsx Normal file
View file

@ -0,0 +1,128 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useActiveChat } from "@/hooks/use-active-chat";
import type { Attachment, ChatMessage } from "@/lib/types";
import { ChatHeader } from "./chat-header";
import { DataStreamHandler } from "./data-stream-handler";
import { submitEditedMessage } from "./message-editor";
import { Messages } from "./messages";
import { MultimodalInput } from "./multimodal-input";
export function ChatShell() {
const {
chatId,
messages,
setMessages,
sendMessage,
status,
stop,
regenerate,
addToolApprovalResponse,
input,
setInput,
visibilityType,
isReadonly,
isLoading,
votes,
currentModelId,
setCurrentModelId,
} = useActiveChat();
const [editingMessage, setEditingMessage] = useState<ChatMessage | null>(
null
);
const [attachments, setAttachments] = useState<Attachment[]>([]);
const stopRef = useRef(stop);
stopRef.current = stop;
const prevChatIdRef = useRef(chatId);
useEffect(() => {
if (prevChatIdRef.current !== chatId) {
prevChatIdRef.current = chatId;
stopRef.current();
setEditingMessage(null);
setAttachments([]);
}
}, [chatId]);
return (
<>
<div className="flex h-dvh w-full flex-row overflow-hidden">
<div className="flex min-w-0 flex-col bg-sidebar w-full">
<ChatHeader
chatId={chatId}
isReadonly={isReadonly}
selectedVisibilityType={visibilityType}
/>
<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden bg-background md:rounded-tl-[12px] md:border-t md:border-l md:border-border/40">
<Messages
addToolApprovalResponse={addToolApprovalResponse}
chatId={chatId}
isLoading={isLoading}
isReadonly={isReadonly}
messages={messages}
onEditMessage={(msg) => {
const text = msg.parts
?.filter((p) => p.type === "text")
.map((p) => p.text)
.join("");
setInput(text ?? "");
setEditingMessage(msg);
}}
regenerate={regenerate}
selectedModelId={currentModelId}
setMessages={setMessages}
status={status}
votes={votes}
/>
<div className="sticky bottom-0 z-1 mx-auto flex w-full max-w-4xl gap-2 border-t-0 bg-background px-2 pb-3 md:px-4 md:pb-4">
{!isReadonly && (
<MultimodalInput
attachments={attachments}
chatId={chatId}
editingMessage={editingMessage}
input={input}
isLoading={isLoading}
messages={messages}
onCancelEdit={() => {
setEditingMessage(null);
setInput("");
}}
onModelChange={setCurrentModelId}
selectedModelId={currentModelId}
selectedVisibilityType={visibilityType}
sendMessage={
editingMessage
? async () => {
const msg = editingMessage;
setEditingMessage(null);
await submitEditedMessage({
message: msg,
text: input,
setMessages,
regenerate,
});
setInput("");
}
: sendMessage
}
setAttachments={setAttachments}
setInput={setInput}
setMessages={setMessages}
status={status}
stop={stop}
/>
)}
</div>
</div>
</div>
</div>
<DataStreamHandler />
</>
);
}

View file

@ -0,0 +1,124 @@
import Link from "next/link";
import { memo } from "react";
import { useChatVisibility } from "@/hooks/use-chat-visibility";
import type { Chat } from "@/lib/db/schema";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import {
SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
} from "../ui/sidebar";
import {
CheckCircleFillIcon,
GlobeIcon,
LockIcon,
MoreHorizontalIcon,
ShareIcon,
TrashIcon,
} from "./icons";
const PureChatItem = ({
chat,
isActive,
onDelete,
setOpenMobile,
}: {
chat: Chat;
isActive: boolean;
onDelete: (chatId: string) => void;
setOpenMobile: (open: boolean) => void;
}) => {
const { visibilityType, setVisibilityType } = useChatVisibility({
chatId: chat.id,
initialVisibilityType: chat.visibility,
});
return (
<SidebarMenuItem>
<SidebarMenuButton
asChild
className="h-8 rounded-none text-[13px] text-sidebar-foreground/50 transition-all duration-150 hover:bg-transparent hover:text-sidebar-foreground data-active:bg-transparent data-active:font-normal data-active:text-sidebar-foreground/50 data-[active=true]:text-sidebar-foreground data-[active=true]:font-medium data-[active=true]:border-b data-[active=true]:border-dashed data-[active=true]:border-sidebar-foreground/50"
isActive={isActive}
>
<Link href={`/chat/${chat.id}`} onClick={() => setOpenMobile(false)}>
<span className="truncate">{chat.title}</span>
</Link>
</SidebarMenuButton>
<DropdownMenu modal={true}>
<DropdownMenuTrigger asChild>
<SidebarMenuAction
className="mr-0.5 rounded-md text-sidebar-foreground/50 ring-0 transition-colors duration-150 focus-visible:ring-0 hover:text-sidebar-foreground data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
showOnHover={!isActive}
>
<MoreHorizontalIcon />
<span className="sr-only">More</span>
</SidebarMenuAction>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" side="bottom">
<DropdownMenuSub>
<DropdownMenuSubTrigger className="cursor-pointer">
<ShareIcon />
<span>Share</span>
</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent>
<DropdownMenuItem
className="cursor-pointer flex-row justify-between"
onClick={() => {
setVisibilityType("private");
}}
>
<div className="flex flex-row items-center gap-2">
<LockIcon size={12} />
<span>Private</span>
</div>
{visibilityType === "private" ? (
<CheckCircleFillIcon />
) : null}
</DropdownMenuItem>
<DropdownMenuItem
className="cursor-pointer flex-row justify-between"
onClick={() => {
setVisibilityType("public");
}}
>
<div className="flex flex-row items-center gap-2">
<GlobeIcon />
<span>Public</span>
</div>
{visibilityType === "public" ? <CheckCircleFillIcon /> : null}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
<DropdownMenuItem
onSelect={() => onDelete(chat.id)}
variant="destructive"
>
<TrashIcon />
<span>Delete</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
);
};
export const ChatItem = memo(PureChatItem, (prevProps, nextProps) => {
if (prevProps.isActive !== nextProps.isActive) {
return false;
}
return true;
});

View file

@ -0,0 +1,373 @@
"use client";
import { isToday, isYesterday, subMonths, subWeeks } from "date-fns";
import { motion } from "framer-motion";
import { usePathname, useRouter } from "next/navigation";
import type { User } from "next-auth";
import { useState } from "react";
import { toast } from "sonner";
import useSWRInfinite from "swr/infinite";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarMenu,
useSidebar,
} from "@/components/ui/sidebar";
import type { Chat } from "@/lib/db/schema";
import { fetcher } from "@/lib/utils";
import { LoaderIcon } from "./icons";
import { ChatItem } from "./sidebar-history-item";
type GroupedChats = {
today: Chat[];
yesterday: Chat[];
lastWeek: Chat[];
lastMonth: Chat[];
older: Chat[];
};
export type ChatHistory = {
chats: Chat[];
hasMore: boolean;
};
const PAGE_SIZE = 20;
const groupChatsByDate = (chats: Chat[]): GroupedChats => {
const now = new Date();
const oneWeekAgo = subWeeks(now, 1);
const oneMonthAgo = subMonths(now, 1);
return chats.reduce(
(groups, chat) => {
const chatDate = new Date(chat.createdAt);
if (isToday(chatDate)) {
groups.today.push(chat);
} else if (isYesterday(chatDate)) {
groups.yesterday.push(chat);
} else if (chatDate > oneWeekAgo) {
groups.lastWeek.push(chat);
} else if (chatDate > oneMonthAgo) {
groups.lastMonth.push(chat);
} else {
groups.older.push(chat);
}
return groups;
},
{
today: [],
yesterday: [],
lastWeek: [],
lastMonth: [],
older: [],
} as GroupedChats
);
};
export function getChatHistoryPaginationKey(
pageIndex: number,
previousPageData: ChatHistory
) {
if (previousPageData && previousPageData.hasMore === false) {
return null;
}
if (pageIndex === 0) {
return `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/history?limit=${PAGE_SIZE}`;
}
const firstChatFromPage = previousPageData.chats.at(-1);
if (!firstChatFromPage) {
return null;
}
return `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/history?ending_before=${firstChatFromPage.id}&limit=${PAGE_SIZE}`;
}
export function SidebarHistory({ user }: { user: User | undefined }) {
const { setOpenMobile } = useSidebar();
const pathname = usePathname();
const id = pathname?.startsWith("/chat/") ? pathname.split("/")[2] : null;
const {
data: paginatedChatHistories,
setSize,
isValidating,
isLoading,
mutate,
} = useSWRInfinite<ChatHistory>(
user ? getChatHistoryPaginationKey : () => null,
fetcher,
{ fallbackData: [], revalidateOnFocus: false }
);
const router = useRouter();
const [deleteId, setDeleteId] = useState<string | null>(null);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const hasReachedEnd = paginatedChatHistories
? paginatedChatHistories.some((page) => page.hasMore === false)
: false;
const hasEmptyChatHistory = paginatedChatHistories
? paginatedChatHistories.every((page) => page.chats.length === 0)
: false;
const handleDelete = () => {
const chatToDelete = deleteId;
const isCurrentChat = pathname === `/chat/${chatToDelete}`;
setShowDeleteDialog(false);
if (isCurrentChat) {
router.replace("/");
}
mutate((chatHistories) => {
if (chatHistories) {
return chatHistories.map((chatHistory) => ({
...chatHistory,
chats: chatHistory.chats.filter((chat) => chat.id !== chatToDelete),
}));
}
});
fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chat?id=${chatToDelete}`,
{ method: "DELETE" }
);
toast.success("Chat deleted");
};
if (!user) {
return (
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
<SidebarGroupContent>
<div className="flex w-full flex-row items-center justify-center gap-2 px-2 text-[13px] text-sidebar-foreground/60">
Login to save and revisit previous chats!
</div>
</SidebarGroupContent>
</SidebarGroup>
);
}
if (isLoading) {
return (
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
<SidebarGroupLabel className="text-[10px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/70">
History
</SidebarGroupLabel>
<SidebarGroupContent>
<div className="flex flex-col gap-0.5 px-1">
{[44, 32, 28, 64, 52].map((item) => (
<div
className="flex h-8 items-center gap-2 rounded-lg px-2"
key={item}
>
<div
className="h-3 max-w-(--skeleton-width) flex-1 animate-pulse rounded-md bg-sidebar-foreground/[0.06]"
style={
{
"--skeleton-width": `${item}%`,
} as React.CSSProperties
}
/>
</div>
))}
</div>
</SidebarGroupContent>
</SidebarGroup>
);
}
if (hasEmptyChatHistory) {
return (
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
<SidebarGroupLabel className="text-[10px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/70">
History
</SidebarGroupLabel>
<SidebarGroupContent>
<div className="flex w-full flex-row items-center justify-center gap-2 px-2 text-[13px] text-sidebar-foreground/60">
Your conversations will appear here once you start chatting!
</div>
</SidebarGroupContent>
</SidebarGroup>
);
}
return (
<>
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
<SidebarGroupLabel className="text-[10px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/70">
History
</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{paginatedChatHistories &&
(() => {
const chatsFromHistory = paginatedChatHistories.flatMap(
(paginatedChatHistory) => paginatedChatHistory.chats
);
const groupedChats = groupChatsByDate(chatsFromHistory);
return (
<div className="flex flex-col gap-4">
{groupedChats.today.length > 0 && (
<div>
<div className="px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/70">
Today
</div>
{groupedChats.today.map((chat) => (
<ChatItem
chat={chat}
isActive={chat.id === id}
key={chat.id}
onDelete={(chatId) => {
setDeleteId(chatId);
setShowDeleteDialog(true);
}}
setOpenMobile={setOpenMobile}
/>
))}
</div>
)}
{groupedChats.yesterday.length > 0 && (
<div>
<div className="px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/70">
Yesterday
</div>
{groupedChats.yesterday.map((chat) => (
<ChatItem
chat={chat}
isActive={chat.id === id}
key={chat.id}
onDelete={(chatId) => {
setDeleteId(chatId);
setShowDeleteDialog(true);
}}
setOpenMobile={setOpenMobile}
/>
))}
</div>
)}
{groupedChats.lastWeek.length > 0 && (
<div>
<div className="px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/70">
Last 7 days
</div>
{groupedChats.lastWeek.map((chat) => (
<ChatItem
chat={chat}
isActive={chat.id === id}
key={chat.id}
onDelete={(chatId) => {
setDeleteId(chatId);
setShowDeleteDialog(true);
}}
setOpenMobile={setOpenMobile}
/>
))}
</div>
)}
{groupedChats.lastMonth.length > 0 && (
<div>
<div className="px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/70">
Last 30 days
</div>
{groupedChats.lastMonth.map((chat) => (
<ChatItem
chat={chat}
isActive={chat.id === id}
key={chat.id}
onDelete={(chatId) => {
setDeleteId(chatId);
setShowDeleteDialog(true);
}}
setOpenMobile={setOpenMobile}
/>
))}
</div>
)}
{groupedChats.older.length > 0 && (
<div>
<div className="px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/70">
Older
</div>
{groupedChats.older.map((chat) => (
<ChatItem
chat={chat}
isActive={chat.id === id}
key={chat.id}
onDelete={(chatId) => {
setDeleteId(chatId);
setShowDeleteDialog(true);
}}
setOpenMobile={setOpenMobile}
/>
))}
</div>
)}
</div>
);
})()}
</SidebarMenu>
<motion.div
onViewportEnter={() => {
if (!isValidating && !hasReachedEnd) {
setSize((size) => size + 1);
}
}}
/>
{hasReachedEnd ? null : (
<div className="mt-1 flex flex-row items-center gap-2 px-4 py-2 text-sidebar-foreground/50">
<div className="animate-spin">
<LoaderIcon />
</div>
<div className="text-[11px]">Loading...</div>
</div>
)}
</SidebarGroupContent>
</SidebarGroup>
<AlertDialog onOpenChange={setShowDeleteDialog} open={showDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete your
chat and remove it from our servers.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete}>
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}

View file

@ -0,0 +1,35 @@
import type { ComponentProps } from "react";
import { type SidebarTrigger, useSidebar } from "@/components/ui/sidebar";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { Button } from "../ui/button";
import { SidebarLeftIcon } from "./icons";
export function SidebarToggle({
className,
}: ComponentProps<typeof SidebarTrigger>) {
const { toggleSidebar } = useSidebar();
return (
<Tooltip>
<TooltipTrigger asChild>
<Button
className={className}
data-testid="sidebar-toggle-button"
onClick={toggleSidebar}
size="icon-sm"
variant="outline"
>
<SidebarLeftIcon size={16} />
</Button>
</TooltipTrigger>
<TooltipContent align="start" className="hidden md:block">
Toggle Sidebar
</TooltipContent>
</Tooltip>
);
}

View file

@ -0,0 +1,121 @@
"use client";
import { ChevronUp } from "lucide-react";
import { useRouter } from "next/navigation";
import type { User } from "next-auth";
import { signOut, useSession } from "next-auth/react";
import { useTheme } from "next-themes";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { guestRegex } from "@/lib/constants";
import { LoaderIcon } from "./icons";
import { toast } from "./toast";
function emailToHue(email: string): number {
let hash = 0;
for (const char of email) {
hash = char.charCodeAt(0) + ((hash << 5) - hash);
}
return Math.abs(hash) % 360;
}
export function SidebarUserNav({ user }: { user: User }) {
const router = useRouter();
const { data, status } = useSession();
const { setTheme, resolvedTheme } = useTheme();
const isGuest = guestRegex.test(data?.user?.email ?? "");
return (
<SidebarMenu>
<SidebarMenuItem>
<DropdownMenu>
<DropdownMenuTrigger asChild>
{status === "loading" ? (
<SidebarMenuButton className="h-10 justify-between rounded-lg bg-transparent text-sidebar-foreground/50 transition-colors duration-150 data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground">
<div className="flex flex-row items-center gap-2">
<div className="size-6 animate-pulse rounded-full bg-sidebar-foreground/10" />
<span className="animate-pulse rounded-md bg-sidebar-foreground/10 text-transparent text-[13px]">
Loading...
</span>
</div>
<div className="animate-spin text-sidebar-foreground/50">
<LoaderIcon />
</div>
</SidebarMenuButton>
) : (
<SidebarMenuButton
className="h-8 px-2 rounded-lg bg-transparent text-sidebar-foreground/70 transition-colors duration-150 hover:text-sidebar-foreground data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
data-testid="user-nav-button"
>
<div
className="size-5 shrink-0 rounded-full ring-1 ring-sidebar-border/50"
style={{
background: `linear-gradient(135deg, oklch(0.35 0.08 ${emailToHue(user.email ?? "")}), oklch(0.25 0.05 ${emailToHue(user.email ?? "") + 40}))`,
}}
/>
<span className="truncate text-[13px]" data-testid="user-email">
{isGuest ? "Guest" : user?.email}
</span>
<ChevronUp className="ml-auto size-3.5 text-sidebar-foreground/50" />
</SidebarMenuButton>
)}
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-(--radix-popper-anchor-width) rounded-lg border border-border/60 bg-card/95 backdrop-blur-xl shadow-[var(--shadow-float)]"
data-testid="user-nav-menu"
side="top"
>
<DropdownMenuItem
className="cursor-pointer text-[13px]"
data-testid="user-nav-item-theme"
onSelect={() =>
setTheme(resolvedTheme === "dark" ? "light" : "dark")
}
>
{`Toggle ${resolvedTheme === "light" ? "dark" : "light"} mode`}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem asChild data-testid="user-nav-item-auth">
<button
className="w-full cursor-pointer text-[13px]"
onClick={() => {
if (status === "loading") {
toast({
type: "error",
description:
"Checking authentication status, please try again!",
});
return;
}
if (isGuest) {
router.push("/login");
} else {
signOut({
redirectTo: "/",
});
}
}}
type="button"
>
{isGuest ? "Login to your account" : "Sign out"}
</button>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
</SidebarMenu>
);
}

View file

@ -0,0 +1,25 @@
import Form from "next/form";
import { signOut } from "@/app/(auth)/auth";
export const SignOutForm = () => {
return (
<Form
action={async () => {
"use server";
await signOut({
redirectTo: "/",
});
}}
className="w-full"
>
<button
className="w-full px-1 py-0.5 text-left text-red-500"
type="submit"
>
Sign out
</button>
</Form>
);
};

View file

@ -0,0 +1,137 @@
"use client";
import {
BombIcon,
ListIcon,
PaletteIcon,
PenLineIcon,
PenSquareIcon,
Trash2Icon,
XIcon,
} from "lucide-react";
import { type ReactNode, useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
export type SlashCommand = {
name: string;
description: string;
icon: ReactNode;
action: string;
shortcut?: string;
};
export const slashCommands: SlashCommand[] = [
{
name: "new",
description: "Start a new chat",
icon: <PenSquareIcon className="size-3.5" />,
action: "new",
},
{
name: "clear",
description: "Clear current chat",
icon: <Trash2Icon className="size-3.5" />,
action: "clear",
},
{
name: "rename",
description: "Rename current chat",
icon: <PenLineIcon className="size-3.5" />,
action: "rename",
},
{
name: "model",
description: "Change the AI model",
icon: <ListIcon className="size-3.5" />,
action: "model",
},
{
name: "theme",
description: "Toggle dark/light mode",
icon: <PaletteIcon className="size-3.5" />,
action: "theme",
},
{
name: "delete",
description: "Delete current chat",
icon: <XIcon className="size-3.5" />,
action: "delete",
},
{
name: "purge",
description: "Delete all chats",
icon: <BombIcon className="size-3.5" />,
action: "purge",
},
];
type SlashCommandMenuProps = {
query: string;
onSelect: (command: SlashCommand) => void;
onClose: () => void;
selectedIndex: number;
};
export function SlashCommandMenu({
query,
onSelect,
onClose: _onClose,
selectedIndex,
}: SlashCommandMenuProps) {
const menuRef = useRef<HTMLDivElement>(null);
const filtered = slashCommands.filter((cmd) =>
cmd.name.startsWith(query.toLowerCase())
);
useEffect(() => {
const selected = menuRef.current?.querySelector("[data-selected='true']");
if (selected) {
selected.scrollIntoView({ block: "nearest" });
}
}, []);
if (filtered.length === 0) {
return null;
}
return (
<div
className="absolute bottom-full left-0 right-0 z-50 mb-2 overflow-hidden rounded-xl border border-border/50 bg-card/95 shadow-[var(--shadow-float)] backdrop-blur-xl"
ref={menuRef}
>
<div className="px-4 py-2.5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/40">
Commands
</div>
<div className="max-h-64 overflow-y-auto pb-1 no-scrollbar">
{filtered.map((cmd, index) => (
<button
className={cn(
"flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors",
index === selectedIndex ? "bg-muted/70" : "hover:bg-muted/40"
)}
data-selected={index === selectedIndex}
key={cmd.name}
onClick={() => onSelect(cmd)}
onMouseDown={(e) => e.preventDefault()}
type="button"
>
<div className="flex size-6 shrink-0 items-center justify-center text-muted-foreground/60">
{cmd.icon}
</div>
<span className="font-mono text-[13px] text-foreground">
/{cmd.name}
</span>
<span className="text-[12px] text-muted-foreground/50">
{cmd.description}
</span>
{cmd.shortcut && (
<span className="ml-auto text-[11px] text-muted-foreground/30">
{cmd.shortcut}
</span>
)}
</button>
))}
</div>
</div>
);
}

View file

@ -0,0 +1,38 @@
"use client";
import { useFormStatus } from "react-dom";
import { LoaderIcon } from "@/components/chat/icons";
import { Button } from "../ui/button";
export function SubmitButton({
children,
isSuccessful,
}: {
children: React.ReactNode;
isSuccessful: boolean;
}) {
const { pending } = useFormStatus();
return (
<Button
aria-disabled={pending || isSuccessful}
className="relative"
disabled={pending || isSuccessful}
type={pending ? "button" : "submit"}
>
{children}
{(pending || isSuccessful) && (
<span className="absolute right-4 animate-spin">
<LoaderIcon />
</span>
)}
<output aria-live="polite" className="sr-only">
{pending || isSuccessful ? "Loading" : "Submit form"}
</output>
</Button>
);
}

View file

@ -0,0 +1,78 @@
"use client";
import type { UseChatHelpers } from "@ai-sdk/react";
import { motion } from "framer-motion";
import { memo } from "react";
import { suggestions } from "@/lib/constants";
import type { ChatMessage } from "@/lib/types";
import { Suggestion } from "../ai-elements/suggestion";
import type { VisibilityType } from "./visibility-selector";
type SuggestedActionsProps = {
chatId: string;
sendMessage: UseChatHelpers<ChatMessage>["sendMessage"];
selectedVisibilityType: VisibilityType;
};
function PureSuggestedActions({ chatId, sendMessage }: SuggestedActionsProps) {
const suggestedActions = suggestions;
return (
<div
className="flex w-full gap-2.5 overflow-x-auto pb-1 sm:grid sm:grid-cols-2 sm:overflow-visible"
data-testid="suggested-actions"
style={{
scrollbarWidth: "none",
WebkitOverflowScrolling: "touch",
msOverflowStyle: "none",
}}
>
{suggestedActions.map((suggestedAction, index) => (
<motion.div
animate={{ opacity: 1, y: 0 }}
className="min-w-[200px] shrink-0 sm:min-w-0 sm:shrink"
exit={{ opacity: 0, y: 16 }}
initial={{ opacity: 0, y: 16 }}
key={suggestedAction}
transition={{
delay: 0.06 * index,
duration: 0.4,
ease: [0.22, 1, 0.36, 1],
}}
>
<Suggestion
className="h-auto w-full whitespace-nowrap rounded-xl border border-border/50 bg-card/30 px-4 py-3 text-left text-[12px] leading-relaxed text-muted-foreground transition-all duration-200 sm:whitespace-normal sm:p-4 sm:text-[13px] hover:-translate-y-0.5 hover:bg-card/60 hover:text-foreground hover:shadow-[var(--shadow-card)]"
onClick={(suggestion) => {
window.history.pushState(
{},
"",
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/chat/${chatId}`
);
sendMessage({
role: "user",
parts: [{ type: "text", text: suggestion }],
});
}}
suggestion={suggestedAction}
>
{suggestedAction}
</Suggestion>
</motion.div>
))}
</div>
);
}
export const SuggestedActions = memo(
PureSuggestedActions,
(prevProps, nextProps) => {
if (prevProps.chatId !== nextProps.chatId) {
return false;
}
if (prevProps.selectedVisibilityType !== nextProps.selectedVisibilityType) {
return false;
}
return true;
}
);

75
components/chat/toast.tsx Normal file
View file

@ -0,0 +1,75 @@
"use client";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { toast as sonnerToast } from "sonner";
import { cn } from "@/lib/utils";
import { CheckCircleFillIcon, WarningIcon } from "./icons";
const iconsByType: Record<"success" | "error", ReactNode> = {
success: <CheckCircleFillIcon />,
error: <WarningIcon />,
};
export function toast(props: Omit<ToastProps, "id">) {
return sonnerToast.custom((id) => (
<Toast description={props.description} id={id} type={props.type} />
));
}
function Toast(props: ToastProps) {
const { id, type, description } = props;
const descriptionRef = useRef<HTMLDivElement>(null);
const [multiLine, setMultiLine] = useState(false);
useEffect(() => {
const el = descriptionRef.current;
if (!el) {
return;
}
const update = () => {
const lineHeight = Number.parseFloat(getComputedStyle(el).lineHeight);
const lines = Math.round(el.scrollHeight / lineHeight);
setMultiLine(lines > 1);
};
update();
const ro = new ResizeObserver(update);
ro.observe(el);
return () => ro.disconnect();
}, []);
return (
<div className="flex toast-mobile:w-[356px] w-full justify-center">
<div
className={cn(
"flex toast-mobile:w-fit w-full flex-row gap-3 rounded-lg bg-card border border-border/50 shadow-[var(--shadow-float)] p-3",
multiLine ? "items-start" : "items-center"
)}
data-testid="toast"
key={id}
>
<div
className={cn(
"data-[type=error]:text-red-600 data-[type=success]:text-green-600",
{ "pt-1": multiLine }
)}
data-type={type}
>
{iconsByType[type]}
</div>
<div className="text-sm text-foreground" ref={descriptionRef}>
{description}
</div>
</div>
</div>
);
}
type ToastProps = {
id: string | number;
type: "success" | "error";
description: string;
};

View file

@ -0,0 +1,111 @@
"use client";
import { type ReactNode, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useChatVisibility } from "@/hooks/use-chat-visibility";
import { cn } from "@/lib/utils";
import {
CheckCircleFillIcon,
ChevronDownIcon,
GlobeIcon,
LockIcon,
} from "./icons";
export type VisibilityType = "private" | "public";
const visibilities: Array<{
id: VisibilityType;
label: string;
description: string;
icon: ReactNode;
}> = [
{
id: "private",
label: "Private",
description: "Only you can access this chat",
icon: <LockIcon />,
},
{
id: "public",
label: "Public",
description: "Anyone with the link can access this chat",
icon: <GlobeIcon />,
},
];
export function VisibilitySelector({
chatId,
className,
selectedVisibilityType,
}: {
chatId: string;
selectedVisibilityType: VisibilityType;
} & React.ComponentProps<typeof Button>) {
const [open, setOpen] = useState(false);
const { visibilityType, setVisibilityType } = useChatVisibility({
chatId,
initialVisibilityType: selectedVisibilityType,
});
const selectedVisibility = useMemo(
() => visibilities.find((visibility) => visibility.id === visibilityType),
[visibilityType]
);
return (
<DropdownMenu onOpenChange={setOpen} open={open}>
<DropdownMenuTrigger
asChild
className={cn(
"w-fit data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
className
)}
>
<Button
className="gap-1.5 rounded-lg border-border/50 text-muted-foreground shadow-none transition-colors hover:text-foreground focus-visible:ring-0 focus-visible:border-border/50 active:translate-y-0"
data-testid="visibility-selector"
size="sm"
variant="outline"
>
{selectedVisibility?.icon}
<span className="md:sr-only">{selectedVisibility?.label}</span>
<ChevronDownIcon />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-[300px]">
{visibilities.map((visibility) => (
<DropdownMenuItem
className="group/item flex flex-row items-center justify-between gap-4"
data-active={visibility.id === visibilityType}
data-testid={`visibility-selector-item-${visibility.id}`}
key={visibility.id}
onSelect={() => {
setVisibilityType(visibility.id);
setOpen(false);
}}
>
<div className="flex flex-col items-start gap-1">
{visibility.label}
{visibility.description && (
<div className="text-muted-foreground text-xs">
{visibility.description}
</div>
)}
</div>
<div className="text-foreground opacity-0 group-data-[active=true]/item:opacity-100 dark:text-foreground">
<CheckCircleFillIcon />
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}

434
components/chat/weather.tsx Normal file
View file

@ -0,0 +1,434 @@
"use client";
import cx from "classnames";
import { format, isWithinInterval } from "date-fns";
import { useEffect, useState } from "react";
const SunIcon = ({ size = 40 }: { size?: number }) => (
<svg fill="none" height={size} viewBox="0 0 24 24" width={size}>
<circle cx="12" cy="12" fill="currentColor" r="5" />
<line stroke="currentColor" strokeWidth="2" x1="12" x2="12" y1="1" y2="3" />
<line
stroke="currentColor"
strokeWidth="2"
x1="12"
x2="12"
y1="21"
y2="23"
/>
<line
stroke="currentColor"
strokeWidth="2"
x1="4.22"
x2="5.64"
y1="4.22"
y2="5.64"
/>
<line
stroke="currentColor"
strokeWidth="2"
x1="18.36"
x2="19.78"
y1="18.36"
y2="19.78"
/>
<line stroke="currentColor" strokeWidth="2" x1="1" x2="3" y1="12" y2="12" />
<line
stroke="currentColor"
strokeWidth="2"
x1="21"
x2="23"
y1="12"
y2="12"
/>
<line
stroke="currentColor"
strokeWidth="2"
x1="4.22"
x2="5.64"
y1="19.78"
y2="18.36"
/>
<line
stroke="currentColor"
strokeWidth="2"
x1="18.36"
x2="19.78"
y1="5.64"
y2="4.22"
/>
</svg>
);
const MoonIcon = ({ size = 40 }: { size?: number }) => (
<svg fill="none" height={size} viewBox="0 0 24 24" width={size}>
<path
d="M21 12.79A9 9 0 1 1 11.21 3A7 7 0 0 0 21 12.79z"
fill="currentColor"
/>
</svg>
);
const CloudIcon = ({ size = 24 }: { size?: number }) => (
<svg fill="none" height={size} viewBox="0 0 24 24" width={size}>
<path
d="M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z"
fill="none"
stroke="currentColor"
strokeWidth="2"
/>
</svg>
);
type WeatherAtLocation = {
latitude: number;
longitude: number;
generationtime_ms: number;
utc_offset_seconds: number;
timezone: string;
timezone_abbreviation: string;
elevation: number;
cityName?: string;
current_units: {
time: string;
interval: string;
temperature_2m: string;
};
current: {
time: string;
interval: number;
temperature_2m: number;
};
hourly_units: {
time: string;
temperature_2m: string;
};
hourly: {
time: string[];
temperature_2m: number[];
};
daily_units: {
time: string;
sunrise: string;
sunset: string;
};
daily: {
time: string[];
sunrise: string[];
sunset: string[];
};
};
const SAMPLE = {
latitude: 37.763_283,
longitude: -122.412_86,
generationtime_ms: 0.027_894_973_754_882_812,
utc_offset_seconds: 0,
timezone: "GMT",
timezone_abbreviation: "GMT",
elevation: 18,
current_units: { time: "iso8601", interval: "seconds", temperature_2m: "°C" },
current: { time: "2024-10-07T19:30", interval: 900, temperature_2m: 29.3 },
hourly_units: { time: "iso8601", temperature_2m: "°C" },
hourly: {
time: [
"2024-10-07T00:00",
"2024-10-07T01:00",
"2024-10-07T02:00",
"2024-10-07T03:00",
"2024-10-07T04:00",
"2024-10-07T05:00",
"2024-10-07T06:00",
"2024-10-07T07:00",
"2024-10-07T08:00",
"2024-10-07T09:00",
"2024-10-07T10:00",
"2024-10-07T11:00",
"2024-10-07T12:00",
"2024-10-07T13:00",
"2024-10-07T14:00",
"2024-10-07T15:00",
"2024-10-07T16:00",
"2024-10-07T17:00",
"2024-10-07T18:00",
"2024-10-07T19:00",
"2024-10-07T20:00",
"2024-10-07T21:00",
"2024-10-07T22:00",
"2024-10-07T23:00",
"2024-10-08T00:00",
"2024-10-08T01:00",
"2024-10-08T02:00",
"2024-10-08T03:00",
"2024-10-08T04:00",
"2024-10-08T05:00",
"2024-10-08T06:00",
"2024-10-08T07:00",
"2024-10-08T08:00",
"2024-10-08T09:00",
"2024-10-08T10:00",
"2024-10-08T11:00",
"2024-10-08T12:00",
"2024-10-08T13:00",
"2024-10-08T14:00",
"2024-10-08T15:00",
"2024-10-08T16:00",
"2024-10-08T17:00",
"2024-10-08T18:00",
"2024-10-08T19:00",
"2024-10-08T20:00",
"2024-10-08T21:00",
"2024-10-08T22:00",
"2024-10-08T23:00",
"2024-10-09T00:00",
"2024-10-09T01:00",
"2024-10-09T02:00",
"2024-10-09T03:00",
"2024-10-09T04:00",
"2024-10-09T05:00",
"2024-10-09T06:00",
"2024-10-09T07:00",
"2024-10-09T08:00",
"2024-10-09T09:00",
"2024-10-09T10:00",
"2024-10-09T11:00",
"2024-10-09T12:00",
"2024-10-09T13:00",
"2024-10-09T14:00",
"2024-10-09T15:00",
"2024-10-09T16:00",
"2024-10-09T17:00",
"2024-10-09T18:00",
"2024-10-09T19:00",
"2024-10-09T20:00",
"2024-10-09T21:00",
"2024-10-09T22:00",
"2024-10-09T23:00",
"2024-10-10T00:00",
"2024-10-10T01:00",
"2024-10-10T02:00",
"2024-10-10T03:00",
"2024-10-10T04:00",
"2024-10-10T05:00",
"2024-10-10T06:00",
"2024-10-10T07:00",
"2024-10-10T08:00",
"2024-10-10T09:00",
"2024-10-10T10:00",
"2024-10-10T11:00",
"2024-10-10T12:00",
"2024-10-10T13:00",
"2024-10-10T14:00",
"2024-10-10T15:00",
"2024-10-10T16:00",
"2024-10-10T17:00",
"2024-10-10T18:00",
"2024-10-10T19:00",
"2024-10-10T20:00",
"2024-10-10T21:00",
"2024-10-10T22:00",
"2024-10-10T23:00",
"2024-10-11T00:00",
"2024-10-11T01:00",
"2024-10-11T02:00",
"2024-10-11T03:00",
],
temperature_2m: [
36.6, 32.8, 29.5, 28.6, 29.2, 28.2, 27.5, 26.6, 26.5, 26, 25, 23.5, 23.9,
24.2, 22.9, 21, 24, 28.1, 31.4, 33.9, 32.1, 28.9, 26.9, 25.2, 23, 21.1,
19.6, 18.6, 17.7, 16.8, 16.2, 15.5, 14.9, 14.4, 14.2, 13.7, 13.3, 12.9,
12.5, 13.5, 15.8, 17.7, 19.6, 21, 21.9, 22.3, 22, 20.7, 18.9, 17.9, 17.3,
17, 16.7, 16.2, 15.6, 15.2, 15, 15, 15.1, 14.8, 14.8, 14.9, 14.7, 14.8,
15.3, 16.2, 17.9, 19.6, 20.5, 21.6, 21, 20.7, 19.3, 18.7, 18.4, 17.9,
17.3, 17, 17, 16.8, 16.4, 16.2, 16, 15.8, 15.7, 15.4, 15.4, 16.1, 16.7,
17, 18.6, 19, 19.5, 19.4, 18.5, 17.9, 17.5, 16.7, 16.3, 16.1,
],
},
daily_units: {
time: "iso8601",
sunrise: "iso8601",
sunset: "iso8601",
},
daily: {
time: [
"2024-10-07",
"2024-10-08",
"2024-10-09",
"2024-10-10",
"2024-10-11",
],
sunrise: [
"2024-10-07T07:15",
"2024-10-08T07:16",
"2024-10-09T07:17",
"2024-10-10T07:18",
"2024-10-11T07:19",
],
sunset: [
"2024-10-07T19:00",
"2024-10-08T18:58",
"2024-10-09T18:57",
"2024-10-10T18:55",
"2024-10-11T18:54",
],
},
};
function n(num: number): number {
return Math.ceil(num);
}
export function Weather({
weatherAtLocation = SAMPLE,
}: {
weatherAtLocation?: WeatherAtLocation;
}) {
const currentHigh = Math.max(
...weatherAtLocation.hourly.temperature_2m.slice(0, 24)
);
const currentLow = Math.min(
...weatherAtLocation.hourly.temperature_2m.slice(0, 24)
);
const isDay = isWithinInterval(new Date(weatherAtLocation.current.time), {
start: new Date(weatherAtLocation.daily.sunrise[0]),
end: new Date(weatherAtLocation.daily.sunset[0]),
});
const [isMobile, setIsMobile] = useState(false);
useEffect(() => {
const handleResize = () => {
setIsMobile(window.innerWidth < 768);
};
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
const hoursToShow = isMobile ? 5 : 6;
const currentTimeIndex = weatherAtLocation.hourly.time.findIndex(
(time) => new Date(time) >= new Date(weatherAtLocation.current.time)
);
const displayTimes = weatherAtLocation.hourly.time.slice(
currentTimeIndex,
currentTimeIndex + hoursToShow
);
const displayTemperatures = weatherAtLocation.hourly.temperature_2m.slice(
currentTimeIndex,
currentTimeIndex + hoursToShow
);
const location =
weatherAtLocation.cityName ||
`${weatherAtLocation.latitude?.toFixed(1)}°, ${weatherAtLocation.longitude?.toFixed(1)}°`;
return (
<div
className={cx(
"relative flex w-full flex-col gap-3 overflow-hidden rounded-2xl p-4 shadow-lg backdrop-blur-sm",
{
"bg-gradient-to-br from-sky-400 via-blue-500 to-blue-600": isDay,
},
{
"bg-gradient-to-br from-indigo-900 via-purple-900 to-slate-900":
!isDay,
}
)}
>
<div className="absolute inset-0 bg-white/10 backdrop-blur-sm" />
<div className="relative z-10">
<div className="mb-2 flex items-center justify-between">
<div className="font-medium text-white/80 text-xs">{location}</div>
<div className="text-white/60 text-xs">
{format(new Date(weatherAtLocation.current.time), "MMM d, h:mm a")}
</div>
</div>
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-3">
<div
className={cx("text-white/90", {
"text-yellow-200": isDay,
"text-blue-200": !isDay,
})}
>
{isDay ? <SunIcon size={32} /> : <MoonIcon size={32} />}
</div>
<div className="font-light text-3xl text-white">
{n(weatherAtLocation.current.temperature_2m)}
<span className="text-lg text-white/80">
{weatherAtLocation.current_units.temperature_2m}
</span>
</div>
</div>
<div className="text-right">
<div className="font-medium text-white/90 text-xs">
H: {n(currentHigh)}°
</div>
<div className="text-white/70 text-xs">L: {n(currentLow)}°</div>
</div>
</div>
<div className="rounded-xl bg-white/10 p-3 backdrop-blur-sm">
<div className="mb-2 font-medium text-white/80 text-xs">
Hourly Forecast
</div>
<div className="flex justify-between gap-1">
{displayTimes.map((time, index) => {
const hourTime = new Date(time);
const isCurrentHour =
hourTime.getHours() === new Date().getHours();
return (
<div
className={cx(
"flex min-w-0 flex-1 flex-col items-center gap-1 rounded-md px-1 py-1.5",
{
"bg-white/20": isCurrentHour,
}
)}
key={time}
>
<div className="font-medium text-white/70 text-xs">
{index === 0 ? "Now" : format(hourTime, "ha")}
</div>
<div
className={cx("text-white/60", {
"text-yellow-200": isDay,
"text-blue-200": !isDay,
})}
>
<CloudIcon size={16} />
</div>
<div className="font-medium text-white text-xs">
{n(displayTemperatures[index])}°
</div>
</div>
);
})}
</div>
</div>
<div className="mt-2 flex justify-between text-white/60 text-xs">
<div>
Sunrise:{" "}
{format(new Date(weatherAtLocation.daily.sunrise[0]), "h:mm a")}
</div>
<div>
Sunset:{" "}
{format(new Date(weatherAtLocation.daily.sunset[0]), "h:mm a")}
</div>
</div>
</div>
</div>
);
}