CSNET's picture
ต่อไปทำปุ่ม IF Timer ให้ใช้งานได้ 100% เช่นการเซตเลือกประเภททำ IF และแนะนำวิธีการทำ พร้อมความยากง่าย
00b70a9 verified
Raw History Blame Contribute Delete
41.1 kB
// Pulse App Main JavaScript class PulseApp { constructor() { this.currentPage = 'dashboard'; this.isIFActive = false; this.ifTimer = null; this.ifStartTime = null; this.init(); } init() { // Set current date this.updateDate(); // Initialize navigation this.initNavigation(); // Initialize IF timer this.initIFTimer(); // Initialize page-specific features this.initMoodLogging(); this.initNutritionTracking(); this.initActivityTracking(); this.initSleepTracking(); // Simulate real-time data updates this.startRealTimeUpdates(); // Initialize location services this.requestLocationPermission(); // Check device capabilities this.checkDeviceCapabilities(); } updateDate() { const date = new Date(); const options = { day: 'numeric', month: 'short', year: 'numeric' }; const thaiDate = date.toLocaleDateString('th-TH', options); const dateElement = document.getElementById('currentDate'); if (dateElement) { dateElement.textContent = thaiDate; } } initNavigation() { // Set active navigation this.setActiveNav('dashboard'); } setActiveNav(page) { const navButtons = document.querySelectorAll('.nav-btn'); navButtons.forEach(btn => { btn.classList.remove('active'); if (btn.dataset.page === page) { btn.classList.add('active'); } }); // Hide all navigation items for special pages const specialPages = ['recovery', 'strain']; const nav = document.querySelector('nav.fixed.bottom-0'); if (nav) { if (specialPages.includes(page)) { nav.classList.add('hidden'); } else { nav.classList.remove('hidden'); } } } // Initialize mood logging initMoodLogging() { const moodButtons = document.querySelectorAll('.mood-btn'); moodButtons.forEach(btn => { btn.addEventListener('click', (e) => { moodButtons.forEach(b => b.classList.remove('selected')); btn.classList.add('selected'); const mood = btn.querySelector('span:last-child').textContent; this.logMood(mood); }); }); } logMood(mood) { // Save mood to localStorage const today = new Date().toISOString().split('T')[0]; const moodLog = JSON.parse(localStorage.getItem('moodLog') || '{}'); moodLog[today] = { mood: mood, timestamp: new Date().toISOString(), factors: this.getSelectedStressFactors() }; localStorage.setItem('moodLog', JSON.stringify(moodLog)); this.showNotification(`บันทึกอารมณ์: ${mood}`); } getSelectedStressFactors() { const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked'); return Array.from(checkboxes).map(cb => { const label = cb.parentElement.querySelector('span'); return label ? label.textContent : ''; }).filter(text => text); } // Initialize nutrition tracking initNutritionTracking() { this.updateNutritionDisplay(); this.loadRecentMeals(); } updateNutritionDisplay() { const today = new Date().toISOString().split('T')[0]; const nutritionData = JSON.parse(localStorage.getItem('nutritionData') || '{}'); if (nutritionData[today]) { const data = nutritionData[today]; const caloriesElement = document.querySelector('.nutrition-calories'); const carbsElement = document.querySelector('.nutrition-carbs'); const proteinElement = document.querySelector('.nutrition-protein'); if (caloriesElement) caloriesElement.textContent = data.calories || 0; if (carbsElement) carbsElement.textContent = (data.carbs || 0) + 'g'; if (proteinElement) proteinElement.textContent = (data.protein || 0) + 'g'; } } loadRecentMeals() { const today = new Date().toISOString().split('T')[0]; const mealsData = JSON.parse(localStorage.getItem('mealsData') || '{}'); if (mealsData[today]) { const recentMeals = mealsData[today].slice(-3); // Update recent meals display this.displayRecentMeals(recentMeals); } } displayRecentMeals(meals) { const recentMealsContainer = document.querySelector('#nutrition .space-y-3'); if (!recentMealsContainer) return; let mealsHTML = ''; meals.forEach(meal => { mealsHTML += ` <div class="bg-white rounded-xl p-3 shadow-sm border border-gray-100"> <div class="flex items-center justify-between"> <div> <p class="font-semibold text-sm">${meal.name}</p> <p class="text-xs text-gray-500">แคลอรี่: ${meal.calories} kcal</p> </div> <span class="text-xs text-gray-400">${meal.time}</span> </div> </div> `; }); if (mealsHTML) { recentMealsContainer.innerHTML = mealsHTML; } } // Initialize activity tracking initActivityTracking() { this.updateActivityDisplay(); this.loadThaiActivities(); } updateActivityDisplay() { const today = new Date().toISOString().split('T')[0]; const activityData = JSON.parse(localStorage.getItem('activityData') || '{}'); if (activityData[today]) { const data = activityData[today]; // Update strain display const strainElements = document.querySelectorAll('.strain-score'); strainElements.forEach(el => { if (el) el.textContent = data.strain || '0.0'; }); } } loadThaiActivities() { // Thai activity database const thaiActivities = [ { name: 'มวยไทย', strain: 9.5, duration: 60, icon: '🥊' }, { name: 'นั่งสมาธิ', strain: 1.5, duration: 30, icon: '🧘' }, { name: 'เดินจงกรม', strain: 2.0, duration: 45, icon: '🚶' }, { name: 'แบดมินตัน', strain: 7.0, duration: 90, icon: '🏸' }, { name: 'เวทเทรนนิ่ง', strain: 8.0, duration: 75, icon: '🏋️' }, { name: 'สวดมนต์', strain: 1.0, duration: 20, icon: '📿' } ]; // Update activity buttons with Thai activities const activityButtons = document.querySelectorAll('#activity .grid button'); thaiActivities.forEach((activity, index) => { if (activityButtons[index]) { activityButtons[index].addEventListener('click', () => { this.startActivity(activity); }); } }); } startActivity(activity) { const confirmation = confirm(`เริ่ม ${activity.name}?\nระยะเวลา: ${activity.duration} นาที\nStrain: ${activity.strain}`); if (confirmation) { this.showNotification(`เริ่ม ${activity.name}!`); // Save activity start this.saveActivityStart(activity); } } saveActivityStart(activity) { const today = new Date().toISOString().split('T')[0]; const activityData = JSON.parse(localStorage.getItem('activityData') || '{}'); if (!activityData[today]) { activityData[today] = { activities: [], totalStrain: 0, startTime: new Date().toISOString() }; } activityData[today].activities.push({ ...activity, startTime: new Date().toISOString() }); localStorage.setItem('activityData', JSON.stringify(activityData)); } // Initialize sleep tracking initSleepTracking() { this.updateSleepDisplay(); this.loadSleepInsights(); } updateSleepDisplay() { const lastNight = this.getLastSleepDate(); const sleepData = JSON.parse(localStorage.getItem('sleepData') || '{}'); if (sleepData[lastNight]) { const data = sleepData[lastNight]; // Update sleep score const sleepScoreElements = document.querySelectorAll('.sleep-score'); sleepScoreElements.forEach(el => { if (el) el.textContent = data.performance + '%'; }); // Update sleep duration const durationElements = document.querySelectorAll('.sleep-duration'); durationElements.forEach(el => { if (el) { const hours = Math.floor(data.duration / 60); const minutes = data.duration % 60; el.textContent = `${hours}ชม ${minutes}นาที`; } }); } } getLastSleepDate() { const now = new Date(); const yesterday = new Date(now); yesterday.setDate(yesterday.getDate() - 1); return yesterday.toISOString().split('T')[0]; } loadSleepInsights() { const insights = [ 'Deep Sleep เพิ่มขึ้น 20% หลังงดกินกาแฟหลังบ่าย', 'ความสม่ำเสมอดีขึ้น 88% จากสัปดาห์ที่แล้ว 75%', 'ควรรักษาเวลานอนที่ 22:00-06:00 ต่อเนื่อง', 'อุณหภูมิห้องเหมาะสมที่ 22-24°C ช่วยให้นอนหลับลึกขึ้น' ]; // Display random insight const insightElement = document.querySelector('.sleep-insights ul'); if (insightElement) { const randomInsight = insights[Math.floor(Math.random() * insights.length)]; insightElement.innerHTML = `<li>• ${randomInsight}</li>`; } } showPage(page) { // Hide all sections document.querySelectorAll('.page-section').forEach(section => { section.classList.add('hidden'); }); // Show selected section const targetSection = document.getElementById(page); if (targetSection) { targetSection.classList.remove('hidden'); this.currentPage = page; this.setActiveNav(page); // Scroll to top window.scrollTo({ top: 0, behavior: 'smooth' }); // Re-initialize icons for new content if (typeof feather !== 'undefined') { feather.replace(); } } } // IF (Intermittent Fasting) Properties ifType = '16:8'; isIFPaused = false; ifPausedTime = 0; ifTotalDuration = 16 * 60 * 60 * 1000; // 16 hours in milliseconds ifEatingWindow = 8 * 60 * 60 * 1000; // 8 hours in milliseconds initIFTimer() { // Check if IF was active before const ifState = localStorage.getItem('ifState'); if (ifState === 'active' || ifState === 'paused') { const startTime = localStorage.getItem('ifStartTime'); const ifType = localStorage.getItem('ifType') || '16:8'; const ifPausedTime = localStorage.getItem('ifPausedTime') || 0; if (startTime) { this.ifType = ifType; this.ifPausedTime = parseInt(ifPausedTime); this.updateIFConfiguration(); if (ifState === 'paused') { this.isIFPaused = true; this.showPausedIF(); } else { this.startIF(new Date(startTime)); } } } } updateIFConfiguration() { const configs = { '16:8': { fast: 16, eat: 8, difficulty: 'ง่าย', difficultyColor: 'green', difficultyPercent: 20 }, '18:6': { fast: 18, eat: 6, difficulty: 'ปานกลาง', difficultyColor: 'yellow', difficultyPercent: 40 }, '20:4': { fast: 20, eat: 4, difficulty: 'ยาก', difficultyColor: 'orange', difficultyPercent: 60 }, 'eat-stop-eat': { fast: 24, eat: 0, difficulty: 'ยากมาก', difficultyColor: 'red', difficultyPercent: 80 }, '5:2': { fast: 0, eat: 0, difficulty: 'พิเศษ', difficultyColor: 'purple', difficultyPercent: 100 } }; const config = configs[this.ifType]; if (config) { this.ifTotalDuration = config.fast * 60 * 60 * 1000; this.ifEatingWindow = config.eat * 60 * 60 * 1000; // Update UI const difficultyLevel = document.getElementById('difficultyLevel'); const difficultyBar = document.getElementById('difficultyBar'); const ifPhase = document.getElementById('ifPhase'); if (difficultyLevel) { difficultyLevel.textContent = config.difficulty; difficultyLevel.className = `font-semibold text-${config.difficultyColor}-600`; } if (difficultyBar) { difficultyBar.className = `bg-${config.difficultyColor}-500 h-2 rounded-full transition-all duration-300`; difficultyBar.style.width = `${config.difficultyPercent}%`; } if (ifPhase) { if (this.ifType === '5:2') { ifPhase.textContent = 'ลดแคลอรี่ 500-600 กิโลแคลอรี ในวันที่ไม่ทาน'; } else { ifPhase.textContent = `กำหนดการ: งดอาหาร ${config.fast} ชั่วโมง`; } } this.updateIFGuide(); } } updateIFGuide() { const guides = { '16:8': { title: '16:8 คืออะไร?', content: [ '• งดอาหาร 16 ชั่วโมง', '• กินอาหารได้ 8 ชั่วโมง', '• เหมาะสำหรับผู้เริ่มต้น', '• ช่วยลดน้ำหนัก 2-4 กิโล/เดือน' ], tips: [ '• เริ่มจาก 12:12 แล้วค่อยๆ เพิ่มเวลา', '• ดื่มน้ำมากๆ ในช่วงงดอาหาร', '• กินอาหารสมดุลในช่วง 8 ชั่วโมง' ] }, '18:6': { title: '18:6 คืออะไร?', content: [ '• งดอาหาร 18 ชั่วโมง', '• กินอาหารได้ 6 ชั่วโมง', '• ผลลัพธ์เร็วกว่า 16:8', '• ช่วยลดน้ำหนัก 3-5 กิโล/เดือน' ], tips: [ '• ควรทำ 16:8 มา 2-3 สัปดาห์ก่อน', '• เลือกช่วงเวลาที่สะดวก (เช่น 12:00-18:00)', '• ระวังอาการหิวในช่วงแรกๆ' ] }, '20:4': { title: '20:4 (Warrior Diet) คืออะไร?', content: [ '• งดอาหาร 20 ชั่วโมง', '• กินอาหารได้ 4 ชั่วโมง', '• ผลลัพธ์รวดเร็วมาก', '• ช่วยลดน้ำหนัก 4-6 กิโล/เดือน' ], tips: [ '• เหมาะสำหรับคนที่มีประสบการณ์ IF แล้ว', '• ดื่มน้ำเกลือแร่เพื่อป้องกันภาวะขาดน้ำ', '• วางแผนมื้ออาหารให้ดีในช่วง 4 ชั่วโมง' ] }, 'eat-stop-eat': { title: 'Eat-Stop-Eat คืออะไร?', content: [ '• งดอาหาร 24 ชั่วโมง', '• ทำ 1-2 ครั้งต่อสัปดาห์', '• ในวันอื่นกินตามปกติ', '• ช่วยลดน้ำหนัก 1-2 กิโล/สัปดาห์' ], tips: [ '• เริ่มจาก 1 ครั้งต่อสัปดาห์ก่อน', '• งดในวันที่ไม่มีกิจกรรมมาก', '• ดื่มน้ำ ชา กาแฟดำ ได้' ] }, '5:2': { title: '5:2 Diet คืออะไร?', content: [ '• กินตามปกติ 5 วัน', '• ลดแคลอรี่เหลือ 500-600 ใน 2 วัน', '• ไม่ต้องงดอาหารสนิท', '• ช่วยลดน้ำหนัก 2-3 กิโล/เดือน' ], tips: [ '• เลือกวันที่สะดวก (เช่น อังคาร-ศุกร์)', '• แบ่งแคลอรี่เป็น 2-3 มื้อเล็กๆ', '• กินอาหารโปรตีนสูงในวันลดแคล' ] } }; const guide = guides[this.ifType]; if (guide) { const guideContent = document.getElementById('ifGuideContent'); if (guideContent) { let html = `<p><strong>${guide.title}</strong></p>`; guide.content.forEach(line => { html += `<p>${line}</p>`; }); html += `<p class="mt-3"><strong>เคล็ดลับ:</strong></p>`; guide.tips.forEach(tip => { html += `<p>${tip}</p>`; }); guideContent.innerHTML = html; } } } changeIFType() { const select = document.getElementById('ifTypeSelect'); if (select) { this.ifType = select.value; localStorage.setItem('ifType', this.ifType); this.updateIFConfiguration(); // Update display const ifTypeDisplay = document.getElementById('ifTypeDisplay'); if (ifTypeDisplay) { ifTypeDisplay.textContent = this.ifType; } // Reset IF if active if (this.isIFActive) { if (confirm('การเปลี่ยนประเภท IF จะรีเซ็ตการนับเวลา ต้องการเปลี่ยนหรือไม่?')) { this.stopIF(); } else { // Revert selection select.value = localStorage.getItem('ifType') || '16:8'; } } } } startIF(startTime = new Date()) { this.isIFActive = true; this.isIFPaused = false; this.ifStartTime = startTime; this.ifPausedTime = 0; localStorage.setItem('ifState', 'active'); localStorage.setItem('ifStartTime', startTime); localStorage.setItem('ifPausedTime', 0); localStorage.setItem('ifType', this.ifType); this.ifTimer = setInterval(() => { this.updateIFDisplay(); }, 1000); this.updateIFDisplay(); this.updateIFButtons('running'); this.showNotification(`เริ่ม ${this.ifType} แล้ว! 💪`); } stopIF() { this.isIFActive = false; this.isIFPaused = false; clearInterval(this.ifTimer); localStorage.setItem('ifState', 'inactive'); localStorage.removeItem('ifStartTime'); localStorage.removeItem('ifPausedTime'); this.updateIFDisplay(); this.updateIFButtons('stopped'); this.showNotification('หยุด IF แล้ว'); } pauseIF() { if (!this.isIFActive || this.isIFPaused) return; this.isIFPaused = true; this.ifPausedTime = Date.now() - this.ifStartTime; localStorage.setItem('ifState', 'paused'); localStorage.setItem('ifPausedTime', this.ifPausedTime); clearInterval(this.ifTimer); this.updateIFButtons('paused'); this.showNotification('พัก IF ชั่วคราว'); } resumeIF() { if (!this.isIFActive || !this.isIFPaused) return; this.isIFPaused = false; this.ifStartTime = new Date(Date.now() - this.ifPausedTime); localStorage.setItem('ifState', 'active'); this.ifTimer = setInterval(() => { this.updateIFDisplay(); }, 1000); this.updateIFButtons('running'); this.showNotification('ทำ IF ต่อ'); } updateIFDisplay() { const timerElement = document.getElementById('ifTimer'); const statusElement = document.getElementById('ifStatus'); const ifTypeDisplay = document.getElementById('ifTypeDisplay'); if (ifTypeDisplay) { ifTypeDisplay.textContent = this.ifType; } if (!timerElement || !statusElement) return; if (!this.isIFActive) { timerElement.textContent = '--:--:--'; statusElement.textContent = 'ยังไม่ได้เริ่ม'; return; } if (this.isIFPaused) { const pausedDuration = this.ifPausedTime; const hours = Math.floor(pausedDuration / 3600000); const minutes = Math.floor((pausedDuration % 3600000) / 60000); const seconds = Math.floor((pausedDuration % 60000) / 1000); timerElement.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; statusElement.textContent = 'พักชั่วคราว'; return; } const now = new Date(); const diff = now - this.ifStartTime; const hours = Math.floor(diff / 3600000); const minutes = Math.floor((diff % 3600000) / 60000); const seconds = Math.floor((diff % 60000) / 1000); timerElement.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; // Calculate progress const fastHours = this.ifType === '5:2' ? 0 : parseInt(this.ifType.split(':')[0]); const totalDuration = fastHours * 60 * 60 * 1000; if (this.ifType !== '5:2') { const progress = (diff / totalDuration) * 100; if (progress >= 100) { statusElement.textContent = 'ครบกำหนดแล้ว! 🎉'; this.completeIF(); } else if (progress >= 75) { statusElement.textContent = 'ใกล้ครบแล้ว!'; } else if (progress >= 50) { statusElement.textContent = 'ผ่านครึ่งทางแล้ว'; } else if (progress >= 25) { statusElement.textContent = 'กำลังดำเนินการ'; } else { statusElement.textContent = 'เริ่มต้น'; } } else { statusElement.textContent = 'วันลดแคลอรี่'; } } updateIFButtons(state) { const startBtn = document.getElementById('startIFBtn'); const stopBtn = document.getElementById('stopIFBtn'); const pauseBtn = document.getElementById('pauseIFBtn'); const resumeBtn = document.getElementById('resumeIFBtn'); // Hide all buttons first if (startBtn) startBtn.classList.add('hidden'); if (stopBtn) stopBtn.classList.add('hidden'); if (pauseBtn) pauseBtn.classList.add('hidden'); if (resumeBtn) resumeBtn.classList.add('hidden'); // Show buttons based on state switch(state) { case 'stopped': if (startBtn) startBtn.classList.remove('hidden'); break; case 'running': if (stopBtn) stopBtn.classList.remove('hidden'); if (pauseBtn) pauseBtn.classList.remove('hidden'); break; case 'paused': if (stopBtn) stopBtn.classList.remove('hidden'); if (resumeBtn) resumeBtn.classList.remove('hidden'); break; } } showPausedIF() { this.updateIFDisplay(); this.updateIFButtons('paused'); } completeIF() { this.stopIF(); // Save completion record const today = new Date().toISOString().split('T')[0]; const ifHistory = JSON.parse(localStorage.getItem('ifHistory') || '{}'); if (!ifHistory[today]) { ifHistory[today] = []; } ifHistory[today].push({ type: this.ifType, completedAt: new Date().toISOString(), duration: this.ifTotalDuration }); localStorage.setItem('ifHistory', JSON.stringify(ifHistory)); this.showNotification('🎉 ทำ IF ครบกำหนดแล้ว! เยี่ยมมาก!'); // Show achievement notification setTimeout(() => { this.showNotification('🏆 ได้รับความสำเร็จ: IF Warrior'); }, 2000); } toggleIF() { if (this.isIFActive) { if (this.isIFPaused) { this.resumeIF(); } else { this.pauseIF(); } } else { this.startIF(); } } startRealTimeUpdates() { // Update vitals every minute setInterval(() => { this.updateVitals(); }, 60000); // Update environmental data every 5 minutes setInterval(() => { this.updateEnvironmentalData(); }, 300000); } updateVitals() { // Simulate HRV and other vital changes // In real app, this would fetch from HealthKit/Health Connect console.log('Updating vitals...'); } async updateEnvironmentalData() { try { // Get user location if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(async (position) => { const { latitude, longitude } = position.coords; // Fetch AQI data (using Thailand AQI API if available) // This is a placeholder - replace with actual API const aqiData = await this.fetchAQIData(latitude, longitude); this.updateAQIDisplay(aqiData); // Fetch weather data const weatherData = await this.fetchWeatherData(latitude, longitude); this.updateWeatherDisplay(weatherData); // Fetch traffic data (for home/work routes) const trafficData = await this.fetchTrafficData(); this.updateTrafficDisplay(trafficData); }); } } catch (error) { console.error('Error updating environmental data:', error); } } async fetchAQIData(lat, lon) { // Placeholder for AQI API // In production, use GISTDA or other Thai AQI APIs return { pm25: 65, aqi: 102, quality: 'ปานกลาง' }; } async fetchWeatherData(lat, lon) { // Placeholder for weather API // In production, use Thai Meteorological Department API return { temperature: 35, heatIndex: 39, uvIndex: 9, humidity: 75 }; } async fetchTrafficData() { // Placeholder for traffic API // In production, use Google Maps or Longdo Maps API return { status: 'ติดขัด', route: 'กลับบ้าน', delay: '45 นาที' }; } updateAQIDisplay(data) { // Update AQI display in UI const aqiElements = document.querySelectorAll('[data-aqi]'); aqiElements.forEach(el => { if (data.aqi > 100) { el.classList.add('text-red-600'); el.classList.remove('text-green-600', 'text-yellow-600'); } else if (data.aqi > 50) { el.classList.add('text-yellow-600'); el.classList.remove('text-green-600', 'text-red-600'); } else { el.classList.add('text-green-600'); el.classList.remove('text-yellow-600', 'text-red-600'); } }); } updateWeatherDisplay(data) { // Update weather display in UI if (data.heatIndex > 37) { // Show heat warning this.showNotification('⚠️ คำเตือน: ดัชนีความร้อนสูง งดออกกำลังกายกลางแจ้ง'); } } updateTrafficDisplay(data) { // Update traffic display in UI if (data.status === 'ติดขัดหนัก') { // Suggest stress management this.showNotification('🚗 รถติดหนัก ลองใช้ฟีเจอร์ฝึกหายใจก่อนถึงบ้านนะครับ'); } } requestLocationPermission() { if ('geolocation' in navigator) { navigator.permissions.query({ name: 'geolocation' }).then((result) => { if (result.state === 'granted') { console.log('Location permission granted'); } else if (result.state === 'prompt') { // User hasn't decided yet console.log('Location permission not decided'); } else { // Permission denied console.log('Location permission denied'); this.showNotification('📍 ต้องการอนุญาตตำแหน่งเพื่อแสดงข้อมูล AQI และสภาพอากาศ'); } }); } } checkDeviceCapabilities() { // Check if device supports HealthKit/Health Connect const supportsHealthKit = 'HealthKit' in window; const supportsHealthConnect = 'HealthConnect' in window; if (supportsHealthKit || supportsHealthConnect) { console.log('Device supports health data integration'); // Initialize health data sync this.initHealthDataSync(); } else { console.log('Device does not support health data integration'); // Show alternative input methods this.showManualInputOptions(); } } initHealthDataSync() { // Placeholder for health data integration // In production, integrate with HealthKit (iOS) or Health Connect (Android) console.log('Initializing health data sync...'); } showManualInputOptions() { // Show manual input options for devices without health integration console.log('Showing manual input options...'); } showNotification(message) { // Create notification element const notification = document.createElement('div'); notification.className = 'fixed top-4 right-4 bg-white rounded-lg shadow-lg p-4 max-w-xs z-50 animate-pulse'; notification.innerHTML = ` <p class="text-sm font-medium text-gray-800">${message}</p> `; document.body.appendChild(notification); // Remove after 5 seconds setTimeout(() => { notification.remove(); }, 5000); } // Modal functions showAirQualityModal() { document.getElementById('airQualityModal').classList.remove('hidden'); feather.replace(); } showHeatIndexModal() { document.getElementById('heatIndexModal').classList.remove('hidden'); feather.replace(); } showTrafficModal() { document.getElementById('trafficModal').classList.remove('hidden'); feather.replace(); } showUVIndexModal() { document.getElementById('uvIndexModal').classList.remove('hidden'); feather.replace(); } closeModal(modalId) { document.getElementById(modalId).classList.add('hidden'); } updateAirQualityData() { const location = document.getElementById('airQualityLocation').value; console.log('Updating air quality data for:', location); // In real app, fetch new data based on location this.showNotification('อัพเดทข้อมูลคุณภาพอากาศ'); } updateHeatIndexData() { const location = document.getElementById('heatIndexLocation').value; console.log('Updating heat index data for:', location); // In real app, fetch new data based on location this.showNotification('อัพเดทข้อมูลดัชนีความร้อน'); } updateTrafficData() { const route = document.getElementById('trafficRoute').value; console.log('Updating traffic data for route:', route); // In real app, fetch new data based on route this.showNotification('อัพเดทข้อมูลการจราจร'); } updateUVIndexData() { const location = document.getElementById('uvIndexLocation').value; console.log('Updating UV index data for:', location); // In real app, fetch new data based on location this.showNotification('อัพเดทข้อมูลดัชนี UV'); } setAirQualityTimeRange(range) { // Update button states const buttons = document.querySelectorAll('#airQualityModal .flex button'); buttons.forEach(btn => { btn.classList.remove('bg-primary-600', 'text-white'); btn.classList.add('bg-gray-200', 'text-gray-700'); }); event.target.classList.remove('bg-gray-200', 'text-gray-700'); event.target.classList.add('bg-primary-600', 'text-white'); console.log('Setting air quality time range:', range); this.showNotification(`แสดงข้อมูล ${range === 'today' ? 'วันนี้' : range === 'week' ? '7 วัน' : '30 วัน'}`); } setTrafficTime(time) { // Update button states const buttons = document.querySelectorAll('#trafficModal .flex button'); buttons.forEach(btn => { btn.classList.remove('bg-primary-600', 'text-white'); btn.classList.add('bg-gray-200', 'text-gray-700'); }); event.target.classList.remove('bg-gray-200', 'text-gray-700'); event.target.classList.add('bg-primary-600', 'text-white'); console.log('Setting traffic time:', time); this.showNotification(`แสดงข้อมูลการจราจร ${time === 'now' ? 'ตอนนี้' : time === 'morning' ? 'ช่วงเช้า' : 'ช่วงเย็น'}`); } // Thai food database helper searchThaiFood(query) { const thaiFoodDatabase = [ { name: 'ข้าวมันไก่', calories: 450, protein: 30, carbs: 45, fat: 15 }, { name: 'กะเพราไข่ดาว', calories: 520, protein: 25, carbs: 35, fat: 30 }, { name: 'แกงเขียวหวาน', calories: 380, protein: 20, carbs: 25, fat: 22 }, { name: 'ต้มยำกุ้ง', calories: 180, protein: 25, carbs: 10, fat: 5 }, { name: 'ส้มตำไทย', calories: 120, protein: 3, carbs: 20, fat: 4 }, { name: 'ขนมจีนน้ำยา', calories: 420, protein: 12, carbs: 65, fat: 15 }, { name: 'ข้าวผัด', calories: 480, protein: 15, carbs: 70, fat: 15 }, { name: 'มักกะโรนีผัด', calories: 550, protein: 18, carbs: 65, fat: 25 }, { name: 'ชานมไข่มุก', calories: 320, protein: 8, carbs: 55, fat: 8 }, { name: 'โอเลี้ยง', calories: 400, protein: 12, carbs: 50, fat: 18 } ]; return thaiFoodDatabase.filter(food => food.name.toLowerCase().includes(query.toLowerCase()) ); } // Activity detection detectActivity() { // Placeholder for activity detection // In production, use device sensors or manual input console.log('Detecting activity...'); } // AI Coach insights generation generateAIInsight() { const insights = [ 'วันนี้ฝุ่นเยอะ Recovery 60% แนะนำออกกำลังในร่ม และทานอาหารต้านอักเสบเช่นขิง ข่า ตะไคร้', 'เราสังเกตว่า HRV ลดลง 15% หลังจากวันที่ PM2.5 สูง ลองพักผ่อนมากขึ้นนะครับ', 'การจราจรติดขัดเมื่อวานทำให้ HR สูงค้าง ลองใช้ฟีเจอร์ฝึกหายใจก่อนถึงบ้าน', 'ดัชนีความร้อนสูง การวิ่งสร้าง Strain สูงกว่าปกติ 30% แนะนำให้ดื่มน้ำเกลือแร่' ]; return insights[Math.floor(Math.random() * insights.length)]; } } // Initialize app const app = new PulseApp(); // Global functions for onclick handlers function showPage(page) { app.showPage(page); } function toggleIF() { app.toggleIF(); } function startIF() { app.startIF(); } function stopIF() { app.stopIF(); } function pauseIF() { app.pauseIF(); } function resumeIF() { app.resumeIF(); } function changeIFType() { app.changeIFType(); } function showAirQualityModal() { app.showAirQualityModal(); } function showHeatIndexModal() { app.showHeatIndexModal(); } function showTrafficModal() { app.showTrafficModal(); } function showUVIndexModal() { app.showUVIndexModal(); } function closeModal(modalId) { app.closeModal(modalId); } function updateAirQualityData() { app.updateAirQualityData(); } function updateHeatIndexData() { app.updateHeatIndexData(); } function updateTrafficData() { app.updateTrafficData(); } function updateUVIndexData() { app.updateUVIndexData(); } function setAirQualityTimeRange(range) { app.setAirQualityTimeRange(range); } function setTrafficTime(time) { app.setTrafficTime(time); } // Add to global scope for component access window.PulseApp = PulseApp;
// Pulse App Main JavaScript
class PulseApp {
constructor() {
this.currentPage = 'dashboard';
this.isIFActive = false;
this.ifTimer = null;
this.ifStartTime = null;
this.init();
}
init() {
// Set current date
this.updateDate();
// Initialize navigation
this.initNavigation();
// Initialize IF timer
this.initIFTimer();
// Initialize page-specific features
this.initMoodLogging();
this.initNutritionTracking();
this.initActivityTracking();
this.initSleepTracking();
// Simulate real-time data updates
this.startRealTimeUpdates();
// Initialize location services
this.requestLocationPermission();
// Check device capabilities
this.checkDeviceCapabilities();
}
updateDate() {
const date = new Date();
const options = { day: 'numeric', month: 'short', year: 'numeric' };
const thaiDate = date.toLocaleDateString('th-TH', options);
const dateElement = document.getElementById('currentDate');
if (dateElement) {
dateElement.textContent = thaiDate;
}
}
initNavigation() {
// Set active navigation
this.setActiveNav('dashboard');
}
setActiveNav(page) {
const navButtons = document.querySelectorAll('.nav-btn');
navButtons.forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.page === page) {
btn.classList.add('active');
}
});
// Hide all navigation items for special pages
const specialPages = ['recovery', 'strain'];
const nav = document.querySelector('nav.fixed.bottom-0');
if (nav) {
if (specialPages.includes(page)) {
nav.classList.add('hidden');
} else {
nav.classList.remove('hidden');
}
}
}
// Initialize mood logging
initMoodLogging() {
const moodButtons = document.querySelectorAll('.mood-btn');
moodButtons.forEach(btn => {
btn.addEventListener('click', (e) => {
moodButtons.forEach(b => b.classList.remove('selected'));
btn.classList.add('selected');
const mood = btn.querySelector('span:last-child').textContent;
this.logMood(mood);
});
});
}
logMood(mood) {
// Save mood to localStorage
const today = new Date().toISOString().split('T')[0];
const moodLog = JSON.parse(localStorage.getItem('moodLog') || '{}');
moodLog[today] = {
mood: mood,
timestamp: new Date().toISOString(),
factors: this.getSelectedStressFactors()
};
localStorage.setItem('moodLog', JSON.stringify(moodLog));
this.showNotification(`บันทึกอารมณ์: ${mood}`);
}