pulse-whoop / script.js
CSNET's picture
ช่วยแก้ JS และกราฟ ไม่ให้เพี้ยนที
9539581 verified
Raw History Blame Contribute Delete
13.7 kB
// Global App State
const AppState = {
currentUser: {
name: 'พิมพ์',
recovery: 78,
strain: 12.5,
sleep: 82,
heartRate: 68
},
// Mock data for chart
heartRateData: {
labels: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'],
datasets: [{
label: 'Heart Rate',
data: [58, 62, 75, 82, 78, 70, 62],
borderColor: '#34d399',
backgroundColor: 'rgba(52, 211, 153, 0.1)',
tension: 0.4,
fill: true,
pointRadius: 0,
pointHoverRadius: 6
}]
}
};
// Initialize Heart Rate Chart
function initHeartRateChart() {
try {
const ctx = document.getElementById('hrChart');
if (!ctx) return;
new Chart(ctx, {
type: 'line',
data: AppState.heartRateData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: 'rgba(17, 24, 39, 0.9)',
titleColor: '#34d399',
bodyColor: '#e5e7eb',
borderColor: '#34d399',
borderWidth: 1,
callbacks: {
label: function(context) {
return `${context.parsed.y} bpm`;
}
}
}
},
scales: {
x: {
grid: { display: false },
ticks: {
color: '#9ca3af'
}
},
y: {
grid: {
color: 'rgba(75, 85, 99, 0.3)',
borderDash: [5, 5]
},
ticks: {
color: '#9ca3af'
}
}
},
interaction: {
intersect: false,
mode: 'index'
}
}
});
} catch (error) {
console.error('Chart initialization error:', error);
}
}
// Simulate Real-time Heart Rate Updates
function simulateRealtimeHR() {
try {
const hrElement = document.querySelector('.text-sm.font-medium');
if (!hrElement || !hrElement.textContent.includes('bpm')) return;
setInterval(() => {
try {
const variation = Math.floor(Math.random() * 10) - 5;
const newHR = Math.max(55, Math.min(85, AppState.currentUser.heartRate + variation));
hrElement.textContent = `${newHR} bpm`;
} catch (e) {
console.warn('HR update error:', e);
}
}, 3000);
} catch (error) {
console.error('Realtime HR simulation error:', error);
}
}
// Quick Log Button Actions
function setupQuickLogButtons() {
try {
const buttons = document.querySelectorAll('.quick-log-btn');
buttons.forEach(button => {
button.addEventListener('click', function(e) {
e.preventDefault();
try {
// Add ripple effect
const ripple = document.createElement('div');
ripple.className = 'absolute inset-0 bg-white/20 rounded-xl animate-ping';
this.appendChild(ripple);
setTimeout(() => ripple.remove(), 600);
// Show Thai notification
const text = this.textContent.trim();
showNotification(`กำลังบันทึก: ${text}...`, 'success');
} catch (innerError) {
console.error('Quick log button error:', innerError);
}
});
});
} catch (error) {
console.error('Setup quick log buttons error:', error);
}
}
// Notification System
function showNotification(message, type = 'info') {
try {
// Remove existing notification
const existing = document.querySelector('.notification-toast');
if (existing) {
existing.remove();
}
const notification = document.createElement('div');
notification.className = `notification-toast fixed top-4 left-4 right-4 z-50 p-4 rounded-xl shadow-lg transform translate-y-[-100px] opacity-0 transition-all duration-300 ${
type === 'success' ? 'bg-green-500' :
type === 'error' ? 'bg-red-500' :
type === 'warning' ? 'bg-yellow-500' : 'bg-blue-500'
}`;
notification.textContent = message;
document.body.appendChild(notification);
// Animate in
setTimeout(() => {
notification.style.transform = 'translateY(0)';
notification.style.opacity = '1';
}, 100);
// Remove after 3 seconds
setTimeout(() => {
notification.style.transform = 'translateY(-100px)';
notification.style.opacity = '0';
setTimeout(() => notification.remove(), 300);
}, 3000);
} catch (error) {
console.error('Notification error:', error);
// Fallback to alert
if (message) alert(message);
}
}
// Animate elements on scroll
function setupScrollAnimations() {
try {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate-fadeInUp');
}
});
}, { threshold: 0.1 });
document.querySelectorAll('.glass-card').forEach(card => {
observer.observe(card);
});
} catch (error) {
console.error('Scroll animation setup error:', error);
}
}
// AI Coach Dynamic Messages
function updateAICoachMessage() {
try {
const messages = [
"วันนี้คุณฟื้นตัวเต็มที่! เหมาะสำหรับการออกกำลังกายระดับกลาง-หนัก อย่าลืมทานอาหารให้ครบ 5 หมู่นะคะ",
"ค่า HRV ของคุณดีขึ้น 15% จากสัปดาห์ที่แล้ว! แสดงว่าร่างกายกำลังฟื้นตัวได้ดีมากเลยค่ะ",
"พบว่าคืนที่คุณดื่มกาแฟหลัง 3 ทุ่ม คุณภาพการนอนจะลดลง 30% ลองเลี่ยงดื่มกาแฟในช่วงบ่ายดูนะคะ",
"วันนี้ความเครียดสะสมอยู่ในระดับปานกลาง แนะนำให้นั่งสมาธิ 10 นาทีก่อนนอนเพื่อลดระดับคอร์ติซอลค่ะ"
];
const coachCard = document.querySelector('ai-coach-card');
if (coachCard && Math.random() > 0.7 && typeof coachCard.updateMessage === 'function') {
const randomMessage = messages[Math.floor(Math.random() * messages.length)];
coachCard.updateMessage(randomMessage);
}
} catch (error) {
console.error('AI Coach update error:', error);
}
}
// Hardware Pairing Simulation
function simulateHardwareConnection() {
try {
const devices = [
{ name: 'Apple Watch Series 9', connected: true },
{ name: 'Oura Ring Gen 3', connected: false },
{ name: 'Polar H10', connected: false }
];
// Check if hardware is connected
const connectedDevice = devices.find(d => d.connected);
if (connectedDevice) {
console.log(`เชื่อมต่อกับ ${connectedDevice.name} เรียบร้อยแล้ว`);
}
} catch (error) {
console.error('Hardware simulation error:', error);
}
}
// Office Syndrome Alert
function setupSedentaryAlert() {
try {
let sittingTime = 0;
setInterval(() => {
// Simulate sedentary behavior (in real app, use accelerometer data)
const isSitting = Math.random() > 0.3;
if (isSitting) {
sittingTime += 1;
if (sittingTime >= 60) { // 1 hour
showOfficeSyndromeAlert();
sittingTime = 0;
}
} else {
sittingTime = 0;
}
}, 60000); // Check every minute
} catch (error) {
console.error('Sedentary alert setup error:', error);
}
}
function showOfficeSyndromeAlert() {
try {
// Remove existing alert
const existing = document.querySelector('.office-alert');
if (existing) existing.remove();
const alert = document.createElement('div');
alert.className = 'office-alert fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4';
alert.innerHTML = `
<div class="glass-card rounded-2xl p-6 max-w-sm w-full border border-gray-700/50">
<div class="text-center">
<div class="w-16 h-16 bg-red-500 rounded-full mx-auto mb-4 flex items-center justify-center pulse-animation">
<i data-feather="alert-circle" class="w-8 h-8 text-white"></i>
</div>
<h3 class="text-xl font-bold mb-2">เตือนภัย Office Syndrome!</h3>
<p class="text-gray-400 mb-4">คุณนั่งนิ่งนานเกิน 1 ชั่วโมงแล้ว ลุกขึ้นมายืดเส้นยืดสายกันดีกว่าค่ะ</p>
<div class="flex gap-3">
<button onclick="this.closest('.office-alert').remove()" class="flex-1 bg-gray-700 hover:bg-gray-600 py-3 rounded-xl font-medium transition-colors">
เลื่อนไปก่อน
</button>
<button onclick="startMicroWorkout(); this.closest('.office-alert').remove()" class="flex-1 bg-gradient-to-r from-green-500 to-emerald-600 py-3 rounded-xl font-medium transition-all hover:scale-[1.02]">
เริ่มเลย!
</button>
</div>
</div>
</div>
`;
document.body.appendChild(alert);
if (typeof feather !== 'undefined') {
feather.replace({ root: alert });
}
// Auto close after 30 seconds
setTimeout(() => {
if (document.body.contains(alert)) {
alert.remove();
}
}, 30000);
} catch (error) {
console.error('Office syndrome alert error:', error);
}
}
function startMicroWorkout() {
try {
showNotification('กำลังเปิดวิดีโอท่ายืดเหยียด...', 'success');
// In real app, would open video player
} catch (error) {
console.error('Micro workout start error:', error);
}
}
// Initialize App
document.addEventListener('DOMContentLoaded', function() {
try {
console.log('Initializing ชีพจร app...');
// Set initial animations
document.querySelectorAll('section').forEach((section, index) => {
section.style.animationDelay = `${index * 0.1}s`;
section.classList.add('animate-fadeInUp');
});
// Initialize components with delays to avoid conflicts
setTimeout(() => {
initHeartRateChart();
}, 100);
setTimeout(() => {
simulateRealtimeHR();
}, 200);
setTimeout(() => {
setupQuickLogButtons();
}, 300);
setTimeout(() => {
setupScrollAnimations();
}, 400);
setTimeout(() => {
simulateHardwareConnection();
}, 500);
// Simulate periodic updates
setInterval(() => {
updateAICoachMessage();
}, 10000);
setTimeout(() => {
setupSedentaryAlert();
}, 5000); // Start checking after 5 seconds
// Request permissions (in real app)
console.log('กำลังขอสิทธิ์เข้าถึงข้อมูลสุขภาพ...');
// Show welcome notification
setTimeout(() => {
showNotification('ยินดีต้อนรับสู่ ชีพจร! AI กำลังวิเคราะห์ข้อมูลของคุณ...', 'success');
}, 1000);
console.log('App initialization complete');
} catch (error) {
console.error('App initialization error:', error);
}
});
// Export for other modules
window.AppState = AppState;
window.showNotification = showNotification;
window.initHeartRateChart = initHeartRateChart;