import { useState, useRef, useEffect } from 'react';
import { GraphyAiSdk } from '@graphysdk/ai';
function ChartEditor({ config, onUpdate }) {
const [progress, setProgress] = useState(0);
const [status, setStatus] = useState('');
const [isLoading, setIsLoading] = useState(false);
const abortRef = useRef<AbortController | null>(null);
const handleGenerate = async (prompt: string) => {
// Cancel any in-flight request
abortRef.current?.abort();
abortRef.current = new AbortController();
setIsLoading(true);
setProgress(0);
try {
const stream = await ai.generateGraphStream(
{ config, userPrompt: prompt },
abortRef.current.signal
);
for await (const event of stream) {
if (event.type === 'progress') {
setProgress(event.percentage);
setStatus(event.message || '');
}
if (event.type === 'complete') {
onUpdate(event.data.config);
}
}
} catch (error) {
// Ignore abort errors - user cancelled intentionally
if (error.name !== 'AbortError') {
console.error('Generation failed:', error);
}
} finally {
setIsLoading(false);
}
};
// Clean up on unmount
useEffect(() => {
return () => abortRef.current?.abort();
}, []);
return (
<div>
{isLoading && (
<>
<progress value={progress} max={100} />
<span>{status}</span>
<button onClick={() => abortRef.current?.abort()}>
Cancel
</button>
</>
)}
</div>
);
}