File size: 11,091 Bytes
763be49
 
 
 
 
 
02ce812
763be49
 
 
0817dc1
763be49
 
 
 
 
 
 
 
02ce812
 
763be49
 
02ce812
763be49
 
02ce812
763be49
 
 
 
 
 
545f5f7
763be49
 
0817dc1
545f5f7
 
763be49
 
 
 
 
 
545f5f7
763be49
 
0817dc1
545f5f7
 
763be49
 
 
 
 
 
 
02ce812
 
 
 
 
 
763be49
 
 
 
545f5f7
 
 
 
763be49
545f5f7
 
 
 
763be49
545f5f7
 
763be49
545f5f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763be49
7df968b
 
 
763be49
 
545f5f7
763be49
 
545f5f7
 
763be49
 
545f5f7
763be49
 
 
 
 
 
 
 
 
 
 
 
 
545f5f7
763be49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ce812
 
763be49
 
 
 
 
 
 
02ce812
763be49
 
 
 
 
 
 
 
02ce812
763be49
 
 
 
 
 
 
 
 
0817dc1
 
 
 
 
 
 
 
 
 
763be49
0817dc1
763be49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ce812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763be49
 
 
 
 
 
 
 
 
 
 
 
 
02ce812
 
763be49
 
 
 
 
 
 
 
 
02ce812
 
763be49
 
02ce812
763be49
 
02ce812
763be49
02ce812
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import { useState, useCallback } from 'react';
import { ToastMessage } from './useToasts';
import { dataURLtoBlob, calculateSHA256, copyToClipboard } from '../utils/canvasUtils';
import { CanvasHistoryHook } from './useCanvasHistory';

const SHARE_API_URL = 'https://sharefile.suisuy.eu.org';
const ASK_API_URL = 'https://getai.deno.dev/';
const MAX_UPLOAD_SIZE_BYTES = 50 * 1024 * 1024; // 50MB

export type AiImageQuality = 'low' | 'medium' | 'hd';
export type AiDimensionsMode = 'api_default' | 'match_canvas' | 'fixed_1024';

interface AiFeaturesHook {
  isMagicUploading: boolean;
  showAiEditModal: boolean;
  aiPrompt: string;
  isGeneratingAiImage: boolean;
  sharedImageUrlForAi: string | null;
  aiEditError: string | null;
  isAskingAi: boolean;
  askUrl: string | null;
  handleMagicUpload: () => Promise<void>;
  handleGenerateAiImage: () => Promise<void>;
  handleAskAi: () => Promise<void>;
  handleCancelAiEdit: () => void;
  setAiPrompt: React.Dispatch<React.SetStateAction<string>>;
  clearAskUrl: () => void;
}

interface UseAiFeaturesProps {
  currentDataURL: string | null;
  showToast: (message: string, type: ToastMessage['type']) => void;
  updateCanvasState: CanvasHistoryHook['updateCanvasState'];
  setZoomLevel: (zoom: number) => void; 
  aiImageQuality: AiImageQuality;
  aiApiEndpoint: string;
  aiDimensionsMode: AiDimensionsMode;
  currentCanvasWidth: number; 
  currentCanvasHeight: number; 
}

