Spaces:
Running
Running
File size: 3,340 Bytes
f93e15c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | const CACHE_NAME = 'chipat-health-v1.0.0';
const urlsToCache = [
'/',
'/index.html',
'/sleep.html',
'/activity.html',
'/nutrition.html',
'/profile.html',
'/style.css',
'/script.js',
'/components/navbar.js',
'/components/ai-coach-card.js',
'/components/hardware-status.js',
'/components/vital-circle.js',
'/components/mood-logger.js',
'/components/meal-logger-enhanced.js',
'https://cdn.tailwindcss.com',
'https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js',
'https://cdn.jsdelivr.net/npm/chart.js'
];
// Install event
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => {
console.log('กำลังเปิด cache');
return cache.addAll(urlsToCache);
})
);
});
// Fetch event
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request).then(
(response) => {
// Check if we received a valid response
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// Clone the response
const responseToCache = response.clone();
caches.open(CACHE_NAME)
.then((cache) => {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
// Activate event
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
})
);
});
// Background sync for health data
self.addEventListener('sync', (event) => {
if (event.tag === 'health-data-sync') {
event.waitUntil(syncHealthData());
}
});
async function syncHealthData() {
try {
// Get pending data from IndexedDB
const pendingData = await getPendingHealthData();
for (const data of pendingData) {
// Send to server (in real app)
await fetch('/api/health-data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
// Remove from pending queue
await removePendingData(data.id);
}
console.log('ซิงค์ข้อมูลสุขภาพสำเร็จ');
} catch (error) {
console.error('ซิงค์ข้อมูลล้มเหลว:', error);
}
} |