chatbot-template/artifacts/image/client.tsx

77 lines
2 KiB
TypeScript
Raw Normal View History

import { Artifact } from '@/components/create-artifact';
import { CopyIcon, RedoIcon, UndoIcon } from '@/components/icons';
import { ImageEditor } from '@/components/image-editor';
import { toast } from 'sonner';
2025-01-27 14:19:47 +05:30
export const imageArtifact = new Artifact({
kind: 'image',
description: 'Useful for image generation',
onStreamPart: ({ streamPart, setArtifact }) => {
if (streamPart.type === 'data-imageDelta') {
setArtifact((draftArtifact) => ({
...draftArtifact,
content: streamPart.data,
2025-01-27 14:19:47 +05:30
isVisible: true,
status: 'streaming',
2025-01-27 14:19:47 +05:30
}));
}
},
content: ImageEditor,
actions: [
{
icon: <UndoIcon size={18} />,
description: 'View Previous version',
2025-01-27 14:19:47 +05:30
onClick: ({ handleVersionChange }) => {
handleVersionChange('prev');
2025-01-27 14:19:47 +05:30
},
isDisabled: ({ currentVersionIndex }) => {
if (currentVersionIndex === 0) {
return true;
}
return false;
},
2025-01-27 14:19:47 +05:30
},
{
icon: <RedoIcon size={18} />,
description: 'View Next version',
2025-01-27 14:19:47 +05:30
onClick: ({ handleVersionChange }) => {
handleVersionChange('next');
2025-01-27 14:19:47 +05:30
},
isDisabled: ({ isCurrentVersion }) => {
if (isCurrentVersion) {
return true;
}
return false;
},
2025-01-27 14:19:47 +05:30
},
{
icon: <CopyIcon size={18} />,
description: 'Copy image to clipboard',
2025-01-27 14:19:47 +05:30
onClick: ({ content }) => {
const img = new Image();
img.src = `data:image/png;base64,${content}`;
img.onload = () => {
const canvas = document.createElement('canvas');
2025-01-27 14:19:47 +05:30
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
2025-01-27 14:19:47 +05:30
ctx?.drawImage(img, 0, 0);
canvas.toBlob((blob) => {
if (blob) {
navigator.clipboard.write([
new ClipboardItem({ 'image/png': blob }),
2025-01-27 14:19:47 +05:30
]);
}
}, 'image/png');
2025-01-27 14:19:47 +05:30
};
toast.success('Copied image to clipboard!');
2025-01-27 14:19:47 +05:30
},
},
],
toolbar: [],
});