import { DiagramToCodePlugin, exportToBlob, getTextFromElements, MIME_TYPES, TTDDialog, TTDStreamFetch, } from "@excalidraw/excalidraw"; import { getDataURL } from "@excalidraw/excalidraw/data/blob"; import { safelyParseJSON } from "@excalidraw/common"; import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types"; import { TTDIndexedDBAdapter } from "../data/TTDStorage"; export const AIComponents = ({ excalidrawAPI, }: { excalidrawAPI: ExcalidrawImperativeAPI; }) => { return ( <> { const appState = excalidrawAPI.getAppState(); const blob = await exportToBlob({ elements: children, appState: { ...appState, exportBackground: true, viewBackgroundColor: appState.viewBackgroundColor, }, exportingFrame: frame, files: excalidrawAPI.getFiles(), mimeType: MIME_TYPES.jpg, }); const dataURL = await getDataURL(blob); const textFromFrameChildren = getTextFromElements(children); const response = await fetch( `${ import.meta.env.VITE_APP_AI_BACKEND }/v1/ai/diagram-to-code/generate`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ texts: textFromFrameChildren, image: dataURL, theme: appState.theme, }), }, ); if (!response.ok) { const text = await response.text(); const errorJSON = safelyParseJSON(text); if (!errorJSON) { throw new Error(text); } if (errorJSON.statusCode === 429) { return { html: `
Too many requests today,
please try again tomorrow!


You can also try Excalidraw+ to get more requests.
`, }; } throw new Error(errorJSON.message || text); } try { const { html } = await response.json(); if (!html) { throw new Error("Generation failed (invalid response)"); } return { html, }; } catch (error: any) { throw new Error("Generation failed (invalid response)"); } }} /> { const { onChunk, onStreamCreated, signal, messages } = props; const result = await TTDStreamFetch({ url: `${ import.meta.env.VITE_APP_AI_BACKEND }/v1/ai/text-to-diagram/chat-streaming`, messages, onChunk, onStreamCreated, extractRateLimits: true, signal, }); return result; }} persistenceAdapter={TTDIndexedDBAdapter} /> ); };