feat: v1 — persistent shell, model gateway, artifact improvements (#1462)
This commit is contained in:
parent
3651670fb9
commit
f9652b452a
161 changed files with 5166 additions and 8009 deletions
165
components/chat/app-sidebar.tsx
Normal file
165
components/chat/app-sidebar.tsx
Normal 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
119
components/chat/artifact-actions.tsx
Normal file
119
components/chat/artifact-actions.tsx
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { memo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
|
||||
import { artifactDefinitions, type UIArtifact } from "./artifact";
|
||||
import type { ArtifactActionContext } from "./create-artifact";
|
||||
|
||||
type ArtifactActionsProps = {
|
||||
artifact: UIArtifact;
|
||||
handleVersionChange: (type: "next" | "prev" | "toggle" | "latest") => void;
|
||||
currentVersionIndex: number;
|
||||
isCurrentVersion: boolean;
|
||||
mode: "edit" | "diff";
|
||||
metadata: ArtifactActionContext["metadata"];
|
||||
setMetadata: ArtifactActionContext["setMetadata"];
|
||||
};
|
||||
|
||||
function PureArtifactActions({
|
||||
artifact,
|
||||
handleVersionChange,
|
||||
currentVersionIndex,
|
||||
isCurrentVersion,
|
||||
mode,
|
||||
metadata,
|
||||
setMetadata,
|
||||
}: ArtifactActionsProps) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const artifactDefinition = artifactDefinitions.find(
|
||||
(definition) => definition.kind === artifact.kind
|
||||
);
|
||||
|
||||
if (!artifactDefinition) {
|
||||
throw new Error("Artifact definition not found!");
|
||||
}
|
||||
|
||||
const actionContext: ArtifactActionContext = {
|
||||
content: artifact.content,
|
||||
handleVersionChange,
|
||||
currentVersionIndex,
|
||||
isCurrentVersion,
|
||||
mode,
|
||||
metadata,
|
||||
setMetadata,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-0.5">
|
||||
{artifactDefinition.actions.map((action) => {
|
||||
const disabled =
|
||||
isLoading || artifact.status === "streaming"
|
||||
? true
|
||||
: action.isDisabled
|
||||
? action.isDisabled(actionContext)
|
||||
: false;
|
||||
|
||||
return (
|
||||
<Tooltip key={action.description}>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
className={cn(
|
||||
"flex items-center justify-center rounded-full p-3 text-muted-foreground transition-all duration-150",
|
||||
"hover:text-foreground",
|
||||
"active:scale-95",
|
||||
"disabled:pointer-events-none disabled:opacity-30",
|
||||
{
|
||||
"text-foreground":
|
||||
mode === "diff" && action.description === "View changes",
|
||||
}
|
||||
)}
|
||||
disabled={disabled}
|
||||
onClick={async () => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await Promise.resolve(action.onClick(actionContext));
|
||||
} catch (_error) {
|
||||
toast.error("Failed to execute action");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
{action.icon}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="left" sideOffset={8}>
|
||||
{action.description}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const ArtifactActions = memo(
|
||||
PureArtifactActions,
|
||||
(prevProps, nextProps) => {
|
||||
if (prevProps.artifact.status !== nextProps.artifact.status) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.currentVersionIndex !== nextProps.currentVersionIndex) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.isCurrentVersion !== nextProps.isCurrentVersion) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.artifact.content !== nextProps.artifact.content) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.mode !== nextProps.mode) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
);
|
||||
29
components/chat/artifact-close-button.tsx
Normal file
29
components/chat/artifact-close-button.tsx
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { memo } from "react";
|
||||
import { initialArtifactData, useArtifact } from "@/hooks/use-artifact";
|
||||
import { CrossIcon } from "./icons";
|
||||
|
||||
function PureArtifactCloseButton() {
|
||||
const { setArtifact } = useArtifact();
|
||||
|
||||
return (
|
||||
<button
|
||||
className="group flex size-8 items-center justify-center rounded-lg border border-transparent text-muted-foreground transition-all duration-150 hover:border-border hover:bg-muted hover:text-foreground active:scale-95"
|
||||
data-testid="artifact-close-button"
|
||||
onClick={() => {
|
||||
setArtifact((currentArtifact) =>
|
||||
currentArtifact.status === "streaming"
|
||||
? {
|
||||
...currentArtifact,
|
||||
isVisible: false,
|
||||
}
|
||||
: { ...initialArtifactData, status: "idle" }
|
||||
);
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<CrossIcon size={16} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export const ArtifactCloseButton = memo(PureArtifactCloseButton, () => true);
|
||||
115
components/chat/artifact-messages.tsx
Normal file
115
components/chat/artifact-messages.tsx
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import type { UseChatHelpers } from "@ai-sdk/react";
|
||||
import equal from "fast-deep-equal";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { memo } from "react";
|
||||
import { useMessages } from "@/hooks/use-messages";
|
||||
import type { Vote } from "@/lib/db/schema";
|
||||
import type { ChatMessage } from "@/lib/types";
|
||||
import type { UIArtifact } from "./artifact";
|
||||
import { PreviewMessage, ThinkingMessage } from "./message";
|
||||
|
||||
type ArtifactMessagesProps = {
|
||||
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;
|
||||
artifactStatus: UIArtifact["status"];
|
||||
};
|
||||
|
||||
function PureArtifactMessages({
|
||||
addToolApprovalResponse,
|
||||
chatId,
|
||||
status,
|
||||
votes,
|
||||
messages,
|
||||
setMessages,
|
||||
regenerate,
|
||||
isReadonly,
|
||||
}: ArtifactMessagesProps) {
|
||||
const {
|
||||
containerRef: messagesContainerRef,
|
||||
endRef: messagesEndRef,
|
||||
onViewportEnter,
|
||||
onViewportLeave,
|
||||
hasSentMessage,
|
||||
} = useMessages({
|
||||
status,
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex h-full flex-col items-center gap-4 overflow-y-scroll px-4 pt-20"
|
||||
ref={messagesContainerRef}
|
||||
>
|
||||
{messages.map((message, index) => (
|
||||
<PreviewMessage
|
||||
addToolApprovalResponse={addToolApprovalResponse}
|
||||
chatId={chatId}
|
||||
isLoading={status === "streaming" && index === messages.length - 1}
|
||||
isReadonly={isReadonly}
|
||||
key={message.id}
|
||||
message={message}
|
||||
regenerate={regenerate}
|
||||
requiresScrollPadding={
|
||||
hasSentMessage && index === messages.length - 1
|
||||
}
|
||||
setMessages={setMessages}
|
||||
vote={
|
||||
votes
|
||||
? votes.find((vote) => vote.messageId === message.id)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
|
||||
<AnimatePresence mode="wait">
|
||||
{status === "submitted" &&
|
||||
!messages.some((msg) =>
|
||||
msg.parts?.some(
|
||||
(part) => "state" in part && part.state === "approval-responded"
|
||||
)
|
||||
) && <ThinkingMessage key="thinking" />}
|
||||
</AnimatePresence>
|
||||
|
||||
<motion.div
|
||||
className="min-h-[24px] min-w-[24px] shrink-0"
|
||||
onViewportEnter={onViewportEnter}
|
||||
onViewportLeave={onViewportLeave}
|
||||
ref={messagesEndRef}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function areEqual(
|
||||
prevProps: ArtifactMessagesProps,
|
||||
nextProps: ArtifactMessagesProps
|
||||
) {
|
||||
if (
|
||||
prevProps.artifactStatus === "streaming" &&
|
||||
nextProps.artifactStatus === "streaming"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (prevProps.status !== nextProps.status) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.status && nextProps.status) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.messages.length !== nextProps.messages.length) {
|
||||
return false;
|
||||
}
|
||||
if (!equal(prevProps.votes, nextProps.votes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export const ArtifactMessages = memo(PureArtifactMessages, areEqual);
|
||||
482
components/chat/artifact.tsx
Normal file
482
components/chat/artifact.tsx
Normal file
|
|
@ -0,0 +1,482 @@
|
|||
import type { UseChatHelpers } from "@ai-sdk/react";
|
||||
import { formatDistance } from "date-fns";
|
||||
import equal from "fast-deep-equal";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import {
|
||||
type Dispatch,
|
||||
memo,
|
||||
type SetStateAction,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useWindowSize } from "usehooks-ts";
|
||||
import { codeArtifact } from "@/artifacts/code/client";
|
||||
import { imageArtifact } from "@/artifacts/image/client";
|
||||
import { sheetArtifact } from "@/artifacts/sheet/client";
|
||||
import { textArtifact } from "@/artifacts/text/client";
|
||||
import { useArtifact } from "@/hooks/use-artifact";
|
||||
import type { Document, Vote } from "@/lib/db/schema";
|
||||
import type { Attachment, ChatMessage } from "@/lib/types";
|
||||
import { fetcher } from "@/lib/utils";
|
||||
import { useSidebar } from "../ui/sidebar";
|
||||
import { ArtifactActions } from "./artifact-actions";
|
||||
import { ArtifactCloseButton } from "./artifact-close-button";
|
||||
import { LoaderIcon } from "./icons";
|
||||
import { Toolbar } from "./toolbar";
|
||||
import { VersionFooter } from "./version-footer";
|
||||
import type { VisibilityType } from "./visibility-selector";
|
||||
|
||||
export const artifactDefinitions = [
|
||||
textArtifact,
|
||||
codeArtifact,
|
||||
imageArtifact,
|
||||
sheetArtifact,
|
||||
];
|
||||
export type ArtifactKind = (typeof artifactDefinitions)[number]["kind"];
|
||||
|
||||
export type UIArtifact = {
|
||||
title: string;
|
||||
documentId: string;
|
||||
kind: ArtifactKind;
|
||||
content: string;
|
||||
isVisible: boolean;
|
||||
status: "streaming" | "idle";
|
||||
boundingBox: {
|
||||
top: number;
|
||||
left: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
};
|
||||
|
||||
function PureArtifact({
|
||||
addToolApprovalResponse: _addToolApprovalResponse,
|
||||
chatId: _chatId,
|
||||
input: _input,
|
||||
setInput: _setInput,
|
||||
status,
|
||||
stop,
|
||||
attachments: _attachments,
|
||||
setAttachments: _setAttachments,
|
||||
sendMessage,
|
||||
messages: _messages,
|
||||
setMessages,
|
||||
regenerate: _regenerate,
|
||||
votes: _votes,
|
||||
isReadonly: _isReadonly,
|
||||
selectedVisibilityType: _selectedVisibilityType,
|
||||
selectedModelId: _selectedModelId,
|
||||
}: {
|
||||
addToolApprovalResponse: UseChatHelpers<ChatMessage>["addToolApprovalResponse"];
|
||||
chatId: string;
|
||||
input: string;
|
||||
setInput: Dispatch<SetStateAction<string>>;
|
||||
status: UseChatHelpers<ChatMessage>["status"];
|
||||
stop: UseChatHelpers<ChatMessage>["stop"];
|
||||
attachments: Attachment[];
|
||||
setAttachments: Dispatch<SetStateAction<Attachment[]>>;
|
||||
messages: ChatMessage[];
|
||||
setMessages: UseChatHelpers<ChatMessage>["setMessages"];
|
||||
votes: Vote[] | undefined;
|
||||
sendMessage: UseChatHelpers<ChatMessage>["sendMessage"];
|
||||
regenerate: UseChatHelpers<ChatMessage>["regenerate"];
|
||||
isReadonly: boolean;
|
||||
selectedVisibilityType: VisibilityType;
|
||||
selectedModelId: string;
|
||||
}) {
|
||||
const { artifact, setArtifact, metadata, setMetadata } = useArtifact();
|
||||
|
||||
const {
|
||||
data: documents,
|
||||
isLoading: isDocumentsFetching,
|
||||
mutate: mutateDocuments,
|
||||
} = useSWR<Document[]>(
|
||||
artifact.documentId !== "init" && artifact.status !== "streaming"
|
||||
? `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/document?id=${artifact.documentId}`
|
||||
: null,
|
||||
fetcher
|
||||
);
|
||||
|
||||
const [mode, setMode] = useState<"edit" | "diff">("edit");
|
||||
const [document, setDocument] = useState<Document | null>(null);
|
||||
const [currentVersionIndex, setCurrentVersionIndex] = useState(-1);
|
||||
|
||||
const { state: sidebarState } = useSidebar();
|
||||
const artifactContentRef = useRef<HTMLDivElement>(null);
|
||||
const userScrolledArtifact = useRef(false);
|
||||
const [isContentDirty, setIsContentDirty] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (artifact.status !== "streaming") {
|
||||
userScrolledArtifact.current = false;
|
||||
return;
|
||||
}
|
||||
if (userScrolledArtifact.current) {
|
||||
return;
|
||||
}
|
||||
const el = artifactContentRef.current;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
el.scrollTo({ top: el.scrollHeight });
|
||||
}, [artifact.status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (documents && documents.length > 0) {
|
||||
const mostRecentDocument = documents.at(-1);
|
||||
|
||||
if (mostRecentDocument) {
|
||||
setDocument(mostRecentDocument);
|
||||
setCurrentVersionIndex(documents.length - 1);
|
||||
if (artifact.status === "streaming" || !isContentDirty) {
|
||||
setArtifact((currentArtifact) => ({
|
||||
...currentArtifact,
|
||||
content: mostRecentDocument.content ?? "",
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [documents, setArtifact, artifact.status, isContentDirty]);
|
||||
|
||||
useEffect(() => {
|
||||
mutateDocuments();
|
||||
}, [mutateDocuments]);
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
|
||||
const handleContentChange = useCallback(
|
||||
(updatedContent: string) => {
|
||||
if (!artifact) {
|
||||
return;
|
||||
}
|
||||
|
||||
mutate<Document[]>(
|
||||
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/document?id=${artifact.documentId}`,
|
||||
async (currentDocuments) => {
|
||||
if (!currentDocuments) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const currentDocument = currentDocuments.at(-1);
|
||||
|
||||
if (!currentDocument || !currentDocument.content) {
|
||||
setIsContentDirty(false);
|
||||
return currentDocuments;
|
||||
}
|
||||
|
||||
if (currentDocument.content === updatedContent) {
|
||||
setIsContentDirty(false);
|
||||
return currentDocuments;
|
||||
}
|
||||
|
||||
await fetch(
|
||||
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/document?id=${artifact.documentId}`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
title: artifact.title,
|
||||
content: updatedContent,
|
||||
kind: artifact.kind,
|
||||
isManualEdit: true,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
setIsContentDirty(false);
|
||||
|
||||
return currentDocuments.map((doc, i) =>
|
||||
i === currentDocuments.length - 1
|
||||
? { ...doc, content: updatedContent }
|
||||
: doc
|
||||
);
|
||||
},
|
||||
{ revalidate: false }
|
||||
);
|
||||
},
|
||||
[artifact, mutate]
|
||||
);
|
||||
|
||||
const latestContentRef = useRef<string>("");
|
||||
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const saveContent = useCallback(
|
||||
(updatedContent: string, debounce: boolean) => {
|
||||
latestContentRef.current = updatedContent;
|
||||
setIsContentDirty(true);
|
||||
|
||||
if (saveTimerRef.current) {
|
||||
clearTimeout(saveTimerRef.current);
|
||||
saveTimerRef.current = null;
|
||||
}
|
||||
|
||||
if (debounce) {
|
||||
saveTimerRef.current = setTimeout(() => {
|
||||
handleContentChange(latestContentRef.current);
|
||||
saveTimerRef.current = null;
|
||||
}, 2000);
|
||||
} else {
|
||||
handleContentChange(updatedContent);
|
||||
}
|
||||
},
|
||||
[handleContentChange]
|
||||
);
|
||||
|
||||
function getDocumentContentById(index: number) {
|
||||
if (!documents) {
|
||||
return "";
|
||||
}
|
||||
if (!documents[index]) {
|
||||
return "";
|
||||
}
|
||||
return documents[index].content ?? "";
|
||||
}
|
||||
|
||||
const handleVersionChange = (type: "next" | "prev" | "toggle" | "latest") => {
|
||||
if (!documents) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === "latest") {
|
||||
setCurrentVersionIndex(documents.length - 1);
|
||||
setMode("edit");
|
||||
}
|
||||
|
||||
if (type === "toggle") {
|
||||
setMode((currentMode) => (currentMode === "edit" ? "diff" : "edit"));
|
||||
}
|
||||
|
||||
if (type === "prev") {
|
||||
if (currentVersionIndex > 0) {
|
||||
setCurrentVersionIndex((index) => index - 1);
|
||||
}
|
||||
} else if (type === "next" && currentVersionIndex < documents.length - 1) {
|
||||
setCurrentVersionIndex((index) => index + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const [isToolbarVisible, setIsToolbarVisible] = useState(true);
|
||||
|
||||
const isCurrentVersion =
|
||||
documents && documents.length > 0
|
||||
? currentVersionIndex === documents.length - 1
|
||||
: true;
|
||||
|
||||
const { width: windowWidth, height: windowHeight } = useWindowSize();
|
||||
const isMobile = windowWidth ? windowWidth < 768 : false;
|
||||
|
||||
const artifactDefinition = artifactDefinitions.find(
|
||||
(definition) => definition.kind === artifact.kind
|
||||
);
|
||||
|
||||
if (!artifactDefinition) {
|
||||
throw new Error("Artifact definition not found!");
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (artifact.documentId !== "init" && artifactDefinition.initialize) {
|
||||
artifactDefinition.initialize({
|
||||
documentId: artifact.documentId,
|
||||
setMetadata,
|
||||
});
|
||||
}
|
||||
}, [artifact.documentId, artifactDefinition, setMetadata]);
|
||||
|
||||
if (!artifact.isVisible && !isMobile) {
|
||||
return (
|
||||
<div
|
||||
className="h-dvh w-0 shrink-0 overflow-hidden transition-[width] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]"
|
||||
data-testid="artifact"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!artifact.isVisible) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const consoleError =
|
||||
metadata?.outputs
|
||||
?.filter((o: { status: string }) => o.status === "failed")
|
||||
.flatMap((o: { contents: { type: string; value: string }[] }) =>
|
||||
o.contents.filter((c) => c.type === "text").map((c) => c.value)
|
||||
)
|
||||
.join("\n") || undefined;
|
||||
|
||||
const artifactPanel = (
|
||||
<>
|
||||
{sidebarState !== "collapsed" && (
|
||||
<div className="flex h-[calc(3.5rem+1px)] shrink-0 items-center justify-between border-b border-border/50 px-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<ArtifactCloseButton />
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<div className="text-sm font-semibold leading-tight tracking-tight">
|
||||
{artifact.title}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isContentDirty ? (
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<div className="size-1.5 animate-pulse rounded-full bg-amber-500" />
|
||||
Saving...
|
||||
</div>
|
||||
) : document ? (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{`Updated ${formatDistance(new Date(document.createdAt), new Date(), { addSuffix: true })}`}
|
||||
</div>
|
||||
) : artifact.status === "streaming" ? (
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<div className="animate-spin">
|
||||
<LoaderIcon size={12} />
|
||||
</div>
|
||||
Generating...
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-3 w-24 animate-pulse rounded bg-muted-foreground/10" />
|
||||
)}
|
||||
{documents && documents.length > 1 && (
|
||||
<div className="rounded-md bg-muted px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground">
|
||||
v{currentVersionIndex + 1}/{documents.length}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className="relative flex-1 overflow-y-auto bg-background"
|
||||
data-slot="artifact-content"
|
||||
onScroll={() => {
|
||||
const el = artifactContentRef.current;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
const atBottom =
|
||||
el.scrollHeight - el.scrollTop - el.clientHeight < 40;
|
||||
userScrolledArtifact.current = !atBottom;
|
||||
}}
|
||||
ref={artifactContentRef}
|
||||
>
|
||||
<artifactDefinition.content
|
||||
content={
|
||||
isCurrentVersion
|
||||
? artifact.content
|
||||
: getDocumentContentById(currentVersionIndex)
|
||||
}
|
||||
currentVersionIndex={currentVersionIndex}
|
||||
getDocumentContentById={getDocumentContentById}
|
||||
isCurrentVersion={isCurrentVersion}
|
||||
isInline={false}
|
||||
isLoading={isDocumentsFetching && !artifact.content}
|
||||
metadata={metadata}
|
||||
mode={mode}
|
||||
onSaveContent={saveContent}
|
||||
setMetadata={setMetadata}
|
||||
status={artifact.status}
|
||||
suggestions={[]}
|
||||
title={artifact.title}
|
||||
/>
|
||||
<AnimatePresence>
|
||||
{isCurrentVersion && (
|
||||
<Toolbar
|
||||
artifactActions={
|
||||
<ArtifactActions
|
||||
artifact={artifact}
|
||||
currentVersionIndex={currentVersionIndex}
|
||||
handleVersionChange={handleVersionChange}
|
||||
isCurrentVersion={isCurrentVersion}
|
||||
metadata={metadata}
|
||||
mode={mode}
|
||||
setMetadata={setMetadata}
|
||||
/>
|
||||
}
|
||||
artifactKind={artifact.kind}
|
||||
consoleError={consoleError}
|
||||
documentId={artifact.documentId}
|
||||
isToolbarVisible={isToolbarVisible}
|
||||
onClose={() => {
|
||||
setArtifact((prev) => ({ ...prev, isVisible: false }));
|
||||
}}
|
||||
sendMessage={sendMessage}
|
||||
setIsToolbarVisible={setIsToolbarVisible}
|
||||
setMessages={setMessages}
|
||||
status={status}
|
||||
stop={stop}
|
||||
/>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
<AnimatePresence>
|
||||
{!isCurrentVersion && (
|
||||
<VersionFooter
|
||||
currentVersionIndex={currentVersionIndex}
|
||||
documents={documents}
|
||||
handleVersionChange={handleVersionChange}
|
||||
mode={mode}
|
||||
setMode={setMode}
|
||||
/>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</>
|
||||
);
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<motion.div
|
||||
animate={{
|
||||
opacity: 1,
|
||||
x: 0,
|
||||
y: 0,
|
||||
height: windowHeight,
|
||||
width: "100dvw",
|
||||
borderRadius: 0,
|
||||
}}
|
||||
className="fixed inset-0 z-50 flex h-dvh flex-col overflow-hidden bg-sidebar"
|
||||
data-testid="artifact"
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
initial={{
|
||||
opacity: 1,
|
||||
x: artifact.boundingBox.left,
|
||||
y: artifact.boundingBox.top,
|
||||
height: artifact.boundingBox.height,
|
||||
width: artifact.boundingBox.width,
|
||||
borderRadius: 50,
|
||||
}}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
>
|
||||
{artifactPanel}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex h-dvh w-[60%] shrink-0 flex-col overflow-hidden border-l border-border/50 bg-sidebar transition-[width] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]"
|
||||
data-testid="artifact"
|
||||
>
|
||||
{artifactPanel}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const Artifact = memo(PureArtifact, (prevProps, nextProps) => {
|
||||
if (prevProps.status !== nextProps.status) {
|
||||
return false;
|
||||
}
|
||||
if (!equal(prevProps.votes, nextProps.votes)) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.input !== nextProps.input) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.messages.length !== nextProps.messages.length) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.selectedVisibilityType !== nextProps.selectedVisibilityType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
53
components/chat/auth-form.tsx
Normal file
53
components/chat/auth-form.tsx
Normal 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="••••••••"
|
||||
required
|
||||
type="password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
76
components/chat/chat-header.tsx
Normal file
76
components/chat/chat-header.tsx
Normal 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
|
||||
);
|
||||
});
|
||||
154
components/chat/code-editor.tsx
Normal file
154
components/chat/code-editor.tsx
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
"use client";
|
||||
|
||||
import { python } from "@codemirror/lang-python";
|
||||
import { EditorState, Transaction } from "@codemirror/state";
|
||||
import { oneDark } from "@codemirror/theme-one-dark";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { basicSetup } from "codemirror";
|
||||
import { memo, useEffect, useRef } from "react";
|
||||
import type { Suggestion } from "@/lib/db/schema";
|
||||
|
||||
type EditorProps = {
|
||||
content: string;
|
||||
onSaveContent: (updatedContent: string, debounce: boolean) => void;
|
||||
status: "streaming" | "idle";
|
||||
isCurrentVersion: boolean;
|
||||
currentVersionIndex: number;
|
||||
suggestions: Suggestion[];
|
||||
};
|
||||
|
||||
function PureCodeEditor({ content, onSaveContent, status }: EditorProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
const userScrolledRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (containerRef.current && !editorRef.current) {
|
||||
const startState = EditorState.create({
|
||||
doc: content,
|
||||
extensions: [basicSetup, python(), oneDark],
|
||||
});
|
||||
|
||||
editorRef.current = new EditorView({
|
||||
state: startState,
|
||||
parent: containerRef.current,
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (editorRef.current) {
|
||||
editorRef.current.destroy();
|
||||
editorRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [content]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current) {
|
||||
const updateListener = EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) {
|
||||
const transaction = update.transactions.find(
|
||||
(tr) => !tr.annotation(Transaction.remote)
|
||||
);
|
||||
|
||||
if (transaction) {
|
||||
const newContent = update.state.doc.toString();
|
||||
onSaveContent(newContent, true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const scrollListener = EditorView.domEventHandlers({
|
||||
scroll() {
|
||||
if (status !== "streaming") {
|
||||
return;
|
||||
}
|
||||
const dom = editorRef.current?.scrollDOM;
|
||||
if (!dom) {
|
||||
return;
|
||||
}
|
||||
const atBottom =
|
||||
dom.scrollHeight - dom.scrollTop - dom.clientHeight < 40;
|
||||
userScrolledRef.current = !atBottom;
|
||||
},
|
||||
});
|
||||
|
||||
const currentSelection = editorRef.current.state.selection;
|
||||
|
||||
const newState = EditorState.create({
|
||||
doc: editorRef.current.state.doc,
|
||||
extensions: [
|
||||
basicSetup,
|
||||
python(),
|
||||
oneDark,
|
||||
updateListener,
|
||||
scrollListener,
|
||||
],
|
||||
selection: currentSelection,
|
||||
});
|
||||
|
||||
editorRef.current.setState(newState);
|
||||
}
|
||||
}, [onSaveContent, status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (status !== "streaming") {
|
||||
userScrolledRef.current = false;
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current && content) {
|
||||
const currentContent = editorRef.current.state.doc.toString();
|
||||
|
||||
if (status === "streaming" || currentContent !== content) {
|
||||
const transaction = editorRef.current.state.update({
|
||||
changes: {
|
||||
from: 0,
|
||||
to: currentContent.length,
|
||||
insert: content,
|
||||
},
|
||||
annotations: [Transaction.remote.of(true)],
|
||||
});
|
||||
|
||||
editorRef.current.dispatch(transaction);
|
||||
|
||||
if (status === "streaming" && !userScrolledRef.current) {
|
||||
requestAnimationFrame(() => {
|
||||
const dom = editorRef.current?.scrollDOM;
|
||||
if (dom) {
|
||||
dom.scrollTo({ top: dom.scrollHeight });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [content, status]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="not-prose relative w-full min-h-[300px] pb-[calc(50dvh)]"
|
||||
ref={containerRef}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export const CodeEditor = memo(PureCodeEditor, (prevProps, nextProps) => {
|
||||
if (prevProps.status === "streaming" && nextProps.status === "streaming") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (prevProps.content !== nextProps.content) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (prevProps.status !== nextProps.status) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (prevProps.currentVersionIndex !== nextProps.currentVersionIndex) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
191
components/chat/console.tsx
Normal file
191
components/chat/console.tsx
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
import {
|
||||
type Dispatch,
|
||||
type SetStateAction,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useArtifactSelector } from "@/hooks/use-artifact";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
import { Spinner } from "../ui/spinner";
|
||||
import { CrossSmallIcon, TerminalWindowIcon } from "./icons";
|
||||
|
||||
export type ConsoleOutputContent = {
|
||||
type: "text" | "image";
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type ConsoleOutput = {
|
||||
id: string;
|
||||
status: "in_progress" | "loading_packages" | "completed" | "failed";
|
||||
contents: ConsoleOutputContent[];
|
||||
};
|
||||
|
||||
type ConsoleProps = {
|
||||
consoleOutputs: ConsoleOutput[];
|
||||
setConsoleOutputs: Dispatch<SetStateAction<ConsoleOutput[]>>;
|
||||
};
|
||||
|
||||
export function Console({ consoleOutputs, setConsoleOutputs }: ConsoleProps) {
|
||||
const [height, setHeight] = useState<number>(300);
|
||||
const [isResizing, setIsResizing] = useState(false);
|
||||
|
||||
const isArtifactVisible = useArtifactSelector((state) => state.isVisible);
|
||||
|
||||
const minHeight = 100;
|
||||
const maxHeight = 800;
|
||||
|
||||
const startResizing = useCallback(() => {
|
||||
setIsResizing(true);
|
||||
}, []);
|
||||
|
||||
const stopResizing = useCallback(() => {
|
||||
setIsResizing(false);
|
||||
}, []);
|
||||
|
||||
const resize = useCallback(
|
||||
(e: MouseEvent) => {
|
||||
if (isResizing) {
|
||||
const newHeight = window.innerHeight - e.clientY;
|
||||
if (newHeight >= minHeight && newHeight <= maxHeight) {
|
||||
setHeight(newHeight);
|
||||
}
|
||||
}
|
||||
},
|
||||
[isResizing]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener("mousemove", resize);
|
||||
window.addEventListener("mouseup", stopResizing);
|
||||
return () => {
|
||||
window.removeEventListener("mousemove", resize);
|
||||
window.removeEventListener("mouseup", stopResizing);
|
||||
};
|
||||
}, [resize, stopResizing]);
|
||||
|
||||
const consoleContainerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (consoleOutputs.length > 0) {
|
||||
consoleContainerRef.current?.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
}, [consoleOutputs.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isArtifactVisible) {
|
||||
setConsoleOutputs([]);
|
||||
}
|
||||
}, [isArtifactVisible, setConsoleOutputs]);
|
||||
|
||||
return consoleOutputs.length > 0 ? (
|
||||
<>
|
||||
<div
|
||||
aria-label="Resize console"
|
||||
aria-orientation="horizontal"
|
||||
aria-valuemax={maxHeight}
|
||||
aria-valuemin={minHeight}
|
||||
aria-valuenow={height}
|
||||
className="fixed z-50 h-2 w-full cursor-ns-resize"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "ArrowUp") {
|
||||
setHeight((prev) => Math.min(prev + 10, maxHeight));
|
||||
} else if (e.key === "ArrowDown") {
|
||||
setHeight((prev) => Math.max(prev - 10, minHeight));
|
||||
}
|
||||
}}
|
||||
onMouseDown={startResizing}
|
||||
role="slider"
|
||||
style={{ bottom: height - 4 }}
|
||||
tabIndex={0}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"fixed bottom-0 z-40 flex w-full flex-col overflow-x-hidden overflow-y-auto border-t border-border/50 bg-background",
|
||||
{ "select-none": isResizing }
|
||||
)}
|
||||
ref={consoleContainerRef}
|
||||
style={{ height }}
|
||||
>
|
||||
<div className="sticky top-0 z-50 flex h-10 w-full items-center justify-between border-b border-border/50 bg-background px-3">
|
||||
<div className="flex items-center gap-2.5 text-[13px] text-muted-foreground">
|
||||
<TerminalWindowIcon />
|
||||
<span>Console</span>
|
||||
</div>
|
||||
<Button
|
||||
className="size-7 text-muted-foreground/50 hover:text-foreground"
|
||||
onClick={() => setConsoleOutputs([])}
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
>
|
||||
<CrossSmallIcon />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="bg-background">
|
||||
{[...consoleOutputs].reverse().map((consoleOutput, index) => (
|
||||
<div
|
||||
className="flex border-b border-border/30 px-4 py-2.5 font-mono text-[12px] leading-relaxed"
|
||||
key={consoleOutput.id}
|
||||
>
|
||||
<div
|
||||
className={cn("w-10 shrink-0 tabular-nums", {
|
||||
"text-muted-foreground": [
|
||||
"in_progress",
|
||||
"loading_packages",
|
||||
].includes(consoleOutput.status),
|
||||
"text-emerald-500": consoleOutput.status === "completed",
|
||||
"text-red-400": consoleOutput.status === "failed",
|
||||
})}
|
||||
>
|
||||
[{consoleOutputs.length - index}]
|
||||
</div>
|
||||
{["in_progress", "loading_packages"].includes(
|
||||
consoleOutput.status
|
||||
) ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Spinner className="size-3.5" />
|
||||
<span className="text-muted-foreground">
|
||||
{consoleOutput.status === "in_progress"
|
||||
? "Initializing..."
|
||||
: consoleOutput.status === "loading_packages"
|
||||
? consoleOutput.contents.map((content) =>
|
||||
content.type === "text" ? content.value : null
|
||||
)
|
||||
: null}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="no-scrollbar flex w-full min-w-0 flex-col gap-2 overflow-x-auto text-foreground">
|
||||
{consoleOutput.contents.map((content) =>
|
||||
content.type === "image" ? (
|
||||
<picture
|
||||
key={`${consoleOutput.id}-img-${content.value.slice(0, 32)}`}
|
||||
>
|
||||
<img
|
||||
alt="output"
|
||||
className="max-w-full rounded-md"
|
||||
src={content.value}
|
||||
/>
|
||||
</picture>
|
||||
) : (
|
||||
<div
|
||||
className="w-full whitespace-pre-line break-words"
|
||||
key={`${consoleOutput.id}-txt-${content.value.slice(0, 32)}`}
|
||||
>
|
||||
{content.value}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null;
|
||||
}
|
||||
93
components/chat/create-artifact.tsx
Normal file
93
components/chat/create-artifact.tsx
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import type { UseChatHelpers } from "@ai-sdk/react";
|
||||
import type { DataUIPart } from "ai";
|
||||
import type { ComponentType, Dispatch, ReactNode, SetStateAction } from "react";
|
||||
import type { Suggestion } from "@/lib/db/schema";
|
||||
import type { ChatMessage, CustomUIDataTypes } from "@/lib/types";
|
||||
import type { UIArtifact } from "./artifact";
|
||||
|
||||
export type ArtifactActionContext<M = any> = {
|
||||
content: string;
|
||||
handleVersionChange: (type: "next" | "prev" | "toggle" | "latest") => void;
|
||||
currentVersionIndex: number;
|
||||
isCurrentVersion: boolean;
|
||||
mode: "edit" | "diff";
|
||||
metadata: M;
|
||||
setMetadata: Dispatch<SetStateAction<M>>;
|
||||
};
|
||||
|
||||
type ArtifactAction<M = any> = {
|
||||
icon: ReactNode;
|
||||
label?: string;
|
||||
description: string;
|
||||
onClick: (context: ArtifactActionContext<M>) => Promise<void> | void;
|
||||
isDisabled?: (context: ArtifactActionContext<M>) => boolean;
|
||||
};
|
||||
|
||||
export type ArtifactToolbarContext = {
|
||||
sendMessage: UseChatHelpers<ChatMessage>["sendMessage"];
|
||||
};
|
||||
|
||||
export type ArtifactToolbarItem = {
|
||||
description: string;
|
||||
icon: ReactNode;
|
||||
onClick: (context: ArtifactToolbarContext) => void;
|
||||
};
|
||||
|
||||
type ArtifactContent<M = any> = {
|
||||
title: string;
|
||||
content: string;
|
||||
mode: "edit" | "diff";
|
||||
isCurrentVersion: boolean;
|
||||
currentVersionIndex: number;
|
||||
status: "streaming" | "idle";
|
||||
suggestions: Suggestion[];
|
||||
onSaveContent: (updatedContent: string, debounce: boolean) => void;
|
||||
isInline: boolean;
|
||||
getDocumentContentById: (index: number) => string;
|
||||
isLoading: boolean;
|
||||
metadata: M;
|
||||
setMetadata: Dispatch<SetStateAction<M>>;
|
||||
};
|
||||
|
||||
type InitializeParameters<M = any> = {
|
||||
documentId: string;
|
||||
setMetadata: Dispatch<SetStateAction<M>>;
|
||||
};
|
||||
|
||||
type ArtifactConfig<T extends string, M = any> = {
|
||||
kind: T;
|
||||
description: string;
|
||||
content: ComponentType<ArtifactContent<M>>;
|
||||
actions: ArtifactAction<M>[];
|
||||
toolbar: ArtifactToolbarItem[];
|
||||
initialize?: (parameters: InitializeParameters<M>) => void;
|
||||
onStreamPart: (args: {
|
||||
setMetadata: Dispatch<SetStateAction<M>>;
|
||||
setArtifact: Dispatch<SetStateAction<UIArtifact>>;
|
||||
streamPart: DataUIPart<CustomUIDataTypes>;
|
||||
}) => void;
|
||||
};
|
||||
|
||||
export class Artifact<T extends string, M = any> {
|
||||
readonly kind: T;
|
||||
readonly description: string;
|
||||
readonly content: ComponentType<ArtifactContent<M>>;
|
||||
readonly actions: ArtifactAction<M>[];
|
||||
readonly toolbar: ArtifactToolbarItem[];
|
||||
readonly initialize?: (parameters: InitializeParameters) => void;
|
||||
readonly onStreamPart: (args: {
|
||||
setMetadata: Dispatch<SetStateAction<M>>;
|
||||
setArtifact: Dispatch<SetStateAction<UIArtifact>>;
|
||||
streamPart: DataUIPart<CustomUIDataTypes>;
|
||||
}) => void;
|
||||
|
||||
constructor(config: ArtifactConfig<T, M>) {
|
||||
this.kind = config.kind;
|
||||
this.description = config.description;
|
||||
this.content = config.content;
|
||||
this.actions = config.actions || [];
|
||||
this.toolbar = config.toolbar || [];
|
||||
this.initialize = config.initialize || (async () => ({}));
|
||||
this.onStreamPart = config.onStreamPart;
|
||||
}
|
||||
}
|
||||
91
components/chat/data-stream-handler.tsx
Normal file
91
components/chat/data-stream-handler.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { unstable_serialize } from "swr/infinite";
|
||||
import { initialArtifactData, useArtifact } from "@/hooks/use-artifact";
|
||||
import { artifactDefinitions } from "./artifact";
|
||||
import { useDataStream } from "./data-stream-provider";
|
||||
import { getChatHistoryPaginationKey } from "./sidebar-history";
|
||||
|
||||
export function DataStreamHandler() {
|
||||
const { dataStream, setDataStream } = useDataStream();
|
||||
const { mutate } = useSWRConfig();
|
||||
|
||||
const { artifact, setArtifact, setMetadata } = useArtifact();
|
||||
|
||||
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));
|
||||
continue;
|
||||
}
|
||||
const artifactDefinition = artifactDefinitions.find(
|
||||
(currentArtifactDefinition) =>
|
||||
currentArtifactDefinition.kind === artifact.kind
|
||||
);
|
||||
|
||||
if (artifactDefinition?.onStreamPart) {
|
||||
artifactDefinition.onStreamPart({
|
||||
streamPart: delta,
|
||||
setArtifact,
|
||||
setMetadata,
|
||||
});
|
||||
}
|
||||
|
||||
setArtifact((draftArtifact) => {
|
||||
if (!draftArtifact) {
|
||||
return { ...initialArtifactData, status: "streaming" };
|
||||
}
|
||||
|
||||
switch (delta.type) {
|
||||
case "data-id":
|
||||
return {
|
||||
...draftArtifact,
|
||||
documentId: delta.data,
|
||||
status: "streaming",
|
||||
};
|
||||
|
||||
case "data-title":
|
||||
return {
|
||||
...draftArtifact,
|
||||
title: delta.data,
|
||||
status: "streaming",
|
||||
};
|
||||
|
||||
case "data-kind":
|
||||
return {
|
||||
...draftArtifact,
|
||||
kind: delta.data,
|
||||
status: "streaming",
|
||||
};
|
||||
|
||||
case "data-clear":
|
||||
return {
|
||||
...draftArtifact,
|
||||
content: "",
|
||||
status: "streaming",
|
||||
};
|
||||
|
||||
case "data-finish":
|
||||
return {
|
||||
...draftArtifact,
|
||||
status: "idle",
|
||||
};
|
||||
|
||||
default:
|
||||
return draftArtifact;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [dataStream, setArtifact, setMetadata, artifact, setDataStream, mutate]);
|
||||
|
||||
return null;
|
||||
}
|
||||
41
components/chat/data-stream-provider.tsx
Normal file
41
components/chat/data-stream-provider.tsx
Normal 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;
|
||||
}
|
||||
114
components/chat/diffview.tsx
Normal file
114
components/chat/diffview.tsx
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import OrderedMap from "orderedmap";
|
||||
import {
|
||||
DOMParser,
|
||||
type MarkSpec,
|
||||
type Node as ProsemirrorNode,
|
||||
Schema,
|
||||
} from "prosemirror-model";
|
||||
import { schema } from "prosemirror-schema-basic";
|
||||
import { addListNodes } from "prosemirror-schema-list";
|
||||
import { EditorState } from "prosemirror-state";
|
||||
import { EditorView } from "prosemirror-view";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { renderToString } from "react-dom/server";
|
||||
|
||||
import { MessageResponse } from "@/components/ai-elements/message";
|
||||
import { DiffType, diffEditor } from "@/lib/editor/diff";
|
||||
|
||||
const diffSchema = new Schema({
|
||||
nodes: addListNodes(schema.spec.nodes, "paragraph block*", "block"),
|
||||
marks: OrderedMap.from({
|
||||
...schema.spec.marks.toObject(),
|
||||
diffMark: {
|
||||
attrs: { type: { default: "" } },
|
||||
toDOM(mark) {
|
||||
let className = "";
|
||||
|
||||
switch (mark.attrs.type) {
|
||||
case DiffType.Inserted:
|
||||
className =
|
||||
"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 rounded-sm px-0.5 -mx-0.5";
|
||||
break;
|
||||
case DiffType.Deleted:
|
||||
className =
|
||||
"bg-red-500/15 line-through text-red-600 dark:text-red-400 rounded-sm px-0.5 -mx-0.5 opacity-70";
|
||||
break;
|
||||
default:
|
||||
className = "";
|
||||
}
|
||||
return ["span", { class: className }, 0];
|
||||
},
|
||||
} as MarkSpec,
|
||||
}),
|
||||
});
|
||||
|
||||
function computeDiff(oldDoc: ProsemirrorNode, newDoc: ProsemirrorNode) {
|
||||
return diffEditor(diffSchema, oldDoc.toJSON(), newDoc.toJSON());
|
||||
}
|
||||
|
||||
type DiffEditorProps = {
|
||||
oldContent: string;
|
||||
newContent: string;
|
||||
};
|
||||
|
||||
export const DiffView = ({ oldContent, newContent }: DiffEditorProps) => {
|
||||
const editorRef = useRef<HTMLDivElement>(null);
|
||||
const viewRef = useRef<EditorView | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current && !viewRef.current) {
|
||||
const parser = DOMParser.fromSchema(diffSchema);
|
||||
|
||||
const oldHtmlContent = renderToString(
|
||||
<MessageResponse>{oldContent}</MessageResponse>
|
||||
);
|
||||
const newHtmlContent = renderToString(
|
||||
<MessageResponse>{newContent}</MessageResponse>
|
||||
);
|
||||
|
||||
const oldContainer = document.createElement("div");
|
||||
oldContainer.innerHTML = oldHtmlContent;
|
||||
|
||||
const newContainer = document.createElement("div");
|
||||
newContainer.innerHTML = newHtmlContent;
|
||||
|
||||
const oldDoc = parser.parse(oldContainer);
|
||||
const newDoc = parser.parse(newContainer);
|
||||
|
||||
const diffedDoc = computeDiff(oldDoc, newDoc);
|
||||
|
||||
const state = EditorState.create({
|
||||
doc: diffedDoc,
|
||||
plugins: [],
|
||||
});
|
||||
|
||||
viewRef.current = new EditorView(editorRef.current, {
|
||||
state,
|
||||
editable: () => false,
|
||||
});
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const firstDiff = editorRef.current?.querySelector(
|
||||
"[class*='bg-emerald'], [class*='bg-red']"
|
||||
);
|
||||
if (firstDiff) {
|
||||
firstDiff.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (viewRef.current) {
|
||||
viewRef.current.destroy();
|
||||
viewRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [oldContent, newContent]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="diff-editor prose dark:prose-invert prose-neutral relative max-w-none"
|
||||
ref={editorRef}
|
||||
/>
|
||||
);
|
||||
};
|
||||
308
components/chat/document-preview.tsx
Normal file
308
components/chat/document-preview.tsx
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
"use client";
|
||||
|
||||
import equal from "fast-deep-equal";
|
||||
import {
|
||||
type MouseEvent,
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from "react";
|
||||
import useSWR from "swr";
|
||||
import { useArtifact } from "@/hooks/use-artifact";
|
||||
import type { Document } from "@/lib/db/schema";
|
||||
import { cn, fetcher } from "@/lib/utils";
|
||||
import type { ArtifactKind, UIArtifact } from "./artifact";
|
||||
import { CodeEditor } from "./code-editor";
|
||||
import { InlineDocumentSkeleton } from "./document-skeleton";
|
||||
import {
|
||||
CodeIcon,
|
||||
FileIcon,
|
||||
FullscreenIcon,
|
||||
ImageIcon,
|
||||
LoaderIcon,
|
||||
} from "./icons";
|
||||
import { ImageEditor } from "./image-editor";
|
||||
import { SpreadsheetEditor } from "./sheet-editor";
|
||||
import { Editor } from "./text-editor";
|
||||
|
||||
type DocumentToolOutput = {
|
||||
id: string;
|
||||
title: string;
|
||||
kind: ArtifactKind;
|
||||
content?: string;
|
||||
};
|
||||
|
||||
type DocumentPreviewProps = {
|
||||
isReadonly: boolean;
|
||||
result?: Partial<DocumentToolOutput>;
|
||||
args?: Partial<DocumentToolOutput> & { isUpdate?: boolean };
|
||||
};
|
||||
|
||||
export function DocumentPreview({
|
||||
isReadonly: _isReadonly,
|
||||
result,
|
||||
args,
|
||||
}: DocumentPreviewProps) {
|
||||
const { artifact, setArtifact } = useArtifact();
|
||||
|
||||
const { data: documents, isLoading: isDocumentsFetching } = useSWR<
|
||||
Document[]
|
||||
>(
|
||||
result
|
||||
? `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/document?id=${result.id}`
|
||||
: null,
|
||||
fetcher
|
||||
);
|
||||
|
||||
const previewDocument = useMemo(() => documents?.[0], [documents]);
|
||||
const hitboxRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const boundingBox = hitboxRef.current?.getBoundingClientRect();
|
||||
|
||||
if (artifact.documentId && boundingBox) {
|
||||
setArtifact((currentArtifact) => ({
|
||||
...currentArtifact,
|
||||
boundingBox: {
|
||||
left: boundingBox.x,
|
||||
top: boundingBox.y,
|
||||
width: boundingBox.width,
|
||||
height: boundingBox.height,
|
||||
},
|
||||
}));
|
||||
}
|
||||
}, [artifact.documentId, setArtifact]);
|
||||
|
||||
if (isDocumentsFetching) {
|
||||
const kind = result?.kind ?? args?.kind ?? artifact.kind;
|
||||
const title = result?.title ?? args?.title ?? artifact.title;
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-[450px]">
|
||||
{title ? (
|
||||
<DocumentHeader isStreaming={true} kind={kind} title={title} />
|
||||
) : (
|
||||
<div className="flex flex-row items-center justify-between gap-2 rounded-t-2xl border border-b-0 border-border/50 px-4 py-3 dark:bg-muted">
|
||||
<div className="flex flex-row items-center gap-2.5">
|
||||
<div className="size-3.5 animate-pulse rounded bg-muted-foreground/15" />
|
||||
<div className="h-3.5 w-24 animate-pulse rounded bg-muted-foreground/15" />
|
||||
</div>
|
||||
<div className="w-8" />
|
||||
</div>
|
||||
)}
|
||||
<div className="h-[257px] overflow-hidden rounded-b-2xl border border-t-0 border-border/50 bg-muted p-6">
|
||||
<InlineDocumentSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const document: Document | null = previewDocument
|
||||
? previewDocument
|
||||
: artifact.status === "streaming"
|
||||
? {
|
||||
title: artifact.title,
|
||||
kind: artifact.kind,
|
||||
content: artifact.content,
|
||||
id: artifact.documentId,
|
||||
createdAt: new Date(),
|
||||
userId: "noop",
|
||||
}
|
||||
: null;
|
||||
|
||||
if (!document) {
|
||||
return <LoadingSkeleton artifactKind={artifact.kind} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative w-full max-w-[450px] cursor-pointer">
|
||||
<HitboxLayer
|
||||
hitboxRef={hitboxRef}
|
||||
result={result}
|
||||
setArtifact={setArtifact}
|
||||
/>
|
||||
<DocumentHeader
|
||||
isStreaming={artifact.status === "streaming"}
|
||||
kind={document.kind}
|
||||
title={document.title}
|
||||
/>
|
||||
<DocumentContent document={document} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const LoadingSkeleton = ({ artifactKind }: { artifactKind: ArtifactKind }) => (
|
||||
<div className="w-full max-w-[450px]">
|
||||
<div className="flex flex-row items-center justify-between gap-2 rounded-t-2xl border border-b-0 border-border/50 px-4 py-3 dark:bg-muted">
|
||||
<div className="flex flex-row items-center gap-2.5">
|
||||
<div className="size-3.5 animate-pulse rounded bg-muted-foreground/15" />
|
||||
<div className="h-3.5 w-24 animate-pulse rounded bg-muted-foreground/15" />
|
||||
</div>
|
||||
<div className="w-8" />
|
||||
</div>
|
||||
{artifactKind === "image" ? (
|
||||
<div className="overflow-hidden rounded-b-2xl border border-t-0 border-border/50 bg-muted">
|
||||
<div className="h-[257px] w-full animate-pulse bg-muted-foreground/10" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-[257px] overflow-hidden rounded-b-2xl border border-t-0 border-border/50 bg-muted p-6">
|
||||
<InlineDocumentSkeleton />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
const PureHitboxLayer = ({
|
||||
hitboxRef,
|
||||
result,
|
||||
setArtifact,
|
||||
}: {
|
||||
hitboxRef: React.RefObject<HTMLDivElement>;
|
||||
result?: Partial<DocumentToolOutput>;
|
||||
setArtifact: (
|
||||
updaterFn: UIArtifact | ((currentArtifact: UIArtifact) => UIArtifact)
|
||||
) => void;
|
||||
}) => {
|
||||
const handleClick = useCallback(
|
||||
(event: MouseEvent<HTMLElement>) => {
|
||||
const boundingBox = event.currentTarget.getBoundingClientRect();
|
||||
|
||||
setArtifact((artifact) => ({
|
||||
...artifact,
|
||||
...(result?.id && { documentId: result.id }),
|
||||
...(result?.title && { title: result.title }),
|
||||
...(result?.kind && { kind: result.kind }),
|
||||
isVisible: true,
|
||||
boundingBox: {
|
||||
left: boundingBox.x,
|
||||
top: boundingBox.y,
|
||||
width: boundingBox.width,
|
||||
height: boundingBox.height,
|
||||
},
|
||||
}));
|
||||
},
|
||||
[setArtifact, result]
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="absolute top-0 left-0 z-10 size-full rounded-xl"
|
||||
onClick={handleClick}
|
||||
ref={hitboxRef}
|
||||
role="presentation"
|
||||
>
|
||||
<div className="flex w-full items-center justify-end p-4">
|
||||
<div className="absolute top-[13px] right-[9px] rounded-lg p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
|
||||
<FullscreenIcon />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const HitboxLayer = memo(PureHitboxLayer, (prevProps, nextProps) => {
|
||||
if (!equal(prevProps.result, nextProps.result)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const PureDocumentHeader = ({
|
||||
title,
|
||||
kind,
|
||||
isStreaming,
|
||||
}: {
|
||||
title: string;
|
||||
kind: ArtifactKind;
|
||||
isStreaming: boolean;
|
||||
}) => (
|
||||
<div className="flex flex-row items-center justify-between gap-2 rounded-t-2xl border border-b-0 border-border/50 px-4 py-3 dark:bg-muted">
|
||||
<div className="flex flex-row items-center gap-2.5">
|
||||
<div className="text-muted-foreground">
|
||||
{isStreaming ? (
|
||||
<div className="animate-spin">
|
||||
<LoaderIcon size={14} />
|
||||
</div>
|
||||
) : kind === "image" ? (
|
||||
<ImageIcon size={14} />
|
||||
) : kind === "code" ? (
|
||||
<CodeIcon size={14} />
|
||||
) : (
|
||||
<FileIcon size={14} />
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm font-medium">{title}</div>
|
||||
</div>
|
||||
<div className="w-8" />
|
||||
</div>
|
||||
);
|
||||
|
||||
const DocumentHeader = memo(PureDocumentHeader, (prevProps, nextProps) => {
|
||||
if (prevProps.title !== nextProps.title) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.isStreaming !== nextProps.isStreaming) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
const DocumentContent = ({ document }: { document: Document }) => {
|
||||
const { artifact } = useArtifact();
|
||||
|
||||
const containerClassName = cn(
|
||||
"h-[257px] overflow-hidden rounded-b-2xl border border-t-0 border-border/50 dark:bg-muted",
|
||||
{
|
||||
"p-4 sm:px-10 sm:py-10": document.kind === "text",
|
||||
"p-0": document.kind === "code",
|
||||
}
|
||||
);
|
||||
|
||||
const commonProps = {
|
||||
content: document.content ?? "",
|
||||
isCurrentVersion: true,
|
||||
currentVersionIndex: 0,
|
||||
status: artifact.status,
|
||||
saveContent: () => null,
|
||||
suggestions: [],
|
||||
};
|
||||
|
||||
const handleSaveContent = () => null;
|
||||
|
||||
return (
|
||||
<div className={cn(containerClassName, "relative")}>
|
||||
{document.kind === "text" ? (
|
||||
<Editor {...commonProps} onSaveContent={handleSaveContent} />
|
||||
) : document.kind === "code" ? (
|
||||
<div className="relative flex w-full flex-1">
|
||||
<div className="absolute inset-0">
|
||||
<CodeEditor {...commonProps} onSaveContent={handleSaveContent} />
|
||||
</div>
|
||||
</div>
|
||||
) : document.kind === "sheet" ? (
|
||||
<div className="relative flex size-full flex-1 p-4">
|
||||
<div className="absolute inset-0">
|
||||
<SpreadsheetEditor {...commonProps} />
|
||||
</div>
|
||||
</div>
|
||||
) : document.kind === "image" ? (
|
||||
<ImageEditor
|
||||
content={document.content ?? ""}
|
||||
currentVersionIndex={0}
|
||||
isCurrentVersion={true}
|
||||
isInline={true}
|
||||
status={artifact.status}
|
||||
title={document.title}
|
||||
/>
|
||||
) : null}
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-muted to-transparent dark:from-muted" />
|
||||
{document.kind === "code" && (
|
||||
<div className="pointer-events-none absolute inset-y-0 right-0 w-12 bg-gradient-to-l from-muted to-transparent dark:from-muted" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
38
components/chat/document-skeleton.tsx
Normal file
38
components/chat/document-skeleton.tsx
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
"use client";
|
||||
|
||||
import type { ArtifactKind } from "./artifact";
|
||||
|
||||
export const DocumentSkeleton = ({
|
||||
artifactKind,
|
||||
}: {
|
||||
artifactKind: ArtifactKind;
|
||||
}) => {
|
||||
return artifactKind === "image" ? (
|
||||
<div className="flex h-[calc(100dvh-60px)] w-full flex-col items-center justify-center gap-4">
|
||||
<div className="size-96 animate-pulse rounded-lg bg-muted-foreground/10" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex w-full flex-col gap-4 px-4 py-8 md:px-20 md:py-12">
|
||||
<div className="h-8 w-2/5 animate-pulse rounded-md bg-muted-foreground/10" />
|
||||
<div className="h-4 w-full animate-pulse rounded-md bg-muted-foreground/8" />
|
||||
<div className="h-4 w-full animate-pulse rounded-md bg-muted-foreground/8" />
|
||||
<div className="h-4 w-3/4 animate-pulse rounded-md bg-muted-foreground/8" />
|
||||
<div className="h-4 w-0 rounded-md" />
|
||||
<div className="h-6 w-1/3 animate-pulse rounded-md bg-muted-foreground/10" />
|
||||
<div className="h-4 w-5/6 animate-pulse rounded-md bg-muted-foreground/8" />
|
||||
<div className="h-4 w-2/3 animate-pulse rounded-md bg-muted-foreground/8" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const InlineDocumentSkeleton = () => {
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<div className="h-3.5 w-48 animate-pulse rounded bg-muted-foreground/10" />
|
||||
<div className="h-3.5 w-3/4 animate-pulse rounded bg-muted-foreground/8" />
|
||||
<div className="h-3.5 w-1/2 animate-pulse rounded bg-muted-foreground/8" />
|
||||
<div className="h-3.5 w-64 animate-pulse rounded bg-muted-foreground/8" />
|
||||
<div className="h-3.5 w-40 animate-pulse rounded bg-muted-foreground/8" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
161
components/chat/document.tsx
Normal file
161
components/chat/document.tsx
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
import { memo } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useArtifact } from "@/hooks/use-artifact";
|
||||
import type { ArtifactKind } from "./artifact";
|
||||
import { FileIcon, LoaderIcon, MessageIcon, PencilEditIcon } from "./icons";
|
||||
|
||||
const getActionText = (
|
||||
type: "create" | "update" | "request-suggestions",
|
||||
tense: "present" | "past"
|
||||
) => {
|
||||
switch (type) {
|
||||
case "create":
|
||||
return tense === "present" ? "Creating" : "Created";
|
||||
case "update":
|
||||
return tense === "present" ? "Updating" : "Updated";
|
||||
case "request-suggestions":
|
||||
return tense === "present"
|
||||
? "Adding suggestions"
|
||||
: "Added suggestions to";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
type DocumentToolResultProps = {
|
||||
type: "create" | "update" | "request-suggestions";
|
||||
result: { id: string; title: string; kind: ArtifactKind };
|
||||
isReadonly: boolean;
|
||||
};
|
||||
|
||||
function PureDocumentToolResult({
|
||||
type,
|
||||
result,
|
||||
isReadonly,
|
||||
}: DocumentToolResultProps) {
|
||||
const { setArtifact } = useArtifact();
|
||||
|
||||
return (
|
||||
<button
|
||||
className="flex w-fit cursor-pointer flex-row items-center gap-2 rounded-xl border bg-background px-3 py-2"
|
||||
onClick={(event) => {
|
||||
if (isReadonly) {
|
||||
toast.error(
|
||||
"Viewing files in shared chats is currently not supported."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
|
||||
const boundingBox = {
|
||||
top: rect.top,
|
||||
left: rect.left,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
};
|
||||
|
||||
setArtifact((currentArtifact) => ({
|
||||
documentId: result.id,
|
||||
kind: result.kind,
|
||||
content: currentArtifact.content,
|
||||
title: result.title,
|
||||
isVisible: true,
|
||||
status: "idle",
|
||||
boundingBox,
|
||||
}));
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<div className="text-muted-foreground">
|
||||
{type === "create" ? (
|
||||
<FileIcon />
|
||||
) : type === "update" ? (
|
||||
<PencilEditIcon />
|
||||
) : type === "request-suggestions" ? (
|
||||
<MessageIcon />
|
||||
) : null}
|
||||
</div>
|
||||
<div className="text-left">
|
||||
{`${getActionText(type, "past")} "${result.title}"`}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export const DocumentToolResult = memo(PureDocumentToolResult, () => true);
|
||||
|
||||
type DocumentToolCallProps = {
|
||||
type: "create" | "update" | "request-suggestions";
|
||||
args:
|
||||
| { title: string; kind: ArtifactKind }
|
||||
| { id: string; description: string }
|
||||
| { documentId: string };
|
||||
isReadonly: boolean;
|
||||
};
|
||||
|
||||
function PureDocumentToolCall({
|
||||
type,
|
||||
args,
|
||||
isReadonly,
|
||||
}: DocumentToolCallProps) {
|
||||
const { setArtifact } = useArtifact();
|
||||
|
||||
return (
|
||||
<button
|
||||
className="cursor pointer flex w-fit flex-row items-start justify-between gap-3 rounded-xl border px-3 py-2"
|
||||
onClick={(event) => {
|
||||
if (isReadonly) {
|
||||
toast.error(
|
||||
"Viewing files in shared chats is currently not supported."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
|
||||
const boundingBox = {
|
||||
top: rect.top,
|
||||
left: rect.left,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
};
|
||||
|
||||
setArtifact((currentArtifact) => ({
|
||||
...currentArtifact,
|
||||
isVisible: true,
|
||||
boundingBox,
|
||||
}));
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<div className="flex flex-row items-start gap-3">
|
||||
<div className="mt-1 text-neutral-500">
|
||||
{type === "create" ? (
|
||||
<FileIcon />
|
||||
) : type === "update" ? (
|
||||
<PencilEditIcon />
|
||||
) : type === "request-suggestions" ? (
|
||||
<MessageIcon />
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="text-left">
|
||||
{`${getActionText(type, "present")} ${
|
||||
type === "create" && "title" in args && args.title
|
||||
? `"${args.title}"`
|
||||
: type === "update" && "description" in args
|
||||
? `"${args.description}"`
|
||||
: type === "request-suggestions"
|
||||
? "for document"
|
||||
: ""
|
||||
}`}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-1 animate-spin">{<LoaderIcon />}</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export const DocumentToolCall = memo(PureDocumentToolCall, () => true);
|
||||
24
components/chat/greeting.tsx
Normal file
24
components/chat/greeting.tsx
Normal 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
1213
components/chat/icons.tsx
Normal file
File diff suppressed because it is too large
Load diff
48
components/chat/image-editor.tsx
Normal file
48
components/chat/image-editor.tsx
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import cn from "classnames";
|
||||
import { LoaderIcon } from "./icons";
|
||||
|
||||
type ImageEditorProps = {
|
||||
title: string;
|
||||
content: string;
|
||||
isCurrentVersion: boolean;
|
||||
currentVersionIndex: number;
|
||||
status: string;
|
||||
isInline: boolean;
|
||||
};
|
||||
|
||||
export function ImageEditor({
|
||||
title,
|
||||
content,
|
||||
status,
|
||||
isInline,
|
||||
}: ImageEditorProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn("flex w-full flex-row items-center justify-center", {
|
||||
"h-[calc(100dvh-60px)]": !isInline,
|
||||
"h-[200px]": isInline,
|
||||
})}
|
||||
>
|
||||
{status === "streaming" ? (
|
||||
<div className="flex flex-row items-center gap-4">
|
||||
{!isInline && (
|
||||
<div className="animate-spin">
|
||||
<LoaderIcon />
|
||||
</div>
|
||||
)}
|
||||
<div>Generating Image...</div>
|
||||
</div>
|
||||
) : (
|
||||
<picture>
|
||||
<img
|
||||
alt={title}
|
||||
className={cn("h-fit w-full max-w-[800px]", {
|
||||
"p-0 md:p-20": !isInline,
|
||||
})}
|
||||
src={`data:image/png;base64,${content}`}
|
||||
/>
|
||||
</picture>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
207
components/chat/message-actions.tsx
Normal file
207
components/chat/message-actions.tsx
Normal 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;
|
||||
}
|
||||
);
|
||||
33
components/chat/message-editor.tsx
Normal file
33
components/chat/message-editor.tsx
Normal 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();
|
||||
}
|
||||
37
components/chat/message-reasoning.tsx
Normal file
37
components/chat/message-reasoning.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
387
components/chat/message.tsx
Normal file
387
components/chat/message.tsx
Normal file
|
|
@ -0,0 +1,387 @@
|
|||
"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,
|
||||
ToolOutput,
|
||||
} from "../ai-elements/tool";
|
||||
import { useDataStream } from "./data-stream-provider";
|
||||
import { DocumentToolResult } from "./document";
|
||||
import { DocumentPreview } from "./document-preview";
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "tool-createDocument") {
|
||||
const { toolCallId } = part;
|
||||
|
||||
if (part.output && "error" in part.output) {
|
||||
return (
|
||||
<div
|
||||
className="rounded-lg border border-red-200 bg-red-50 p-4 text-red-500 dark:bg-red-950/50"
|
||||
key={toolCallId}
|
||||
>
|
||||
Error creating document: {String(part.output.error)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DocumentPreview
|
||||
isReadonly={isReadonly}
|
||||
key={toolCallId}
|
||||
result={part.output}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "tool-updateDocument") {
|
||||
const { toolCallId } = part;
|
||||
|
||||
if (part.output && "error" in part.output) {
|
||||
return (
|
||||
<div
|
||||
className="rounded-lg border border-red-200 bg-red-50 p-4 text-red-500 dark:bg-red-950/50"
|
||||
key={toolCallId}
|
||||
>
|
||||
Error updating document: {String(part.output.error)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative" key={toolCallId}>
|
||||
<DocumentPreview
|
||||
args={{ ...part.output, isUpdate: true }}
|
||||
isReadonly={isReadonly}
|
||||
result={part.output}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "tool-requestSuggestions") {
|
||||
const { toolCallId, state } = part;
|
||||
|
||||
return (
|
||||
<Tool
|
||||
className="w-[min(100%,450px)]"
|
||||
defaultOpen={true}
|
||||
key={toolCallId}
|
||||
>
|
||||
<ToolHeader state={state} type="tool-requestSuggestions" />
|
||||
<ToolContent>
|
||||
{state === "input-available" && <ToolInput input={part.input} />}
|
||||
{state === "output-available" && (
|
||||
<ToolOutput
|
||||
errorText={undefined}
|
||||
output={
|
||||
"error" in part.output ? (
|
||||
<div className="rounded border p-2 text-red-500">
|
||||
Error: {String(part.output.error)}
|
||||
</div>
|
||||
) : (
|
||||
<DocumentToolResult
|
||||
isReadonly={isReadonly}
|
||||
result={part.output}
|
||||
type="request-suggestions"
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</ToolContent>
|
||||
</Tool>
|
||||
);
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
};
|
||||
129
components/chat/messages.tsx
Normal file
129
components/chat/messages.tsx
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
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;
|
||||
isArtifactVisible: boolean;
|
||||
isLoading?: boolean;
|
||||
selectedModelId: string;
|
||||
onEditMessage?: (message: ChatMessage) => void;
|
||||
};
|
||||
|
||||
function PureMessages({
|
||||
addToolApprovalResponse,
|
||||
chatId,
|
||||
status,
|
||||
votes,
|
||||
messages,
|
||||
setMessages,
|
||||
regenerate,
|
||||
isReadonly,
|
||||
isArtifactVisible,
|
||||
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}
|
||||
style={isArtifactVisible ? { scrollbarWidth: "none" } : undefined}
|
||||
>
|
||||
<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;
|
||||
816
components/chat/multimodal-input.tsx
Normal file
816
components/chat/multimodal-input.tsx
Normal 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);
|
||||
56
components/chat/preview-attachment.tsx
Normal file
56
components/chat/preview-attachment.tsx
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import Image from "next/image";
|
||||
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") ? (
|
||||
<Image
|
||||
alt={name ?? "attachment"}
|
||||
className="size-full object-cover"
|
||||
height={96}
|
||||
src={url}
|
||||
width={96}
|
||||
/>
|
||||
) : (
|
||||
<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>
|
||||
);
|
||||
};
|
||||
59
components/chat/preview.tsx
Normal file
59
components/chat/preview.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
141
components/chat/sheet-editor.tsx
Normal file
141
components/chat/sheet-editor.tsx
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
"use client";
|
||||
|
||||
import { useTheme } from "next-themes";
|
||||
import { parse, unparse } from "papaparse";
|
||||
import { memo, useEffect, useMemo, useState } from "react";
|
||||
import DataGrid, { textEditor } from "react-data-grid";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import "react-data-grid/lib/styles.css";
|
||||
|
||||
type SheetEditorProps = {
|
||||
content: string;
|
||||
saveContent: (content: string, isCurrentVersion: boolean) => void;
|
||||
currentVersionIndex: number;
|
||||
isCurrentVersion: boolean;
|
||||
status: string;
|
||||
};
|
||||
|
||||
const MIN_ROWS = 50;
|
||||
const MIN_COLS = 26;
|
||||
|
||||
const PureSpreadsheetEditor = ({ content, saveContent }: SheetEditorProps) => {
|
||||
const { resolvedTheme } = useTheme();
|
||||
|
||||
const parseData = useMemo(() => {
|
||||
if (!content) {
|
||||
return new Array(MIN_ROWS).fill(new Array(MIN_COLS).fill(""));
|
||||
}
|
||||
const result = parse<string[]>(content, { skipEmptyLines: true });
|
||||
|
||||
const paddedData = result.data.map((row) => {
|
||||
const paddedRow = [...row];
|
||||
while (paddedRow.length < MIN_COLS) {
|
||||
paddedRow.push("");
|
||||
}
|
||||
return paddedRow;
|
||||
});
|
||||
|
||||
while (paddedData.length < MIN_ROWS) {
|
||||
paddedData.push(new Array(MIN_COLS).fill(""));
|
||||
}
|
||||
|
||||
return paddedData;
|
||||
}, [content]);
|
||||
|
||||
const columns = useMemo(() => {
|
||||
const rowNumberColumn = {
|
||||
key: "rowNumber",
|
||||
name: "",
|
||||
frozen: true,
|
||||
width: 50,
|
||||
renderCell: ({ rowIdx }: { rowIdx: number }) => rowIdx + 1,
|
||||
cellClass: "border-t border-r dark:bg-neutral-950 dark:text-neutral-50",
|
||||
headerCellClass:
|
||||
"border-t border-r dark:bg-neutral-900 dark:text-neutral-50",
|
||||
};
|
||||
|
||||
const dataColumns = Array.from({ length: MIN_COLS }, (_, i) => ({
|
||||
key: i.toString(),
|
||||
name: String.fromCharCode(65 + i),
|
||||
renderEditCell: textEditor,
|
||||
width: 120,
|
||||
cellClass: cn("border-t dark:bg-neutral-950 dark:text-neutral-50", {
|
||||
"border-l": i !== 0,
|
||||
}),
|
||||
headerCellClass: cn("border-t dark:bg-neutral-900 dark:text-neutral-50", {
|
||||
"border-l": i !== 0,
|
||||
}),
|
||||
}));
|
||||
|
||||
return [rowNumberColumn, ...dataColumns];
|
||||
}, []);
|
||||
|
||||
const initialRows = useMemo(() => {
|
||||
return parseData.map((row, rowIndex) => {
|
||||
const rowData: Record<string, string | number> = {
|
||||
id: rowIndex,
|
||||
rowNumber: rowIndex + 1,
|
||||
};
|
||||
|
||||
columns.slice(1).forEach((col, colIndex) => {
|
||||
rowData[col.key] = row[colIndex] || "";
|
||||
});
|
||||
|
||||
return rowData;
|
||||
});
|
||||
}, [parseData, columns]);
|
||||
|
||||
const [localRows, setLocalRows] = useState(initialRows);
|
||||
|
||||
useEffect(() => {
|
||||
setLocalRows(initialRows);
|
||||
}, [initialRows]);
|
||||
|
||||
const generateCsv = (data: string[][]) => {
|
||||
return unparse(data);
|
||||
};
|
||||
|
||||
const handleRowsChange = (newRows: Record<string, string | number>[]) => {
|
||||
setLocalRows(newRows);
|
||||
|
||||
const updatedData = newRows.map((row) => {
|
||||
return columns.slice(1).map((col) => String(row[col.key] ?? ""));
|
||||
});
|
||||
|
||||
const newCsvContent = generateCsv(updatedData);
|
||||
saveContent(newCsvContent, true);
|
||||
};
|
||||
|
||||
return (
|
||||
<DataGrid
|
||||
className={resolvedTheme === "dark" ? "rdg-dark" : "rdg-light"}
|
||||
columns={columns}
|
||||
defaultColumnOptions={{
|
||||
resizable: true,
|
||||
sortable: true,
|
||||
}}
|
||||
enableVirtualization
|
||||
onCellClick={(args) => {
|
||||
if (args.column.key !== "rowNumber") {
|
||||
args.selectCell(true);
|
||||
}
|
||||
}}
|
||||
onRowsChange={handleRowsChange}
|
||||
rows={localRows}
|
||||
style={{ height: "100%" }}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
function areEqual(prevProps: SheetEditorProps, nextProps: SheetEditorProps) {
|
||||
return (
|
||||
prevProps.currentVersionIndex === nextProps.currentVersionIndex &&
|
||||
prevProps.isCurrentVersion === nextProps.isCurrentVersion &&
|
||||
!(prevProps.status === "streaming" && nextProps.status === "streaming") &&
|
||||
prevProps.content === nextProps.content &&
|
||||
prevProps.saveContent === nextProps.saveContent
|
||||
);
|
||||
}
|
||||
|
||||
export const SpreadsheetEditor = memo(PureSpreadsheetEditor, areEqual);
|
||||
205
components/chat/shell.tsx
Normal file
205
components/chat/shell.tsx
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { useActiveChat } from "@/hooks/use-active-chat";
|
||||
import {
|
||||
initialArtifactData,
|
||||
useArtifact,
|
||||
useArtifactSelector,
|
||||
} from "@/hooks/use-artifact";
|
||||
import type { Attachment, ChatMessage } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Artifact } from "./artifact";
|
||||
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,
|
||||
showCreditCardAlert,
|
||||
setShowCreditCardAlert,
|
||||
} = useActiveChat();
|
||||
|
||||
const [editingMessage, setEditingMessage] = useState<ChatMessage | null>(
|
||||
null
|
||||
);
|
||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||
const isArtifactVisible = useArtifactSelector((state) => state.isVisible);
|
||||
const { setArtifact } = useArtifact();
|
||||
|
||||
const stopRef = useRef(stop);
|
||||
stopRef.current = stop;
|
||||
|
||||
const prevChatIdRef = useRef(chatId);
|
||||
useEffect(() => {
|
||||
if (prevChatIdRef.current !== chatId) {
|
||||
prevChatIdRef.current = chatId;
|
||||
stopRef.current();
|
||||
setArtifact(initialArtifactData);
|
||||
setEditingMessage(null);
|
||||
setAttachments([]);
|
||||
}
|
||||
}, [chatId, setArtifact]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-dvh w-full flex-row overflow-hidden">
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 flex-col bg-sidebar transition-[width] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]",
|
||||
isArtifactVisible ? "w-[40%]" : "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}
|
||||
isArtifactVisible={isArtifactVisible}
|
||||
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>
|
||||
|
||||
<Artifact
|
||||
addToolApprovalResponse={addToolApprovalResponse}
|
||||
attachments={attachments}
|
||||
chatId={chatId}
|
||||
input={input}
|
||||
isReadonly={isReadonly}
|
||||
messages={messages}
|
||||
regenerate={regenerate}
|
||||
selectedModelId={currentModelId}
|
||||
selectedVisibilityType={visibilityType}
|
||||
sendMessage={sendMessage}
|
||||
setAttachments={setAttachments}
|
||||
setInput={setInput}
|
||||
setMessages={setMessages}
|
||||
status={status}
|
||||
stop={stop}
|
||||
votes={votes}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataStreamHandler />
|
||||
|
||||
<AlertDialog
|
||||
onOpenChange={setShowCreditCardAlert}
|
||||
open={showCreditCardAlert}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Activate AI Gateway</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This application requires{" "}
|
||||
{process.env.NODE_ENV === "production" ? "the owner" : "you"} to
|
||||
activate Vercel AI Gateway.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
window.open(
|
||||
"https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%3Fmodal%3Dadd-credit-card",
|
||||
"_blank"
|
||||
);
|
||||
window.location.href = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/`;
|
||||
}}
|
||||
>
|
||||
Activate
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
124
components/chat/sidebar-history-item.tsx
Normal file
124
components/chat/sidebar-history-item.tsx
Normal 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;
|
||||
});
|
||||
373
components/chat/sidebar-history.tsx
Normal file
373
components/chat/sidebar-history.tsx
Normal 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
35
components/chat/sidebar-toggle.tsx
Normal file
35
components/chat/sidebar-toggle.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
121
components/chat/sidebar-user-nav.tsx
Normal file
121
components/chat/sidebar-user-nav.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
25
components/chat/sign-out-form.tsx
Normal file
25
components/chat/sign-out-form.tsx
Normal 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>
|
||||
);
|
||||
};
|
||||
137
components/chat/slash-commands.tsx
Normal file
137
components/chat/slash-commands.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
38
components/chat/submit-button.tsx
Normal file
38
components/chat/submit-button.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
78
components/chat/suggested-actions.tsx
Normal file
78
components/chat/suggested-actions.tsx
Normal 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;
|
||||
}
|
||||
);
|
||||
78
components/chat/suggestion.tsx
Normal file
78
components/chat/suggestion.tsx
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
"use client";
|
||||
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
|
||||
import type { UISuggestion } from "@/lib/editor/suggestions";
|
||||
import { Button } from "../ui/button";
|
||||
import { CrossIcon, SparklesIcon } from "./icons";
|
||||
|
||||
export const SuggestionDialog = ({
|
||||
suggestion,
|
||||
onApply,
|
||||
onClose,
|
||||
}: {
|
||||
suggestion: UISuggestion;
|
||||
onApply: () => void;
|
||||
onClose: () => void;
|
||||
}) => {
|
||||
return (
|
||||
<AnimatePresence>
|
||||
<div className="sticky inset-0 z-40 h-full w-full">
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="absolute inset-0 bg-black/20 backdrop-blur-[2px]"
|
||||
onClick={onClose}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Escape") {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
role="presentation"
|
||||
/>
|
||||
<motion.div
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="absolute left-1/2 top-1/2 z-50 flex w-[min(20rem,calc(100%-2rem))] -translate-x-1/2 -translate-y-1/2 flex-col gap-3 rounded-2xl border bg-background p-4 font-sans text-sm shadow-xl"
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
key={suggestion.id}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
<div className="flex flex-row items-center justify-between">
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<div className="flex size-5 items-center justify-center rounded-md bg-muted/60 text-muted-foreground ring-1 ring-border/50">
|
||||
<SparklesIcon size={10} />
|
||||
</div>
|
||||
<div className="font-medium">Suggestion</div>
|
||||
</div>
|
||||
<button
|
||||
className="flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
onClick={onClose}
|
||||
type="button"
|
||||
>
|
||||
<CrossIcon size={12} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="text-muted-foreground leading-relaxed">
|
||||
{suggestion.description}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
className="w-fit rounded-full px-3 py-1.5"
|
||||
onClick={onApply}
|
||||
variant="outline"
|
||||
>
|
||||
Apply
|
||||
</Button>
|
||||
<Button
|
||||
className="w-fit rounded-full px-3 py-1.5"
|
||||
onClick={onClose}
|
||||
variant="ghost"
|
||||
>
|
||||
Dismiss
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</AnimatePresence>
|
||||
);
|
||||
};
|
||||
242
components/chat/text-editor.tsx
Normal file
242
components/chat/text-editor.tsx
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
"use client";
|
||||
|
||||
import { exampleSetup } from "prosemirror-example-setup";
|
||||
import { inputRules } from "prosemirror-inputrules";
|
||||
import { EditorState } from "prosemirror-state";
|
||||
import { type Decoration, DecorationSet, EditorView } from "prosemirror-view";
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
import type { Suggestion } from "@/lib/db/schema";
|
||||
import {
|
||||
documentSchema,
|
||||
handleTransaction,
|
||||
headingRule,
|
||||
} from "@/lib/editor/config";
|
||||
import {
|
||||
buildContentFromDocument,
|
||||
buildDocumentFromContent,
|
||||
createDecorations,
|
||||
} from "@/lib/editor/functions";
|
||||
import {
|
||||
projectWithPositions,
|
||||
suggestionsPlugin,
|
||||
suggestionsPluginKey,
|
||||
type UISuggestion,
|
||||
} from "@/lib/editor/suggestions";
|
||||
import { SuggestionDialog } from "./suggestion";
|
||||
|
||||
type EditorProps = {
|
||||
content: string;
|
||||
onSaveContent: (updatedContent: string, debounce: boolean) => void;
|
||||
status: "streaming" | "idle";
|
||||
isCurrentVersion: boolean;
|
||||
currentVersionIndex: number;
|
||||
suggestions: Suggestion[];
|
||||
onSuggestionSelect?: (suggestion: UISuggestion | null) => void;
|
||||
onSuggestionApply?: () => void;
|
||||
activeSuggestion?: UISuggestion | null;
|
||||
};
|
||||
|
||||
function PureEditor({
|
||||
content,
|
||||
onSaveContent,
|
||||
suggestions,
|
||||
status,
|
||||
}: EditorProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
const [activeSuggestion, setActiveSuggestion] = useState<UISuggestion | null>(
|
||||
null
|
||||
);
|
||||
const suggestionsRef = useRef<UISuggestion[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (containerRef.current && !editorRef.current) {
|
||||
const state = EditorState.create({
|
||||
doc: buildDocumentFromContent(content),
|
||||
plugins: [
|
||||
...exampleSetup({ schema: documentSchema, menuBar: false }),
|
||||
inputRules({
|
||||
rules: [
|
||||
headingRule(1),
|
||||
headingRule(2),
|
||||
headingRule(3),
|
||||
headingRule(4),
|
||||
headingRule(5),
|
||||
headingRule(6),
|
||||
],
|
||||
}),
|
||||
suggestionsPlugin,
|
||||
],
|
||||
});
|
||||
|
||||
editorRef.current = new EditorView(containerRef.current, {
|
||||
state,
|
||||
handleDOMEvents: {
|
||||
click(_view, event) {
|
||||
const target = event.target as HTMLElement;
|
||||
const highlight = target.closest(".suggestion-highlight");
|
||||
if (highlight) {
|
||||
const id = highlight.getAttribute("data-suggestion-id");
|
||||
const found = suggestionsRef.current.find((s) => s.id === id);
|
||||
if (found) {
|
||||
setActiveSuggestion(found);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (editorRef.current) {
|
||||
editorRef.current.destroy();
|
||||
editorRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [content]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current) {
|
||||
editorRef.current.setProps({
|
||||
dispatchTransaction: (transaction) => {
|
||||
handleTransaction({
|
||||
transaction,
|
||||
editorRef,
|
||||
onSaveContent,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
}, [onSaveContent]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current && content) {
|
||||
const currentContent = buildContentFromDocument(
|
||||
editorRef.current.state.doc
|
||||
);
|
||||
|
||||
if (status === "streaming") {
|
||||
const newDocument = buildDocumentFromContent(content);
|
||||
|
||||
const transaction = editorRef.current.state.tr.replaceWith(
|
||||
0,
|
||||
editorRef.current.state.doc.content.size,
|
||||
newDocument.content
|
||||
);
|
||||
|
||||
transaction.setMeta("no-save", true);
|
||||
editorRef.current.dispatch(transaction);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentContent !== content) {
|
||||
const newDocument = buildDocumentFromContent(content);
|
||||
|
||||
const transaction = editorRef.current.state.tr.replaceWith(
|
||||
0,
|
||||
editorRef.current.state.doc.content.size,
|
||||
newDocument.content
|
||||
);
|
||||
|
||||
transaction.setMeta("no-save", true);
|
||||
editorRef.current.dispatch(transaction);
|
||||
}
|
||||
}
|
||||
}, [content, status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current?.state.doc && content) {
|
||||
const projectedSuggestions = projectWithPositions(
|
||||
editorRef.current.state.doc,
|
||||
suggestions
|
||||
).filter(
|
||||
(suggestion) => suggestion.selectionStart && suggestion.selectionEnd
|
||||
);
|
||||
|
||||
suggestionsRef.current = projectedSuggestions;
|
||||
|
||||
const decorations = createDecorations(
|
||||
projectedSuggestions,
|
||||
editorRef.current
|
||||
);
|
||||
|
||||
const transaction = editorRef.current.state.tr;
|
||||
transaction.setMeta(suggestionsPluginKey, { decorations });
|
||||
editorRef.current.dispatch(transaction);
|
||||
}
|
||||
}, [suggestions, content]);
|
||||
|
||||
const handleApply = useCallback(() => {
|
||||
if (!editorRef.current || !activeSuggestion) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { state, dispatch } = editorRef.current;
|
||||
const currentState = suggestionsPluginKey.getState(state);
|
||||
const currentDecorations = currentState?.decorations;
|
||||
|
||||
if (currentDecorations) {
|
||||
const newDecorations = DecorationSet.create(
|
||||
state.doc,
|
||||
currentDecorations.find().filter((decoration: Decoration) => {
|
||||
return decoration.spec.suggestionId !== activeSuggestion.id;
|
||||
})
|
||||
);
|
||||
|
||||
const decorationTransaction = state.tr;
|
||||
decorationTransaction.setMeta(suggestionsPluginKey, {
|
||||
decorations: newDecorations,
|
||||
selected: null,
|
||||
});
|
||||
dispatch(decorationTransaction);
|
||||
}
|
||||
|
||||
const textTransaction = editorRef.current.state.tr.replaceWith(
|
||||
activeSuggestion.selectionStart,
|
||||
activeSuggestion.selectionEnd,
|
||||
state.schema.text(activeSuggestion.suggestedText)
|
||||
);
|
||||
textTransaction.setMeta("no-debounce", true);
|
||||
dispatch(textTransaction);
|
||||
|
||||
setActiveSuggestion(null);
|
||||
}, [activeSuggestion]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className="prose dark:prose-invert prose-neutral relative max-w-none"
|
||||
ref={containerRef}
|
||||
/>
|
||||
{activeSuggestion &&
|
||||
containerRef.current?.closest("[data-slot='artifact-content']") &&
|
||||
createPortal(
|
||||
<SuggestionDialog
|
||||
onApply={handleApply}
|
||||
onClose={() => setActiveSuggestion(null)}
|
||||
suggestion={activeSuggestion}
|
||||
/>,
|
||||
containerRef.current.closest(
|
||||
"[data-slot='artifact-content']"
|
||||
) as HTMLElement
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function areEqual(prevProps: EditorProps, nextProps: EditorProps) {
|
||||
return (
|
||||
prevProps.suggestions === nextProps.suggestions &&
|
||||
prevProps.currentVersionIndex === nextProps.currentVersionIndex &&
|
||||
prevProps.isCurrentVersion === nextProps.isCurrentVersion &&
|
||||
!(prevProps.status === "streaming" && nextProps.status === "streaming") &&
|
||||
prevProps.content === nextProps.content &&
|
||||
prevProps.onSaveContent === nextProps.onSaveContent
|
||||
);
|
||||
}
|
||||
|
||||
export const Editor = memo(PureEditor, areEqual);
|
||||
75
components/chat/toast.tsx
Normal file
75
components/chat/toast.tsx
Normal 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;
|
||||
};
|
||||
486
components/chat/toolbar.tsx
Normal file
486
components/chat/toolbar.tsx
Normal file
|
|
@ -0,0 +1,486 @@
|
|||
"use client";
|
||||
import type { UseChatHelpers } from "@ai-sdk/react";
|
||||
import cx from "classnames";
|
||||
import { motion, useMotionValue, useTransform } from "framer-motion";
|
||||
import { WrenchIcon, XIcon } from "lucide-react";
|
||||
import { nanoid } from "nanoid";
|
||||
import {
|
||||
type Dispatch,
|
||||
memo,
|
||||
type ReactNode,
|
||||
type SetStateAction,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useOnClickOutside } from "usehooks-ts";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { ChatMessage } from "@/lib/types";
|
||||
import { type ArtifactKind, artifactDefinitions } from "./artifact";
|
||||
import type { ArtifactToolbarItem } from "./create-artifact";
|
||||
import { ArrowUpIcon, StopIcon, SummarizeIcon } from "./icons";
|
||||
|
||||
type ToolProps = {
|
||||
description: string;
|
||||
icon: ReactNode;
|
||||
selectedTool: string | null;
|
||||
setSelectedTool: Dispatch<SetStateAction<string | null>>;
|
||||
isToolbarVisible?: boolean;
|
||||
setIsToolbarVisible?: Dispatch<SetStateAction<boolean>>;
|
||||
isAnimating: boolean;
|
||||
sendMessage: UseChatHelpers<ChatMessage>["sendMessage"];
|
||||
onClick: ({
|
||||
sendMessage,
|
||||
}: {
|
||||
sendMessage: UseChatHelpers<ChatMessage>["sendMessage"];
|
||||
}) => void;
|
||||
};
|
||||
|
||||
const Tool = ({
|
||||
description,
|
||||
icon,
|
||||
selectedTool,
|
||||
setSelectedTool,
|
||||
isToolbarVisible,
|
||||
setIsToolbarVisible,
|
||||
isAnimating,
|
||||
sendMessage,
|
||||
onClick,
|
||||
}: ToolProps) => {
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedTool !== description) {
|
||||
setIsHovered(false);
|
||||
}
|
||||
}, [selectedTool, description]);
|
||||
|
||||
const handleSelect = () => {
|
||||
if (!isToolbarVisible && setIsToolbarVisible) {
|
||||
setIsToolbarVisible(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedTool) {
|
||||
setIsHovered(true);
|
||||
setSelectedTool(description);
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedTool === description) {
|
||||
setSelectedTool(null);
|
||||
onClick({ sendMessage });
|
||||
} else {
|
||||
setSelectedTool(description);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Tooltip open={isHovered && !isAnimating}>
|
||||
<TooltipTrigger asChild>
|
||||
<motion.div
|
||||
animate={{ opacity: 1, transition: { delay: 0.1 } }}
|
||||
className={cx("rounded-full p-3", {
|
||||
"bg-primary text-primary-foreground!": selectedTool === description,
|
||||
})}
|
||||
exit={{
|
||||
scale: 0.9,
|
||||
opacity: 0,
|
||||
transition: { duration: 0.1 },
|
||||
}}
|
||||
initial={{ scale: 1, opacity: 0 }}
|
||||
onClick={() => {
|
||||
handleSelect();
|
||||
}}
|
||||
onHoverEnd={() => {
|
||||
if (selectedTool !== description) {
|
||||
setIsHovered(false);
|
||||
}
|
||||
}}
|
||||
onHoverStart={() => {
|
||||
setIsHovered(true);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
handleSelect();
|
||||
}
|
||||
}}
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
>
|
||||
{selectedTool === description ? <ArrowUpIcon /> : icon}
|
||||
</motion.div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
className="rounded-2xl bg-foreground p-3 px-4 text-background"
|
||||
side="left"
|
||||
sideOffset={16}
|
||||
>
|
||||
{description}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
|
||||
const randomArr = [...new Array(6)].map((_x) => nanoid(5));
|
||||
|
||||
const ReadingLevelSelector = ({
|
||||
setSelectedTool,
|
||||
sendMessage,
|
||||
isAnimating,
|
||||
}: {
|
||||
setSelectedTool: Dispatch<SetStateAction<string | null>>;
|
||||
isAnimating: boolean;
|
||||
sendMessage: UseChatHelpers<ChatMessage>["sendMessage"];
|
||||
}) => {
|
||||
const LEVELS = [
|
||||
"Elementary",
|
||||
"Middle School",
|
||||
"Keep current level",
|
||||
"High School",
|
||||
"College",
|
||||
"Graduate",
|
||||
];
|
||||
|
||||
const y = useMotionValue(-40 * 2);
|
||||
const dragConstraints = 5 * 40 + 2;
|
||||
const yToLevel = useTransform(y, [0, -dragConstraints], [0, 5]);
|
||||
|
||||
const [currentLevel, setCurrentLevel] = useState(2);
|
||||
const [hasUserSelectedLevel, setHasUserSelectedLevel] =
|
||||
useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = yToLevel.on("change", (latest) => {
|
||||
const level = Math.min(5, Math.max(0, Math.round(Math.abs(latest))));
|
||||
setCurrentLevel(level);
|
||||
});
|
||||
|
||||
return () => unsubscribe();
|
||||
}, [yToLevel]);
|
||||
|
||||
return (
|
||||
<div className="relative flex flex-col items-center justify-end">
|
||||
{randomArr.map((id) => (
|
||||
<motion.div
|
||||
animate={{ opacity: 1 }}
|
||||
className="flex size-[40px] flex-row items-center justify-center"
|
||||
exit={{ opacity: 0 }}
|
||||
initial={{ opacity: 0 }}
|
||||
key={id}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<div className="size-2 rounded-full bg-muted-foreground/40" />
|
||||
</motion.div>
|
||||
))}
|
||||
|
||||
<TooltipProvider>
|
||||
<Tooltip open={!isAnimating}>
|
||||
<TooltipTrigger asChild>
|
||||
<motion.div
|
||||
className={cx(
|
||||
"absolute flex flex-row items-center rounded-full border bg-background p-3",
|
||||
{
|
||||
"bg-primary text-primary-foreground": currentLevel !== 2,
|
||||
"bg-background text-foreground": currentLevel === 2,
|
||||
}
|
||||
)}
|
||||
drag="y"
|
||||
dragConstraints={{ top: -dragConstraints, bottom: 0 }}
|
||||
dragElastic={0}
|
||||
dragMomentum={false}
|
||||
onClick={() => {
|
||||
if (currentLevel !== 2 && hasUserSelectedLevel) {
|
||||
sendMessage({
|
||||
role: "user",
|
||||
parts: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Please adjust the reading level to ${LEVELS[currentLevel]} level.`,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
setSelectedTool(null);
|
||||
}
|
||||
}}
|
||||
onDragEnd={() => {
|
||||
if (currentLevel === 2) {
|
||||
setSelectedTool(null);
|
||||
} else {
|
||||
setHasUserSelectedLevel(true);
|
||||
}
|
||||
}}
|
||||
onDragStart={() => {
|
||||
setHasUserSelectedLevel(false);
|
||||
}}
|
||||
style={{ y }}
|
||||
transition={{ duration: 0.1 }}
|
||||
whileHover={{ scale: 1.05 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
>
|
||||
{currentLevel === 2 ? <SummarizeIcon /> : <ArrowUpIcon />}
|
||||
</motion.div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
className="rounded-2xl bg-foreground p-3 px-4 text-background text-sm"
|
||||
side="left"
|
||||
sideOffset={16}
|
||||
>
|
||||
{LEVELS[currentLevel]}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const Tools = ({
|
||||
selectedTool,
|
||||
setSelectedTool,
|
||||
sendMessage,
|
||||
isAnimating,
|
||||
tools,
|
||||
}: {
|
||||
selectedTool: string | null;
|
||||
setSelectedTool: Dispatch<SetStateAction<string | null>>;
|
||||
sendMessage: UseChatHelpers<ChatMessage>["sendMessage"];
|
||||
isAnimating: boolean;
|
||||
tools: ArtifactToolbarItem[];
|
||||
}) => {
|
||||
return (
|
||||
<motion.div
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="flex flex-col gap-1.5"
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
>
|
||||
{[...tools].reverse().map((tool) => (
|
||||
<Tool
|
||||
description={tool.description}
|
||||
icon={tool.icon}
|
||||
isAnimating={isAnimating}
|
||||
key={tool.description}
|
||||
onClick={tool.onClick}
|
||||
selectedTool={selectedTool}
|
||||
sendMessage={sendMessage}
|
||||
setSelectedTool={setSelectedTool}
|
||||
/>
|
||||
))}
|
||||
</motion.div>
|
||||
);
|
||||
};
|
||||
|
||||
const createFixErrorTool = (
|
||||
consoleOutput: string,
|
||||
documentId?: string
|
||||
): ArtifactToolbarItem => ({
|
||||
icon: <WrenchIcon className="size-4" />,
|
||||
description: "Fix error",
|
||||
onClick: ({ sendMessage: send }) => {
|
||||
send({
|
||||
role: "user",
|
||||
parts: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Fix the error in the existing script${documentId ? ` (id: ${documentId})` : ""} using updateDocument. Do not create a new script. Console error:\n\n${consoleOutput}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const PureToolbar = ({
|
||||
isToolbarVisible: _isToolbarVisible,
|
||||
setIsToolbarVisible,
|
||||
sendMessage,
|
||||
status,
|
||||
stop,
|
||||
setMessages,
|
||||
artifactKind,
|
||||
consoleError,
|
||||
documentId,
|
||||
artifactActions,
|
||||
onClose,
|
||||
}: {
|
||||
isToolbarVisible: boolean;
|
||||
setIsToolbarVisible: Dispatch<SetStateAction<boolean>>;
|
||||
status: UseChatHelpers<ChatMessage>["status"];
|
||||
sendMessage: UseChatHelpers<ChatMessage>["sendMessage"];
|
||||
stop: UseChatHelpers<ChatMessage>["stop"];
|
||||
setMessages: UseChatHelpers<ChatMessage>["setMessages"];
|
||||
artifactKind: ArtifactKind;
|
||||
consoleError?: string;
|
||||
documentId?: string;
|
||||
artifactActions?: ReactNode;
|
||||
onClose?: () => void;
|
||||
}) => {
|
||||
const toolbarRef = useRef<HTMLDivElement>(null);
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
|
||||
|
||||
const [selectedTool, setSelectedTool] = useState<string | null>(null);
|
||||
const [isAnimating, setIsAnimating] = useState(false);
|
||||
|
||||
useOnClickOutside(toolbarRef, () => {
|
||||
setIsToolbarVisible(false);
|
||||
setSelectedTool(null);
|
||||
});
|
||||
|
||||
const startCloseTimer = () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
setSelectedTool(null);
|
||||
setIsToolbarVisible(false);
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
const cancelCloseTimer = () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "streaming") {
|
||||
setIsToolbarVisible(false);
|
||||
}
|
||||
}, [status, setIsToolbarVisible]);
|
||||
|
||||
const artifactDefinition = artifactDefinitions.find(
|
||||
(definition) => definition.kind === artifactKind
|
||||
);
|
||||
|
||||
if (!artifactDefinition) {
|
||||
throw new Error("Artifact definition not found!");
|
||||
}
|
||||
|
||||
const toolsByArtifactKind = consoleError
|
||||
? [
|
||||
createFixErrorTool(consoleError, documentId),
|
||||
...artifactDefinition.toolbar.slice(1),
|
||||
]
|
||||
: artifactDefinition.toolbar;
|
||||
|
||||
if (toolsByArtifactKind.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<motion.div
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
className="fixed right-6 bottom-6 z-50 flex cursor-pointer flex-col items-center rounded-3xl border bg-background py-1 shadow-lg"
|
||||
exit={{ opacity: 0, y: -20, transition: { duration: 0.1 } }}
|
||||
initial={{ opacity: 0, y: -20, scale: 1 }}
|
||||
onAnimationComplete={() => {
|
||||
setIsAnimating(false);
|
||||
}}
|
||||
onAnimationStart={() => {
|
||||
setIsAnimating(true);
|
||||
}}
|
||||
onHoverEnd={() => {
|
||||
if (status === "streaming") {
|
||||
return;
|
||||
}
|
||||
|
||||
startCloseTimer();
|
||||
}}
|
||||
onHoverStart={() => {
|
||||
if (status === "streaming") {
|
||||
return;
|
||||
}
|
||||
|
||||
cancelCloseTimer();
|
||||
setIsToolbarVisible(true);
|
||||
}}
|
||||
ref={toolbarRef}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 25 }}
|
||||
>
|
||||
{onClose && (
|
||||
<motion.div
|
||||
animate={{ opacity: 1 }}
|
||||
className="p-3 text-muted-foreground transition-colors hover:text-foreground"
|
||||
initial={{ opacity: 0 }}
|
||||
onClick={onClose}
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{status === "streaming" ? (
|
||||
<motion.div
|
||||
animate={{ scale: 1.4 }}
|
||||
className="p-3"
|
||||
exit={{ scale: 1 }}
|
||||
initial={{ scale: 1 }}
|
||||
key="stop-icon"
|
||||
onClick={() => {
|
||||
stop();
|
||||
setMessages((messages) => messages);
|
||||
}}
|
||||
>
|
||||
<StopIcon />
|
||||
</motion.div>
|
||||
) : selectedTool === "adjust-reading-level" ? (
|
||||
<ReadingLevelSelector
|
||||
isAnimating={isAnimating}
|
||||
key="reading-level-selector"
|
||||
sendMessage={sendMessage}
|
||||
setSelectedTool={setSelectedTool}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{artifactActions}
|
||||
<Tools
|
||||
isAnimating={isAnimating}
|
||||
key="tools"
|
||||
selectedTool={selectedTool}
|
||||
sendMessage={sendMessage}
|
||||
setSelectedTool={setSelectedTool}
|
||||
tools={toolsByArtifactKind}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</motion.div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export const Toolbar = memo(PureToolbar, (prevProps, nextProps) => {
|
||||
if (prevProps.status !== nextProps.status) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.isToolbarVisible !== nextProps.isToolbarVisible) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.artifactKind !== nextProps.artifactKind) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.consoleError !== nextProps.consoleError) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.artifactActions !== nextProps.artifactActions) {
|
||||
return false;
|
||||
}
|
||||
if (prevProps.onClose !== nextProps.onClose) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
148
components/chat/version-footer.tsx
Normal file
148
components/chat/version-footer.tsx
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
"use client";
|
||||
|
||||
import { isAfter } from "date-fns";
|
||||
import { motion } from "framer-motion";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, DiffIcon } from "lucide-react";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState } from "react";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { useArtifact } from "@/hooks/use-artifact";
|
||||
import type { Document } from "@/lib/db/schema";
|
||||
import { cn, getDocumentTimestampByIndex } from "@/lib/utils";
|
||||
import { LoaderIcon } from "./icons";
|
||||
|
||||
type VersionFooterProps = {
|
||||
handleVersionChange: (type: "next" | "prev" | "toggle" | "latest") => void;
|
||||
documents: Document[] | undefined;
|
||||
currentVersionIndex: number;
|
||||
mode: "edit" | "diff";
|
||||
setMode: Dispatch<SetStateAction<"edit" | "diff">>;
|
||||
};
|
||||
|
||||
export const VersionFooter = ({
|
||||
handleVersionChange,
|
||||
documents,
|
||||
currentVersionIndex,
|
||||
mode,
|
||||
setMode,
|
||||
}: VersionFooterProps) => {
|
||||
const { artifact } = useArtifact();
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
const [isMutating, setIsMutating] = useState(false);
|
||||
|
||||
if (!documents) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isFirst = currentVersionIndex === 0;
|
||||
const isLast = currentVersionIndex === documents.length - 1;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
animate={{ opacity: 1 }}
|
||||
className="z-50 flex w-full shrink-0 items-center justify-between gap-3 border-t border-border/50 bg-background px-4 py-3"
|
||||
exit={{ opacity: 0, transition: { duration: 0 } }}
|
||||
initial={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-30"
|
||||
disabled={isFirst}
|
||||
onClick={() => handleVersionChange("prev")}
|
||||
type="button"
|
||||
>
|
||||
<ChevronLeftIcon className="size-4" />
|
||||
</button>
|
||||
<span className="min-w-[4rem] text-center text-xs tabular-nums text-muted-foreground">
|
||||
{currentVersionIndex + 1} of {documents.length}
|
||||
</span>
|
||||
<button
|
||||
className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-30"
|
||||
disabled={isLast}
|
||||
onClick={() => handleVersionChange("next")}
|
||||
type="button"
|
||||
>
|
||||
<ChevronRightIcon className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className={cn(
|
||||
"flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
|
||||
mode === "diff" && "bg-muted text-foreground"
|
||||
)}
|
||||
onClick={() => setMode(mode === "diff" ? "edit" : "diff")}
|
||||
title="Show changes"
|
||||
type="button"
|
||||
>
|
||||
<DiffIcon className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row gap-2">
|
||||
<button
|
||||
className="inline-flex items-center justify-center gap-2 rounded-lg bg-foreground px-3 py-1.5 text-sm font-medium text-background transition-all duration-150 hover:opacity-90 active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50"
|
||||
disabled={isMutating}
|
||||
onClick={async () => {
|
||||
setIsMutating(true);
|
||||
|
||||
try {
|
||||
await mutate(
|
||||
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/document?id=${artifact.documentId}`,
|
||||
await fetch(
|
||||
`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/document?id=${artifact.documentId}×tamp=${getDocumentTimestampByIndex(
|
||||
documents,
|
||||
currentVersionIndex
|
||||
)}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
}
|
||||
),
|
||||
{
|
||||
optimisticData: documents
|
||||
? [
|
||||
...documents.filter((document) =>
|
||||
isAfter(
|
||||
new Date(document.createdAt),
|
||||
new Date(
|
||||
getDocumentTimestampByIndex(
|
||||
documents,
|
||||
currentVersionIndex
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
]
|
||||
: [],
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
setIsMutating(false);
|
||||
}
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
Restore
|
||||
{isMutating && (
|
||||
<div className="animate-spin">
|
||||
<LoaderIcon size={14} />
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
className="inline-flex items-center justify-center rounded-lg border border-border px-3 py-1.5 text-sm font-medium transition-all duration-150 hover:bg-muted active:scale-[0.98]"
|
||||
onClick={() => {
|
||||
setMode("edit");
|
||||
handleVersionChange("latest");
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
Latest
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
};
|
||||
111
components/chat/visibility-selector.tsx
Normal file
111
components/chat/visibility-selector.tsx
Normal 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
434
components/chat/weather.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue