Spaces:
Paused
Paused
Update scripts/ui.js
Browse files12343 unmodified lines891011121314151617181920212223241 unmodified line2627282930313233343536373839404142434445464748495051525354551 unmodified line575859606162636465666768697071724 unmodified lines7778798081828384858687888990// scripts/ui.js -- Final version with form handlingconst BACKEND_URL = 'https://stream-ai-backend.smplushypermedia.workers.dev';3 unmodified linesfunction showNotification(message, isError = false) {const container = getElement('notification');if (!container) return;const bgColor = isError ? 'bg-red-500' : 'bg-green-500';container.innerHTML = `<div class="flex items-center text-white p-4 rounded-lg shadow-lg ${bgColor}"><i class="fas fa-check-circle mr-3"></i><p>${message}</p></div>`;container.classList.add('show');setTimeout(() => { container.classList.remove('show'); }, 4000);}// --- Core Functions ---async function loadRecommendations() {const container = getElement('recommendations-container');if (!container) return;1 unmodified lineconst response = await fetch(`${BACKEND_URL}/api/recommendations`);if (!response.ok) throw new Error(`Network Error: ${response.statusText}`);const listings = await response.json();container.innerHTML = ''; // Clear before loadingif (listings.length === 0) {container.innerHTML = `<p class="text-center col-span-full text-gray-500">No recommendations available yet.</p>`;return;}listings.forEach(item => {const card = document.createElement('div');// ... (The card rendering logic from the previous step remains the same) ...container.appendChild(card);});} catch (error) {container.innerHTML = `<p class="text-center col-span-full text-red-500">Could not load recommendations.</p>`;}}async function handleFormSubmit(event) {event.preventDefault(); // Stop the browser from reloading the pageconst form = event.target;const submitButton = getElement('submit-listing-btn');submitButton.disabled = true;submitButton.textContent = 'Submitting...';const formData = new FormData(form);const listingData = Object.fromEntries(formData.entries());try {const response = await fetch(`${BACKEND_URL}/api/add-listing`, {1 unmodified lineheaders: { 'Content-Type': 'application/json' },body: JSON.stringify(listingData),});const result = await response.json();if (!response.ok) {throw new Error(result.details || 'Submission failed.');}showNotification('Success! Your recommendation has been added.');form.reset(); // Clear the form fieldsloadRecommendations(); // Refresh the list to show the new item} catch (error) {showNotification(`Error: ${error.message}`, true);4 unmodified lines}// --- Initialization ---export function initUI() {const addListingForm = getElement('add-listing-form');if (addListingForm) {addListingForm.addEventListener('submit', handleFormSubmit);}// Load the initial recommendations when the page loadsloadRecommendations();}12343 unmodified lines89101112131415161718192021222324252627282930313233341 unmodified line363738394041424344454647484950515253545556575859601 unmodified line6263646566676869707172737475767778798081824 unmodified lines87888990919293949596979899100101102103104105106107108// scripts/ui.js -- Final version with dropdown form and instant UI updateconst BACKEND_URL = 'https://stream-ai-backend.smplushypermedia.workers.dev';3 unmodified linesfunction showNotification(message, isError = false) {const container = getElement('notification');if (!container) return;const bgColor = isError ? 'bg-red-500' : 'bg-green-500';container.innerHTML = `<div class="flex items-center text-white p-4 rounded-lg shadow-lg ${bgColor}"><i class="fas fa-check-circle mr-3"></i><p>${message}</p></div>`;container.classList.add('show');setTimeout(() => { container.classList.remove('show'); }, 4000);}// --- Card Rendering ---function createListingCard(item) {const card = document.createElement('div');const pinnedClass = item.is_pinned ? 'border-2 border-indigo-400' : 'shadow-md';card.className = `stream-card bg-white rounded-lg overflow-hidden hover:shadow-xl transition duration-300 p-4 relative ${pinnedClass}`;card.innerHTML = `${item.is_pinned ? '<div class="absolute top-2 right-2 text-xs bg-indigo-500 text-white px-2 py-1 rounded-full animate-pulse"><i class="fas fa-thumbtack mr-1"></i> Pinned</div>' : ''}<div class="mb-3"><h3 class="font-bold text-base">${item.title}</h3><div class="text-xs text-gray-500 mb-2 mt-1">From: <span class="font-semibold text-indigo-600">${item.source_name}</span></div></div><p class="text-gray-700 text-sm mb-4">${item.description || ''}</p><div class="flex justify-between items-center mt-auto"><span class="text-xs font-bold uppercase text-gray-400">${(item.category || '').replace('_', ' ')}</span><a href="${item.url}" target="_blank" rel="noopener noreferrer" class="bg-indigo-600 hover:bg-indigo-700 text-white px-3 py-1 rounded-full text-xs font-medium transition">Visit Site</a></div>`;return card;}// --- Core Logic ---async function loadRecommendations() {const container = getElement('recommendations-container');if (!container) return;1 unmodified lineconst response = await fetch(`${BACKEND_URL}/api/recommendations`);if (!response.ok) throw new Error(`Network Error: ${response.statusText}`);const listings = await response.json();container.innerHTML = '';if (listings.length === 0) {container.innerHTML = `<p class="text-center col-span-full text-gray-500">No recommendations available yet.</p>`;return;}listings.forEach(item => container.appendChild(createListingCard(item)));} catch (error) {container.innerHTML = `<p class="text-center col-span-full text-red-500">Could not load recommendations.</p>`;}}async function handleFormSubmit(event) {event.preventDefault();const form = event.target;const submitButton = getElement('submit-listing-btn');submitButton.disabled = true;submitButton.textContent = 'Submitting...';const listingData = Object.fromEntries(new FormData(form).entries());try {const response = await fetch(`${BACKEND_URL}/api/add-listing`, {1 unmodified lineheaders: { 'Content-Type': 'application/json' },body: JSON.stringify(listingData),});const result = await response.json();if (!response.ok) throw new Error(result.details || 'Submission failed.');showNotification('Success! Your recommendation has been added.');// --- BUG FIX: INSTANT UI UPDATE ---// 1. Create a new card with the data we just submitted.const newCard = createListingCard(listingData);// 2. Add it to the top of the list for an instant refresh.getElement('recommendations-container').prepend(newCard);// 3. Close the form.getElement('form-container').classList.add('hidden');getElement('form-chevron').classList.remove('rotate-180');form.reset();} catch (error) {showNotification(`Error: ${error.message}`, true);4 unmodified lines}// --- Initialization ---export function initUI() {const addListingForm = getElement('add-listing-form');const toggleBtn = getElement('toggle-form-btn');const formContainer = getElement('form-container');const chevron = getElement('form-chevron');if (toggleBtn && formContainer && chevron) {toggleBtn.addEventListener('click', () => {formContainer.classList.toggle('hidden');chevron.classList.toggle('rotate-180');});}if (addListingForm) {addListingForm.addEventListener('submit', handleFormSubmit);}loadRecommendations();}
scripts/ui.js+41-23