File size: 11,834 Bytes
7c7ef49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Get the current hostname (will work both locally and in Docker)
const API_BASE = `${window.location.protocol}//${window.location.hostname}:8002`;

// Interface switching
function setupNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    
    navItems.forEach(item => {
        item.addEventListener('click', () => {
            const mode = item.dataset.mode;
            
            // Update navigation state
            navItems.forEach(nav => nav.classList.remove('active'));
            item.classList.add('active');
            
            // Update interface visibility
            document.querySelectorAll('.interface').forEach(interface => {
                interface.classList.remove('active');
            });
            document.getElementById(mode).classList.add('active');
        });
    });
}

// Helper functions
function setLoading(button, isLoading) {
    if (isLoading) {
        button.classList.add('loading');
        button.disabled = true;
    } else {
        button.classList.remove('loading');
        button.disabled = false;
    }
}

function showError(container, message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message || 'An error occurred. Please try again.';
    container.innerHTML = '';
    container.appendChild(errorDiv);
    updateResultsPanel(null); // Clear the results panel
}

function updateResultsPanel(textData) {
    const panel = document.getElementById('resultsPanel');
    const mainContent = document.querySelector('.main-content');
    
    if (!textData) {
        panel.classList.remove('visible');
        mainContent.classList.remove('with-panel');
        return;
    }

    panel.innerHTML = ''; // Clear previous content
    
    // Add title
    const title = document.createElement('h2');
    title.textContent = 'Generated Information';
    title.style.marginBottom = '1.5rem';
    panel.appendChild(title);

    if (typeof textData === 'string') {
        // Handle legacy string data
        const p = document.createElement('p');
        p.textContent = textData;
        panel.appendChild(p);
    } else {
        // Handle structured data
        Object.entries(textData).forEach(([section, content]) => {
            const sectionDiv = document.createElement('div');
            sectionDiv.className = 'text-section';
            
            const title = document.createElement('h3');
            title.className = 'section-title';
            title.textContent = section.split('_').map(word => 
                word.charAt(0).toUpperCase() + word.slice(1)
            ).join(' ');
            
            const content_p = document.createElement('p');
            content_p.textContent = content;
            
            sectionDiv.appendChild(title);
            sectionDiv.appendChild(content_p);
            panel.appendChild(sectionDiv);
        });
    }

    panel.classList.add('visible');
    mainContent.classList.add('with-panel');
}

function createResultElement(item) {
    if (item.type === 'text') {
        // Update the panel with text data
        updateResultsPanel(item.data);
        return null; // Don't create an element in the main content area
    } else if (item.type === 'image') {
        const wrapper = document.createElement('div');
        wrapper.className = 'image-wrapper';
        
        const img = document.createElement('img');
        img.src = item.data;
        img.addEventListener('load', () => wrapper.classList.add('loaded'));
        
        wrapper.appendChild(img);
        return wrapper;
    }
    return null;
}

// File input handling
function setupFileInput() {
    const fileInput = document.getElementById('inputImage');
    const dropZone = document.querySelector('.file-input-wrapper');
    
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
    });
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, () => {
            dropZone.classList.add('highlight');
        });
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, () => {
            dropZone.classList.remove('highlight');
        });
    });
    
    dropZone.addEventListener('drop', (e) => {
        const dt = e.dataTransfer;
        const files = dt.files;
        fileInput.files = files;
        updateFileLabel(files[0]?.name);
    });
    
    fileInput.addEventListener('change', (e) => {
        updateFileLabel(e.target.files[0]?.name);
    });
}

function updateFileLabel(filename) {
    const label = document.querySelector('label[for="inputImage"] span');
    label.textContent = filename || 'Choose an image or drag & drop here';
}

// Text to Image Generation
document.getElementById('generate').addEventListener('click', async () => {
    const prompt = document.getElementById('prompt').value.trim();
    const category = document.getElementById('category').value;
    const generateButton = document.getElementById('generate');
    const resultsDiv = document.getElementById('results');
    
    if (!prompt) {
        showError(resultsDiv, 'Please enter a description for the schematic.');
        return;
    }
    
    resultsDiv.innerHTML = '';
    setLoading(generateButton, true);
    
    try {
        const res = await fetch(`${API_BASE}/generate`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ prompt, category })
        });
        
        if (!res.ok) {
            throw new Error(`Server responded with ${res.status}`);
        }
        
        const data = await res.json();
        const resultElements = data.results
            .map(createResultElement)
            .filter(element => element !== null);
            
        if (resultElements.length === 0) {
            showError(resultsDiv, 'No results generated. Please try again.');
            return;
        }
        
        resultElements.forEach(element => resultsDiv.appendChild(element));
        
    } catch (err) {
        console.error(err);
        showError(resultsDiv, 'Error generating schematic. Please try again.');
    } finally {
        setLoading(generateButton, false);
    }
});