export const useAiFeatures = ({
  currentDataURL,
  showToast,
  updateCanvasState,
  setZoomLevel, 
  aiImageQuality,
  aiApiEndpoint,
  aiDimensionsMode,
  currentCanvasWidth, 
  currentCanvasHeight, 
}: UseAiFeaturesProps): AiFeaturesHook => {
  const [isMagicUploading, setIsMagicUploading] = useState<boolean>(false);
  const [showAiEditModal, setShowAiEditModal] = useState<boolean>(false);
  const [aiPrompt, setAiPrompt] = useState<string>('');
  const [isGeneratingAiImage, setIsGeneratingAiImage] = useState<boolean>(false);
  const [sharedImageUrlForAi, setSharedImageUrlForAi] = useState<string | null>(null);
  const [aiEditError, setAiEditError] = useState<string | null>(null);
  const [isAskingAi, setIsAskingAi] = useState<boolean>(false);
  const [askUrl, setAskUrl] = useState<string | null>(null);

  const clearAskUrl = useCallback(() => {
    setAskUrl(null);
  }, []);

  const loadAiImageOntoCanvas = useCallback((aiImageDataUrl: string) => {
    const img = new Image();
    img.onload = () => {
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = currentCanvasWidth;
        tempCanvas.height = currentCanvasHeight;
        const tempCtx = tempCanvas.getContext('2d');

        if (tempCtx) {
            // Fill background (e.g., white)
            tempCtx.fillStyle = '#FFFFFF';
            tempCtx.fillRect(0, 0, currentCanvasWidth, currentCanvasHeight);

            let drawWidth = img.naturalWidth;
            let drawHeight = img.naturalHeight;

            // Scale image if it's larger than the canvas, preserving aspect ratio
            if (img.naturalWidth > currentCanvasWidth || img.naturalHeight > currentCanvasHeight) {
                const aspectRatio = img.naturalWidth / img.naturalHeight;
                if (currentCanvasWidth / aspectRatio <= currentCanvasHeight) {
                    drawWidth = currentCanvasWidth;
                    drawHeight = currentCanvasWidth / aspectRatio;
                } else {
                    drawHeight = currentCanvasHeight;
                    drawWidth = currentCanvasHeight * aspectRatio;
                }
            }
            
            // Ensure dimensions are at least 1px
            drawWidth = Math.max(1, Math.floor(drawWidth));
            drawHeight = Math.max(1, Math.floor(drawHeight));

            // Change: Draw image at top-left (0,0)
            const drawX = 0;
            const drawY = 0;

            tempCtx.drawImage(img, drawX, drawY, drawWidth, drawHeight);
            
            const newCanvasState = tempCanvas.toDataURL('image/png');

            // Update canvas state with the new image, but keep original canvas dimensions
            updateCanvasState(newCanvasState, currentCanvasWidth, currentCanvasHeight);

            setShowAiEditModal(false);
            showToast('AI image applied to canvas!', 'success');
            setAiPrompt(''); 
            setSharedImageUrlForAi(null);
        } else {
            setAiEditError('Failed to create drawing context for AI image.');
        }
        setIsGeneratingAiImage(false);
    };
    img.onerror = () => {
        setAiEditError('Failed to load the generated AI image. It might be an invalid image format.');
        setIsGeneratingAiImage(false);
    };
    img.crossOrigin = "anonymous"; 
    img.src = aiImageDataUrl;
  }, [showToast, updateCanvasState, currentCanvasWidth, currentCanvasHeight]);

  const handleMagicUpload = useCallback(async () => {
    if (isMagicUploading || !currentDataURL) {
        showToast('No canvas content to share.', 'info');
        return;
    }

    setIsMagicUploading(true);
    setAiEditError(null);
    showToast('Uploading image...', 'info');

    try {
        const blob = await dataURLtoBlob(currentDataURL);

        if (blob.size > MAX_UPLOAD_SIZE_BYTES) {
            showToast(`Image too large (${(blob.size / 1024 / 1024).toFixed(2)}MB). Max 50MB.`, 'error');
            setIsMagicUploading(false);
            return;
        }

        const hash = await calculateSHA256(blob);
        const filename = `tempaint_${hash}.png`;
        const uploadUrl = `${SHARE_API_URL}/${filename}`;

        const response = await fetch(uploadUrl, {
            method: 'POST',
            headers: { 'Content-Type': blob.type || 'image/png' },
            body: blob,
        });

        if (!response.ok) {
            let errorMsg = `Upload failed: ${response.statusText}`;
            try { const errorBody = await response.text(); errorMsg = `Upload failed: ${errorBody || response.statusText}`; } catch (e) { /* ignore */ }
            throw new Error(errorMsg);
        }

        const returnedObjectName = await response.text();
        const finalShareUrl = `https://pub-cb2c87ea7373408abb1050dd43e3cd8e.r2.dev/${returnedObjectName}`;
        
        setSharedImageUrlForAi(finalShareUrl);
        setShowAiEditModal(true); 
        setAiPrompt(''); 
        setAiEditError(null);
        clearAskUrl();

    } catch (error: any) {
        console.error('Magic upload error:', error);
        showToast(error.message || 'Magic upload failed. Check console.', 'error');
    } finally {
        setIsMagicUploading(false); 
    }
  }, [isMagicUploading, currentDataURL, showToast, clearAskUrl]);

  const handleGenerateAiImage = useCallback(async () => {
    if (!aiPrompt.trim() || !sharedImageUrlForAi) {
      setAiEditError('Please enter a prompt and ensure an image was uploaded.');
      return;
    }
    setIsGeneratingAiImage(true);
    setAiEditError(null);
    clearAskUrl();
    showToast('Generating AI image...', 'info');

    const encodedPrompt = encodeURIComponent(aiPrompt);
    const encodedImageUrl = encodeURIComponent(sharedImageUrlForAi);
    
    let finalApiUrl = aiApiEndpoint
        .replace('{prompt}', encodedPrompt)
        .replace('{imgurl.url}', encodedImageUrl);
        
    if (finalApiUrl.includes('{quality}')) {
        finalApiUrl = finalApiUrl.replace('{quality}', aiImageQuality);
    }

    if (finalApiUrl.includes('{size_params}')) {
        let sizeParamsString = '';
        if (aiDimensionsMode === 'match_canvas') {
            sizeParamsString = `&width=${currentCanvasWidth}&height=${currentCanvasHeight}`;
        } else if (aiDimensionsMode === 'fixed_1024') {
            sizeParamsString = `&width=1024&height=1024`;
        }
        finalApiUrl = finalApiUrl.replace('{size_params}', sizeParamsString);
    }
    
    try {
      const response = await fetch(finalApiUrl);
      if (!response.ok) {
        let errorMsg = `AI image generation failed: ${response.status} ${response.statusText}`;
        try {
            const errorBody = await response.text(); 
            if (errorBody && !errorBody.toLowerCase().includes('<html')) {
                 errorMsg += ` - ${errorBody.substring(0,100)}`;
            }
        } catch(e) { /* ignore if can't read body */ }
        throw new Error(errorMsg);
      }
      
      const imageBlob = await response.blob();
      if (!imageBlob.type.startsWith('image/')) {
        throw new Error('AI service did not return a valid image. Please try a different prompt or check the API endpoint.');
      }

      const reader = new FileReader();
      reader.onloadend = () => {
        if (typeof reader.result === 'string') {
          loadAiImageOntoCanvas(reader.result);
        } else {
          setAiEditError('Failed to read AI image data as string.');
          setIsGeneratingAiImage(false);
        }
      };
      reader.onerror = () => {
        setAiEditError('Failed to read AI image data.');
        setIsGeneratingAiImage(false);
      }
      reader.readAsDataURL(imageBlob);

    } catch (error: any) {
      console.error('AI image generation error:', error);
      setAiEditError(error.message || 'An unknown error occurred during AI image generation.');
      setIsGeneratingAiImage(false);
    }
  }, [aiPrompt, sharedImageUrlForAi, showToast, loadAiImageOntoCanvas, aiImageQuality, aiApiEndpoint, aiDimensionsMode, currentCanvasWidth, currentCanvasHeight, clearAskUrl]);

  const handleAskAi = useCallback(async () => {
    if (!aiPrompt.trim() || !sharedImageUrlForAi) {
      setAiEditError('Please enter a question about the image.');
      return;
    }
    setIsAskingAi(true);
    setAiEditError(null);
    setAskUrl(null); // Clear previous URL first

    try {
        const encodedPrompt = encodeURIComponent(aiPrompt);
        const encodedImageUrl = encodeURIComponent(sharedImageUrlForAi);
        const finalAskUrl = `${ASK_API_URL}?q=${encodedPrompt}&image=${encodedImageUrl}`;
        setAskUrl(finalAskUrl);

    } catch (error: any) {
        console.error('AI ask error:', error);
        setAiEditError(error.message || 'An unknown error occurred while asking AI.');
    } finally {
        setIsAskingAi(false);
    }
  }, [aiPrompt, sharedImageUrlForAi]);
  

  const handleCancelAiEdit = () => {
    setShowAiEditModal(false);
    if (sharedImageUrlForAi) {
        copyToClipboard(sharedImageUrlForAi, (msg, type) => showToast(msg,type as 'info' | 'error')).then(copied => {
            if(copied) {
                 showToast(`Image uploaded! URL: ${sharedImageUrlForAi} (Copied!)`, 'success');
            }
        });
    }
    setAiPrompt('');
    setAiEditError(null);
    setSharedImageUrlForAi(null);
    clearAskUrl();
  };

  return {
    isMagicUploading,
    showAiEditModal,
    aiPrompt,
    isGeneratingAiImage,
    sharedImageUrlForAi,
    aiEditError,
    isAskingAi,
    askUrl,
    handleMagicUpload,
    handleGenerateAiImage,
    handleAskAi,
    handleCancelAiEdit,
    setAiPrompt,
    clearAskUrl,
  };
};