thai-health-edge / script.js
CSNET's picture
ชื่อโปรเจกต์: Thai-Max Recovery (TMR) Appเป้าหมาย: สร้างแอปพลิเคชันติดตามและวิเคราะห์สุขภาพแบบองค์รวม (Holistic Health & Recovery) ที่มี คะแนนความพร้อม (Readiness Score) แม่นยำที่สุด สำหรับบริบทของคนไทย โดยรวมปัจจัยด้านสภาพแวดล้อมและพฤติกรรมเฉพาะถิ่นเข้ากับการวิเคราะห์ทางชีวภาพ (Biometric Data)1. 🥇 ฟีเจอร์หลักที่เหนือกว่า Whoop (The Thai Edge)ฟีเจอร์หลัก (Module)รายละเอียดการทำงานที่เหนือกว่าMetric ที่ใช้Recovery Score 2.0 (ค่าน้ำนม)ใช้ชื่อเรียกให้เป็นภาษาไทย/เข้าใจง่าย เช่น "คะแนนน้ำนม" หรือ "พลังกายพร้อมรบ" และเพิ่มตัวแปรการคำนวณที่เกี่ยวข้องกับสภาพแวดล้อมไทยHRV, RHR, Sleep Performance, Temp Delta, Air Quality Index (AQI)Hyper-Localized Strainคำนวณความตึงเครียดจากกิจกรรมควบคู่กับ สภาพอากาศ ในพื้นที่ (อุณหภูมิและความชื้น) และ มลพิษ (PM 2.5)Ambient Temp, Humidity, AQI, Activity Strain (HR)Thai Food Impact Analysisฟังก์ชัน Journal ขั้นสูงที่เน้นอาหารไทย/เอเชีย เพื่อวิเคราะห์ผลกระทบของ รสจัด/เผ็ด และ น้ำตาล/โซเดียม ต่อการนอนหลับ/RHRJournal Data (Spicy, Sugar, Salt intake), RHR, Sleep LatencySocial Stress & Traffic Indexเพิ่มมิติความเครียดทางอารมณ์/สังคมที่สูงในเมืองไทย (รถติด, มลพิษเสียง) เข้าไปในคะแนนความเครียดรายวันJournal Data (Traffic Time/Duration), Perceived Stress Score2. 🧠 โครงสร้างข้อมูล Mockup (Advanced Biometric & Contextual Data)ต้องสร้าง Mock Data ที่สมจริง 30 วันสำหรับผู้ใช้ 1 คน (User Persona: พนักงานออฟฟิศในกรุงเทพฯ ที่วิ่งมาราธอน) โดยมีชุดข้อมูลหลักและชุดข้อมูลบริบท:A. Core Biometric Data (30 Days)MetricRangeDependency (เมื่อสูง/ต่ำ)recoveryScore0-100$\downarrow$ เมื่อ HRV ต่ำ, RHR สูง, ป่วย, หรือ PM 2.5 สูงhrv (RMSSD)30-140 ms$\downarrow$ เมื่อดื่มแอลกอฮอล์, อากาศร้อนจัด, เครียดสูงrhr40-80 bpm$\uparrow$ เมื่อป่วย, ดื่มกาแฟตอนบ่าย, ทานเผ็ดมื้อดึกsleepScore0-100$\downarrow$ เมื่ออุณหภูมิห้องสูง, PM 2.5 สูง, Traffic Index สูงrespiratoryRate12-20 brpm$\uparrow$ เมื่อป่วย (สัญญาณเตือน)tempDelta$\pm 0.5 \text{ }^\circ\text{C}$$\uparrow$ เมื่อมีไข้, $\downarrow$ เมื่อรอบเดือนมาB. Contextual/Environmental Data (30 Days)MetricRangeDescription (บริบทไทย)aqi_pm2520-300ดึงค่า PM 2.5 จำลอง (สูงมากในเดือนที่มีมลพิษ)ambientTemp$25-40 \text{ }^\circ\text{C}$อุณหภูมิภายนอก (ใช้ในการคำนวณ Strain ในการวิ่ง)trafficIndex1-10ระดับความเครียดจากการจราจร (10 คือรถติดหนักมาก)spicyIntake0-3ระดับความเผ็ด (0: ไม่เผ็ด, 3: เผ็ดมาก)sugarIntake0-5ปริมาณน้ำตาล (หน่วย: ช้อนชาเทียบเท่า)sodiumIntake0-5ปริมาณโซเดียม (หน่วย: กรัมเทียบเท่า)3. 🎯 ฟังก์ชันการทำงานโดยละเอียด (Deep Site Function Specifications)A. Recovery Dashboard (คะแนนน้ำนม)Featureคำอธิบายภาษาไทย (UI/Insight)Data SourceCore Scoreพลังกายพร้อมรบ (ตัวเลข 0-100) พร้อมสี (เขียว/เหลือง/แดง)recoveryScoreEnvironmental Warning"สภาพอากาศวันนี้: 🌡️ ร้อนและมี PM 2.5 สูง การฝึกหนักอาจส่งผลต่อ HRV ของคุณ"aqi_pm25, ambientTempStrain Suggestion"ความตึงเครียดวันนี้: แนะนำให้ไม่เกิน 12.5 เนื่องจากอัตราการหายใจสูงกว่าปกติ"recoveryScore, respiratoryRateHRV Visualizationกราฟเส้น 7 วันของ "ความผันผวนของหัวใจ" (HRV) เทียบกับ "ความเครียดที่รับรู้"hrv, trafficIndex (เทียบกัน)B. Sleep Analytics (การนอนหลับ)Featureคำอธิบายภาษาไทย (UI/Insight)Data SourceSleep Qualityประสิทธิภาพการนอน (0-100) และ หนี้การนอน (ชั่วโมง)sleepScore, sleepDebtBedroom Impact"การนอนหลับของคุณถูกขัดจังหวะ 3 ครั้งในช่วง 03:00-05:00 น. อาจเกี่ยวข้องกับ อุณหภูมิห้องที่สูง ในช่วงนั้น"sleepScore, ambientTempSpicy Food Alert"มื้ออาหารเผ็ดเมื่อคืนนี้ ทำให้ RHR สูงขึ้น 4 bpm ในช่วงต้นของการนอนหลับ"rhr, spicyIntake (จาก Journal)Respiratory Statusอัตราการหายใจ เทียบกับค่า Baseline พร้อมคำเตือน "อาจมีอาการป่วยเริ่มต้น"respiratoryRate, tempDeltaC. Journal & Behaviour (บันทึกพฤติกรรมเชิงลึก)ใช้โครงสร้าง Journal ที่ละเอียดจาก Prompt ที่แล้ว รวมถึงฟิลด์บริบทเฉพาะกิจ เพื่อให้ผู้ใช้บันทึกปัจจัยเฉพาะเจาะจง:Field (TH)Data TypeUsage / Analysis Focusเวลาอยู่ในจราจรTime Durationวัดความเครียดทางอารมณ์/มลพิษเสียงระดับเผ็ดของอาหารDropdown (0-3)วิเคราะห์ผลกระทบต่อ RHR/การนอนเครื่องดื่มหวาน/ชานมToggle/Quantityวิเคราะห์ผลกระทบต่อ HRV/RHRความสัมพันธ์ในครอบครัวSelect (ดี/ไม่ดี/เครียด)วัดความเครียดทางสังคม/ครอบครัวช่วงพักร้อน/เที่ยวToggleปรับ Baseline การฟื้นตัวให้ต่ำลง (จากการเดินทาง)D. Advance Lab & Trends (ห้องแล็บขั้นสูง)Featureคำอธิบายภาษาไทย (UI/Insight)Data SourceHolistic Trendกราฟเส้นแสดง คะแนนน้ำนม 30 วัน ควบคู่ไปกับ PM 2.5 และ Traffic Index เพื่อหาความสัมพันธ์recoveryScore, aqi_pm25, trafficIndexNutrition Impact Matrixตารางสรุป: "วันที่มีโซเดียมสูง" โดยเฉลี่ยมี RHR สูงกว่าวันปกติ 3 bpmJournal Data (sodiumIntake, sugarIntake) เทียบกับ rhr, sleepScoreSeasonal Recovery Reportรายงานการฟื้นตัวรายไตรมาส พร้อมคำแนะนำ: "ช่วงเดือนมีนาคมถึงพฤษภาคม เป็นฤดูร้อนที่เครียดที่สุด คุณควรเน้นการฟื้นตัวแบบความเย็น"ambientTemp, recoveryScore (Historical Data)Adaptation Thresholdแสดงขีดจำกัดความพร้อมของร่างกายที่ปรับตัวเข้ากับสภาพแวดล้อม (Baseline การฟื้นตัวใหม่ในช่วง PM 2.5 สูง)hrv, aqi_pm25 (Complex Regression Analysis)4. 🛠️ ข้อกำหนดทางเทคนิค (Deep Site Specifications)ComponentTechnology/RequirementPurposeFrontend/UINative/React Native (Fully localized TH UI)เน้น UX/UI ภาษาไทยที่เข้าใจง่ายและสอดคล้องกับโทนสีอ่อน/เข้มBackend/APINode.js/Python (FastAPI)รองรับการประมวลผลข้อมูลชีวภาพและการคำนวณสูตรซับซ้อน (HRV/Recovery/Strain)Data CalculationCustom Algorithm (ต้องใส่สมการจำลอง)$R_{TMR} = 0.5 R_{WHOOP} + 0.35 R_{ENV} + 0.15 R_{FOOD}$ (สมการจำลองการคำนวณคะแนนน้ำนม)Data Source (Mock)JSON Array 30 วัน (ตาม Section 2)ใช้สำหรับการจำลองผลลัพธ์ที่ซับซ้อนและมีความสัมพันธ์Localizationภาษาไทย 100%ต้องไม่มีคำภาษาอังกฤษหลุดรอดในหน้า Dashboard, Insights, หรือ Reports
41eab66 verified
Raw History Blame Contribute Delete
15.5 kB
// Mock data for 30 days - Bangkok office worker marathon runner
const mockData = {
days: Array.from({ length: 30 }, (_, i) => {
const dayOffset = 29 - i;
const date = new Date();
date.setDate(date.getDate() - dayOffset);
// Simulate realistic patterns
const isWeekend = date.getDay() === 0 || date.getDay() === 6;
const isHotDay = date.getMonth() >= 2 && date.getMonth() <= 5; // March-May hot season
const pollutionLevel = Math.random() > 0.7 ? 'high' : 'normal';
return {
date: date.toISOString().split('T')[0],
recoveryScore: Math.max(20, Math.min(100, Math.floor(
70 + (isWeekend ? 10 : 0) - (pollutionLevel === 'high' ? 15 : 0) - (isHotDay ? 5 : 0) + Math.random() * 20 - 10
))),
hrv: Math.floor(40 + Math.random() * 60 + (isWeekend ? 15 : 0) - (pollutionLevel === 'high' ? 10 : 0)),
rhr: Math.floor(55 + Math.random() * 15 + (pollutionLevel === 'high' ? 5 : 0)),
sleepScore: Math.floor(65 + Math.random() * 25 + (isWeekend ? 8 : 0)),
respiratoryRate: Math.floor(14 + Math.random() * 4 + (Math.random() > 0.9 ? 3 : 0)),
tempDelta: (Math.random() * 1 - 0.5).toFixed(2),
aqi_pm25: pollutionLevel === 'high' ? Math.floor(100 + Math.random() * 150) : Math.floor(20 + Math.random() * 50),
ambientTemp: isHotDay ? Math.floor(35 + Math.random() * 5) : Math.floor(28 + Math.random() * 5),
trafficIndex: Math.floor(2 + Math.random() * 6 + (isWeekend ? -3 : 0)),
spicyIntake: Math.floor(Math.random() * 4),
sugarIntake: Math.floor(Math.random() * 6),
sodiumIntake: Math.floor(Math.random() * 6),
sleepDebt: Math.floor(Math.random() * 3 - (isWeekend ? 2 : 0)),
perceivedStress: Math.floor(3 + Math.random() * 5 + (pollutionLevel === 'high' ? 2 : 0))
};
})
};
// Current day data
const todayData = mockData.days[mockData.days.length - 1];
// Utility functions
function getScoreColor(score) {
if (score >= 80) return '#10b981'; // Green
if (score >= 60) return '#f59e0b'; // Yellow
return '#ef4444'; // Red
}
function getScoreText(score) {
if (score >= 80) return { text: 'พร้อมรบ', color: 'text-green-500' };
if (score >= 60) return { text: 'ปานกลาง', color: 'text-yellow-500' };
return { text: 'ต้องพัก', color: 'text-red-500' };
}
function formatDateThai(dateString) {
const date = new Date(dateString);
const options = { year: 'numeric', month: 'long', day: 'numeric', locale: 'th-TH' };
return date.toLocaleDateString('th-TH', options);
}
function calculateTrend(values) {
const recent = values.slice(-7);
const previous = values.slice(-14, -7);
const recentAvg = recent.reduce((a, b) => a + b, 0) / recent.length;
const prevAvg = previous.reduce((a, b) => a + b, 0) / previous.length;
return recentAvg - prevAvg;
}
// Initialize app
document.addEventListener('DOMContentLoaded', function() {
// Set last update time
document.getElementById('lastUpdate').textContent = formatDateThai(new Date().toISOString());
// Load environmental warnings
loadEnvironmentalWarnings();
// Load daily suggestions
loadDailySuggestions();
// Initialize HRV chart
initHRVChart();
// Load sleep data
loadSleepData();
// Load nutrition matrix
loadNutritionMatrix();
// Load seasonal report
loadSeasonalReport();
// Initialize journal form data
initJournalForm();
});
// Tab navigation
function showSection(sectionName) {
// Hide all sections
document.querySelectorAll('.content-section').forEach(section => {
section.classList.add('hidden');
});
// Show selected section
document.getElementById(`${sectionName}-section`).classList.remove('hidden');
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active', 'bg-secondary');
btn.classList.add('bg-cardBg');
});
event.target.closest('.tab-btn').classList.add('active', 'bg-secondary');
event.target.closest('.tab-btn').classList.remove('bg-cardBg');
// Trigger chart resize if needed
if (sectionName === 'trends' && window.trendsChartInstance) {
setTimeout(() => window.trendsChartInstance.resize(), 100);
}
}
// Environmental warnings
function loadEnvironmentalWarnings() {
const warningsContainer = document.getElementById('environmental-warnings');
const warnings = [];
if (todayData.aqi_pm25 > 100) {
warnings.push(`🌫️ ค่า PM 2.5 สูง (${todayData.aqi_pm25} μg/m³) อาจลด HRV ของคุณได้`);
}
if (todayData.ambientTemp > 35) {
warnings.push(`🌡️ อุณหภูมิสูง (${todayData.ambientTemp}°C) เพิ่มความเครียดในการออกกำลังกาย`);
}
if (todayData.trafficIndex > 7) {
warnings.push(`🚗 รถติดหนัก (ระดับ ${todayData.trafficIndex}/10) เพิ่มความเครียดทางอารมณ์`);
}
warningsContainer.innerHTML = warnings.length > 0
? warnings.map(w => `<div class="flex items-start"><span class="mr-2">•</span><span>${w}</span></div>`).join('')
: '<div class="text-green-500">✅ สภาพแวดล้อมอยู่ในเกณฑ์ดี</div>';
}
// Daily suggestions
function loadDailySuggestions() {
const suggestionsContainer = document.getElementById('daily-suggestions');
const suggestions = [];
if (todayData.recoveryScore < 60) {
suggestions.push(`⚠️ ควรลดความตึงเครียดวันนี้ไม่เกิน 12.5 จุด`);
suggestions.push(`💤 แนะนำให้นอนกลางวัน 20-30 นาที`);
} else if (todayData.recoveryScore < 80) {
suggestions.push(`💪 สามารถฝึกกลางได้ตามปกติ แต่ควรหลีกเลี่ยงช่วงเที่ยง`);
suggestions.push(`🥤 เพิ่มการดื่มน้ำ 2 เท่า จากภาวะอากาศร้อน`);
} else {
suggestions.push(`🔥 พร้อมสำหรับการฝึกซ้อมหนักวันนี้!`);
suggestions.push(`🏃‍♂️ เหมาะสำหรับการวิ่งระยะไกล`);
}
if (todayData.spicyIntake > 2) {
suggestions.push(`🌶️ ระวังอาหารเผ็ดอาจทำให้ RHR สูงขึ้นตอนนอน`);
}
suggestionsContainer.innerHTML = suggestions.map(s =>
`<div class="flex items-start"><span class="mr-2">•</span><span>${s}</span></div>`
).join('');
}
// HRV Chart
function initHRVChart() {
const ctx = document.getElementById('hrvChart').getContext('2d');
const last7Days = mockData.days.slice(-7);
new Chart(ctx, {
type: 'line',
data: {
labels: last7Days.map(d => formatDateThai(d.date).split(' ')[0]),
datasets: [{
label: 'HRV (ms)',
data: last7Days.map(d => d.hrv),
borderColor: '#14b8a6',
backgroundColor: 'rgba(20, 184, 166, 0.1)',
tension: 0.4,
yAxisID: 'y'
}, {
label: 'ความเครียด',
data: last7Days.map(d => d.perceivedStress),
borderColor: '#f97316',
backgroundColor: 'rgba(249, 115, 22, 0.1)',
tension: 0.4,
yAxisID: 'y1'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'index',
intersect: false
},
plugins: {
legend: {
labels: {
color: '#9ca3af'
}
}
},
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
title: {
display: true,
text: 'HRV (ms)',
color: '#9ca3af'
},
grid: {
color: 'rgba(156, 163, 175, 0.1)'
},
ticks: {
color: '#9ca3af'
}
},
y1: {
type: 'linear',
display: true,
position: 'right',
title: {
display: true,
text: 'ระดับความเครียด (1-10)',
color: '#9ca3af'
},
grid: {
drawOnChartArea: false
},
ticks: {
color: '#9ca3af'
}
},
x: {
ticks: {
color: '#9ca3af'
},
grid: {
color: 'rgba(156, 163, 175, 0.1)'
}
}
}
}
});
}
// Sleep data
function loadSleepData() {
// Respiratory status
const respiratoryContainer = document.getElementById('respiratory-status');
const baselineRR = 16;
const currentRR = todayData.respiratoryRate;
const diff = currentRR - baselineRR;
let status = 'good';
let message = 'อัตราการหายใจปกติ';
if (diff > 3) {
status = 'danger';
message = '⚠️ อัตราการหายใจสูงผิดปกติ อาจมีอาการป่วยเริ่มต้น';
} else if (diff > 1) {
status = 'warning';
message = 'อัตราการหายใจสูงกว่าปกติเล็กน้อย';
}
respiratoryContainer.innerHTML = `
<div class="flex justify-between items-center mb-2">
<span class="text-textSecondary">ปัจจุบัน</span>
<span class="text-2xl font-bold ${status === 'danger' ? 'text-red-500' : status === 'warning' ? 'text-yellow-500' : 'text-green-500'}">${currentRR}</span>
</div>
<div class="flex justify-between items-center mb-4">
<span class="text-textSecondary">Baseline</span>
<span class="text-xl font-medium">${baselineRR}</span>
</div>
<div class="p-3 rounded-lg bg-darkBg text-sm">
${message}
</div>
`;
// Food impact on sleep
const foodContainer = document.getElementById('food-impact-sleep');
const foodImpacts = [];
if (todayData.spicyIntake > 2) {
foodImpacts.push(`🌶️ อาหารเผ็ดมาก ทำให้ RHR สูงขึ้น ${Math.floor(Math.random() * 5 + 3)} bpm ตอนเริ่มนอน`);
}
if (todayData.sodiumIntake > 3) {
foodImpacts.push(`🧂 โซเดียมสูง อาจทำให้คุณภาพการนอนลดลง 15%`);
}
if (todayData.sugarIntake > 4) {
foodImpacts.push(`🍬 น้ำตาลสูง ทำให้ Sleep Latency เพิ่มขึ้น 20 นาที`);
}
foodContainer.innerHTML = foodImpacts.length > 0
? foodImpacts.map(i => `<div class="p-3 rounded-lg bg-darkBg text-sm">${i}</div>`).join('')
: '<div class="text-green-500">✅ อาหารวันนี้ไม่มีผลกระทบต่อการนอน</div>';
}
// Nutrition matrix
function loadNutritionMatrix() {
const container = document.getElementById('nutrition-matrix');
// Calculate average RHR on high sodium days vs normal days
const highSodiumDays = mockData.days.filter(d => d.sodiumIntake >= 4);
const normalSodiumDays = mockData.days.filter(d => d.sodiumIntake < 3);
const avgRHR_highSodium = highSodiumDays.length > 0
? highSodiumDays.reduce((sum, d) => sum + d.rhr, 0) / highSodiumDays.length
: 0;
const avgRHR_normal = normalSodiumDays.length > 0
? normalSodiumDays.reduce((sum, d) => sum + d.rhr, 0) / normalSodiumDays.length
: 0;
const diff = Math.abs(avgRHR_highSodium - avgRHR_normal).toFixed(1);
container.innerHTML = `
<div class="space-y-4">
<div class="flex justify-between items-center p-3 rounded-lg bg-darkBg">
<span>วันที่กินเค็มมาก</span>
<span class="font-bold text-red-500">${avgRHR_highSodium.toFixed(1)} bpm</span>
</div>
<div class="flex justify-between items-center p-3 rounded-lg bg-darkBg">
<span>วันที่กินปกติ</span>
<span class="font-bold text-green-500">${avgRHR_normal.toFixed(1)} bpm</span>
</div>
<div class="p-3 rounded-lg border border-primary bg-primary bg-opacity-10 text-sm">
🔍 วันที่มีโซเดียมสูงเฉลี่ย RHR สูงกว่า <strong>${diff} bpm</strong>
</div>
</div>
`;
}
// Seasonal report
function loadSeasonalReport() {
const container = document.getElementById('seasonal-report');
const hotSeasonData = mockData.days.filter(d => {
const month = new Date(d.date).getMonth();
return month >= 2 && month <= 5; // March-May
});
const avgRecoveryHotSeason = hotSeasonData.length > 0
? hotSeasonData.reduce((sum, d) => sum + d.recoveryScore, 0) / hotSeasonData.length
: 70;
container.innerHTML = `
<div class="space-y-3">
<p>📊 ช่วงเดือนมีนาคมถึงพฤษภาคม เป็นฤดูร้อนที่เครียดที่สุด</p>
<p class="p-3 rounded-lg bg-darkBg">
⚠️ ค่าเฉลี่ยพลังกายพร้อมรบในฤดูร้อน: <strong>${avgRecoveryHotSeason.toFixed(1)}</strong>
</p>
<p class="text-green-400">
💡 แนะนำ: เน้นการฟื้นตัวแบบความเย็น ลดการออกกำลังกายกลางแจ้งในช่วง 10:00-16:00
</p>
<p class="text-blue-400">
🧊 เพิ่มการดื่มน้ำเกลือแร่ อาบน้ำเย็น และใช้ห้องแอร์ 24-26°C
</p>
</div>
`;
}
// Initialize journal form data
function initJournalForm() {
const journalForm = document.querySelector('journal-form');
if (journalForm) {
journalForm.setTodayData(todayData);
}
}