-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
511 lines (441 loc) · 15.5 KB
/
script.js
File metadata and controls
511 lines (441 loc) · 15.5 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
// DOM Elements
const birthDateInput = document.getElementById('birthDate');
const lifeExpectancyInput = document.getElementById('lifeExpectancy');
const dotGrid = document.getElementById('dotGrid');
const passedCountEl = document.getElementById('passedCount');
const remainingCountEl = document.getElementById('remainingCount');
const percentageEl = document.getElementById('percentage');
const tabs = document.querySelectorAll('.tab');
const tooltip = document.getElementById('tooltip');
const liveClock = document.getElementById('liveClock');
const quoteEl = document.getElementById('quote');
const exportBtn = document.getElementById('exportBtn');
// State
let currentView = 'hours';
let isPaused = false;
let updateInterval;
// Quotes that hit different
const quotes = [
"You have lived {passed} {unit}. You will never get them back.",
"Every dot that turns red is gone forever.",
"{remaining} {unit} left. Maybe. If you're lucky.",
"The dot turning red right now? That was your life.",
"You're watching yourself run out of time.",
"Each green dot is a promise. Each red dot is a receipt.",
"Time doesn't care about your plans.",
"{percentage}% of your {unit} are gone. What did you do with them?",
"The next dot will turn red. Then the next. Then you.",
"This isn't an app. It's a mirror."
];
// localStorage keys
const STORAGE_KEYS = {
birthDate: 'dots_birthDate',
lifeExpectancy: 'dots_lifeExpectancy'
};
// Initialize
function init() {
loadSettings();
setupEventListeners();
render();
startLiveUpdates();
updateClock();
}
// Load settings from localStorage
function loadSettings() {
const savedBirthDate = localStorage.getItem(STORAGE_KEYS.birthDate);
const savedLifeExpectancy = localStorage.getItem(STORAGE_KEYS.lifeExpectancy);
if (savedBirthDate) {
birthDateInput.value = savedBirthDate;
}
if (savedLifeExpectancy) {
lifeExpectancyInput.value = savedLifeExpectancy;
}
}
// Save settings to localStorage
function saveSettings() {
localStorage.setItem(STORAGE_KEYS.birthDate, birthDateInput.value);
localStorage.setItem(STORAGE_KEYS.lifeExpectancy, lifeExpectancyInput.value);
}
// Setup event listeners
function setupEventListeners() {
birthDateInput.addEventListener('change', () => {
saveSettings();
render();
});
lifeExpectancyInput.addEventListener('change', () => {
saveSettings();
render();
});
tabs.forEach(tab => {
tab.addEventListener('click', () => {
switchView(tab.dataset.view);
});
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.target.tagName === 'INPUT') return;
switch(e.key) {
case '1': switchView('hours'); break;
case '2': switchView('days'); break;
case '3': switchView('weeks'); break;
case '4': switchView('months'); break;
case '5': switchView('years'); break;
case ' ':
e.preventDefault();
togglePause();
break;
}
});
// Tooltip events
dotGrid.addEventListener('mousemove', handleDotHover);
dotGrid.addEventListener('mouseleave', () => {
tooltip.classList.remove('visible');
});
// Export button
exportBtn.addEventListener('click', exportImage);
}
function switchView(view) {
tabs.forEach(t => t.classList.remove('active'));
document.querySelector(`[data-view="${view}"]`).classList.add('active');
currentView = view;
render();
}
function togglePause() {
isPaused = !isPaused;
document.body.classList.toggle('paused', isPaused);
if (isPaused) {
clearInterval(updateInterval);
} else {
startLiveUpdates();
}
}
function startLiveUpdates() {
clearInterval(updateInterval);
updateInterval = setInterval(() => {
if (!isPaused) {
render();
updateClock();
}
}, 1000);
}
function updateClock() {
const now = new Date();
liveClock.textContent = now.toLocaleTimeString('en-US', {
hour12: false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
}
// Calculation functions
function getHoursInDay() {
const now = new Date();
const hoursPassed = now.getHours();
const minutePercent = (now.getMinutes() / 60) * 100;
return {
passed: hoursPassed,
total: 24,
current: hoursPassed,
fillPercent: minutePercent,
getLabel: (i) => {
const hour = i.toString().padStart(2, '0') + ':00';
if (i < hoursPassed) return `${hour} - Gone`;
if (i === hoursPassed) return `${hour} - NOW (${now.getMinutes()} min gone)`;
return `${hour} - Ahead`;
}
};
}
function getDaysInYear() {
const now = new Date();
const year = now.getFullYear();
const startOfYear = new Date(year, 0, 1);
const endOfYear = new Date(year + 1, 0, 1);
const totalDays = Math.floor((endOfYear - startOfYear) / (1000 * 60 * 60 * 24));
const daysPassed = Math.floor((now - startOfYear) / (1000 * 60 * 60 * 24));
const hourPercent = ((now.getHours() * 60 + now.getMinutes()) / 1440) * 100;
return {
passed: daysPassed,
total: totalDays,
current: daysPassed,
fillPercent: hourPercent,
getLabel: (i) => {
const date = new Date(year, 0, i + 1);
const formatted = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
if (i < daysPassed) return `${formatted} - Gone`;
if (i === daysPassed) return `${formatted} - TODAY (${Math.round(hourPercent)}% gone)`;
return `${formatted} - Ahead`;
}
};
}
function getWeeksInYear() {
const now = new Date();
const year = now.getFullYear();
const startOfYear = new Date(year, 0, 1);
const daysPassed = Math.floor((now - startOfYear) / (1000 * 60 * 60 * 24));
const weeksPassed = Math.floor(daysPassed / 7);
const dayInWeek = daysPassed % 7;
const weekPercent = (dayInWeek / 7) * 100;
return {
passed: weeksPassed,
total: 52,
current: weeksPassed,
fillPercent: weekPercent,
getLabel: (i) => {
if (i < weeksPassed) return `Week ${i + 1} - Gone`;
if (i === weeksPassed) return `Week ${i + 1} - NOW (Day ${dayInWeek + 1} of 7)`;
return `Week ${i + 1} - Ahead`;
}
};
}
function getMonthsInYear() {
const now = new Date();
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const monthsPassed = now.getMonth();
const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
const monthPercent = (now.getDate() / daysInMonth) * 100;
return {
passed: monthsPassed,
total: 12,
current: monthsPassed,
fillPercent: monthPercent,
getLabel: (i) => {
if (i < monthsPassed) return `${monthNames[i]} - Gone`;
if (i === monthsPassed) return `${monthNames[i]} - NOW (Day ${now.getDate()} of ${daysInMonth})`;
return `${monthNames[i]} - Ahead`;
}
};
}
function getYearsInLife() {
const birthDate = birthDateInput.value;
const lifeExpectancy = parseInt(lifeExpectancyInput.value) || 80;
if (!birthDate) {
return {
passed: 0,
total: lifeExpectancy,
current: 0,
fillPercent: 0,
getLabel: (i) => `Year ${i + 1} - Set your birth date`
};
}
const birth = new Date(birthDate);
const now = new Date();
const birthYear = birth.getFullYear();
let yearsPassed = now.getFullYear() - birthYear;
const birthThisYear = new Date(now.getFullYear(), birth.getMonth(), birth.getDate());
if (now < birthThisYear) {
yearsPassed--;
}
yearsPassed = Math.max(0, yearsPassed);
// Calculate how far into current year of life
const lastBirthday = new Date(now.getFullYear(), birth.getMonth(), birth.getDate());
if (now < lastBirthday) {
lastBirthday.setFullYear(lastBirthday.getFullYear() - 1);
}
const nextBirthday = new Date(lastBirthday);
nextBirthday.setFullYear(nextBirthday.getFullYear() + 1);
const yearLength = nextBirthday - lastBirthday;
const yearProgress = now - lastBirthday;
const yearPercent = (yearProgress / yearLength) * 100;
return {
passed: yearsPassed,
total: lifeExpectancy,
current: yearsPassed,
fillPercent: yearPercent,
getLabel: (i) => {
const year = birthYear + i;
const age = i;
if (i < yearsPassed) return `${year} (Age ${age}) - Lived`;
if (i === yearsPassed) return `${year} (Age ${age}) - NOW (${Math.round(yearPercent)}% through)`;
if (i === lifeExpectancy - 1) return `${year} (Age ${age}) - THE END`;
return `${year} (Age ${age}) - Ahead`;
}
};
}
// Get data based on current view
function getViewData() {
switch (currentView) {
case 'hours': return { ...getHoursInDay(), unit: 'hours' };
case 'days': return { ...getDaysInYear(), unit: 'days' };
case 'weeks': return { ...getWeeksInYear(), unit: 'weeks' };
case 'months': return { ...getMonthsInYear(), unit: 'months' };
case 'years': return { ...getYearsInLife(), unit: 'years' };
default: return { ...getHoursInDay(), unit: 'hours' };
}
}
// Handle dot hover for tooltip
function handleDotHover(e) {
const dot = e.target.closest('.dot');
if (!dot) {
tooltip.classList.remove('visible');
return;
}
const index = parseInt(dot.dataset.index);
const data = getViewData();
const label = data.getLabel(index);
tooltip.textContent = label;
tooltip.classList.add('visible');
const rect = dot.getBoundingClientRect();
tooltip.style.left = rect.left + 'px';
tooltip.style.top = (rect.top - 40) + 'px';
}
// Render dots
function renderDots(passed, total, current, fillPercent) {
dotGrid.innerHTML = '';
if (currentView === 'years') {
dotGrid.classList.add('years-view');
} else {
dotGrid.classList.remove('years-view');
}
for (let i = 0; i < total; i++) {
const dot = document.createElement('div');
dot.className = 'dot';
dot.dataset.index = i;
if (i < passed) {
dot.classList.add('passed');
} else {
dot.classList.add('remaining');
}
if (i === current) {
dot.classList.add('current');
// Set the fill percentage for the current dot
dot.style.setProperty('--fill-percent', `${fillPercent}%`);
}
// Mark the final dot
if (i === total - 1) {
dot.classList.add('final');
}
dotGrid.appendChild(dot);
}
}
// Update stats display
function updateStats(passed, total, unit) {
const remaining = total - passed;
const percentage = total > 0 ? Math.round((passed / total) * 100) : 0;
passedCountEl.textContent = passed;
remainingCountEl.textContent = remaining;
percentageEl.textContent = percentage + '%';
// Update quote
const quote = quotes[Math.floor(Date.now() / 10000) % quotes.length]
.replace('{passed}', passed)
.replace('{remaining}', remaining)
.replace('{percentage}', percentage)
.replace(/{unit}/g, unit);
quoteEl.textContent = quote;
}
// Main render function
function render() {
const { passed, total, current, unit, fillPercent } = getViewData();
renderDots(passed, total, current, fillPercent);
updateStats(passed, total, unit);
}
// Export 4K image
function exportImage() {
const data = getViewData();
const { passed, total, unit, fillPercent } = data;
// 4K resolution
const width = 3840;
const height = 2160;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
// Background
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, width, height);
// Calculate dot grid layout
const padding = 200;
const availableWidth = width - (padding * 2);
const availableHeight = height - 600; // Leave space for text
// Calculate optimal dot size and grid
let cols, rows, dotSize, gap;
if (total <= 24) {
cols = Math.min(total, 12);
rows = Math.ceil(total / cols);
dotSize = 120;
gap = 40;
} else if (total <= 52) {
cols = 13;
rows = Math.ceil(total / cols);
dotSize = 80;
gap = 30;
} else if (total <= 100) {
cols = 10;
rows = Math.ceil(total / cols);
dotSize = 70;
gap = 25;
} else {
cols = Math.ceil(Math.sqrt(total * 1.5));
rows = Math.ceil(total / cols);
dotSize = Math.min(50, Math.floor((availableWidth - (cols - 1) * 20) / cols));
gap = 20;
}
const gridWidth = cols * dotSize + (cols - 1) * gap;
const gridHeight = rows * dotSize + (rows - 1) * gap;
const startX = (width - gridWidth) / 2;
const startY = 500;
// Draw title
ctx.fillStyle = '#2563eb';
ctx.font = 'bold 140px Courier New';
ctx.textAlign = 'center';
ctx.fillText('DOTS', width / 2, 200);
// Draw subtitle
ctx.fillStyle = '#64748b';
ctx.font = '40px Courier New';
ctx.fillText('MY LIFE IN ' + unit.toUpperCase(), width / 2, 280);
// Draw stats
ctx.font = 'bold 60px Courier New';
ctx.fillStyle = '#e74c3c';
ctx.fillText(passed + ' GONE', width / 2 - 400, 400);
ctx.fillStyle = '#2ecc71';
ctx.fillText((total - passed) + ' LEFT', width / 2 + 400, 400);
ctx.fillStyle = '#2563eb';
const percentage = Math.round((passed / total) * 100);
ctx.fillText(percentage + '% LIVED', width / 2, 400);
// Draw dots
for (let i = 0; i < total; i++) {
const col = i % cols;
const row = Math.floor(i / cols);
const x = startX + col * (dotSize + gap);
const y = startY + row * (dotSize + gap);
// Dot color
if (i < passed) {
ctx.fillStyle = '#e74c3c';
} else if (i === passed) {
// Current dot - draw green background first
ctx.fillStyle = '#2ecc71';
ctx.fillRect(x, y, dotSize, dotSize);
// Draw red fill from bottom
const fillHeight = (fillPercent / 100) * dotSize;
ctx.fillStyle = '#e74c3c';
ctx.fillRect(x, y + dotSize - fillHeight, dotSize, fillHeight);
// Draw border for current
ctx.strokeStyle = '#2563eb';
ctx.lineWidth = 6;
ctx.strokeRect(x - 6, y - 6, dotSize + 12, dotSize + 12);
continue;
} else if (i === total - 1) {
ctx.fillStyle = '#1d4ed8';
} else {
ctx.fillStyle = '#2ecc71';
}
ctx.fillRect(x, y, dotSize, dotSize);
}
// Draw footer
ctx.fillStyle = '#94a3b8';
ctx.font = '36px Courier New';
ctx.fillText(new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
}), width / 2, height - 120);
ctx.font = '28px Courier New';
ctx.fillText('Generated with DOTS - Make every moment count', width / 2, height - 60);
// Download
const link = document.createElement('a');
link.download = `dots-${unit}-${new Date().toISOString().split('T')[0]}.png`;
link.href = canvas.toDataURL('image/png');
link.click();
}
// Start the app
init();