-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbeat-add-0.js
More file actions
504 lines (438 loc) · 16 KB
/
beat-add-0.js
File metadata and controls
504 lines (438 loc) · 16 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
/**
* FILE: beat-add-0.js
* PROJECT: Beat ADD Time Tracker
* PURPOSE: Manages the core application state, dynamic row creation, and local storage persistence.
*
* KEY DESIGN DECISIONS:
* 1. DOM-as-Database: Eliminates global state arrays in favor of reading directly from the DOM
* to ensure the UI is always the single source of truth.
* 2. ID-less Traversal: Uses parent/sibling relationships (closest, lastElementChild) to
* manage rows, making the system immune to ID-desync bugs.
* 3. Event Delegation: A single listener on the table body handles all edits and deletions,
* reducing memory overhead for long-running sessions.
*
* CORE LOGIC:
* - handleRadioChange: Captures task intent and opens the modal.
* - handleRadioCommit: Triggers task switching and "Stop-to-Gap" transformation on Set.
* - parseTimeString: Regex-based utility to bridge localized strings and Date math.
* - editRow: Injects a temporary <input type="time"> for precision editing.
*/
console.log("beat-add-0.js FROM FILE");
/* Guarded top-level DOM refs (initialized in DOMContentLoaded) */
let closeButton = null;
let modal = null;
let distractionPenaltyCount = 0;
window.pendingActivity = null;
// Helper: update the status line with activity and optional time string
function updateStatusLine(activity, timeStr) {
const statusEl = document.getElementById("statusLine");
if (!statusEl) return;
if (!activity) {
statusEl.textContent = "Status: idle";
return;
}
if (timeStr) {
statusEl.textContent = `Status: ${activity} — ${timeStr}`;
} else {
statusEl.textContent = `Status: ${activity} — waiting`;
}
}
function editRow(span) {
const fieldType = span.closest("td").dataset.field;
// Logic: Only use the time picker for start/end fields
if (fieldType !== "start" && fieldType !== "end") {
const result = prompt("Edit value:", span.textContent);
if (result !== null) {
span.textContent = result.trim();
updateRunningTotals();
saveToLocalStorage();
}
return;
}
// Create the Time Input
const oldTimeStr = span.textContent;
const input = document.createElement("input");
input.type = "time";
input.step = "1"; // Allows seconds precision
// Convert "1:02:03 PM" display string to "13:02:03" for the input.value
const d = parseTimeString(oldTimeStr);
if (d) {
input.value = `${String(d.getHours()).padStart(2, "0")}:${String(
d.getMinutes(),
).padStart(2, "0")}:${String(d.getSeconds()).padStart(2, "0")}`;
}
// Swap span for input
span.style.display = "none";
span.parentNode.insertBefore(input, span);
input.focus();
// Save on blur or Enter key
const saveChange = () => {
if (input.value) {
// Create a date object from the picker value to get localized string back
const [h, m, s] = input.value.split(":");
const newDate = new Date();
newDate.setHours(h, m, s || 0, 0);
span.textContent = newDate.toLocaleTimeString();
const row = span.closest("tr");
// Recalculate duration for the row
const startStr = row.querySelector(
'[data-field="start"] span',
).textContent;
const endStr = row.querySelector('[data-field="end"] span').textContent;
const sDate = parseTimeString(startStr);
const eDate = parseTimeString(endStr);
if (sDate && eDate) {
row.querySelector('[data-field="duration"] span').textContent =
formatDuration(timeDifference(sDate, eDate));
}
}
input.remove();
span.style.display = "";
updateRunningTotals();
saveToLocalStorage();
};
input.onblur = saveChange;
input.onkeydown = (e) => {
if (e.key === "Enter") saveChange();
};
}
function parseTimeString(timeStr) {
if (!timeStr || typeof timeStr !== "string" || timeStr.trim() === "")
return null;
const d = new Date();
// Regex to extract hours, mins, secs, and optional AM/PM
const match = timeStr.match(/(\d+):(\d+):(\d+)\s*(AM|PM)?/i);
if (!match) return null;
let [_, hours, minutes, seconds, modifier] = match;
hours = parseInt(hours);
minutes = parseInt(minutes);
seconds = parseInt(seconds);
// LOGIC: Convert 12-hour AM/PM to 24-hour math
if (modifier) {
if (modifier.toUpperCase() === "PM" && hours < 12) hours += 12;
if (modifier.toUpperCase() === "AM" && hours === 12) hours = 0;
}
d.setHours(hours, minutes, seconds, 0);
return d;
}
function updateRunningTotals() {
const totalsMs = {};
let dayTotalMs = 0;
let productiveMs = 0;
const focusCategories = [
"study",
"prototyping",
"Beat ADD",
"exercise",
"legal case",
];
document.querySelectorAll("#tableBody tr").forEach((row) => {
const activity = row.querySelector(
'[data-field="activity"] span',
)?.textContent;
const startStr = row.querySelector(
'[data-field="start"] span',
)?.textContent;
const endStr = row.querySelector('[data-field="end"] span')?.textContent;
if (activity && startStr && endStr && endStr.trim() !== "") {
const diff = parseTimeString(endStr) - parseTimeString(startStr);
if (!isNaN(diff)) {
totalsMs[activity] = (totalsMs[activity] || 0) + diff;
dayTotalMs += diff;
if (focusCategories.includes(activity)) productiveMs += diff;
}
}
});
document.querySelectorAll("tfoot [data-total]").forEach((cell) => {
const category = cell.getAttribute("data-total");
const totalMs = totalsMs[category] || 0;
const dObj = timeDifference(new Date(0), new Date(totalMs));
cell.textContent = totalMs > 0 ? formatDuration(dObj) : "0s";
cell.classList.add("total-updated");
setTimeout(() => cell.classList.remove("total-updated"), 1000);
});
const scoreCell = document.getElementById("live-focus-score");
if (scoreCell) {
// Math: (Productive / Total) * 100
let momentumScore =
dayTotalMs > 0 ? Math.round((productiveMs / dayTotalMs) * 100) : 0;
// Subtract 5% for every missed nudge (Distraction)
momentumScore = Math.max(0, momentumScore - distractionPenaltyCount * 5);
scoreCell.textContent = `${momentumScore}%`;
scoreCell.style.color =
momentumScore >= 70
? "#2ed573"
: momentumScore >= 40
? "#ffa502"
: "#ff4757";
}
}
/**
* NEW: Split intent capture from commit.
* - handleRadioChange: capture intent + open modal
* - handleRadioCommit: actually mutate rows when Set is pressed
*/
/**
* ONE FUNCTION ONLY:
* - Called with a DOM element → user clicked a radio button:
* • store the selected activity as pendingActivity
* • update the UI label
* • open the modal
*
* - Called with a string → modal confirmed:
* • seal previous row
* • add new row
* • reset pendingActivity + UI
*/
function handleRadioChange(arg) {
// --- USER CLICKED A RADIO BUTTON (arg is a DOM element) ---
if (arg && typeof arg === "object" && "value" in arg) {
const currentActivity = arg.value;
// Save until modal confirms
window.pendingActivity = currentActivity;
// STOP/GAP: commit immediately (skip modal)
if (currentActivity === "stop" || currentActivity === "gap") {
handleRadioChange(currentActivity); // jump to commit phase
return;
}
// Update UI label
updateStatusLine(currentActivity || "—");
// Open the modal
const activityDurationModal = document.getElementById(
"activity-duration-modal",
);
if (
activityDurationModal &&
currentActivity !== "stop" &&
currentActivity !== "gap"
) {
activityDurationModal.showModal();
}
return; // Do NOT write a row yet
}
// --- MODAL CONFIRMED (arg is a string) ---
const currentActivity =
typeof arg === "string" ? arg : window.pendingActivity;
if (!currentActivity) {
console.warn("handleRadioChange: no activity to commit");
return;
}
const tableBody = document.getElementById("tableBody");
const lastRow = tableBody?.lastElementChild || null;
const currentTime = new Date();
console.log(
`[activity]: ${currentActivity} | [LAST ROW]:`,
lastRow
? lastRow.querySelector('[data-field="activity"] span').textContent
: "None",
);
// --- STOP CASE ---
if (currentActivity === "stop") {
if (typeof window.activityDurationAlarm_stop === "function")
window.activityDurationAlarm_stop();
if (lastRow) {
window.updateRow(lastRow, currentTime);
}
addRow(currentTime, undefined, "stop", undefined, "Stopped");
// Reset state + UI
window.pendingActivity = null;
updateStatusLine(null);
return;
}
// --- DOUBLE-CLICK PREVENTION ---
if (
lastRow &&
lastRow.querySelector('[data-field="activity"] span').textContent ===
currentActivity
) {
console.log("[DEBUG]: Double-click blocked.");
return;
}
// --- FIRST ROW EVER ---
if (!lastRow) {
console.log("[DEBUG]: First row of session.");
addRow(currentTime, undefined, currentActivity, undefined, "");
} else {
const lastActivity = lastRow.querySelector(
'[data-field="activity"] span',
).textContent;
console.log(`[DEBUG]: Last Activity was: "${lastActivity}"`);
// Seal previous row
window.updateRow(lastRow, currentTime);
// Convert stop → gap
if (lastActivity.toLowerCase().trim() === "stop") {
console.log("[DEBUG]: Transforming stop into gap.");
lastRow.querySelector('[data-field="activity"] span').textContent = "gap";
window.updateRow(lastRow, currentTime);
addRow(currentTime, undefined, currentActivity, undefined, "");
} else {
addRow(currentTime, undefined, currentActivity, undefined, "");
}
}
// --- RESET STATE + UI ---
window.pendingActivity = null;
updateStatusLine(null);
console.log("[STATE]: Row added successfully.");
}
window.updateRow = function (row, eTime, manualDuration) {
if (!row) return;
const endSpan = row.querySelector('[data-field="end"] span');
const durSpan = row.querySelector('[data-field="duration"] span');
if (eTime) {
endSpan.textContent =
eTime instanceof Date ? eTime.toLocaleTimeString() : eTime;
}
if (!manualDuration) {
const startStr = row.querySelector('[data-field="start"] span').textContent;
const sDate = parseTimeString(startStr);
const eDate = parseTimeString(endSpan.textContent);
if (sDate && eDate)
durSpan.textContent = formatDuration(timeDifference(sDate, eDate));
} else {
durSpan.textContent = formatDuration(manualDuration);
}
updateRunningTotals();
saveToLocalStorage();
};
// Instead of deleteRow(rowId), use the element itself:
function deleteRow(buttonElement) {
const row = buttonElement.closest("tr");
row.remove();
updateRunningTotals();
saveToLocalStorage();
}
function addRow(startTime, endTime, actionDone, formattedDuration, note) {
const tableBody = document.getElementById("tableBody");
const newRow = tableBody.insertRow();
const createCell = (fieldName, content) => {
const cell = newRow.insertCell();
cell.dataset.field = fieldName;
const span = document.createElement("span");
span.textContent = content;
cell.appendChild(span);
return span;
};
createCell(
"start",
startTime instanceof Date ? startTime.toLocaleTimeString() : startTime,
);
createCell(
"end",
endTime instanceof Date ? endTime.toLocaleTimeString() : endTime || "",
);
createCell("activity", actionDone);
createCell("duration", formattedDuration || "");
createCell("note", note);
// LOGIC: Use the btn-delete class for the delegation listener to catch
const actionCell = newRow.insertCell();
actionCell.dataset.field = "actions";
// Cleaned-up button inside addRow
actionCell.innerHTML = `
<button class="btn-delete" title="Delete Entry" style="background:none; border:none; cursor:pointer;">
<svg xmlns="http://www.w3.org" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a55b5b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
</button>
`;
saveToLocalStorage();
return newRow;
}
function timeDifference(startTime, endTime) {
// Midnight rollover fix
if (endTime < startTime) {
endTime = new Date(endTime.getTime() + 24 * 3600 * 1000);
}
const diffMs = endTime - startTime;
const totalSecs = Math.floor(diffMs / 1000);
return {
hours: Math.floor(totalSecs / 3600),
minutes: Math.floor((totalSecs % 3600) / 60),
seconds: totalSecs % 60,
};
}
function formatDuration(obj) {
let p = [];
if (obj.hours > 0) p.push(`${obj.hours}h`);
if (obj.minutes > 0) p.push(`${obj.minutes}m`);
if (obj.seconds > 0 || p.length === 0) p.push(`${obj.seconds}s`);
return p.join(" ");
}
function saveToLocalStorage() {
const rows = [];
document.querySelectorAll("#tableBody tr").forEach((row) => {
rows.push({
start: row.querySelector('[data-field="start"] span').textContent,
end: row.querySelector('[data-field="end"] span').textContent,
activity: row.querySelector('[data-field="activity"] span').textContent,
duration: row.querySelector('[data-field="duration"] span').textContent,
note: row.querySelector('[data-field="note"] span').textContent,
});
});
localStorage.setItem("beatADD_backup", JSON.stringify(rows));
}
function loadFromLocalStorage() {
const saved = localStorage.getItem("beatADD_backup");
if (!saved) return;
try {
JSON.parse(saved).forEach((d) => {
addRow(d.start, d.end, d.activity, d.duration, d.note);
});
updateRunningTotals();
} catch (e) {
console.warn("Corrupted localStorage detected. Resetting backup.");
localStorage.removeItem("beatADD_backup");
}
}
document.addEventListener("DOMContentLoaded", () => {
document.getElementById("caption-id").textContent =
`${new Date().toLocaleDateString()} - Tracking`;
// Initialize guarded DOM refs
modal = document.getElementById("activity-duration-modal");
// 1. Hydrate existing data
loadFromLocalStorage();
// 2. THE VETERAN LISTENER: One listener for the whole table
document.getElementById("tableBody").addEventListener("click", (e) => {
const deleteBtn = e.target.closest(".btn-delete");
if (deleteBtn) {
if (confirm("Delete this entry?")) {
deleteBtn.closest("tr").remove();
updateRunningTotals();
saveToLocalStorage();
}
return;
}
const span = e.target.closest(
"td[data-field]:not([data-field='actions']) span",
);
if (span) {
editRow(span);
}
});
const setBtn = document.getElementById("setUnlockBtn");
if (setBtn) {
setBtn.addEventListener("click", () => {
const alarmTimeInput = document.getElementById("alarmTime");
const minutes = alarmTimeInput ? parseInt(alarmTimeInput.value, 10) : 0;
if (!minutes || minutes <= 0) {
alert("Please enter minutes for this task.");
return;
}
// Advanced modal: we already captured the intent in window.pendingActivity
if (window.pendingActivity) {
// Commit the activity (this will seal the previous row and add a new one)
handleRadioChange(window.pendingActivity);
window.pendingActivity = null;
} else {
console.warn("Set clicked but no pending activity was stored.");
}
if (modal && typeof modal.close === "function") modal.close();
});
}
});
function clearSession() {
localStorage.removeItem("beatADD_backup");
const tbody = document.getElementById("tableBody");
if (tbody) tbody.innerHTML = "";
updateRunningTotals();
}