import React, { useState, useCallback, useRef, useEffect } from 'react' import { Stack, Text, Card, Button, Box, Flex } from '@sanity/ui' import { set, useFormValue, useClient } from 'sanity' import { domToBlob } from 'modern-screenshot' interface ImageGeneratorProps { onChange: (event: any) => void renderDefault: (props: any) => React.ReactElement } export function ImageGenerator (props: ImageGeneratorProps) { const { onChange, renderDefault } = props const [isGenerating, setIsGenerating] = useState(false) const [hasPreview, setHasPreview] = useState(false) const terminalRef = useRef(null) const documentContent = useFormValue(['content']) as string const client = useClient({ apiVersion: '2025-02-10' }) useEffect(() => { if (documentContent?.trim()) { setHasPreview(true) } else { setHasPreview(false) } }, [documentContent]) const generateImage = useCallback(async () => { if (!documentContent || !hasPreview || !terminalRef.current) return setIsGenerating(true) try { const blob = await domToBlob(terminalRef.current, { width: 1200, height: 630, scale: 2, style: { transform: 'scale(1)', transformOrigin: 'top left', }, }) if (blob) { try { // Upload the image to Sanity as an asset const asset = await client.assets.upload('image', blob, { filename: `ama-generated-${Date.now()}.png`, }) onChange(set({ _type: 'image', asset: { _type: 'reference', _ref: asset._id, }, })) } catch (error) { console.error('Error uploading image to Sanity:', error) } } setIsGenerating(false) } catch (error) { console.error('Error generating image:', error) setIsGenerating(false) } }, [documentContent, hasPreview, onChange, client]) // Split text into lines that fit the terminal width const formatTextLines = useCallback((text: string) => { const words = text.split(' ') const lines: string[] = [] let currentLine = '' const length = 58 for (const word of words) { if (currentLine.length + word.length + 1 <= length) { currentLine += (currentLine ? ' ' : '') + word } else { if (currentLine) { lines.push(currentLine) } currentLine = word } } if (currentLine) { lines.push(currentLine) } return lines }, []) const textLines = documentContent ? formatTextLines(documentContent) : [] return ( Generated Image