Skip to content

Commit 98acfed

Browse files
authored
fix: notifications across browsers, show every notification, in-app dialogs (#20)
* fix: show every notification instead of silently replacing the previous one ## Summary Session-complete notifications did not pop up after the sample notification. **Cause:** every notification reused one tag (web) / id (extension). When a notification with the same tag is still in the notification list, Chrome swaps the new content into it *silently*, without showing a pop-up. The sample sent on "Turn on" stayed in the list, so "Focus session complete" replaced it invisibly. **Fix:** each notification gets a fresh id, and the previous one is closed (web) / cleared (extension) first, so only one is ever listed and every session or break end pops up. ## Testing - Lint, typecheck, unit tests and build pass. - Stubbed Notification API: sample opens without a tag, is closed, then "Focus session complete" opens fresh. - Reported scenario (Turn on → sample shown → session ends → nothing shown) to be re-checked on a real machine. * fix: ask Chrome for notification permission directly on first open Drop the in-app 'Turn on' banner and the app-level on/off setting. The app calls Notification.requestPermission() on first open, so Chrome's own Allow/Block prompt is the only step; the extension is granted by its manifest and needs no ask. Menu → Settings → Notifications shows On / Blocked (with how to change it), or 'Turn on notifications' to ask again when the prompt was dismissed. * feat: in-app dialogs and notification permission for Firefox and Safari Replace every window.alert/confirm with an in-app dialog (OK, or Cancel/confirm with a red Delete for destructive actions; Esc cancels, Enter confirms, queued one at a time). Firefox and Safari ignore a permission request that is not inside a click or key press and answer 'default' at once, so the ask on load never showed a prompt there. When that happens the app now asks again on the user's first click or key press. A dismissed Chrome prompt (which takes the user time to answer) is not asked again.
1 parent 0fc9ff2 commit 98acfed

14 files changed

Lines changed: 264 additions & 172 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Runs as a web app or as a browser extension, and keeps every bit of data in your
1919
## What you get
2020

2121
- **Focus timer** with pause, resume, breaks, extend-on-complete and goal history (press <kbd>↑</kbd>/<kbd>↓</kbd> in the goal field).
22-
- **Notifications** when a focus session or break runs out. The app asks the first time you open it and sends a sample when you turn them on; switch them on or off any time from **Menu → Settings → Notifications**. If the sample never appears, allow notifications for your browser in your system settings and turn off Do Not Disturb / Focus.
22+
- **Notifications** when a focus session or break runs out. The app asks for permission with Chrome's own prompt the first time you open it; **Menu → Settings → Notifications** shows the current state and asks again if you dismissed the prompt. If nothing appears, allow notifications for your browser in your system settings and turn off Do Not Disturb / Focus.
2323
- **Pixel-art progress animations** — a coffee cup that fills, a battery that charges, a rocket that lifts off — plus an auto-shuffle option.
2424
- **To-dos** with time estimates, notes, drag-and-drop ordering, a backlog and archive; start a focus session straight from a to-do.
2525
- **Habits** with 7- and 30-day grids and notes per day.

‎src/components/BoostApp.tsx‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22

33
import dynamic from "next/dynamic";
44
import { Suspense, useCallback, useEffect, useRef, useState } from "react";
5+
import { DialogProvider } from "./dialogs/DialogProvider";
56
import { FocusTimer } from "./focus/FocusTimer";
7+
import { askForNotificationsOnFirstOpen } from "./focus/notifications";
68
import { HotkeysProvider, useHotkey, useHotkeyMap } from "./hotkeys/HotkeysProvider";
79
import { databaseService } from "./lib/database-service";
810
import { getLocalUserId } from "./lib/local-db";
911
import { getDisplayName, saveDisplayName } from "./lib/profile";
1012
import { BottomNav } from "./shell/BottomNav";
11-
import { NotificationPrompt } from "./shell/NotificationPrompt";
1213
import { StartMenu } from "./shell/StartMenu";
1314
import { TopBar } from "./shell/TopBar";
1415
import { MOBILE_NAV_OFFSET, MOBILE_QUERY, SHORT_VIEWPORT_QUERY, useMediaQuery } from "./shell/use-media-query";
@@ -28,9 +29,11 @@ function formatTodayMinutes(minutes: number): string {
2829

2930
export function BoostApp() {
3031
return (
31-
<HotkeysProvider>
32-
<AppShell />
33-
</HotkeysProvider>
32+
<DialogProvider>
33+
<HotkeysProvider>
34+
<AppShell />
35+
</HotkeysProvider>
36+
</DialogProvider>
3437
);
3538
}
3639

@@ -53,6 +56,8 @@ function AppShell() {
5356
const isMobile = useMediaQuery(MOBILE_QUERY);
5457
const isShortViewport = useMediaQuery(SHORT_VIEWPORT_QUERY);
5558

59+
useEffect(() => askForNotificationsOnFirstOpen(), []);
60+
5661
useEffect(() => {
5762
databaseService.getTodayFocusMinutes().then(setTodayMinutes, (error: unknown) => {
5863
console.error("Error loading today minutes:", error);
@@ -210,7 +215,6 @@ function AppShell() {
210215
<BottomNav activeTab={tab} onTabChange={setTab} />
211216
</div>
212217
<StartMenu onNavigate={navigateFromCurrent} />
213-
<NotificationPrompt />
214218
</>
215219
);
216220
}

‎src/components/boost/BoostFeed.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { useHotkey } from "../hotkeys/HotkeysProvider";
66
import { getDisplayName } from "../lib/profile";
77
import { getLocalUserId, localDb, type Row } from "../lib/local-db";
88
import { PostContent } from "./PostContent";
9+
import { useDialog } from "../dialogs/DialogProvider";
910

1011
type BoostPost = Row & {
1112
user_id: string;
@@ -86,6 +87,7 @@ function UploadedPhoto({ src }: { src: string }) {
8687
}
8788

8889
export function BoostFeed() {
90+
const dialog = useDialog();
8991
const [posts, setPosts] = useState<BoostPost[]>([]);
9092
const [likes, setLikes] = useState(new Map<string, LikeState>());
9193
const [loading, setLoading] = useState(true);
@@ -132,11 +134,11 @@ export function BoostFeed() {
132134
const isImage = file.type.startsWith("image/");
133135
if (!isVideo && !isImage) return;
134136
if (isVideo && file.size > MAX_VIDEO_BYTES) {
135-
alert("Video must be smaller than 100MB");
137+
void dialog.alert("Video must be smaller than 100MB");
136138
return;
137139
}
138140
if (isImage && file.size > MAX_IMAGE_BYTES) {
139-
alert("Image must be smaller than 10MB");
141+
void dialog.alert("Image must be smaller than 10MB");
140142
return;
141143
}
142144
setMediaFile(file);
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
"use client";
2+
3+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
4+
5+
interface DialogOptions {
6+
title?: string;
7+
confirmLabel?: string;
8+
/** Styles the confirm button red for irreversible actions such as deletes. */
9+
destructive?: boolean;
10+
}
11+
12+
interface DialogApi {
13+
/** In-app replacement for `window.alert`; resolves when dismissed. */
14+
alert(message: string, options?: DialogOptions): Promise<void>;
15+
/** In-app replacement for `window.confirm`; resolves true on confirm, false on cancel. */
16+
confirm(message: string, options?: DialogOptions): Promise<boolean>;
17+
}
18+
19+
interface OpenDialog extends DialogOptions {
20+
id: number;
21+
kind: "alert" | "confirm";
22+
message: string;
23+
resolve(confirmed: boolean): void;
24+
}
25+
26+
const DialogContext = createContext<DialogApi | null>(null);
27+
28+
function Dialog({ dialog, onClose }: { dialog: OpenDialog; onClose(confirmed: boolean): void }) {
29+
const confirmRef = useRef<HTMLButtonElement>(null);
30+
const isConfirm = dialog.kind === "confirm";
31+
32+
useEffect(() => {
33+
confirmRef.current?.focus();
34+
// Capture phase so Esc/Enter reach the dialog before page shortcuts and inputs behind it.
35+
const onKeyDown = (event: KeyboardEvent) => {
36+
if (event.key !== "Escape" && event.key !== "Enter") return;
37+
event.preventDefault();
38+
event.stopPropagation();
39+
onClose(event.key === "Enter");
40+
};
41+
window.addEventListener("keydown", onKeyDown, true);
42+
return () => window.removeEventListener("keydown", onKeyDown, true);
43+
}, [onClose]);
44+
45+
const confirmColor = dialog.destructive ? "bg-red-600 hover:bg-red-700" : "bg-blue-600 hover:bg-blue-700";
46+
47+
return (
48+
<div
49+
className="fixed inset-0 z-[70] bg-black/60 flex items-center justify-center p-4 motion-safe:animate-[bft-fade-in_150ms_ease-out]"
50+
onMouseDown={(event) => {
51+
if (event.target === event.currentTarget) onClose(false);
52+
}}
53+
role="presentation"
54+
>
55+
<div
56+
role="alertdialog"
57+
aria-modal="true"
58+
aria-labelledby={dialog.title ? "app-dialog-title" : undefined}
59+
aria-describedby="app-dialog-message"
60+
className="bg-gray-800 rounded-2xl p-6 max-w-md w-full border border-gray-700 shadow-2xl motion-safe:animate-[bft-sheet-in_200ms_ease-out]"
61+
>
62+
{dialog.title ? (
63+
<h2 id="app-dialog-title" className="text-lg font-bold text-white mb-3">
64+
{dialog.title}
65+
</h2>
66+
) : null}
67+
<p id="app-dialog-message" className="text-gray-300 mb-6 whitespace-pre-line">
68+
{dialog.message}
69+
</p>
70+
<div className="flex gap-3 justify-end">
71+
{isConfirm ? (
72+
<button
73+
onClick={() => onClose(false)}
74+
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg font-medium transition-colors"
75+
>
76+
Cancel
77+
</button>
78+
) : null}
79+
<button
80+
ref={confirmRef}
81+
onClick={() => onClose(true)}
82+
className={`px-4 py-2 ${confirmColor} text-white rounded-lg font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400`}
83+
>
84+
{dialog.confirmLabel ?? (isConfirm ? "Confirm" : "OK")}
85+
</button>
86+
</div>
87+
</div>
88+
</div>
89+
);
90+
}
91+
92+
export function DialogProvider({ children }: { children: ReactNode }) {
93+
// A queue, so a second dialog requested while one is open waits its turn instead of replacing it.
94+
const [queue, setQueue] = useState<OpenDialog[]>([]);
95+
const nextId = useRef(0);
96+
97+
const open = useCallback((kind: OpenDialog["kind"], message: string, options?: DialogOptions) => {
98+
const id = nextId.current++;
99+
return new Promise<boolean>((resolve) => setQueue((current) => [...current, { ...options, id, kind, message, resolve }]));
100+
}, []);
101+
102+
const api = useMemo<DialogApi>(
103+
() => ({
104+
alert: async (message, options) => {
105+
await open("alert", message, options);
106+
},
107+
confirm: (message, options) => open("confirm", message, options),
108+
}),
109+
[open],
110+
);
111+
112+
const current = queue[0];
113+
const close = useCallback(
114+
(confirmed: boolean) => {
115+
current?.resolve(confirmed);
116+
setQueue((pending) => pending.filter((dialog) => dialog.id !== current?.id));
117+
},
118+
[current],
119+
);
120+
121+
return (
122+
<DialogContext.Provider value={api}>
123+
{children}
124+
{current ? <Dialog key={current.id} dialog={current} onClose={close} /> : null}
125+
</DialogContext.Provider>
126+
);
127+
}
128+
129+
export function useDialog(): DialogApi {
130+
const context = useContext(DialogContext);
131+
if (!context) throw new Error("useDialog must be used inside <DialogProvider>");
132+
return context;
133+
}

‎src/components/focus/FocusTimer.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { GoalForm, hotkeyHint } from "./GoalForm";
1111
import { PixelArt } from "./PixelArt";
1212
import { notify } from "./notifications";
1313
import { playSound } from "./sounds";
14+
import { useDialog } from "../dialogs/DialogProvider";
1415

1516
const DEFAULT_TITLE = "Boost Focus Timer";
1617
const HEARTBEAT_MS = 5000;
@@ -127,6 +128,7 @@ function TimerButton({
127128
}
128129

129130
export const FocusTimer = forwardRef<FocusTimerHandle, FocusTimerProps>(function FocusTimer(props, ref) {
131+
const dialog = useDialog();
130132
const { isActive, onNavigateToTab, onTodayMinutesChange } = props;
131133

132134
const [focus, setFocus] = useState<Countdown>(IDLE);
@@ -329,9 +331,9 @@ export const FocusTimer = forwardRef<FocusTimerHandle, FocusTimerProps>(function
329331
});
330332

331333
const startFocus = async () => {
332-
if (!goal.trim() && !session) return alert("Please enter a focus goal");
334+
if (!goal.trim() && !session) return void dialog.alert("Please enter a focus goal");
333335
const minutes = parseInt(inputMinutes);
334-
if (!minutes || minutes <= 0) return alert("Please enter a valid time in minutes");
336+
if (!minutes || minutes <= 0) return void dialog.alert("Please enter a valid time in minutes");
335337
localStorage.setItem("lastFocusDuration", String(minutes));
336338
try {
337339
const created = await databaseService.createFocusSession({ goal, planned_duration_minutes: minutes, session_type: "focus" });
@@ -348,7 +350,7 @@ export const FocusTimer = forwardRef<FocusTimerHandle, FocusTimerProps>(function
348350
sendHeartbeat(created);
349351
} catch (error) {
350352
console.error("Failed to start session:", error);
351-
alert("Failed to start focus session. Please try again.");
353+
void dialog.alert("Failed to start focus session. Please try again.");
352354
}
353355
};
354356

@@ -382,21 +384,21 @@ export const FocusTimer = forwardRef<FocusTimerHandle, FocusTimerProps>(function
382384

383385
const extendFocus = async () => {
384386
const minutes = parseInt(extendMinutes);
385-
if (isNaN(minutes) || minutes <= 0) return alert("Please enter a valid number of minutes");
387+
if (isNaN(minutes) || minutes <= 0) return void dialog.alert("Please enter a valid number of minutes");
386388
try {
387389
if (session) setSession(await databaseService.updateFocusSession(session.id, { completed: false, end_time: null }));
388390
setFocus({ minutes, seconds: 0, isRunning: true, isCompleted: false });
389391
setFocusStart(Date.now());
390392
setFocusTotalMs(minutes * MINUTE_MS);
391393
} catch (error) {
392394
console.error("Failed to extend session:", error);
393-
alert("Failed to extend session. Please try again.");
395+
void dialog.alert("Failed to extend session. Please try again.");
394396
}
395397
};
396398

397399
const startBreak = async () => {
398400
const minutes = parseInt(breakMinutes);
399-
if (!minutes || minutes <= 0) return alert("Please enter a valid break time in minutes");
401+
if (!minutes || minutes <= 0) return void dialog.alert("Please enter a valid break time in minutes");
400402
localStorage.setItem("lastBreakDuration", String(minutes));
401403
setSession(null);
402404
setBreakTimer(IDLE);

‎src/components/focus/GoalForm.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from
44
import { Check, Clock, Pencil, Plus, Tag as TagIcon, Target, X } from "../icons";
55
import { useHotkey, useHotkeyLabel } from "../hotkeys/HotkeysProvider";
66
import { databaseService, type Tag } from "../lib/database-service";
7+
import { useDialog } from "../dialogs/DialogProvider";
78

89
export const hotkeyHint = (label: string, combo: string | null): string | undefined =>
910
combo ? `${label} (${combo})` : undefined;
@@ -107,6 +108,7 @@ function TagSelector({
107108
onEditTags(): void;
108109
isActive: boolean;
109110
}) {
111+
const dialog = useDialog();
110112
const [allTags, setAllTags] = useState<Tag[]>([]);
111113
const [isOpen, setIsOpen] = useState(false);
112114
const [isCreating, setIsCreating] = useState(false);
@@ -139,7 +141,7 @@ function TagSelector({
139141
setIsCreating(false);
140142
} catch (error) {
141143
console.error("Failed to create tag:", error);
142-
alert("Failed to create tag. It might already exist.");
144+
void dialog.alert("Failed to create tag. It might already exist.");
143145
}
144146
};
145147

0 commit comments

Comments
 (0)