-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
641 lines (534 loc) · 23.2 KB
/
Copy pathindex.html
File metadata and controls
641 lines (534 loc) · 23.2 KB
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timer and Goal Tracker</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
h1 {
text-align: center;
}
.container {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
.chart-container {
width: 300px;
height: 300px;
margin: 20px;
}
.stats {
text-align: center;
margin-top: 10px;
}
#countdownTimer {
font-size: 1.5em;
font-weight: bold;
}
#timerStats {
font-size: 1.2em;
margin-top: 10px;
}
#targetDateDisplay {
font-size: 1.2em;
margin-top: 10px;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<h1>Timer and Goal Tracker</h1>
<div id="errorMessage" style="color: red;"></div>
<!-- Timer Section -->
<div id="countdownTimer"></div>
<div id="timerStats"></div>
<div id="targetDateDisplay"></div>
<div class="container">
<!-- Timer Chart -->
<div class="chart-container">
<canvas id="timerChart"></canvas>
</div>
<!-- Goal Charts -->
<div class="chart-container">
<canvas id="followerChart"></canvas>
<div id="followerStats" class="stats"></div>
</div>
<div class="chart-container">
<canvas id="subscriptionChart"></canvas>
<div id="subscriptionStats" class="stats"></div>
</div>
<div class="chart-container">
<canvas id="bitsChart"></canvas>
<div id="bitsStats" class="stats"></div>
</div>
<div class="chart-container">
<canvas id="donationChart"></canvas>
<div id="donationStats" class="stats"></div>
</div>
<div id="refreshTracker" style="text-align:center; margin-top:20px; font-size:1.2em; color:blue;">
Last refresh: N/A
</div>
</div>
<script>
let initiationComplete = false;
let targetDate = 0;
let startTime;
let endTime;
let timerChart = null; // Initialize as null, not empty object
const goalCharts = {};
let followerCurrent = 0, followerGoal = 0;
let subCurrent = 0, subGoal = 0;
let donationCurrent = 0, donationGoal = 0;
let bitsCurrent = 0, bitsGoal = 0;
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const canvasSize = 2200;
canvas.width = canvasSize;
canvas.height = canvasSize;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const donutWidth = 40;
const donutSpacing = 15;
const cameraRadius = 670;
const baseRadius = cameraRadius + donutSpacing + donutWidth;
const cameraImage = new Image();
cameraImage.src = 'https://static-cdn.jtvnw.net/jtv_user_pictures/4ae8547d-3e84-47bd-a024-ba09885f1bbe-profile_image-300x300.png';
// Function to fetch data from a URL
async function fetchData(url) {
try {
console.log(`Fetching data from: ${url}`); // Debug log
const response = await fetch(url);
if (!response.ok) throw new Error("Network error");
const data = await response.json();
console.log(`Fetched data:`, data); // Debug log
return data;
} catch (error) {
console.error("Fetch error:", error);
document.getElementById("errorMessage").textContent = "Failed to load data. Retrying...";
return null;
}
}
// Load initial data including the timer and goal data
async function loadInitialData() {
console.log("Loading initial data..."); // Debug log
const timerData = await fetchData("https://script.google.com/macros/s/AKfycby4UKXfW68KHrWyGoRUpuPnUcTk2Eu2SyLxm3XrcYPX7qwtlWG6I02WWrckkbAgI3Af/exec?action=getTimer&timerName=Timer");
if (timerData) {
console.log("Timer data loaded:", timerData); // Debug log
startTime = new Date(timerData.startTime);
endTime = new Date(timerData.endTime);
targetDate = new Date(timerData.endTime);
document.getElementById("targetDateDisplay").textContent = `Target Date: ${endTime.toDateString()} ${endTime.toLocaleTimeString()}`;
await updateTimerChart();
await updateCountdown(startTime, endTime);
}
// Fetch goal data for each goal type
await fetchAllGoalData();
initiationComplete = true;
}
// Update countdown timer
function updateCountdown() {
const countdownElement = document.getElementById("countdownTimer");
const now = new Date();
const timeRemaining = endTime - now;
const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
countdownElement.textContent = `Countdown: ${days}d ${hours}h ${minutes}m ${seconds}s`;
if (timeRemaining <= 0) {
countdownElement.textContent = "Time's up!";
}
}
// Calculate timer progress and update chart
async function updateTimerChart() {
const now = new Date();
const elapsedTime = now - startTime;
const totalTime = endTime - startTime;
const progressPercentage = Math.min(100, (elapsedTime / totalTime) * 100);
console.log("Timer progress: ", progressPercentage); // Debug log
const ctx = document.getElementById("timerChart")?.getContext('2d');
if (!ctx) {
console.error("Chart context for Overall Timer not found.");
return; // This is okay: it stops the function if context is not found.
}
// If the timerChart does not exist, initialize it
if (!timerChart) {
timerChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Progress", "Remaining"],
datasets: [{
data: [progressPercentage, 100 - progressPercentage],
backgroundColor: ["#4caf50", "#ddd"]
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
datalabels: {
color: 'white',
font: {
weight: 'bold',
size: 14
},
formatter: function(value, context) {
if (context.dataset.data[0] === value) {
return `${Math.round(progressPercentage)}%`;
} else {
return '';
}
}
}
}
},
plugins: [ChartDataLabels]
});
} else {
timerChart.data.datasets[0].data = [progressPercentage, 100 - progressPercentage];
timerChart.update();
}
document.getElementById("timerStats").textContent = `Timer Progress: ${Math.round(progressPercentage)}%`;
}
// Fetch all goal data
async function fetchAllGoalData() {
console.log("Fetching goal data..."); // Debug log
const goalTypes = ["Follower Goal", "Subscription Goal", "Bits Goal", "Donation Goal"];
await Promise.all(goalTypes.map(fetchGoalData));
}
// Fetch data for a specific goal
async function fetchGoalData(goalType) {
const url = `https://script.google.com/macros/s/AKfycby4UKXfW68KHrWyGoRUpuPnUcTk2Eu2SyLxm3XrcYPX7qwtlWG6I02WWrckkbAgI3Af/exec?action=getGoal&goalType=${encodeURIComponent(goalType)}`;
console.log(`Fetching goal data for ${goalType} from: ${url}`); // Debug log
const goalData = await fetchData(url);
if (goalData) {
console.log(`Fetched data for ${goalType}:`, goalData); // Debug log
const current = goalData.CurrentCount;
const goal = goalData.goalValue;
if (current !== undefined && goal !== undefined) {
updateGoalChart(goalType, current, goal);
updateGoalStats(goalType, current, goal);
} else {
console.error(`Missing CurrentCount or goalValue for ${goalType}`);
}
} else {
console.error(`Failed to fetch goal data for ${goalType}`);
}
}
function updateGoalChart(goalType, current, goal) {
const goalToChartId = {
"Follower Goal": "followerChart",
"Subscription Goal": "subscriptionChart",
"Bits Goal": "bitsChart",
"Donation Goal": "donationChart"
};
const chartId = goalToChartId[goalType];
const ctx = document.getElementById(chartId)?.getContext('2d');
if (!ctx) {
console.error(`Chart context for ${goalType} not found.`);
return;
}
// Calculate the progress and remaining values
const progress = Math.min(100, (current / goal) * 100); // Ensure it's a percentage
const remaining = 100 - progress; // Remaining percentage
// Check if the chart already exists
if (!goalCharts[goalType]) {
goalCharts[goalType] = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Progress", "Remaining"],
datasets: [{
data: [progress, remaining],
backgroundColor: ["#4caf50", "#ddd"]
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
datalabels: {
color: 'white',
font: {
weight: 'bold',
size: 14
},
formatter: function(value, context) {
const currentData = context.chart.data.datasets[0].data;
const total = currentData[0] + currentData[1];
const currentPercent = Math.round((currentData[0] / total) * 100);
// Ensure correct label for progress and remaining sections
if (context.dataset.data[0] === value) {
return `${currentPercent}%`; // Show progress percentage
} else {
const remainingPercent = 100 - currentPercent;
return `${remainingPercent}%`; // Show remaining percentage
}
}
}
}
},
plugins: [ChartDataLabels]
});
} else {
// Update existing chart
goalCharts[goalType].data.datasets[0].data = [progress, remaining];
goalCharts[goalType].update();
}
if(goalType === "Follower Goal") {
followerCurrent = current;
followerGoal = goal;
};
if(goalType === "Subscription Goal") {
subCurrent = current;
subGoal = goal;
};
if(goalType === "Bits Goal") {
bitsCurrent = current;
bitsGoal = goal;
};
if(goalType === "Donation Goal") {
donationCurrent = current;
donationGoal = goal;
}
}
// Update the statistics for each goal
function updateGoalStats(goalType, current, goal) {
const goalToStatsId = {
"Follower Goal": "followerStats",
"Subscription Goal": "subscriptionStats",
"Bits Goal": "bitsStats",
"Donation Goal": "donationStats"
};
const statsId = goalToStatsId[goalType];
let currentFormatted = current;
let goalFormatted = goal;
// Only format the Donation Goal as currency
if (goalType === "Donation Goal") {
currentFormatted = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(current);
goalFormatted = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(goal);
}
document.getElementById(statsId).textContent = `${goalType}: ${currentFormatted} / ${goalFormatted}`;
}
function getTimeRemaining() {
const now = new Date().getTime();
const timeLeft = endTime - now;
const totalDuration = endTime - startTime;
const percentage = Math.max(0, Math.min(1, 1 - timeLeft / totalDuration));
return {
countdownDays: Math.floor(timeLeft / (1000 * 60 * 60 * 24)),
countdownHours: Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
countdownMinutes: Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60)),
countdownSeconds: Math.floor((timeLeft % (1000 * 60)) / 1000),
percentage: percentage
};
}
function drawCameraCircle(x, y, radius, transparency) {
ctx.save();
ctx.globalAlpha = transparency;
// Draw the image as a circular clip
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.clip();
ctx.drawImage(cameraImage, x - radius, y - radius, radius * 2, radius * 2);
ctx.restore(); // Restore state to avoid clipping affecting stroke
// Draw the border
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.lineWidth = 8;
//
ctx.strokeStyle = '#FF0000CC';
ctx.stroke();
}
function drawDonut(x, y, radius, width, percentage, color) {
if (percentage <= 0) return; // Skip if nothing to draw
const endAngle = Math.PI * 2 * percentage - Math.PI / 2;
// Main donut
ctx.beginPath();
ctx.arc(x, y, radius, -Math.PI / 2, endAngle);
ctx.lineWidth = width;
ctx.strokeStyle = color; // Use the passed color
ctx.stroke();
// Outer border (same color as main donut for smooth transition)
ctx.beginPath();
ctx.arc(x, y, radius + width / 2, -Math.PI / 2, endAngle);
ctx.lineWidth = 5;
ctx.strokeStyle = color; // <-- remove ctx.lineColor
ctx.stroke();
// Inner border
ctx.beginPath();
ctx.arc(x, y, radius - width / 2, -Math.PI / 2, endAngle);
ctx.lineWidth = 5;
ctx.strokeStyle = 'black'; // Inner border remains black
ctx.stroke();
}
function drawLabelWithLine(label, x, y, radius, percentage, labelIndex, totalLabels, textColor, lineColor, borderColor) {
const padding = 10;
const fontSize = 80;
ctx.font = `bold ${fontSize}px Arial`;
ctx.fillStyle = 'white';
const textWidth = ctx.measureText(label).width;
const labelWidth = textWidth + padding * 2;
const labelHeight = fontSize + padding * 2;
const reversedIndex = totalLabels - labelIndex - 1;
const labelX = 100;
const labelY = 100 + reversedIndex * (labelHeight + 10);
const angle = (-Math.PI / 2) + (Math.PI * 2 * percentage);
const startX = x + radius * Math.cos(angle);
const startY = y + radius * Math.sin(angle);
// 🎯 Draw the line first so it's behind the label
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(labelX + labelWidth, labelY + labelHeight / 2);
ctx.strokeStyle = "#870101D9";
ctx.lineWidth = 4;
ctx.stroke();
// 🖋️ Draw the label border
ctx.strokeStyle = borderColor;
ctx.lineWidth = 10;
ctx.strokeRect(labelX, labelY, labelWidth, labelHeight);
// 🖼️ Draw the label background
ctx.fillStyle = '#0000007F';
//ctx.globalAlpha = .5;
ctx.fillRect(labelX, labelY, labelWidth, labelHeight);
// 📝 Draw the label text
ctx.fillStyle = "white";
ctx.textAlign = "left";
ctx.fillText(label, labelX + padding, labelY + fontSize + padding / 2);
}
function lerpColor(color1, color2, t) {
// color1 and color2 are {r, g, b} objects
return {
r: Math.round(color1.r + (color2.r - color1.r) * t),
g: Math.round(color1.g + (color2.g - color1.g) * t),
b: Math.round(color1.b + (color2.b - color1.b) * t)
};
}
function rgbToHex(color) {
return "#" + ((1 << 24) + (color.r << 16) + (color.g << 8) + color.b)
.toString(16)
.slice(1);
}
const red = { r: 255, g: 0, b: 0 };
const blue = { r: 0, g: 0, b: 255 };
function drawAll() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Update the countdown text in the DOM
updateCountdown();
// Draw the central camera circle
drawCameraCircle(centerX, centerY, cameraRadius + 20, 0.13);
// Get current countdown info and percentage
const { countdownDays, countdownHours, countdownMinutes, countdownSeconds, percentage } = getTimeRemaining();
const countdownText = `Time to Live: ${countdownDays}d ${countdownHours}h ${countdownMinutes}m ${countdownSeconds}s`;
// Smooth color oscillation for donuts
const now = Date.now() / 1000; // seconds
const t = (Math.sin(now) + 1) / 2; // oscillates 0 → 1 → 0 smoothly
const currentColor = lerpColor(red, blue, t);
const colorHex = rgbToHex(currentColor);
// Prepare all donut data
const data = [
{ label: `Followers: ${followerCurrent}/${followerGoal}`, percentage: followerCurrent / followerGoal, color: colorHex },
{ label: `Subs: ${subCurrent}/${subGoal}`, percentage: subCurrent / subGoal, color: colorHex },
{ label: `Donations: $${donationCurrent}/$${donationGoal}`, percentage: donationCurrent / donationGoal, color: colorHex },
{ label: `Bits: ${bitsCurrent}/${bitsGoal}`, percentage: bitsCurrent / bitsGoal, color: colorHex },
{ label: countdownText, percentage: percentage, color: colorHex } // ✅ Use the percentage we already calculated
];
// Sort by percentage descending
data.sort((a, b) => b.percentage - a.percentage);
// 1️⃣ Draw all donuts
data.forEach((item, index) => {
drawDonut(
centerX,
centerY,
baseRadius + index * (donutWidth + donutSpacing),
donutWidth,
item.percentage,
item.color
);
});
// 2️⃣ Draw all labels on top
data.forEach((item, index) => {
drawLabelWithLine(
item.label,
centerX,
centerY,
baseRadius + index * (donutWidth + donutSpacing),
item.percentage,
index,
data.length,
'#FF0000CC',
'black',
'black'
);
});
// Continue the animation loop
requestAnimationFrame(drawAll);
}
// Initialize data loading
loadInitialData();
async function getUpdatedTimerData() {
// Re-fetch timer data
const timerData = await fetchData("https://script.google.com/macros/s/AKfycby4UKXfW68KHrWyGoRUpuPnUcTk2Eu2SyLxm3XrcYPX7qwtlWG6I02WWrckkbAgI3Af/exec?action=getTimer&timerName=Timer");
if (timerData) {
startTime = new Date(timerData.startTime);
endTime = new Date(timerData.endTime);
document.getElementById("targetDateDisplay").textContent =
`Target Date: ${endTime.toDateString()} ${endTime.toLocaleTimeString()}`;
updateTimerChart();
updateCountdown();
} else {
console.error("Failed to fetch timer data.");
}
}
// Periodically refresh timer and goal data every 5 seconds
async function refreshDataPeriodically() {
setInterval(async function () {
getUpdatedTimerData();
const trackerDiv = document.getElementById("refreshTracker");
const now = new Date();
if (trackerDiv) trackerDiv.textContent = `Refreshing data at: ${now.toLocaleTimeString()}`;
console.log("Refreshing data..."); // Debug log
try {
// Re-fetch timer data
await getUpdatedTimerData();
// Re-fetch goal data for each goal type
await fetchAllGoalData();
// Refresh each goal chart
for (const goalType of ["Follower Goal", "Subscription Goal", "Bits Goal", "Donation Goal"]) {
const chart = goalCharts[goalType];
if (chart) {
const currentData = chart.data.datasets[0].data;
const [progress, remaining] = currentData;
const total = progress + remaining;
const progressPercentage = total > 0 ? Math.round((progress / total) * 100) : 0;
const remainingPercentage = 100 - progressPercentage;
chart.data.datasets[0].data = [progressPercentage, remainingPercentage];
chart.options.plugins.datalabels.formatter = (value) => `${value}%`;
chart.update();
}
}
} catch (error) {
console.error("Error during periodic data refresh:", error);
}
}, 5000); // every 5 seconds
}
cameraImage.onload = function() {
drawAll();
};
// Initialize data loading
async function init() {
await loadInitialData(); // Load initial timer and goal data
drawAll(); // Start the animation loop
refreshDataPeriodically(); // Start periodic refresh after initial load
}
init();
</script>
</body>
</html>