// Image with Text Generation
document.getElementById('generateWithImage').addEventListener('click', async () => {
    const fileInput = document.getElementById('inputImage');
    const prompt = document.getElementById('imagePrompt').value.trim();
    const generateButton = document.getElementById('generateWithImage');
    const resultsDiv = document.getElementById('resultsImg');
    
    if (!fileInput.files.length) {
        showError(resultsDiv, 'Please select an image file.');
        return;
    }
    
    const file = fileInput.files[0];
    if (!file.type.startsWith('image/')) {
        showError(resultsDiv, 'Please select a valid image file.');
        return;
    }
    
    resultsDiv.innerHTML = '';
    setLoading(generateButton, true);
    
    try {
        const base64 = await new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => resolve(e.target.result);
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
        
        const category = document.getElementById('imageCategory').value;
        
        const res = await fetch(`${API_BASE}/generate_with_image`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
                text: prompt || '',  // Send empty string if no prompt provided
                image: base64,
                category
            })
        });
        
        if (!res.ok) {
            throw new Error(`Server responded with ${res.status}`);
        }
        
        const data = await res.json();
        const resultElements = data.results
            .map(createResultElement)
            .filter(element => element !== null);
            
        if (resultElements.length === 0) {
            showError(resultsDiv, 'No results generated. Please try again.');
            return;
        }
        
        resultElements.forEach(element => resultsDiv.appendChild(element));
        
    } catch (err) {
        console.error(err);
        showError(resultsDiv, 'Error generating modified schematic. Please try again.');
    } finally {
        setLoading(generateButton, false);
    }
});

// Category handling
async function fetchCategories() {
    try {
        const res = await fetch(`${API_BASE}/categories`);
        if (!res.ok) throw new Error('Failed to fetch categories');
        return await res.json();
    } catch (error) {
        console.error('Error fetching categories:', error);
        return null;
    }
}

function updateCategoryInfo(categoryData, infoDiv) {
    if (!infoDiv) {
        console.error('Category info div not found');
        return;
    }

    if (!categoryData) {
        infoDiv.innerHTML = '';
        infoDiv.classList.remove('visible');
        return;
    }

    const html = `
        <h4>${categoryData.name}</h4>
        <p>${categoryData.description}</p>
        <p><strong>Style Guide:</strong> ${categoryData.style_guide}</p>
        
        <h4>Drawing Conventions:</h4>
        <div class="conventions-list">
            ${categoryData.conventions.map(conv => `
                <span class="convention-tag">${conv}</span>
            `).join('')}
        </div>
        
        <h4>Common Elements:</h4>
        <div class="elements-list">
            ${categoryData.common_elements.map(elem => `
                <span class="element-tag">${elem}</span>
            `).join('')}
        </div>
    `;
    
    infoDiv.innerHTML = html;
    infoDiv.classList.add('visible');
}

async function setupCategories() {
    try {
        const categories = await fetchCategories();
        if (!categories) return;
        
        // Setup for both category selects
        [
            { selectId: 'category', infoId: 'categoryInfo' },
            { selectId: 'imageCategory', infoId: 'imageCategoryInfo' }
        ].forEach(({ selectId, infoId }) => {
            const select = document.getElementById(selectId);
            if (!select) {
                console.error(`Select element with id ${selectId} not found`);
                return;
            }
            
            // Clear existing options
            select.innerHTML = '<option value="">Select Engineering Category (Optional)</option>';
            
            // Add category options
            Object.entries(categories).forEach(([key, data]) => {
                const option = document.createElement('option');
                option.value = key;
                option.textContent = data.name;
                select.appendChild(option);
            });
            
            // Add change event listener
            select.addEventListener('change', (e) => {
                const selectedCategory = e.target.value;
                const infoElement = document.getElementById(infoId);
                
                if (selectedCategory && categories[selectedCategory]) {
                    updateCategoryInfo(categories[selectedCategory], infoElement);
                } else {
                    updateCategoryInfo(null, infoElement);
                }
            });
        });
    } catch (error) {
        console.error('Error setting up categories:', error);
    }
}

// Initialize functionality
setupNavigation();
setupFileInput();
setupCategories();