chatbot-template/components/artifact.tsx

515 lines
16 KiB
TypeScript
Raw Normal View History

import { formatDistance } from 'date-fns';
import { AnimatePresence, motion } from 'framer-motion';
2024-10-30 16:01:24 +05:30
import {
2024-11-15 12:18:17 -05:00
type Dispatch,
memo,
2024-11-15 12:18:17 -05:00
type SetStateAction,
2024-10-30 16:01:24 +05:30
useCallback,
useEffect,
useState,
} from 'react';
import useSWR, { useSWRConfig } from 'swr';
import { useDebounceCallback, useWindowSize } from 'usehooks-ts';
import type { Document, Vote } from '@/lib/db/schema';
import { fetcher } from '@/lib/utils';
import { MultimodalInput } from './multimodal-input';
import { Toolbar } from './toolbar';
import { VersionFooter } from './version-footer';
import { ArtifactActions } from './artifact-actions';
import { ArtifactCloseButton } from './artifact-close-button';
import { ArtifactMessages } from './artifact-messages';
import { useSidebar } from './ui/sidebar';
import { useArtifact } from '@/hooks/use-artifact';
import { imageArtifact } from '@/artifacts/image/client';
import { codeArtifact } from '@/artifacts/code/client';
import { sheetArtifact } from '@/artifacts/sheet/client';
import { textArtifact } from '@/artifacts/text/client';
import equal from 'fast-deep-equal';
import type { UseChatHelpers } from '@ai-sdk/react';
import type { VisibilityType } from './visibility-selector';
import type { Attachment, ChatMessage } from '@/lib/types';
export const artifactDefinitions = [
textArtifact,
codeArtifact,
imageArtifact,
sheetArtifact,
];
export type ArtifactKind = (typeof artifactDefinitions)[number]['kind'];
export interface UIArtifact {
2024-10-30 16:01:24 +05:30
title: string;
documentId: string;
kind: ArtifactKind;
2024-10-30 16:01:24 +05:30
content: string;
isVisible: boolean;
status: 'streaming' | 'idle';
2024-10-30 16:01:24 +05:30
boundingBox: {
top: number;
left: number;
width: number;
height: number;
};
}
2024-10-30 16:01:24 +05:30
function PureArtifact({
2024-11-05 17:15:51 +03:00
chatId,
2024-10-30 16:01:24 +05:30
input,
setInput,
status,
2024-10-30 16:01:24 +05:30
stop,
attachments,
setAttachments,
sendMessage,
2024-10-30 16:01:24 +05:30
messages,
setMessages,
regenerate,
2024-11-05 17:15:51 +03:00
votes,
isReadonly,
selectedVisibilityType,
selectedModelId,
2024-10-30 16:01:24 +05:30
}: {
2024-11-05 17:15:51 +03:00
chatId: string;
2024-10-30 16:01:24 +05:30
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: Array<Vote> | undefined;
sendMessage: UseChatHelpers<ChatMessage>['sendMessage'];
regenerate: UseChatHelpers<ChatMessage>['regenerate'];
isReadonly: boolean;
selectedVisibilityType: VisibilityType;
selectedModelId: string;
2024-10-30 16:01:24 +05:30
}) {
const { artifact, setArtifact, metadata, setMetadata } = useArtifact();
2024-10-30 16:01:24 +05:30
const {
data: documents,
isLoading: isDocumentsFetching,
mutate: mutateDocuments,
} = useSWR<Array<Document>>(
artifact.documentId !== 'init' && artifact.status !== 'streaming'
? `/api/document?id=${artifact.documentId}`
2024-10-30 16:01:24 +05:30
: null,
fetcher,
2024-10-30 16:01:24 +05:30
);
const [mode, setMode] = useState<'edit' | 'diff'>('edit');
2024-10-30 16:01:24 +05:30
const [document, setDocument] = useState<Document | null>(null);
const [currentVersionIndex, setCurrentVersionIndex] = useState(-1);
const { open: isSidebarOpen } = useSidebar();
2024-10-30 16:01:24 +05:30
useEffect(() => {
if (documents && documents.length > 0) {
const mostRecentDocument = documents.at(-1);
if (mostRecentDocument) {
setDocument(mostRecentDocument);
setCurrentVersionIndex(documents.length - 1);
setArtifact((currentArtifact) => ({
...currentArtifact,
content: mostRecentDocument.content ?? '',
}));
2024-10-30 16:01:24 +05:30
}
}
}, [documents, setArtifact]);
2024-10-30 16:01:24 +05:30
useEffect(() => {
mutateDocuments();
}, [artifact.status, mutateDocuments]);
2024-10-30 16:01:24 +05:30
const { mutate } = useSWRConfig();
const [isContentDirty, setIsContentDirty] = useState(false);
const handleContentChange = useCallback(
(updatedContent: string) => {
if (!artifact) return;
2024-10-30 16:01:24 +05:30
mutate<Array<Document>>(
`/api/document?id=${artifact.documentId}`,
2024-10-30 16:01:24 +05:30
async (currentDocuments) => {
if (!currentDocuments) return undefined;
2024-10-30 16:01:24 +05:30
const currentDocument = currentDocuments.at(-1);
if (!currentDocument || !currentDocument.content) {
setIsContentDirty(false);
return currentDocuments;
}
if (currentDocument.content !== updatedContent) {
await fetch(`/api/document?id=${artifact.documentId}`, {
method: 'POST',
2024-10-30 16:01:24 +05:30
body: JSON.stringify({
title: artifact.title,
2024-10-30 16:01:24 +05:30
content: updatedContent,
kind: artifact.kind,
2024-10-30 16:01:24 +05:30
}),
});
setIsContentDirty(false);
const newDocument = {
...currentDocument,
content: updatedContent,
createdAt: new Date(),
};
return [...currentDocuments, newDocument];
}
2024-11-15 12:18:17 -05:00
return currentDocuments;
2024-10-30 16:01:24 +05:30
},
{ revalidate: false },
2024-10-30 16:01:24 +05:30
);
},
[artifact, mutate],
2024-10-30 16:01:24 +05:30
);
const debouncedHandleContentChange = useDebounceCallback(
handleContentChange,
2000,
2024-10-30 16:01:24 +05:30
);
const saveContent = useCallback(
(updatedContent: string, debounce: boolean) => {
2024-10-30 16:01:24 +05:30
if (document && updatedContent !== document.content) {
setIsContentDirty(true);
if (debounce) {
debouncedHandleContentChange(updatedContent);
} else {
handleContentChange(updatedContent);
}
2024-10-30 16:01:24 +05:30
}
},
[document, debouncedHandleContentChange, handleContentChange],
2024-10-30 16:01:24 +05:30
);
function getDocumentContentById(index: number) {
if (!documents) return '';
if (!documents[index]) return '';
return documents[index].content ?? '';
2024-10-30 16:01:24 +05:30
}
const handleVersionChange = (type: 'next' | 'prev' | 'toggle' | 'latest') => {
if (!documents) return;
2024-10-30 16:01:24 +05:30
if (type === 'latest') {
2024-10-30 16:01:24 +05:30
setCurrentVersionIndex(documents.length - 1);
setMode('edit');
2024-10-30 16:01:24 +05:30
}
if (type === 'toggle') {
setMode((mode) => (mode === 'edit' ? 'diff' : 'edit'));
2024-10-30 16:01:24 +05:30
}
if (type === 'prev') {
2024-10-30 16:01:24 +05:30
if (currentVersionIndex > 0) {
setCurrentVersionIndex((index) => index - 1);
}
} else if (type === 'next') {
if (currentVersionIndex < documents.length - 1) {
setCurrentVersionIndex((index) => index + 1);
}
2024-10-30 16:01:24 +05:30
}
};
const [isToolbarVisible, setIsToolbarVisible] = useState(false);
/*
* NOTE: if there are no documents, or if
* the documents are being fetched, then
* we mark it as the current version.
*/
const isCurrentVersion =
documents && documents.length > 0
? currentVersionIndex === documents.length - 1
: true;
2024-10-30 16:01:24 +05:30
const { width: windowWidth, height: windowHeight } = useWindowSize();
const isMobile = windowWidth ? windowWidth < 768 : false;
const artifactDefinition = artifactDefinitions.find(
(definition) => definition.kind === artifact.kind,
2025-01-27 14:19:47 +05:30
);
if (!artifactDefinition) {
throw new Error('Artifact definition not found!');
2025-01-27 14:19:47 +05:30
}
useEffect(() => {
if (artifact.documentId !== 'init') {
if (artifactDefinition.initialize) {
artifactDefinition.initialize({
documentId: artifact.documentId,
setMetadata,
});
}
2025-01-27 14:19:47 +05:30
}
}, [artifact.documentId, artifactDefinition, setMetadata]);
2025-01-27 14:19:47 +05:30
2024-10-30 16:01:24 +05:30
return (
<AnimatePresence>
{artifact.isVisible && (
2024-10-30 16:01:24 +05:30
<motion.div
data-testid="artifact"
className="fixed top-0 left-0 z-50 flex h-dvh w-dvw flex-row bg-transparent"
initial={{ opacity: 1 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0, transition: { delay: 0.4 } }}
2024-10-30 16:01:24 +05:30
>
{!isMobile && (
<motion.div
2025-09-09 15:44:07 -04:00
className="fixed h-dvh bg-background"
initial={{
width: isSidebarOpen ? windowWidth - 256 : windowWidth,
right: 0,
}}
animate={{ width: windowWidth, right: 0 }}
exit={{
width: isSidebarOpen ? windowWidth - 256 : windowWidth,
right: 0,
}}
/>
)}
2024-10-30 16:01:24 +05:30
{!isMobile && (
<motion.div
className="relative h-dvh w-[400px] shrink-0 bg-muted dark:bg-background"
initial={{ opacity: 0, x: 10, scale: 1 }}
animate={{
2024-10-30 16:01:24 +05:30
opacity: 1,
x: 0,
scale: 1,
2024-10-30 16:01:24 +05:30
transition: {
delay: 0.1,
type: 'spring',
stiffness: 300,
2024-10-30 16:01:24 +05:30
damping: 30,
},
}}
exit={{
opacity: 0,
x: 0,
scale: 1,
transition: { duration: 0 },
}}
>
<AnimatePresence>
{!isCurrentVersion && (
<motion.div
className="absolute top-0 left-0 z-50 h-dvh w-[400px] bg-zinc-900/50"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
)}
</AnimatePresence>
2025-09-09 15:44:07 -04:00
<div className="flex h-full flex-col items-center justify-between">
<ArtifactMessages
chatId={chatId}
status={status}
votes={votes}
messages={messages}
setMessages={setMessages}
regenerate={regenerate}
isReadonly={isReadonly}
artifactStatus={artifact.status}
/>
2025-09-09 15:44:07 -04:00
<div className="relative flex w-full flex-row items-end gap-2 px-4 pb-4">
<MultimodalInput
chatId={chatId}
input={input}
setInput={setInput}
status={status}
stop={stop}
attachments={attachments}
setAttachments={setAttachments}
messages={messages}
sendMessage={sendMessage}
className="bg-background dark:bg-muted"
setMessages={setMessages}
selectedVisibilityType={selectedVisibilityType}
selectedModelId={selectedModelId}
/>
2025-08-28 14:15:36 +01:00
</div>
2024-10-30 16:01:24 +05:30
</div>
</motion.div>
)}
2024-10-30 16:01:24 +05:30
<motion.div
className="fixed flex h-dvh flex-col overflow-y-scroll border-zinc-200 bg-background md:border-l dark:border-zinc-700 dark:bg-muted"
initial={
isMobile
? {
opacity: 1,
x: artifact.boundingBox.left,
y: artifact.boundingBox.top,
height: artifact.boundingBox.height,
width: artifact.boundingBox.width,
borderRadius: 50,
}
: {
opacity: 1,
x: artifact.boundingBox.left,
y: artifact.boundingBox.top,
height: artifact.boundingBox.height,
width: artifact.boundingBox.width,
borderRadius: 50,
}
}
animate={
isMobile
? {
opacity: 1,
x: 0,
y: 0,
height: windowHeight,
width: windowWidth ? windowWidth : 'calc(100dvw)',
borderRadius: 0,
transition: {
delay: 0,
type: 'spring',
stiffness: 300,
damping: 30,
duration: 0.8,
2024-11-15 13:00:15 -05:00
},
}
: {
opacity: 1,
x: 400,
y: 0,
height: windowHeight,
width: windowWidth
? windowWidth - 400
: 'calc(100dvw-400px)',
borderRadius: 0,
transition: {
delay: 0,
type: 'spring',
stiffness: 300,
damping: 30,
duration: 0.8,
},
}
}
exit={{
opacity: 0,
scale: 0.5,
transition: {
delay: 0.1,
type: 'spring',
stiffness: 600,
damping: 30,
},
}}
>
2025-09-09 15:44:07 -04:00
<div className="flex flex-row items-start justify-between p-2">
<div className="flex flex-row items-start gap-4">
<ArtifactCloseButton />
<div className="flex flex-col">
<div className="font-medium">{artifact.title}</div>
{isContentDirty ? (
2025-09-09 15:44:07 -04:00
<div className="text-muted-foreground text-sm">
Saving changes...
</div>
) : document ? (
2025-09-09 15:44:07 -04:00
<div className="text-muted-foreground text-sm">
{`Updated ${formatDistance(
new Date(document.createdAt),
new Date(),
{
addSuffix: true,
},
)}`}
</div>
) : (
2025-09-09 15:44:07 -04:00
<div className="mt-2 h-3 w-32 animate-pulse rounded-md bg-muted-foreground/20" />
)}
</div>
</div>
<ArtifactActions
artifact={artifact}
2024-10-30 16:01:24 +05:30
currentVersionIndex={currentVersionIndex}
handleVersionChange={handleVersionChange}
isCurrentVersion={isCurrentVersion}
mode={mode}
metadata={metadata}
2025-01-27 14:19:47 +05:30
setMetadata={setMetadata}
2024-10-30 16:01:24 +05:30
/>
</div>
2024-10-30 16:01:24 +05:30
2025-09-09 15:44:07 -04:00
<div className="h-full max-w-full! items-center overflow-y-scroll bg-background dark:bg-muted">
<artifactDefinition.content
title={artifact.title}
content={
isCurrentVersion
? artifact.content
: getDocumentContentById(currentVersionIndex)
}
mode={mode}
status={artifact.status}
currentVersionIndex={currentVersionIndex}
suggestions={[]}
onSaveContent={saveContent}
isInline={false}
isCurrentVersion={isCurrentVersion}
getDocumentContentById={getDocumentContentById}
isLoading={isDocumentsFetching && !artifact.content}
metadata={metadata}
setMetadata={setMetadata}
/>
<AnimatePresence>
{isCurrentVersion && (
<Toolbar
isToolbarVisible={isToolbarVisible}
setIsToolbarVisible={setIsToolbarVisible}
sendMessage={sendMessage}
status={status}
stop={stop}
setMessages={setMessages}
artifactKind={artifact.kind}
/>
)}
</AnimatePresence>
</div>
2024-11-04 20:26:38 +03:00
<AnimatePresence>
{!isCurrentVersion && (
<VersionFooter
currentVersionIndex={currentVersionIndex}
documents={documents}
handleVersionChange={handleVersionChange}
2024-11-04 20:26:38 +03:00
/>
)}
</AnimatePresence>
</motion.div>
</motion.div>
)}
</AnimatePresence>
2024-10-30 16:01:24 +05:30
);
}
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 (!equal(prevProps.messages, nextProps.messages.length)) return false;
if (prevProps.selectedVisibilityType !== nextProps.selectedVisibilityType)
return false;
return true;
});