// 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 { const results = await apiClient.searchImages(query, threshold, maxResults); await displaySearchResults(results, query); } catch (error) { handleApiError(error, 'searching images'); resultsContainer.innerHTML = `
Search failed. Please try again.
`; } } // Display search results async function displaySearchResults(results, query) { const container = document.getElementById('searchResults'); if (!results || results.length === 0) { container.innerHTML = `

No results found

Try adjusting your search query or similarity threshold

`; return; } // Create results HTML with placeholder images first const resultsHtml = `

Search Results

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

${results.map(result => `
${escapeHtml(result.image.description || 'Image')}
${Math.round(result.similarity * 100)}% match
${escapeHtml(truncateText(result.image.description || 'Untitled', 60))}

${formatDate(result.image.upload_date)}

${result.image.tags && result.image.tags.length > 0 ? `
${result.image.tags.slice(0, 3).map(tag => `${escapeHtml(tag)}` ).join('')} ${result.image.tags.length > 3 ? `+${result.image.tags.length - 3}` : '' }
` : ''}
Similarity: ${(result.similarity * 100).toFixed(1)}%
`).join('')}
`; container.innerHTML = resultsHtml; // Load actual images asynchronously (need to import loadImageBlob from images.js) for (const result of results) { if (typeof loadImageBlob === 'function') { loadImageBlob(result.image.id).then(blobUrl => { const imgElement = document.getElementById(`search-img-${result.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 ${result.image.id}:`, error); const imgElement = document.getElementById(`search-img-${result.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 => result.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); });