// AI-powered image search functionality // Initialize search form function initializeSearchForm() { const form = document.getElementById('searchForm'); const thresholdSlider = document.getElementById('similarityThreshold'); const thresholdValue = document.getElementById('thresholdValue'); // Update threshold display thresholdSlider.addEventListener('input', (e) => { thresholdValue.textContent = e.target.value; }); // Handle form submission form.addEventListener('submit', (e) => { e.preventDefault(); performSearch(); }); } // Perform search async function performSearch() { if (!config.isConfigured()) { showAlert('Please configure your API settings first.', 'warning'); return; } const query = document.getElementById('searchQuery').value.trim(); const threshold = parseFloat(document.getElementById('similarityThreshold').value); const maxResults = parseInt(document.getElementById('maxResults').value); if (!query) { showAlert('Please enter a search query', 'danger'); return; } const resultsContainer = document.getElementById('searchResults'); resultsContainer.innerHTML = `

Searching for "${escapeHtml(query)}"...

`; try { console.log('Performing search with:', { query, threshold, maxResults }); const response = await apiClient.searchImages(query, threshold, maxResults); console.log('Search response received:', response); await displaySearchResults(response, query); } catch (error) { console.error('Search error:', error); handleApiError(error, 'searching images'); resultsContainer.innerHTML = `
Search failed. Please try again.
`; } } // Display search results async function displaySearchResults(response, query) { const container = document.getElementById('searchResults'); console.log('displaySearchResults called with:', { response, query }); // Extract results array from response object const results = response.results || response; console.log('Extracted results:', results); console.log('Results is array:', Array.isArray(results)); if (!results || !Array.isArray(results) || results.length === 0) { container.innerHTML = `

No results found

Try adjusting your search query or similarity threshold

`; return; } console.log('Processing', results.length, 'results'); // Create results HTML with placeholder images first const resultsHtml = `

Search Results

Found ${results.length} images matching "${escapeHtml(query)}"

${results.map(result => { // Handle both old format (result.image) and new format (direct result) const image = result.image || result; const similarity = result.similarity || result.similarity_score || 0; console.log('Processing result:', { result, image, similarity }); return `
${escapeHtml(image.description || 'Image')}
${Math.round(similarity * 100)}% match
${escapeHtml(truncateText(image.description || 'Untitled', 60))}

${formatDate(image.upload_date)}

${image.tags && image.tags.length > 0 ? `
${image.tags.slice(0, 3).map(tag => `${escapeHtml(tag)}` ).join('')} ${image.tags.length > 3 ? `+${image.tags.length - 3}` : '' }
` : ''}
Similarity: ${(similarity * 100).toFixed(1)}%
`; }).join('')}
`; container.innerHTML = resultsHtml; // Load actual images asynchronously (need to import loadImageBlob from images.js) for (const result of results) { const image = result.image || result; if (typeof loadImageBlob === 'function') { loadImageBlob(image.id).then(blobUrl => { const imgElement = document.getElementById(`search-img-${image.id}`); const loadingOverlay = imgElement?.parentElement.querySelector('.loading-overlay'); if (imgElement) { imgElement.src = blobUrl; imgElement.style.opacity = '1'; if (loadingOverlay) { loadingOverlay.style.display = 'none'; } } }).catch(error => { console.error(`Failed to load search image ${image.id}:`, error); const imgElement = document.getElementById(`search-img-${image.id}`); const loadingOverlay = imgElement?.parentElement.querySelector('.loading-overlay'); if (imgElement) { imgElement.src = '/placeholder-image.png'; imgElement.style.opacity = '1'; if (loadingOverlay) { loadingOverlay.style.display = 'none'; } } }); } } // Add search refinement options addSearchRefinementOptions(query, results); } // Add search refinement options function addSearchRefinementOptions(query, results) { const container = document.getElementById('searchResults'); // Extract common tags from results const allTags = results.flatMap(result => { const image = result.image || result; return image.tags || []; }); const tagCounts = {}; allTags.forEach(tag => { tagCounts[tag] = (tagCounts[tag] || 0) + 1; }); const popularTags = Object.entries(tagCounts) .sort(([,a], [,b]) => b - a) .slice(0, 8) .map(([tag]) => tag); if (popularTags.length > 0) { const refinementHtml = `
Refine your search

Popular tags in these results:

${popularTags.map(tag => ` `).join('')}
`; container.insertAdjacentHTML('beforeend', refinementHtml); } // Add export/share options const actionsHtml = `
`; container.insertAdjacentHTML('beforeend', actionsHtml); } // Refine search with tag function refineSearchWithTag(tag) { const currentQuery = document.getElementById('searchQuery').value.trim(); const newQuery = currentQuery ? `${currentQuery} ${tag}` : tag; document.getElementById('searchQuery').value = newQuery; performSearch(); } // Export search results function exportSearchResults(query) { // This would typically generate a CSV or JSON export showAlert('Export functionality would be implemented here', 'info'); } // Share search results async function shareSearchResults(query) { const url = `${window.location.origin}${window.location.pathname}#search`; const text = `Check out these AI search results for "${query}"`; if (navigator.share) { try { await navigator.share({ title: 'SeReact Search Results', text: text, url: url }); } catch (error) { console.log('Error sharing:', error); copyToClipboard(url); } } else { copyToClipboard(url); } } // Save search function saveSearch(query) { const savedSearches = JSON.parse(localStorage.getItem('savedSearches') || '[]'); if (!savedSearches.includes(query)) { savedSearches.push(query); localStorage.setItem('savedSearches', JSON.stringify(savedSearches)); showAlert('Search saved successfully!', 'success'); updateSavedSearches(); } else { showAlert('This search is already saved', 'info'); } } // Update saved searches display function updateSavedSearches() { const savedSearches = JSON.parse(localStorage.getItem('savedSearches') || '[]'); if (savedSearches.length === 0) return; const searchForm = document.getElementById('searchForm'); const existingSaved = document.getElementById('savedSearches'); if (existingSaved) { existingSaved.remove(); } const savedHtml = `
Saved Searches
${savedSearches.map(search => ` `).join('')}
`; searchForm.insertAdjacentHTML('afterend', savedHtml); } // Load saved search function loadSavedSearch(query) { document.getElementById('searchQuery').value = query; performSearch(); } // Remove saved search function removeSavedSearch(query) { const savedSearches = JSON.parse(localStorage.getItem('savedSearches') || '[]'); const filtered = savedSearches.filter(search => search !== query); localStorage.setItem('savedSearches', JSON.stringify(filtered)); updateSavedSearches(); showAlert('Saved search removed', 'info'); } // Initialize saved searches on page load document.addEventListener('DOMContentLoaded', () => { // Add a small delay to ensure the search form is loaded setTimeout(updateSavedSearches, 100); });