/** * SignHall AI Search & Q&A Page Logic * Natural language query processing with structured data retrieval */ import { injectLayout, renderExhibitCard } from './layout.js'; import { getAllExhibits } from './data.js'; import { generateAIAnswer, getSuggestedQueries } from './search.js'; import { CATEGORIES } from './config.js'; let allExhibits = []; async function initAISearch() { injectLayout('search'); allExhibits = await getAllExhibits(); // Render suggestion chips const chips = getSuggestedQueries(); const chipsContainer = document.getElementById('suggestion-chips'); chipsContainer.innerHTML = chips.map(q => `${escapeHtml(q)}` ).join(''); // Click on suggestion chips chipsContainer.querySelectorAll('.ai-chip').forEach(chip => { chip.addEventListener('click', () => { const query = chip.getAttribute('data-query'); document.getElementById('ai-input').value = query; handleSearch(query); }); }); // Form submit document.getElementById('ai-form').addEventListener('submit', (e) => { e.preventDefault(); const query = document.getElementById('ai-input').value.trim(); if (query) handleSearch(query); }); // Auto-search if query is in URL const params = new URLSearchParams(window.location.search); const q = params.get('q'); if (q) { document.getElementById('ai-input').value = q; handleSearch(q); } } async function handleSearch(query) { const answerArea = document.getElementById('ai-answer-area'); // Show loading answerArea.innerHTML = `

Searching structured exhibit data...

`; try { const result = await generateAIAnswer(allExhibits, query); renderAIResult(query, result); } catch (err) { answerArea.innerHTML = `

An error occurred while processing your query. Please try again.

`; console.error('AI search error:', err); } } function renderAIResult(query, result) { const answerArea = document.getElementById('ai-answer-area'); // Category badges const catBadges = result.detectedCategories.map(c => { const cat = CATEGORIES[c]; return `${c}`; }).join(''); // Format answer text (convert markdown-style bold to HTML) const formattedAnswer = escapeHtml(result.answer) .replace(/\*\*(.+?)\*\*/g, '$1') .replace(/\n\n/g, '

') .replace(/\n/g, '
'); // Exhibit cards const exhibitCards = result.exhibits.slice(0, 6).map(ex => renderExhibitCard(ex)).join(''); answerArea.innerHTML = `

${catBadges} Query: "${escapeHtml(query)}"

${formattedAnswer}

${result.exhibits.length > 0 ? `

Matched Exhibits (${result.exhibits.length})

${exhibitCards}
` : ''}
`; } function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } function escapeAttr(text) { return text.replace(/"/g, '"').replace(/'/g, '''); } initAISearch();