-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
789 lines (721 loc) · 29.3 KB
/
Copy pathbackground.js
File metadata and controls
789 lines (721 loc) · 29.3 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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
// Service worker: the single owner of timer state. MV3 may kill this worker
// at any time, so state lives in chrome.storage.local and the phase change
// fires from a chrome.alarm — never from setTimeout.
import {
DEFAULT_SETTINGS,
MODES,
PHASE_LABEL,
defaultState,
elapsedMs,
nextPhase,
normalizeState,
overtimeMs,
phaseDurationMs,
phaseTotalMs,
remainingMs,
todayKey,
WORK_PHASES,
} from './core/timer.js';
import { appendEntry, clearLabel, entryId, removeEntry, renameLabel } from './core/log.js';
import { formatHours, parseKey } from './core/stats.js';
import { blockingActive, buildRules, matchesHosts, parseBlockList } from './core/block.js';
const ALARM_PHASE_END = 'phase-end';
const ALARM_BADGE_TICK = 'badge-tick';
const ALARM_PRE_WARN = 'pre-warn'; // soft tick 30s before a break ends
const ALARM_NAG = 'nag'; // one gentle reminder when a finished phase sits idle
const PHASE_COLOR = {
focus: '#E25C3F',
shortBreak: '#A8BD8F',
longBreak: '#93AFC0',
timer: '#E25C3F',
stopwatch: '#E25C3F',
};
async function getState() {
const { state } = await chrome.storage.local.get('state');
if (!state) return defaultState();
// Merge settings so new defaults appear after extension updates.
state.settings = { ...DEFAULT_SETTINGS, ...state.settings };
return normalizeState(state);
}
async function setState(state) {
await chrome.storage.local.set({ state });
await updateBadge(state);
await syncBlocking(state);
return state;
}
chrome.runtime.onInstalled.addListener(async (details) => {
await setState(await getState());
buildMenus();
await migrateLog();
await adoptSyncedSettings();
// First run: the full page doubles as the welcome tour.
if (details.reason === 'install') openApp('#welcome');
});
chrome.runtime.onStartup.addListener(async () => {
await adoptSyncedSettings();
const state = await getState();
// If Chrome was closed past the end of a running phase, complete it now.
// (A running stopwatch has no end — its endsAt is the virtual start.)
if (state.status === 'running' && state.mode !== 'stopwatch' && !state.overtime && state.endsAt <= Date.now()) {
await completePhase(state);
} else {
await updateBadge(state);
}
});
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
const actions = {
start,
pause,
reset,
skip,
finishOvertime,
extend: (s) => extend(s, msg.minutes),
setMode: (s) => setMode(s, msg.mode),
setLabel: (s) => setLabel(s, msg.label),
updateSettings: (s) => updateSettings(s, msg.settings),
logDelete: (s) => logDelete(s, msg.id),
logAdd: (s) => logAdd(s, msg.entry),
labelRename: (s) => labelRename(s, msg.from, msg.to),
labelClear: (s) => labelClear(s, msg.label),
importData: (s) => importData(s, msg.data),
};
const action = actions[msg.type];
if (!action) return false;
getState()
.then((state) => action(state))
.then((state) => sendResponse(state ?? null))
.catch(() => sendResponse(null)); // never leave the channel hanging
return true; // keep the message channel open for the async response
});
chrome.alarms.onAlarm.addListener(async (alarm) => {
const state = await getState();
if (alarm.name === ALARM_PHASE_END) {
if (state.status === 'running' && !state.overtime) await completePhase(state);
} else if (alarm.name === ALARM_BADGE_TICK) {
if (state.status === 'running') await updateBadge(state);
else await chrome.alarms.clear(ALARM_BADGE_TICK);
} else if (alarm.name === ALARM_PRE_WARN) {
const onBreak = state.phase === 'shortBreak' || state.phase === 'longBreak';
if (state.status === 'running' && onBreak && state.settings.sound) {
await sendSound({ type: 'warn', volume: state.settings.volume });
}
} else if (alarm.name === ALARM_NAG) {
if (state.status === 'idle' && state.mode === 'pomodoro' && state.settings.notifications) {
notify(['ember-nag', 'start'], {
title: 'Still there?',
message:
state.phase === 'focus'
? 'Your break is over — ready to focus?'
: `Your ${PHASE_LABEL[state.phase]} is waiting.`,
buttons: [{ title: state.phase === 'focus' ? 'Start focus' : 'Start break' }],
});
}
}
});
/* ---------- global shortcuts, toolbar menu, side panel entry ---------- */
chrome.commands.onCommand.addListener(async (command) => {
const state = await getState();
if (command === 'toggle-timer') {
await (state.status === 'running' ? pause(state) : start(state));
} else if (command === 'skip-phase') {
await skip(state);
} else if (command === 'open-app') {
openApp();
}
});
function buildMenus() {
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({ id: 'toggle', title: 'Start / pause', contexts: ['action'] });
chrome.contextMenus.create({ id: 'skip', title: 'Skip phase', contexts: ['action'] });
chrome.contextMenus.create({ id: 'open-app', title: 'Open full timer', contexts: ['action'] });
chrome.contextMenus.create({ id: 'open-stats', title: 'Open stats', contexts: ['action'] });
// Select a task's text anywhere — an email, a ticket, a doc — and turn
// it into a labeled focus session in two clicks. Chrome fills the %s.
chrome.contextMenus.create({
id: 'focus-selection',
title: 'Start focus on “%s”',
contexts: ['selection'],
});
});
}
chrome.contextMenus.onClicked.addListener(async (info) => {
const state = await getState();
if (info.menuItemId === 'toggle') await (state.status === 'running' ? pause(state) : start(state));
else if (info.menuItemId === 'skip') await skip(state);
else if (info.menuItemId === 'open-app') openApp();
else if (info.menuItemId === 'open-stats') openApp('#stats');
else if (info.menuItemId === 'focus-selection') await startLabeledFocus(state, info.selectionText);
});
// "Focus on this": the selection becomes the session label and focus starts
// now. A running break is cut short (its minutes were never work, nothing is
// lost); a running focus simply adopts the new label and keeps burning.
async function startLabeledFocus(state, text) {
const label = String(text ?? '').replace(/\s+/g, ' ').trim().slice(0, 60);
if (!label) return state;
if (state.mode !== 'pomodoro') state = await setMode(state, 'pomodoro');
if (state.phase !== 'focus') state = await skip(state);
state.label = label;
state.labelDay = todayKey();
if (state.status === 'running') return setState(state);
return start(state);
}
function openApp(hash = '') {
chrome.tabs.create({ url: chrome.runtime.getURL('app.html') + hash });
}
/* ---------- notifications: ids carry their buttons' actions ---------- */
// The worker may be long dead when a button is clicked, so the notification
// id encodes what each button does: 'tag|action0|action1'.
function notify([tag, ...actions], { title, message, buttons = [] }) {
chrome.notifications.create([tag, ...actions].join('|'), {
type: 'basic',
iconUrl: 'icons/icon128.png',
title,
message,
buttons,
silent: true, // we play our own chime
});
}
chrome.notifications.onButtonClicked.addListener(async (id, index) => {
const action = id.split('|')[index + 1];
if (!action) return;
const state = await getState();
if (action === 'start') await start(state);
else if (action === 'finishOvertime') await finishOvertime(state);
else if (action.startsWith('snooze:')) await snoozeBreak(state, action.slice(7));
chrome.notifications.clear(id);
});
chrome.notifications.onClicked.addListener((id) => {
if (!id.startsWith('ember-')) return;
openApp();
chrome.notifications.clear(id);
});
/* ---------- machine lock: don't bank time nobody worked ---------- */
chrome.idle.onStateChanged.addListener(async (idleState) => {
const state = await getState();
if (idleState === 'locked') {
if (!state.settings.pauseOnLock || state.status !== 'running') return;
if (!WORK_PHASES.includes(state.phase)) return; // a break can run unattended
if (state.overtime) {
await finishOvertime(state); // walking away ends the overtime stretch
return;
}
state.autoPausedAt = Date.now();
await pause(state);
} else if (idleState === 'active') {
// Back from a lock that auto-paused: a nudge beats silent confusion.
if (state.status === 'paused' && state.autoPausedAt && state.settings.notifications) {
notify(['ember-resume', 'start'], {
title: 'Paused while you were away',
message: `Your ${PHASE_LABEL[state.phase]} is on hold — resume when ready.`,
buttons: [{ title: 'Resume' }],
});
}
}
});
/* ---------- timer actions ---------- */
async function start(state) {
if (state.status === 'running') return state;
// A fresh run (not a resume) marks its start for the session log.
if (state.status === 'idle') state.startedAt = Date.now();
state.status = 'running';
state.autoPausedAt = null;
await chrome.alarms.clear(ALARM_NAG);
if (state.mode === 'stopwatch') {
// Counting up: no end alarm; endsAt is the virtual start.
state.endsAt = Date.now() - state.remainingMs;
} else {
state.endsAt = Date.now() + state.remainingMs;
await armPhaseEnd(state);
}
await chrome.alarms.create(ALARM_BADGE_TICK, { periodInMinutes: 1 });
await syncAmbient(state);
return setState(state);
}
// The end alarm, plus the optional warning tick shortly before a break ends.
async function armPhaseEnd(state) {
await chrome.alarms.create(ALARM_PHASE_END, { when: state.endsAt });
const onBreak = state.phase === 'shortBreak' || state.phase === 'longBreak';
if (onBreak && state.settings.breakEndWarn && state.settings.sound && state.endsAt - 30_000 > Date.now()) {
await chrome.alarms.create(ALARM_PRE_WARN, { when: state.endsAt - 30_000 });
}
}
async function pause(state) {
if (state.status !== 'running') return state;
if (state.overtime) return finishOvertime(state); // overtime ends, never pauses
state.remainingMs = state.mode === 'stopwatch' ? elapsedMs(state) : remainingMs(state);
state.status = 'paused';
state.endsAt = null;
await clearAlarms();
await syncAmbient(state);
return setState(state);
}
// User reset abandons the run — bank its partial work before tearing down.
async function reset(state) {
await creditAbandoned(state);
return resetCore(state);
}
async function resetCore(state) {
state.status = 'idle';
state.endsAt = null;
state.remainingMs =
state.mode === 'stopwatch' ? 0 : phaseDurationMs(state.phase, state.settings);
state.extendedMs = 0;
state.startedAt = null;
state.overtime = false;
state.autoPausedAt = null;
await clearAlarms();
await syncAmbient(state);
return setState(state);
}
// Switching mode abandons the current run but keeps pomodoro cycle progress
// for when the user switches back.
async function setMode(state, mode) {
if (!MODES.includes(mode) || state.mode === mode) return state;
await creditAbandoned(state); // bank work before the run is replaced
state.mode = mode;
state.phase = mode === 'pomodoro' ? 'focus' : mode;
return resetCore(state); // clears alarms and adopts the mode's duration
}
// Stretch the running phase only — the saved durations are untouched.
async function extend(state, minutes) {
if (state.status !== 'running' || state.overtime || !(minutes > 0)) return state;
const ms = minutes * 60_000;
state.extendedMs = (state.extendedMs ?? 0) + ms;
state.endsAt += ms;
await armPhaseEnd(state);
return setState(state);
}
async function clearAlarms() {
await chrome.alarms.clear(ALARM_PHASE_END);
await chrome.alarms.clear(ALARM_BADGE_TICK);
await chrome.alarms.clear(ALARM_PRE_WARN);
await chrome.alarms.clear(ALARM_NAG);
}
// Skip moves to the next phase without crediting a completed session —
// though minutes already worked still count. Only the pomodoro cycle has a
// next phase to skip to.
async function skip(state) {
if (state.mode !== 'pomodoro') return state;
await creditAbandoned(state);
return advance(state, { credit: false });
}
async function completePhase(state) {
// Fired long past the end (sleep without a lock, Chrome closed): the phase
// still completes, but nothing should chain after it — nobody is there.
const overdue = Date.now() - state.endsAt > 5 * 60_000;
// Overtime: the phase is done, but the clock keeps running up from zero
// until the user ends it — banked all together then.
if (state.settings.overtime && !overdue && (state.phase === 'focus' || state.mode === 'timer')) {
state.overtime = true;
if (state.settings.notifications) {
notify(['ember-overtime', 'finishOvertime'], {
title: state.phase === 'focus' ? 'Focus session complete' : 'Timer finished',
message: 'Counting overtime — end it when you reach a stopping point.',
buttons: [{ title: state.phase === 'focus' ? 'Take a break now' : 'Done' }],
});
}
if (state.settings.sound) await playChime(state);
return setState(state);
}
if (state.settings.notifications) notifyPhaseEnd(state);
if (state.settings.sound) await playChime(state);
// A one-shot timer just rearms itself — but the finished countdown still
// counts as time worked (no session: those are pomodoro currency).
if (state.mode === 'timer') {
await recordWork(state, Math.round(phaseTotalMs(state) / 60_000), {
when: state.endsAt,
completed: true,
});
return resetCore(state);
}
return advance(state, { credit: true, autostart: !overdue });
}
// Ends an overtime stretch: the extra minutes fold into the phase as one
// big extension, then the cycle moves on normally.
async function finishOvertime(state) {
if (!state.overtime || state.status !== 'running') return state;
state.extendedMs = (state.extendedMs ?? 0) + overtimeMs(state);
state.overtime = false;
state.endsAt = Date.now();
if (state.mode === 'timer') {
await recordWork(state, Math.round(phaseTotalMs(state) / 60_000), {
when: state.endsAt,
completed: true,
});
return resetCore(state);
}
return advance(state, { credit: true });
}
// "5 more break minutes" from a break-end notification: steps back onto the
// just-ended break for a short encore. Only valid while the following focus
// phase sits unstarted.
async function snoozeBreak(state, phase) {
if (state.mode !== 'pomodoro' || state.status !== 'idle' || state.phase !== 'focus') return state;
if (phase !== 'shortBreak' && phase !== 'longBreak') return state;
state.phase = phase;
state.remainingMs = 5 * 60_000;
state.extendedMs = 0;
return start(state);
}
async function advance(state, { credit, autostart = true }) {
await clearAlarms(); // start() re-creates them if the next phase auto-starts
const endedPhase = state.phase;
const next = nextPhase(state);
if (endedPhase === 'focus' && credit) {
state.cyclePos += 1;
// Credit what was actually worked, including any "+5 min" extensions —
// dated by when the phase ended, in case an overdue completion is being
// processed after a Chrome restart (possibly days later).
await recordWork(state, Math.round(phaseTotalMs(state) / 60_000), {
sessions: 1,
when: state.endsAt ?? Date.now(),
completed: true,
});
}
if (endedPhase === 'longBreak') state.cyclePos = 0;
state.phase = next;
state.remainingMs = phaseDurationMs(next, state.settings);
state.extendedMs = 0;
state.endsAt = null;
state.status = 'idle';
state.startedAt = null;
state.overtime = false;
state.autoPausedAt = null;
const auto =
(next === 'focus' ? state.settings.autoStartFocus : state.settings.autoStartBreaks) &&
credit &&
autostart;
if (auto) return start(state);
// Focus doesn't auto-start by default, and a missed notification means the
// cycle silently stalls — so one (and only one) reminder follows.
if (state.mode === 'pomodoro' && state.settings.notifications && credit && autostart) {
await chrome.alarms.create(ALARM_NAG, { delayInMinutes: 3 });
}
await syncAmbient(state);
return setState(state);
}
async function updateSettings(state, settings) {
state.settings = { ...state.settings, ...settings };
state.settingsAt = Date.now();
// If the current phase hasn't started, adopt its new duration.
if (state.status === 'idle') {
state.remainingMs = phaseDurationMs(state.phase, state.settings);
state.extendedMs = 0;
}
// Settings follow the user across machines; stats stay local.
chrome.storage.sync
.set({ settings: state.settings, settingsAt: state.settingsAt })
.catch(() => {});
await syncAmbient(state);
return setState(state);
}
// Pull settings saved by another machine (or a fresh install on this one).
// Last write wins, decided by the settingsAt stamp.
async function adoptSyncedSettings() {
try {
const { settings, settingsAt } = await chrome.storage.sync.get(['settings', 'settingsAt']);
if (!settings || !settingsAt) return;
const state = await getState();
if ((state.settingsAt ?? 0) >= settingsAt) return;
state.settings = { ...DEFAULT_SETTINGS, ...settings };
state.settingsAt = settingsAt;
if (state.status === 'idle') {
state.remainingMs = phaseDurationMs(state.phase, state.settings);
state.extendedMs = 0;
}
await syncAmbient(state);
await setState(state);
} catch {
// Sync unavailable (e.g. not signed in) — purely local is fine.
}
}
chrome.storage.onChanged.addListener((changes, area) => {
if (area === 'sync' && changes.settings) adoptSyncedSettings();
});
/* ---------- site blocking: DNR rules track the timer ---------- */
// Every state write lands here (via setState), so the blocklist rules can
// never drift from what the timer is doing. Host access is optional — granted
// the first time the user flips the toggle — so everything is guarded:
// without the grant this is a no-op, and a blocking failure must never break
// a phase transition.
async function syncBlocking(state) {
if (!chrome.declarativeNetRequest) return;
try {
const granted = await chrome.permissions.contains({ origins: ['<all_urls>'] });
if (!granted) return;
const hosts = blockingActive(state, WORK_PHASES) ? parseBlockList(state.settings.blockList) : [];
const existing = await chrome.declarativeNetRequest.getDynamicRules();
// setState runs on every action — skip the churn when nothing changed.
const had = existing.map((r) => r.condition.requestDomains?.[0]).sort();
if (had.length === hosts.length && [...hosts].sort().every((h, i) => h === had[i])) return;
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: existing.map((r) => r.id),
addRules: buildRules(hosts, chrome.runtime.getURL('blocked.html')),
});
// Rules only stop new page loads — a distraction already open in some
// tab stays put. Walk it to the blocked page too, with its URL so the
// page can offer the way back once the block lifts.
if (hosts.length) await sweepOpenTabs(hosts);
} catch {
// Permission revoked mid-flight, rule quota, transient API failure —
// the timer matters more than the blocklist.
}
}
async function sweepOpenTabs(hosts) {
const tabs = await chrome.tabs.query({ url: ['http://*/*', 'https://*/*'] });
for (const tab of tabs) {
if (!matchesHosts(tab.url, hosts)) continue;
const url = `${chrome.runtime.getURL('blocked.html')}?url=${encodeURIComponent(tab.url)}`;
await chrome.tabs.update(tab.id, { url }).catch(() => {});
}
}
/* ---------- the stats ledger ---------- */
// Bank worked minutes (and completed focus sessions) on the day the work
// happened: daily totals for the dashboard, plus a session-log entry that
// carries the run's label so the work can be told apart later.
async function recordWork(state, minutes, { sessions = 0, when = Date.now(), completed = false } = {}) {
if (minutes < 1 && sessions === 0) return;
const key = todayKey(new Date(when));
const { stats = {}, log = [] } = await chrome.storage.local.get(['stats', 'log']);
const day = stats[key] ?? { sessions: 0, minutes: 0 };
day.sessions += sessions;
day.minutes += minutes;
stats[key] = day;
const entry = {
id: entryId(when),
start: state.startedAt ?? when - minutes * 60_000,
end: when,
min: minutes,
label: state.label || null,
mode: state.mode,
completed,
};
await chrome.storage.local.set({ stats, log: appendEntry(log, entry) });
await checkGoal(state, key, day);
}
// One quiet cheer the moment today's work crosses the daily goal.
async function checkGoal(state, key, day) {
const goal = state.settings.goalMin;
if (!goal || day.minutes < goal || key !== todayKey()) return;
if (!state.settings.notifications) return;
const { goalDay } = await chrome.storage.local.get('goalDay');
if (goalDay === key) return;
await chrome.storage.local.set({ goalDay: key });
notify(['ember-goal'], {
title: 'Daily goal reached',
message: `${formatHours(day.minutes)} of focus today — well done.`,
});
}
// The label is an optional "what am I working on" — it tags whatever gets
// banked next and sticks for the day (normalizeState retires stale ones).
async function setLabel(state, label) {
state.label = String(label ?? '')
.trim()
.slice(0, 60);
state.labelDay = state.label ? todayKey() : null;
return setState(state);
}
// Whole minutes of work sitting in the current run that nothing has banked
// yet. Breaks aren't work; an idle run holds nothing.
function unsavedWorkMin(state) {
if (state.status === 'idle') return 0;
if (!WORK_PHASES.includes(state.phase)) return 0;
if (state.overtime) return Math.floor((phaseTotalMs(state) + overtimeMs(state)) / 60_000);
if (state.mode === 'stopwatch') return Math.floor(elapsedMs(state) / 60_000);
return Math.floor((phaseTotalMs(state) - remainingMs(state)) / 60_000);
}
// Abandoning a run (reset, skip, mode switch) still credits the minutes
// already worked — only the session count stays strict about completion.
async function creditAbandoned(state) {
const minutes = unsavedWorkMin(state);
if (minutes >= 1) await recordWork(state, minutes);
}
/* ---------- dashboard edits: the views ask, the worker writes ---------- */
// Removing a log entry takes its minutes (and session credit) back out of
// the day's totals, so the charts agree with the list.
async function logDelete(state, id) {
const { stats = {}, log = [] } = await chrome.storage.local.get(['stats', 'log']);
const entry = log.find((e) => e.id === id);
if (!entry) return state;
const key = todayKey(new Date(entry.end));
const day = stats[key];
if (day) {
day.minutes = Math.max(0, day.minutes - entry.min);
if (entry.completed && entry.mode === 'pomodoro') day.sessions = Math.max(0, day.sessions - 1);
if (day.minutes === 0 && day.sessions === 0) delete stats[key]; // keep streaks honest
}
await chrome.storage.local.set({ stats, log: removeEntry(log, id) });
return state;
}
// Manual entry: work done away from the timer ("2h of reading"). Mode
// 'manual' keeps it out of session counts and the hour histogram.
async function logAdd(state, { minutes, label, date } = {}) {
const min = Math.round(Number(minutes));
if (!(min >= 1) || min > 24 * 60) return state;
const today = todayKey();
const key = /^\d{4}-\d{2}-\d{2}$/.test(date ?? '') ? date : today;
const end = key === today ? Date.now() : parseKey(key).getTime() + 12 * 3_600_000;
const { stats = {}, log = [] } = await chrome.storage.local.get(['stats', 'log']);
const day = stats[key] ?? { sessions: 0, minutes: 0 };
day.minutes += min;
stats[key] = day;
const entry = {
id: entryId(end),
start: end - min * 60_000,
end,
min,
label: String(label ?? '').trim().slice(0, 60) || null,
mode: 'manual',
completed: false,
};
await chrome.storage.local.set({ stats, log: appendEntry(log, entry) });
return state;
}
async function labelRename(state, from, to) {
const { log = [] } = await chrome.storage.local.get('log');
await chrome.storage.local.set({ log: renameLabel(log, from, to) });
if (state.label === from) return setLabel(state, to);
return state;
}
async function labelClear(state, label) {
const { log = [] } = await chrome.storage.local.get('log');
await chrome.storage.local.set({ log: clearLabel(log, label) });
if (state.label === label) return setLabel(state, '');
return state;
}
/* ---------- backup import ---------- */
// Replaces stats, log, and settings with a previously exported backup.
// Returns null (a failed action) if the file doesn't look like one of ours.
async function importData(state, data) {
if (!data || typeof data !== 'object') return null;
const stats = {};
for (const [key, day] of Object.entries(data.stats ?? {})) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(key)) continue;
const sessions = Math.max(0, Math.round(Number(day?.sessions)) || 0);
const minutes = Math.max(0, Math.round(Number(day?.minutes)) || 0);
if (sessions || minutes) stats[key] = { sessions, minutes };
}
if (!Array.isArray(data.log)) return null;
const log = data.log
.filter((e) => e && Number.isFinite(e.end) && Number.isFinite(e.min) && e.min > 0)
.map((e) => ({
id: typeof e.id === 'string' ? e.id : entryId(e.end),
start: Number.isFinite(e.start) ? e.start : e.end - e.min * 60_000,
end: e.end,
min: Math.round(e.min),
label: e.label ? String(e.label).slice(0, 60) : null,
mode: typeof e.mode === 'string' ? e.mode : 'pomodoro',
completed: Boolean(e.completed),
}))
.sort((a, b) => a.end - b.end)
.slice(-4000);
await chrome.storage.local.set({ stats, log });
if (data.settings && typeof data.settings === 'object') {
const known = {};
for (const key of Object.keys(DEFAULT_SETTINGS)) {
if (key in data.settings) known[key] = data.settings[key];
}
return updateSettings(state, known);
}
return state;
}
// Older logs predate entry ids; deletion needs them.
async function migrateLog() {
const { log = [] } = await chrome.storage.local.get('log');
if (!log.some((e) => !e.id)) return;
await chrome.storage.local.set({
log: log.map((e) => (e.id ? e : { ...e, id: entryId(e.end) })),
});
}
/* ---------- badge, notifications, sound ---------- */
async function updateBadge(state) {
let text = '';
if (state.settings.showBadge) {
if (state.status === 'running') {
text = state.overtime
? `+${Math.floor(overtimeMs(state) / 60_000)}m`
: state.mode === 'stopwatch'
? `${Math.floor(elapsedMs(state) / 60_000)}m`
: `${Math.ceil(remainingMs(state) / 60_000)}m`;
} else if (state.status === 'paused') {
text = '||';
}
}
await chrome.action.setBadgeText({ text });
if (text) {
await chrome.action.setBadgeBackgroundColor({ color: PHASE_COLOR[state.phase] });
await chrome.action.setBadgeTextColor({ color: '#1A1310' });
}
}
function notifyPhaseEnd(state) {
if (state.mode === 'timer') {
notify(['ember-end', 'start'], {
title: 'Timer finished',
message: `Your ${Math.round(phaseTotalMs(state) / 60_000)} minute timer is up.`,
buttons: [{ title: 'Start again' }],
});
return;
}
const ended = state.phase;
const next = nextPhase(state);
const willAuto = next === 'focus' ? state.settings.autoStartFocus : state.settings.autoStartBreaks;
const title = ended === 'focus' ? 'Focus session complete' : 'Break is over';
// Name the work when the user named it — "what did I just finish?".
const what = ended === 'focus' && state.label ? `“${state.label}”` : capitalize(PHASE_LABEL[ended]);
const actions = [];
const buttons = [];
if (!willAuto) {
actions.push('start');
buttons.push({ title: next === 'focus' ? 'Start focus' : `Start ${PHASE_LABEL[next]}` });
}
if (ended !== 'focus') {
actions.push(`snooze:${ended}`);
buttons.push({ title: '5 more break minutes' });
}
notify(['ember-end', ...actions], {
title,
message: `${what} finished — up next: ${PHASE_LABEL[next]}.`,
buttons,
});
}
// Sound plays in an offscreen document (workers can't). Chrome reaps it on
// its own ~30s after audio stops, so nobody here closes anything.
async function ensureOffscreen() {
const contexts = await chrome.runtime.getContexts({ contextTypes: ['OFFSCREEN_DOCUMENT'] });
if (contexts.length === 0) {
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['AUDIO_PLAYBACK'],
justification: 'Play timer chimes and optional ambient focus sound',
});
}
}
async function sendSound(msg) {
try {
await ensureOffscreen();
chrome.runtime.sendMessage(msg).catch(() => {});
} catch {
// No sound is better than a crashed phase transition.
}
}
async function playChime(state) {
await sendSound({ type: 'chime', chime: state.settings.chime, volume: state.settings.volume });
}
// Keeps the offscreen ambient loop in step with what's happening: playing
// while focused work runs (when the setting asks for it), silent otherwise.
async function syncAmbient(state) {
const on =
state.status === 'running' &&
WORK_PHASES.includes(state.phase) &&
state.settings.ambient !== 'off';
if (!on) {
// Tell a live document to stop; don't spawn one just to say nothing.
const contexts = await chrome.runtime.getContexts({ contextTypes: ['OFFSCREEN_DOCUMENT'] });
if (contexts.length) chrome.runtime.sendMessage({ type: 'ambient', sound: 'off' }).catch(() => {});
return;
}
await sendSound({ type: 'ambient', sound: state.settings.ambient, volume: state.settings.volume });
}
function capitalize(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}