-
Notifications
You must be signed in to change notification settings - Fork 0
/
weight.html
378 lines (342 loc) · 16.3 KB
/
weight.html
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weight</title>
<link rel="stylesheet" href="weight.css">
</head>
<body>
<header>
<h1>Weight</h1>
<div>
<a href="dashboard.html" class="back-button">Dashboard</a>
<a href="gptcoach.html" class="back-button">GPTCoach</a>
<a href="index.html" class="back-button">Form</a>
<a href="entries.html" class="back-button">Entries</a>
<button id="logoutButton" class="back-button">Logout</button>
</div>
</header>
<div class="container">
<div class="label-container">
<div class="label-selection">
<div>
<label for="dateRange">Select Date Range:</label>
<select id="dateRange">
<option value="7">1 Week</option>
<option value="14">2 Weeks</option>
<option value="30">1 Month</option>
<option value="90">3 Months</option>
<option value="180">6 Months</option>
<option value="all">All</option>
</select>
</div>
<div>
<label for="currentWeight">Current Weight:
<span id="latest-weight">Loading...</span>
</label>
</div>
</div>
<div class="right-align">
<label for="todaysWeight">Today's Weight:</label>
<input type="number" id="todaysWeight" class="weight-input" />
<button id="submitWeight" class="submit-button">Submit</button>
</div>
</div>
<div class="chart-container" id="chartContainer">
<canvas id="weightChart"></canvas>
</div>
</div>
<footer class="footer">
<p>Developed by Ruben Triegaardt</p>
</footer>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0"></script>
<script src="script.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const SUPABASE_URL = 'https://xgujrdvrazidffhxyiyw.supabase.co';
const SUPABASE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhndWpyZHZyYXppZGZmaHh5aXl3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk1NzIyNTEsImV4cCI6MjAzNTE0ODI1MX0.JtDbU7FSCPCPMQYQNU2bMPQEux1TggsfaQWsXpvxqFk';
// Global variable to hold chart instance
let weightChart;
// Function to create and insert a new canvas element
function createNewCanvas() {
const container = document.getElementById('chartContainer');
container.innerHTML = '<canvas id="weightChart"></canvas>';
return document.getElementById('weightChart').getContext('2d');
}
// Authentication check
if (!localStorage.getItem('authenticated')) {
window.location.href = 'login.html';
}
// Session expiration check
const loginTime = localStorage.getItem('loginTime');
if (loginTime && (Date.now() - parseInt(loginTime)) > 3600000) {
localStorage.removeItem('authenticated');
localStorage.removeItem('loginTime');
alert('Session expired. Please log in again.');
window.location.href = 'login.html';
}
// Logout functionality
const logoutButton = document.getElementById('logoutButton');
if (logoutButton) {
logoutButton.addEventListener('click', () => {
localStorage.removeItem('authenticated');
localStorage.removeItem('loginTime');
alert('Logged out successfully.');
window.location.href = 'login.html';
});
}
// Fetch bodybuilding data
async function fetchBodybuildingData() {
try {
const response = await fetch(`${SUPABASE_URL}/rest/v1/bodybuilding_data`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'apikey': SUPABASE_KEY,
'Authorization': `Bearer ${SUPABASE_KEY}`
}
});
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
const responseText = await response.text();
return JSON.parse(responseText);
} catch (error) {
console.error('Error fetching bodybuilding data from Supabase:', error);
alert('Error fetching bodybuilding data from Supabase: ' + error.message);
}
}
// Fetch weight data
async function fetchWeightData() {
try {
const response = await fetch(`${SUPABASE_URL}/rest/v1/weight_data`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'apikey': SUPABASE_KEY,
'Authorization': `Bearer ${SUPABASE_KEY}`
}
});
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
const responseText = await response.text();
return JSON.parse(responseText);
} catch (error) {
console.error('Error fetching data from Supabase:', error);
alert('Error fetching data from Supabase: ' + error.message);
}
}
function filterDataByDateRange(data, range) {
if (range === 'all') return data;
const rangeDays = parseInt(range);
const daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate() - rangeDays);
return data.filter(entry => new Date(entry.date) >= daysAgo).map(entry => ({
...entry,
// Round the date to the nearest day for better alignment with Chart.js
date: new Date(entry.date.getFullYear(), entry.date.getMonth(), entry.date.getDate())
}));
}
// Calculate trendline
function calculateTrendLine(data) {
const n = data.length;
const x = Array.from({length: n}, (v, k) => k);
const y = data.map(d => d.weight);
const sumX = x.reduce((a, b) => a + b, 0);
const sumY = y.reduce((a, b) => a + b, 0);
const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0);
const sumXX = x.reduce((sum, xi) => sum + xi * xi, 0);
const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
const intercept = (sumY - slope * sumX) / n;
return x.map(xi => ({
date: data[xi].date,
weight: slope * xi + intercept
}));
}
function updateChart(data) {
if (weightChart) {
weightChart.destroy();
}
const ctx = createNewCanvas();
weightChart = new Chart(ctx, {
type: 'line',
data: {
labels: data.map(entry => entry.date),
datasets: [
{
label: 'Weight (kg)',
data: data,
backgroundColor: 'white',
borderColor: 'white',
fill: false,
tension: 0.1,
parsing: {
xAxisKey: 'date',
yAxisKey: 'weight'
}
},
{
label: 'Trend Line',
data: calculateTrendLine(data),
backgroundColor: 'rgba(0, 123, 255, 1)',
borderColor: '#007BFF',
fill: false,
borderDash: [10, 5],
tension: 0,
parsing: {
xAxisKey: 'date',
yAxisKey: 'weight'
}
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'nearest',
intersect: true
},
plugins: {
tooltip: {
callbacks: {
label: function (context) {
const entry = context.raw;
return `Date: ${new Date(entry.date).toDateString()}, Weight: ${entry.weight} kg`;
}
}
},
legend: {
display: true,
position: 'top',
labels: {
color: 'white'
}
}
},
scales: {
x: {
type: 'time',
time: {
unit: 'day',
tooltipFormat: 'MMM d, yyyy'
},
title: {
display: true,
text: 'Date',
color: 'white'
},
grid: {
color: 'rgba(255, 255, 255, 0.5)'
},
ticks: {
color: 'white',
autoSkip: true, // Automatically skip ticks to avoid overlapping
maxTicksLimit: 10 // Limit maximum number of ticks for better alignment
}
},
y: {
title: {
display: true,
text: 'Weight (kg)',
color: 'white'
},
grid: {
color: 'rgba(255, 255, 255, 0.5)'
},
ticks: {
color: 'white',
precision: 0,
stepSize: 1 // Ensure the step size is consistent for better alignment
}
}
}
}
});
}
// Check if today's entry exists
async function checkExistingEntry(date) {
const response = await fetch(`${SUPABASE_URL}/rest/v1/weight_data?Date=eq.${date}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'apikey': SUPABASE_KEY,
'Authorization': `Bearer ${SUPABASE_KEY}`
}
});
if (!response.ok) {
throw new Error('Failed to check existing entry');
}
const data = await response.json();
return data.length > 0 ? true : false;
}
// Submit today's weight
async function submitTodaysWeight() {
const weightInput = document.getElementById('todaysWeight').value;
if (!weightInput) return alert('Please enter a weight.');
const date = new Date().toISOString().split('T')[0];
try {
const entryExists = await checkExistingEntry(date);
// If an entry exists, update it. Otherwise, insert a new entry.
const method = entryExists ? 'PATCH' : 'POST';
const url = `${SUPABASE_URL}/rest/v1/weight_data`;
const body = {Date: date, Weight: weightInput}; // Always include Date and Weight
const response = await fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json',
'apikey': SUPABASE_KEY,
'Authorization': `Bearer ${SUPABASE_KEY}`
},
body: JSON.stringify(body)
});
if (!response.ok) {
const errorText = await response.text();
console.error('Error details:', errorText);
throw new Error(`Failed to ${method === 'POST' ? 'submit' : 'update'} weight data.`);
}
document.getElementById('todaysWeight').value = '';
alert(`Weight ${method === 'POST' ? 'submitted' : 'updated'} successfully!`);
// Re-fetch weight data to ensure the chart is updated
await loadAndDisplayWeightData();
} catch (error) {
console.error(error);
alert(error.message);
}
}
document.getElementById('submitWeight').addEventListener('click', submitTodaysWeight);
// Fetch and display weight data
async function loadAndDisplayWeightData() {
const weightData = await fetchWeightData();
if (weightData && weightData.length) {
const parsedWeightData = weightData.map(entry => ({date: new Date(entry.Date), weight: entry.Weight}));
const dateRangeSelect = document.getElementById('dateRange');
// Initialize chart with a default 30-day range
dateRangeSelect.value = '30';
let filteredData = filterDataByDateRange(parsedWeightData, dateRangeSelect.value);
// Log the filtered data for debugging purposes
console.log('Filtered data:', filteredData);
// Create or update the chart
updateChart(filteredData);
// Listen to date range changes
dateRangeSelect.addEventListener('change', () => {
const selectedRange = dateRangeSelect.value;
filteredData = filterDataByDateRange(parsedWeightData, selectedRange);
// Log the updated filtered data for debugging purposes
console.log('Updated filtered data:', filteredData);
updateChart(filteredData);
});
}
}
await loadAndDisplayWeightData();
// Update latest weight
const bodybuildingData = await fetchBodybuildingData();
const latestWeight = bodybuildingData?.[0]?.weight_kg ?? "No Data";
document.getElementById('latest-weight').textContent = latestWeight + ' Kg';
});
</script>
</body>
</html>