From 4c2de1f8a73163c70f69e5a8943146a319c53bef Mon Sep 17 00:00:00 2001 From: Deepak Salunke Date: Wed, 4 Feb 2026 20:56:31 +0530 Subject: [PATCH] Result: Javascript removed & created js file --- assets/js/result.js | 324 ++++++++++++++++++++++++++++++++++++++++++++ result.php | 312 +----------------------------------------- 2 files changed, 325 insertions(+), 311 deletions(-) create mode 100644 assets/js/result.js diff --git a/assets/js/result.js b/assets/js/result.js new file mode 100644 index 0000000..5ee37bd --- /dev/null +++ b/assets/js/result.js @@ -0,0 +1,324 @@ +(function() { + + function getSessionId() { + // Get session_id from URL query parameter + const urlParams = new URLSearchParams(window.location.search); + let sessionId = urlParams.get('session_id'); + + if (!sessionId) { + // No session_id in URL, check localStorage + try { + const submissionData = localStorage.getItem('submission_data'); + + if (submissionData) { + const data = JSON.parse(submissionData); + + if (data.entries && data.entries.length > 0) { + // Sort entries by timestamp (newest first) and get the latest + const sortedEntries = data.entries.sort((a, b) => { + return new Date(b.timestamp) - new Date(a.timestamp); + }); + + const latestEntry = sortedEntries[0]; + sessionId = latestEntry.session_id; + console.log(`Loading session from localStorage: ${sessionId} from ${latestEntry.timestamp}`); + } + } + } catch (error) { + console.error(`Error reading from localStorage: ${error}`); + } + + // If still no session_id, redirect to home + if (!sessionId) { + window.location.href = '/'; + return null; + } + } + + return sessionId; + } + + const API_BASE_URL = 'https://valentinesong.oliver.digital/back'; + let videoPlayer = null; + let resultData = null; + + async function loadResults() { + try { + const response = await fetch(`${API_BASE_URL}/api/results/${sessionId}`); + + if (!response.ok) { + if (response.status === 404) { + showError('Song not found. Please create a new one.'); + return; + } + throw new Error('Failed to load results'); + } + + resultData = await response.json(); + + if (resultData.success && resultData.status === 'success') { + showSuccess(resultData); + } else { + showFailure(resultData); + } + } catch (error) { + console.error('Error loading results:', error); + showError('Failed to load your song. Please try again.'); + } + } + + function escapeHtml(text) { + const div = document.createElement('div'); + div.textContent = text; + return div.innerHTML; + } + + function showSuccess(data) { + // Update page title + const titleEl = document.querySelector('.title1'); + if (titleEl) { + titleEl.textContent = `${data.pet_name}'s Love Song`; + } + + // Replace rotating record with video player + /*const recordContainer = document.querySelector('.record-container'); + if (recordContainer && data.video_url) { + recordContainer.innerHTML = ` + + `; + videoPlayer = document.getElementById('video-player'); + }*/ + + // Replace rotating record with image + const recordContainer = document.querySelector('.record-container'); + if (recordContainer && data.record_image_url) { + document.getElementById("pet-record").src = data.record_image_url; + } + + // Update lyrics + const lyricsEl = document.querySelector('.song-lyrics'); + if (lyricsEl && data.lyrics) { + // Format lyrics with line breaks + lyricsEl.innerHTML = escapeHtml(data.lyrics).replace(/\n/g, '
'); + } + + // Render lyrics + renderLyrics(data.lyrics, lyricsEl); + + // Setup auto-scroll functionality + //setupAutoScroll(videoPlayer, lyricsEl); + + // Hide play/pause controls (video has its own controls) + const songControl = document.querySelector('.song-control'); + if (songControl) { + songControl.style.display = 'none'; + } + + // Setup download button + const downloadBtn = document.querySelector('.download-song-btn'); + if (downloadBtn && data.video_url) { + downloadBtn.href = data.video_url; + downloadBtn.download = `${data.pet_name}-love-song.mp4`; + } + + // Setup copy URL button + const copyBtn = document.querySelector('.copy-btn'); + if (copyBtn) { + copyBtn.addEventListener('click', () => { + navigator.clipboard.writeText(window.location.href).then(() => { + const originalText = copyBtn.textContent; + copyBtn.textContent = 'Copied!'; + setTimeout(() => { + copyBtn.textContent = originalText; + }, 2000); + }).catch(() => { + // Fallback for older browsers + const textArea = document.createElement('textarea'); + textArea.value = window.location.href; + document.body.appendChild(textArea); + textArea.select(); + document.execCommand('copy'); + document.body.removeChild(textArea); + copyBtn.textContent = 'Copied!'; + setTimeout(() => { + copyBtn.textContent = 'Copy URL'; + }, 2000); + }); + }); + } + + // Setup share buttons + setupShareButtons(data); + } + + function showFailure(data) { + const bodyContainer = document.querySelector('.body-container'); + if (bodyContainer) { + bodyContainer.innerHTML = ` +
Oops! Something went wrong
+
We couldn't generate ${escapeHtml(data.pet_name)}'s love song. Please try again.
+ + `; + } + } + + function showError(message) { + const bodyContainer = document.querySelector('.body-container'); + if (bodyContainer) { + bodyContainer.innerHTML = ` +
Error
+
${escapeHtml(message)}
+ + `; + } + } + + function setupShareButtons(data) { + const shareUrl = encodeURIComponent(window.location.href); + const shareText = encodeURIComponent(`Check out ${data.pet_name}'s love song! #PetLoveSongs @PetsatHome`); + + // Facebook share + const fbBtn = document.querySelector('.facebook'); + if (fbBtn) { + fbBtn.style.cursor = 'pointer'; + fbBtn.addEventListener('click', () => { + window.open(`https://www.facebook.com/sharer/sharer.php?u=${shareUrl}`, '_blank', 'width=600,height=400'); + }); + } + + // TikTok - link to TikTok (can't directly share, user downloads and uploads) + const tiktokBtn = document.querySelector('.tiktok'); + if (tiktokBtn) { + tiktokBtn.style.cursor = 'pointer'; + tiktokBtn.addEventListener('click', () => { + alert('Download your video and upload it to TikTok with #PetLoveSongs @PetsatHome'); + }); + } + + // Instagram - similar to TikTok + const instaBtn = document.querySelector('.instagram'); + if (instaBtn) { + instaBtn.style.cursor = 'pointer'; + instaBtn.addEventListener('click', () => { + alert('Download your video and share it on Instagram with #PetLoveSongs @PetsatHome'); + }); + } + } + + function renderLyrics(lyrics, container) { + const lyricsLines = lyrics.split('\n'); + const lyricsHTML = lyricsLines + .map(line => `
${line || ' '}
`) + .join(''); + + container.innerHTML = lyricsHTML; + } + + function setupAutoScroll(audio, lyricsContainer) { + let scrollAnimationId = null; + let totalDuration = 0; + let maxScroll = 0; + + // Update scroll position based on current audio time + function updateScroll() { + const progress = audio.currentTime / totalDuration; + const scrollPosition = progress * maxScroll; + lyricsContainer.scrollTop = scrollPosition; + + // Continue animation if audio is playing + if (!audio.paused) { + scrollAnimationId = requestAnimationFrame(updateScroll); + } + } + + // Initialize scroll parameters when metadata is loaded + audio.addEventListener('loadedmetadata', () => { + totalDuration = audio.duration; + maxScroll = lyricsContainer.scrollHeight - lyricsContainer.clientHeight; + + console.log('Audio duration (seconds):', totalDuration); + console.log('Max scroll distance:', maxScroll); + console.log('Scroll speed:', (maxScroll / totalDuration).toFixed(2), 'pixels per second'); + }); + + // Start scrolling when audio plays + audio.addEventListener('play', () => { + if (scrollAnimationId) { + cancelAnimationFrame(scrollAnimationId); + } + updateScroll(); + }); + + // Stop scrolling when audio pauses + audio.addEventListener('pause', () => { + if (scrollAnimationId) { + cancelAnimationFrame(scrollAnimationId); + scrollAnimationId = null; + } + }); + + // Update scroll position when user seeks + audio.addEventListener('seeked', () => { + const progress = audio.currentTime / totalDuration; + const scrollPosition = progress * maxScroll; + lyricsContainer.scrollTop = scrollPosition; + + // Restart animation if audio is playing + if (!audio.paused) { + if (scrollAnimationId) { + cancelAnimationFrame(scrollAnimationId); + } + updateScroll(); + } + }); + } + + function startCountdown() { + let totalSeconds = 180; // logical countdown time (3 minutes) + const timerElement = document.getElementById("timer"); + + // Each displayed second should last 1.15 real seconds + const intervalTime = 1150; // milliseconds + + const interval = setInterval(() => { + // Calculate minutes and seconds + let minutes = Math.floor(totalSeconds / 60); + let seconds = totalSeconds % 60; + + // Format with leading zero for seconds + timerElement.textContent = `${minutes}:${seconds.toString().padStart(2, "0")}`; + + totalSeconds--; + + if (totalSeconds < 0) { + clearInterval(interval); + timerElement.textContent = "0:00"; + } + }, intervalTime); + } + + // Setup "Need another song" button + const anotherSongBtn = document.querySelector('.make-another-song-btn'); + if (anotherSongBtn) { + anotherSongBtn.addEventListener('click', () => { + window.location.href = '/'; + }); + } + + // Main function + function main() { + sessionId = getSessionId(); + if (!sessionId) return; + + startCountdown(); + + // Load results on page load + loadResults(); + } + + // Initialize + main(); +})(); \ No newline at end of file diff --git a/result.php b/result.php index 058f1c5..d002a78 100644 --- a/result.php +++ b/result.php @@ -63,316 +63,6 @@ - + \ No newline at end of file