Repository navigation
Expand file tree
/
Copy pathidle.js
More file actions
690 lines (636 loc) · 28.8 KB
/
Copy pathidle.js
File metadata and controls
690 lines (636 loc) · 28.8 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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
// Idle detection: when user is inactive, offer to stop timer at last active time
(function(){
if (window.__ttIdleLoaded) return; window.__ttIdleLoaded = true;
function getIdleThresholdMs(){
const meta = document.querySelector('meta[name="idle-timeout-minutes"]');
const mins = meta ? parseInt(meta.getAttribute('content'), 10) : 30;
return (isNaN(mins) || mins < 1 ? 30 : Math.min(480, mins)) * 60 * 1000;
}
function getIdleUnansweredAction(){
const meta = document.querySelector('meta[name="idle-unanswered-action"]');
const v = meta ? (meta.getAttribute('content') || '').trim().toLowerCase() : 'review';
return v === 'auto_stop' ? 'auto_stop' : 'review';
}
const CHECK_INTERVAL_MS = 60 * 1000; // 1 minute
const GRACE_MS = 5 * 60 * 1000; // 5 minutes to answer "Still working?"
let lastActivity = Date.now();
let promptShown = false;
let graceTimerId = null;
let countdownIntervalId = null;
let lastHeartbeatSent = 0;
let hasActiveTimer = false;
let notificationPermissionRequested = false;
let pushEnsureAttempted = false;
let activeIdleNotification = null;
const HEARTBEAT_THROTTLE_MS = 60 * 1000;
function sendHeartbeat(){
if (!hasActiveTimer) return;
const now = Date.now();
if (now - lastHeartbeatSent < HEARTBEAT_THROTTLE_MS) return;
lastHeartbeatSent = now;
try {
fetch('/api/timer/heartbeat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
keepalive: true,
__ttQuiet: true,
}).catch(function(){});
} catch(e) {}
}
/** Ask for Notification permission once a timer is running so idle alerts
* can surface when the TimeTracker tab is not focused (Issue #722). */
function requestNotificationPermission(){
if (notificationPermissionRequested) return;
if (typeof Notification === 'undefined') return;
if (Notification.permission !== 'default') {
notificationPermissionRequested = true;
return;
}
notificationPermissionRequested = true;
try {
Notification.requestPermission().then(function(permission){
if (permission === 'granted' && window.__ttEnsurePushSubscription) {
try { window.__ttEnsurePushSubscription(); } catch(e) {}
}
}).catch(function(){});
} catch(e) {}
}
function closeIdleNotification(){
try {
if (activeIdleNotification) {
activeIdleNotification.close();
activeIdleNotification = null;
}
} catch(e) {
activeIdleNotification = null;
}
}
function markActive(){
// While the "Still working?" grace prompt is open, only Yes/No (or the
// 5-minute auto-stop) may clear it — incidental mouse/keyboard activity
// must not silently dismiss or re-arm the timer.
if (promptShown) return;
lastActivity = Date.now();
sendHeartbeat();
}
['mousemove','keydown','scroll','click','touchstart','visibilitychange'].forEach(evt =>
document.addEventListener(evt, markActive, { passive: true })
);
async function getTimer(){
try {
const r = await fetch('/api/timer/status', { __ttQuiet: true });
if (!r.ok) return null; const j = await r.json();
return j && j.active ? j.timer : null;
} catch(e){ return null; }
}
function formatTime(d){
if (window.formatUserTime) return window.formatUserTime(d);
var hour12 = window.userPrefs && window.userPrefs.timeFormat === '12h';
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: hour12 });
}
function formatCountdown(ms){
const totalSec = Math.max(0, Math.ceil(ms / 1000));
const m = Math.floor(totalSec / 60);
const s = totalSec % 60;
return m + ':' + String(s).padStart(2, '0');
}
function clearGraceTimers(){
if (graceTimerId) { clearTimeout(graceTimerId); graceTimerId = null; }
if (countdownIntervalId) { clearInterval(countdownIntervalId); countdownIntervalId = null; }
}
async function refreshTimerUiAfterStop(){
try {
if (window.floatingTimerBar && typeof window.floatingTimerBar.fetchStatus === 'function') {
await window.floatingTimerBar.fetchStatus();
}
document.dispatchEvent(new CustomEvent('tt:timer-status-changed'));
} catch(e) {}
}
// ---------------------------------------------------------------------------
// Answers go through ONE idempotent endpoint for every client (Issue #722):
// the first device to answer wins; the server reports already_resolved for
// stale answers so this client just dismisses instead of acting on old state.
// ---------------------------------------------------------------------------
let currentIdleToken = null;
// Set when this tab answered so the idle_prompt_resolved socket handler
// can skip the duplicate "stopped due to inactivity" toast.
let localAnswerPending = false;
async function respondIdle(answer){
clearGraceTimers();
closeIdleNotification();
promptShown = false;
try { const el = document.querySelector('[data-tt-idle-prompt]'); if (el) el.remove(); } catch(e) {}
const token = currentIdleToken;
currentIdleToken = null;
localAnswerPending = true;
try {
const r = await fetch('/api/timer/idle-response', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ answer: answer, notified_at: token }),
__ttQuiet: true,
});
if (r.ok){
const j = await r.json().catch(function(){ return {}; });
if (!j.already_resolved){
const msg = j && j.stopped
? (window.i18n?.messages?.timerStopped || 'Timer stopped')
: (window.i18n?.messages?.stillWorkingYes || 'Great — timer continues');
if (window.toastManager && window.toastManager.success) {
window.toastManager.success(msg, '', 5000);
}
}
await refreshTimerUiAfterStop();
}
} catch(e) {}
// Clear after a short window so a late socket event from our own answer
// is suppressed, but a later remote/server stop can still toast.
setTimeout(function(){ localAnswerPending = false; }, 3000);
lastActivity = Date.now();
}
function showUnansweredNotice(){
const msg = window.i18n?.messages?.idleUnanswered ||
'No answer received — the server will flag or stop this timer at its next check.';
if (window.toastManager && window.toastManager.info) {
window.toastManager.info(msg, '', 6000);
}
}
// ---------------------------------------------------------------------------
// Needs-review banner: idle grace expired unanswered. The timer keeps running
// on the server (idle_flagged_at); the user resolves it explicitly.
// ---------------------------------------------------------------------------
let reviewShownForTimerId = null;
let reviewBannerOpen = false;
async function resolveIdleReview(action){
try {
const r = await fetch('/api/timer/review', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: action }),
__ttQuiet: true,
});
if (r.ok){
const j = await r.json().catch(function(){ return {}; });
const msg = j && j.stopped
? (window.i18n?.messages?.timerStopped || 'Timer stopped')
: (window.i18n?.messages?.stillWorkingYes || 'Great — timer continues');
if (window.toastManager && window.toastManager.success) window.toastManager.success(msg, '', 5000);
await refreshTimerUiAfterStop();
}
} catch(e) {}
}
function showNeedsReviewBanner(){
if (reviewBannerOpen || promptShown) return;
reviewBannerOpen = true;
const trimLabel = window.i18n?.messages?.stillWorkingTrim || 'Trim idle time';
const stopLabel = window.i18n?.messages?.timerStopped || 'Stop timer now';
const contLabel = window.i18n?.messages?.stillWorkingYes || 'I am still working';
const msg = escapeHtml(
window.i18n?.messages?.idleNeedsReview ||
'We could not reach you while you were idle. Your timer kept running — trim it back to your last activity, stop it now, or keep working.'
);
buildReminderToast('blue', msg, [
{ label: trimLabel, style: 'primary', onClick: function(){ resolveIdleReview('trim'); } },
{ label: stopLabel, style: 'secondary', onClick: function(){ resolveIdleReview('keep'); } },
{ label: contLabel, style: 'link', onClick: function(){ resolveIdleReview('continue'); } }
], 0, function(){ reviewBannerOpen = false; });
}
function showNativeIdleNotification(stopTs, onStillWorking){
if (typeof Notification === 'undefined') return;
if (Notification.permission !== 'granted') return;
closeIdleNotification();
try {
const title = window.i18n?.messages?.stillWorkingTitle || 'Still working?';
const autoStop = getIdleUnansweredAction() === 'auto_stop';
const body = window.i18n?.messages?.stillWorkingPrompt ||
(autoStop
? ('You seem inactive since ' + formatTime(new Date(stopTs)) +
'. Click to confirm you are still working, or the timer will be stopped and the idle time kept.')
: ('You seem inactive since ' + formatTime(new Date(stopTs)) +
'. Click to confirm you are still working, or the timer will be flagged for review.'));
const n = new Notification(title, {
body: body,
tag: 'tt-still-working',
requireInteraction: true,
renotify: true,
});
activeIdleNotification = n;
n.onclick = function(ev){
try { if (ev && ev.preventDefault) ev.preventDefault(); } catch(e) {}
try { window.focus(); } catch(e) {}
closeIdleNotification();
if (typeof onStillWorking === 'function') onStillWorking();
};
n.onclose = function(){
if (activeIdleNotification === n) activeIdleNotification = null;
};
} catch(e) {}
}
function showIdlePrompt(stopTs, notifiedAt){
if (promptShown) return; promptShown = true;
currentIdleToken = notifiedAt || null;
clearGraceTimers();
const yesLabel = window.i18n?.messages?.stillWorkingYes || 'Yes, still working';
const noLabel = window.i18n?.messages?.stillWorkingNo || 'No, stop timer';
const trimLabel = window.i18n?.messages?.stillWorkingTrim || 'Keep until idle';
const autoStop = getIdleUnansweredAction() === 'auto_stop';
const baseMsg = window.i18n?.messages?.stillWorkingPrompt ||
(autoStop
? ('Still working? You seem inactive since ' + formatTime(new Date(stopTs)) +
'. If you do not answer, the timer will be stopped and the idle time kept.')
: ('Still working? You seem inactive since ' + formatTime(new Date(stopTs)) +
'. If you do not answer, the timer keeps running and is flagged for review.'));
const deadline = Date.now() + GRACE_MS;
function buildMessage(){
return baseMsg + ' (' + formatCountdown(deadline - Date.now()) + ')';
}
function attachHandlers(toastEl, countdownEl){
const yesBtn = toastEl.querySelector('[data-act="yes"]');
const noBtn = toastEl.querySelector('[data-act="no"]');
const trimBtn = toastEl.querySelector('[data-act="trim"]');
if (yesBtn) yesBtn.addEventListener('click', function(){ respondIdle('yes'); });
if (noBtn) noBtn.addEventListener('click', function(){ respondIdle('stop'); });
if (trimBtn) trimBtn.addEventListener('click', function(){ respondIdle('trim'); });
countdownIntervalId = setInterval(function(){
if (countdownEl) countdownEl.textContent = buildMessage();
}, 1000);
graceTimerId = setTimeout(function(){
clearGraceTimers();
closeIdleNotification();
promptShown = false;
currentIdleToken = null;
try { toastEl.remove(); } catch(e){}
if (autoStop) {
// Unanswered: the SERVER sweep stops the timer (credited to last
// activity + idle window). Never stop locally — another device may
// have answered already (Issue #722).
showUnansweredNotice();
} else {
// Review mode: the server flags the timer (idle_flagged_at) at its
// next check; show the banner now so the user can resolve early.
showNeedsReviewBanner(null);
}
}, GRACE_MS);
}
// Native OS notification so the prompt is visible from other tabs (#722)
showNativeIdleNotification(stopTs, function(){
respondIdle('yes');
});
if (window.toastManager) {
const toastEl = document.createElement('div');
toastEl.setAttribute('data-tt-idle-prompt', '1');
toastEl.className = 'flex items-center gap-3 p-4 bg-amber-100 dark:bg-amber-900/30 border border-amber-300 dark:border-amber-700 rounded-lg shadow-lg pointer-events-auto';
toastEl.innerHTML =
'<div class="flex-1 text-sm text-amber-900 dark:text-amber-100" data-countdown>' + buildMessage() + '</div>' +
'<div class="flex gap-2 flex-wrap justify-end">' +
'<button class="px-3 py-1.5 bg-amber-600 hover:bg-amber-700 text-white rounded text-sm font-medium" data-act="yes">' + yesLabel + '</button>' +
'<button class="px-3 py-1.5 bg-amber-200 dark:bg-amber-800 hover:bg-amber-300 dark:hover:bg-amber-700 text-amber-900 dark:text-amber-100 rounded text-sm font-medium" data-act="trim">' + trimLabel + '</button>' +
'<button class="px-3 py-1.5 bg-amber-200 dark:bg-amber-800 hover:bg-amber-300 dark:hover:bg-amber-700 text-amber-900 dark:text-amber-100 rounded text-sm font-medium" data-act="no">' + noLabel + '</button>' +
'</div>';
const container = document.getElementById('toast-notification-container') || document.getElementById('flash-messages-container') || document.body;
container.appendChild(toastEl);
attachHandlers(toastEl, toastEl.querySelector('[data-countdown]'));
return;
}
const t = document.createElement('div');
t.setAttribute('data-tt-idle-prompt', '1');
t.className = 'toast align-items-center text-white bg-warning border-0 fade show';
t.innerHTML =
'<div class="d-flex">' +
'<div class="toast-body" data-countdown>' + buildMessage() + '</div>' +
'<div class="d-flex gap-2 align-items-center me-2">' +
'<button class="btn btn-sm btn-light" data-act="yes">' + yesLabel + '</button>' +
'<button class="btn btn-sm btn-outline-light" data-act="trim">' + trimLabel + '</button>' +
'<button class="btn btn-sm btn-outline-light" data-act="no">' + noLabel + '</button>' +
'</div>' +
'</div>';
const container = document.getElementById('toast-container') || document.body;
container.appendChild(t);
attachHandlers(t, t.querySelector('[data-countdown]'));
}
let longEntryNudgeShown = false;
let lastLongEntryTimerId = null;
function getLongEntryThresholdMs(){
const meta = document.querySelector('meta[name="long-entry-threshold-hours"]');
const hours = meta ? parseFloat(meta.getAttribute('content'), 10) : 8;
return (isNaN(hours) || hours < 1 ? 8 : Math.min(24, hours)) * 60 * 60 * 1000;
}
async function checkLongRunningTimer(active){
if (!active || !active.start_time) return;
if (active.id !== lastLongEntryTimerId) {
lastLongEntryTimerId = active.id;
longEntryNudgeShown = false;
}
if (longEntryNudgeShown || activeReminderToast) return;
const started = (window.ttParseStart ? window.ttParseStart(active.start_time) : new Date(active.start_time).getTime());
if (isNaN(started)) return;
const runningMs = Date.now() - started;
if (runningMs < getLongEntryThresholdMs()) return;
longEntryNudgeShown = true;
const hours = (runningMs / (60 * 60 * 1000)).toFixed(1);
const msg = 'Your timer has been running for ' + hours + ' hours. Did you forget to stop it?';
buildReminderToast(
'amber',
escapeHtml(msg),
[
{
label: (window.i18n?.messages?.timerStopped || 'Stop timer'),
style: 'primary',
onClick: function(){ window.floatingTimerBar && window.floatingTimerBar.stopTimer(); }
},
{
label: (window.i18n?.messages?.dismiss || 'Dismiss'),
style: 'link',
onClick: function(){ longEntryNudgeShown = true; }
}
],
0
);
}
async function tick(){
// Skip status polling while the tab is hidden to avoid burning rate-limit
// budget when the user is idle on another tab (Issue #767). Heartbeats still
// fire from markActive() / sendHeartbeat() when the user returns.
if (document.hidden) return;
const active = await getTimer();
hasActiveTimer = !!active;
if (!active) return;
requestNotificationPermission();
// Make sure a Web Push subscription exists while a timer runs so the server
// can reach us with "Still working?" even when this tab is closed/hidden.
if (!pushEnsureAttempted && typeof Notification !== 'undefined' && Notification.permission === 'granted') {
pushEnsureAttempted = true;
if (typeof window.__ttEnsurePushSubscription === 'function') {
try { window.__ttEnsurePushSubscription(); } catch(e) {}
}
}
// Heartbeat only while the user has been active within the idle window.
// Unconditional tick heartbeats would keep last_heartbeat_at fresh forever
// and the server would never arm idle_notified (Issue #722).
if (!promptShown && (Date.now() - lastActivity) < getIdleThresholdMs()) {
sendHeartbeat();
}
// Server flagged this timer for review (idle grace expired elsewhere): show banner.
if (active.needs_review){
if (reviewShownForTimerId !== active.id){
reviewShownForTimerId = active.id;
showNeedsReviewBanner();
}
} else if (reviewShownForTimerId === active.id) {
reviewShownForTimerId = null;
}
// Prompt ONLY on the server signal (idle_notified, armed by the sweep) so
// every device sees the same check and answers race on one token (#722).
if (active.idle_notified && !promptShown){
const notifiedTs = active.idle_notified_at
? new Date(active.idle_notified_at).getTime()
: (Date.now() - getIdleThresholdMs());
showIdlePrompt(isNaN(notifiedTs) ? Date.now() - getIdleThresholdMs() : notifiedTs, active.idle_notified_at);
}
try { await checkLongRunningTimer(active); } catch(e) {}
// Break reminder follows the active timer state; check on every tick.
try { checkBreakNudge(active); } catch(e) {}
}
// Prime active-timer flag soon after load so early activity can heartbeat.
setTimeout(function(){ tick(); }, 2000);
setInterval(tick, CHECK_INTERVAL_MS);
// ---------------------------------------------------------------------------
// Smart reminder toasts (no-timer nudge, break reminder, end-of-day reminder)
// ---------------------------------------------------------------------------
const REMINDER_POLL_MS = 5 * 60 * 1000; // 5 minutes
let noTimerNudgeShown = false;
let endOfDayNudgeShown = false;
let breakNudgeShown = false;
let activeReminderToast = null;
let lastTimerIdForBreak = null;
let lastNotificationsFetch = { at: 0, payload: null };
let lastResetDay = new Date().toDateString();
function resetReminderFlagsIfNewDay(){
const today = new Date().toDateString();
if (today !== lastResetDay){
lastResetDay = today;
noTimerNudgeShown = false;
endOfDayNudgeShown = false;
breakNudgeShown = false;
}
}
function todayIsoLocal(){
const d = new Date();
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return y + '-' + m + '-' + day;
}
async function fetchNotifications(forceRefresh){
const now = Date.now();
if (!forceRefresh && lastNotificationsFetch.payload && (now - lastNotificationsFetch.at) < REMINDER_POLL_MS){
return lastNotificationsFetch.payload;
}
try {
const r = await fetch('/api/notifications', {
headers: { 'Accept': 'application/json' },
__ttQuiet: true,
});
if (!r.ok) return null;
const j = await r.json();
lastNotificationsFetch = { at: now, payload: j };
return j;
} catch(e){ return null; }
}
function findNotification(payload, kind){
if (!payload || !Array.isArray(payload.notifications)) return null;
return payload.notifications.find(function(n){ return n && n.kind === kind; }) || null;
}
async function dismissNotification(kind, localDate){
try {
await fetch('/api/notifications/dismiss', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ kind: kind, local_date: localDate || todayIsoLocal() })
});
} catch(e) {}
}
function getToastContainer(){
return document.getElementById('toast-notification-container') ||
document.getElementById('flash-messages-container') || document.body;
}
// Pre-built class strings per color so Tailwind's content scan sees literal classes.
// The shape mirrors showIdlePrompt() exactly: just amber → blue/purple/green.
const TOAST_CLASSES = {
blue: {
wrap: 'flex items-center gap-3 p-4 bg-blue-100 dark:bg-blue-900/30 border border-blue-300 dark:border-blue-700 rounded-lg shadow-lg pointer-events-auto',
body: 'flex-1 text-sm text-blue-900 dark:text-blue-100',
primary: 'px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded text-sm font-medium',
secondary: 'px-3 py-1.5 bg-blue-200 dark:bg-blue-800 hover:bg-blue-300 dark:hover:bg-blue-700 text-blue-900 dark:text-blue-100 rounded text-sm font-medium',
link: 'px-3 py-1.5 text-blue-700 dark:text-blue-300 hover:underline text-sm'
},
purple: {
wrap: 'flex items-center gap-3 p-4 bg-purple-100 dark:bg-purple-900/30 border border-purple-300 dark:border-purple-700 rounded-lg shadow-lg pointer-events-auto',
body: 'flex-1 text-sm text-purple-900 dark:text-purple-100',
primary: 'px-3 py-1.5 bg-purple-600 hover:bg-purple-700 text-white rounded text-sm font-medium',
secondary: 'px-3 py-1.5 bg-purple-200 dark:bg-purple-800 hover:bg-purple-300 dark:hover:bg-purple-700 text-purple-900 dark:text-purple-100 rounded text-sm font-medium',
link: 'px-3 py-1.5 text-purple-700 dark:text-purple-300 hover:underline text-sm'
},
green: {
wrap: 'flex items-center gap-3 p-4 bg-green-100 dark:bg-green-900/30 border border-green-300 dark:border-green-700 rounded-lg shadow-lg pointer-events-auto',
body: 'flex-1 text-sm text-green-900 dark:text-green-100',
primary: 'px-3 py-1.5 bg-green-600 hover:bg-green-700 text-white rounded text-sm font-medium',
secondary: 'px-3 py-1.5 bg-green-200 dark:bg-green-800 hover:bg-green-300 dark:hover:bg-green-700 text-green-900 dark:text-green-100 rounded text-sm font-medium',
link: 'px-3 py-1.5 text-green-700 dark:text-green-300 hover:underline text-sm'
}
};
function buildReminderToast(colorKey, message, buttons, autoDismissMs, onClose){
const cls = TOAST_CLASSES[colorKey] || TOAST_CLASSES.blue;
const toastEl = document.createElement('div');
toastEl.className = cls.wrap;
let html = '<div class="' + cls.body + '">' + message + '</div>';
html += '<div class="flex gap-2">';
buttons.forEach(function(b, idx){
const klass = b.style === 'secondary' ? cls.secondary : (b.style === 'link' ? cls.link : cls.primary);
html += '<button class="' + klass + '" data-act="' + idx + '">' + b.label + '</button>';
});
html += '</div>';
toastEl.innerHTML = html;
function close(){
try { toastEl.remove(); } catch(e){}
if (activeReminderToast === toastEl) activeReminderToast = null;
if (typeof onClose === 'function') onClose();
}
buttons.forEach(function(b, idx){
const btn = toastEl.querySelector('[data-act="' + idx + '"]');
if (btn) btn.addEventListener('click', function(){
close();
try { if (typeof b.onClick === 'function') b.onClick(); } catch(e){}
});
});
getToastContainer().appendChild(toastEl);
activeReminderToast = toastEl;
if (autoDismissMs > 0){
setTimeout(function(){ if (document.body.contains(toastEl)) close(); }, autoDismissMs);
}
return toastEl;
}
function escapeHtml(s){
return String(s || '').replace(/[&<>"']/g, function(c){
return ({ '&':'&', '<':'<', '>':'>', '"':'"', "'":''' })[c];
});
}
async function checkNoTimerAndEndOfDayNudges(){
resetReminderFlagsIfNewDay();
if (noTimerNudgeShown && endOfDayNudgeShown) return;
if (activeReminderToast) return;
const payload = await fetchNotifications(false);
if (!payload) return;
// No-timer nudge
if (!noTimerNudgeShown && !activeReminderToast){
const note = findNotification(payload, 'no_tracking_today');
if (note){
noTimerNudgeShown = true;
const msg = escapeHtml(note.message || 'You have not tracked anything today.');
buildReminderToast(
'blue',
msg,
[
{ label: (window.i18n?.messages?.startTimer || 'Start timer'), style: 'primary', onClick: function(){ window.location.href = '/'; } },
{ label: (window.i18n?.messages?.dismiss || 'Dismiss'), style: 'link', onClick: function(){ dismissNotification('no_tracking_today'); } }
],
30000
);
}
}
// End-of-day reminder
if (!endOfDayNudgeShown && !activeReminderToast){
const note = findNotification(payload, 'end_of_day_reminder');
if (note){
endOfDayNudgeShown = true;
const msg = escapeHtml(note.message || "It's nearly end of day.");
buildReminderToast(
'green',
msg,
[
{ label: (window.i18n?.messages?.viewEntries || 'View entries'), style: 'primary', onClick: function(){ window.location.href = '/time-entries'; } },
{ label: (window.i18n?.messages?.dismiss || 'Dismiss'), style: 'link', onClick: function(){ dismissNotification('end_of_day_reminder'); } }
],
60000
);
}
}
}
async function checkBreakNudge(activeTimer){
resetReminderFlagsIfNewDay();
// Reset the per-timer flag whenever the active timer changes (new session = new reminders).
const tid = activeTimer && activeTimer.id;
if (tid !== lastTimerIdForBreak){
lastTimerIdForBreak = tid;
breakNudgeShown = false;
}
if (breakNudgeShown || activeReminderToast || !activeTimer) return;
const payload = await fetchNotifications(false);
if (!payload) return;
const note = findNotification(payload, 'break_reminder');
if (!note) return;
breakNudgeShown = true;
const msg = escapeHtml(note.message || 'Time for a break.');
buildReminderToast(
'purple',
msg,
[
{
label: (window.i18n?.messages?.pauseTimer || 'Pause timer'),
style: 'primary',
onClick: async function(){
try {
const csrf = (document.querySelector('meta[name="csrf-token"]') || {}).content || '';
const res = await fetch('/timer/pause', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRFToken': csrf,
'Accept': 'application/json',
},
body: 'csrf_token=' + encodeURIComponent(csrf),
credentials: 'same-origin',
});
if (!res.ok) return;
await refreshTimerUiAfterStop();
} catch(e){}
}
},
{
label: (window.i18n?.messages?.snooze15 || 'Snooze 15 min'),
style: 'secondary',
onClick: function(){
// Client-side snooze: keep the per-timer flag set for 15 minutes so the
// server-emitted notification is suppressed locally, then re-arm.
breakNudgeShown = true;
setTimeout(function(){ breakNudgeShown = false; }, 15 * 60 * 1000);
}
},
{ label: (window.i18n?.messages?.dismiss || 'Dismiss'), style: 'link', onClick: function(){ dismissNotification('break_reminder'); } }
],
45000
);
}
setInterval(checkNoTimerAndEndOfDayNudges, REMINDER_POLL_MS);
setTimeout(checkNoTimerAndEndOfDayNudges, 5000);
// Allow Socket.IO / other modules to trigger the same prompt (Issue #722)
window.__ttShowIdlePrompt = function(stopTs, notifiedAt){
showIdlePrompt(stopTs || (Date.now() - getIdleThresholdMs()), notifiedAt);
};
window.__ttShowNeedsReview = function(){
showNeedsReviewBanner();
};
window.__ttDismissIdlePrompt = function(){
clearGraceTimers();
closeIdleNotification();
promptShown = false;
currentIdleToken = null;
try { const el = document.querySelector('[data-tt-idle-prompt]'); if (el) el.remove(); } catch(e) {}
};
// True when this tab just answered the idle prompt (suppress duplicate toast).
window.__ttIdleLocalAnswerPending = function(){ return localAnswerPending; };
window.__ttOnIdleAutoStop = function(){
window.__ttDismissIdlePrompt();
refreshTimerUiAfterStop();
};
})();