Skip to content

Commit 0fc9ff2

Browse files
authored
fix: ask for notifications in the extension too and use the extension notification API (#19)
## Summary Fix notifications in the extension and make the setting clear. **Why 0.2.0 never asked in the extension:** the manifest's `notifications` permission makes Chrome grant it up front, so the browser has nothing to ask and the first-run banner (which waited for a browser "default" state) never appeared. - **App-level on/off choice.** Notifications now have their own setting on top of the browser permission. The first-run banner ("Get a notification when a focus session or break ends?" → **Turn on**) appears on first open in both the web app and the extension. - **Sample on turn-on.** Turning them on sends a sample notification and shows a note: if it never arrived, allow notifications for the browser in system settings and turn off Do Not Disturb / Focus — the usual reason a granted notification is silently dropped. - **Extension uses `chrome.notifications`.** Inside the extension, notifications go through the extension API (with the extension's icon); clicking one focuses the timer tab and window. The web app keeps the Notification API. - **Menu switch.** "Notifications on · test" is replaced by a plain switch: *Notifications: On / Off / Blocked*. Blocked explains how to allow them in site settings. - An earlier "Not now" dismissal is honoured as Off. ## Testing - Lint, typecheck, unit tests and build pass. - Web (stubbed permission already granted): banner asks on first open; Turn on sends the sample and shows the note; the menu switch flips On/Off and stores the choice. - Extension page (stubbed `chrome` API): banner asks; Turn on calls `chrome.notifications.create` with the sample and the extension icon; a 1-minute session ending sends "Focus session complete" the same way, with no web notification.
1 parent 7bb1951 commit 0fc9ff2

4 files changed

Lines changed: 162 additions & 60 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 offers to turn them on the first time you open it; you can also turn them on, test them or see why they are blocked from **Menu → Settings → Notifications**.
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.
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.
Lines changed: 96 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,80 @@
1-
const ICON = "/icons/icon-192.png";
2-
// Reusing one tag replaces a stale notification instead of stacking them.
3-
const TAG = "boost-focus-timer";
4-
const OFFER_DISMISSED_KEY = "bft:notificationOfferDismissed";
1+
/*
2+
* Notifications have an app-level on/off choice on top of the browser permission:
3+
* inside the extension the permission is granted by the manifest, so without our own
4+
* choice the user would never be asked.
5+
*/
56

6-
const isSupported = (): boolean => typeof window !== "undefined" && "Notification" in window;
7+
const ICON_PATH = "icons/icon-128.png";
8+
// Reusing one id/tag replaces a stale notification instead of stacking them.
9+
const NOTIFICATION_ID = "boost-focus-timer";
10+
const PREFERENCE_KEY = "bft:notifications";
11+
const LEGACY_DISMISSED_KEY = "bft:notificationOfferDismissed";
12+
export const NOTIFICATIONS_ENABLED_EVENT = "bft:notifications-enabled";
713

8-
/** True until the user has decided: the browser hasn't asked yet and they haven't said "Not now". */
9-
export function shouldOfferNotifications(): boolean {
10-
return isSupported() && Notification.permission === "default" && !localStorage.getItem(OFFER_DISMISSED_KEY);
14+
/** The slice of the extension `chrome` API used here; the web build never has it. */
15+
interface ExtensionApi {
16+
runtime: { id?: string; getURL(path: string): string };
17+
notifications: {
18+
create(id: string, options: { type: "basic"; iconUrl: string; title: string; message: string; silent?: boolean }): Promise<string>;
19+
onClicked: { addListener(listener: (id: string) => void): void };
20+
};
21+
tabs: {
22+
getCurrent(): Promise<{ id?: number; windowId?: number } | undefined>;
23+
update(tabId: number, properties: { active: boolean }): Promise<unknown>;
24+
};
25+
windows: { update(windowId: number, properties: { focused: boolean }): Promise<unknown> };
1126
}
1227

13-
export function dismissNotificationOffer(): void {
14-
localStorage.setItem(OFFER_DISMISSED_KEY, "1");
28+
function extensionApi(): ExtensionApi | null {
29+
const candidate = (globalThis as { chrome?: Partial<ExtensionApi> }).chrome;
30+
return candidate?.runtime?.id && candidate.notifications ? (candidate as ExtensionApi) : null;
1531
}
1632

17-
/** Must run from a click or key press; browsers ignore permission requests made outside a user gesture. */
18-
export async function requestNotificationPermission(): Promise<NotificationPermission | null> {
19-
if (!isSupported()) return null;
20-
try {
21-
return await Notification.requestPermission();
22-
} catch (error) {
23-
console.error("Notification permission request failed:", error);
24-
return null;
25-
}
33+
const hasWebNotifications = (): boolean => typeof window !== "undefined" && "Notification" in window;
34+
35+
export type NotificationStatus = "unsupported" | "undecided" | "on" | "off" | "blocked";
36+
37+
function readPreference(): "on" | "off" | null {
38+
const stored = localStorage.getItem(PREFERENCE_KEY);
39+
if (stored === "on" || stored === "off") return stored;
40+
return localStorage.getItem(LEGACY_DISMISSED_KEY) ? "off" : null;
2641
}
2742

28-
export type NotificationStatus = "unsupported" | NotificationPermission;
43+
const writePreference = (value: "on" | "off") => localStorage.setItem(PREFERENCE_KEY, value);
2944

30-
export const notificationStatus = (): NotificationStatus => (isSupported() ? Notification.permission : "unsupported");
45+
export function notificationStatus(): NotificationStatus {
46+
const preference = readPreference();
47+
if (extensionApi()) return preference ?? "undecided";
48+
if (!hasWebNotifications()) return "unsupported";
49+
if (Notification.permission === "denied") return "blocked";
50+
if (Notification.permission === "default") return preference === "off" ? "off" : "undecided";
51+
return preference ?? "undecided";
52+
}
3153

32-
/** Shows a system notification when the user has allowed them; silent because the end bell already plays. */
33-
export function notify(title: string, body: string): void {
34-
if (!isSupported() || Notification.permission !== "granted") return;
54+
let clickHandlerInstalled = false;
55+
56+
/** Clicking an extension notification brings the timer tab and its window to the front. */
57+
function installExtensionClickHandler(api: ExtensionApi): void {
58+
if (clickHandlerInstalled) return;
59+
clickHandlerInstalled = true;
60+
api.notifications.onClicked.addListener(async () => {
61+
const tab = await api.tabs.getCurrent();
62+
if (tab?.id !== undefined) await api.tabs.update(tab.id, { active: true });
63+
if (tab?.windowId !== undefined) await api.windows.update(tab.windowId, { focused: true });
64+
});
65+
}
66+
67+
function show(title: string, body: string): void {
68+
const api = extensionApi();
3569
try {
36-
const notification = new Notification(title, { body, icon: ICON, tag: TAG, silent: true });
70+
if (api) {
71+
installExtensionClickHandler(api);
72+
const options = { type: "basic" as const, iconUrl: api.runtime.getURL(ICON_PATH), title, message: body, silent: true };
73+
api.notifications.create(NOTIFICATION_ID, options).catch((error: unknown) => console.error("Could not show notification:", error));
74+
return;
75+
}
76+
// Silent because the end bell already plays; the notification is the visual cue.
77+
const notification = new Notification(title, { body, icon: `/${ICON_PATH}`, tag: NOTIFICATION_ID, silent: true });
3778
notification.onclick = () => {
3879
window.focus();
3980
notification.close();
@@ -42,3 +83,33 @@ export function notify(title: string, body: string): void {
4283
console.error("Could not show notification:", error);
4384
}
4485
}
86+
87+
/** Shows a notification when the user turned them on. */
88+
export function notify(title: string, body: string): void {
89+
if (notificationStatus() === "on") show(title, body);
90+
}
91+
92+
/**
93+
* Turns notifications on and sends a sample so the user sees the result straight away.
94+
* Must run from a click: browsers ignore permission requests made outside a user gesture.
95+
*/
96+
export async function enableNotifications(): Promise<NotificationStatus> {
97+
if (!extensionApi() && hasWebNotifications() && Notification.permission === "default") {
98+
const permission = await Notification.requestPermission().catch((error: unknown) => {
99+
console.error("Notification permission request failed:", error);
100+
return "default" as const;
101+
});
102+
// Closing the browser dialog without a choice leaves the user undecided.
103+
if (permission !== "granted") return notificationStatus();
104+
}
105+
const status = notificationStatus();
106+
if (status === "blocked" || status === "unsupported") return status;
107+
writePreference("on");
108+
show("Notifications are on", "You'll get one when a focus session or break ends.");
109+
window.dispatchEvent(new Event(NOTIFICATIONS_ENABLED_EVENT));
110+
return "on";
111+
}
112+
113+
export function disableNotifications(): void {
114+
writePreference("off");
115+
}

‎src/components/shell/NotificationPrompt.tsx‎

Lines changed: 44 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,66 @@
11
"use client";
22

3-
import { useState } from "react";
4-
import { dismissNotificationOffer, requestNotificationPermission, shouldOfferNotifications } from "../focus/notifications";
5-
import { Bell, X } from "../icons";
3+
import { useEffect, useState } from "react";
4+
import { disableNotifications, enableNotifications, notificationStatus, NOTIFICATIONS_ENABLED_EVENT } from "../focus/notifications";
5+
import { Bell, Check, X } from "../icons";
66

7-
/** First-visit banner: the browser only shows its permission dialog after a click, so this provides the click. */
7+
type Stage = "hidden" | "ask" | "sent";
8+
9+
const PANEL =
10+
"fixed top-14 left-1/2 -translate-x-1/2 z-50 w-[calc(100%-1.5rem)] max-w-md flex items-start gap-3 px-4 py-3 bg-gray-900 border border-gray-700 rounded-xl shadow-2xl motion-safe:animate-[bft-sheet-in_200ms_ease-out]";
11+
const CLOSE_BUTTON = "shrink-0 p-1.5 text-gray-400 hover:text-white hover:bg-gray-800 rounded-lg transition-colors";
12+
13+
/**
14+
* Asks on first open (browsers only show their permission dialog after a click) and,
15+
* once notifications are turned on, confirms that a sample was sent and what to check if it never arrived.
16+
*/
817
export function NotificationPrompt() {
9-
const [isVisible, setIsVisible] = useState(shouldOfferNotifications);
18+
const [stage, setStage] = useState<Stage>(() => (notificationStatus() === "undecided" ? "ask" : "hidden"));
19+
20+
useEffect(() => {
21+
const showConfirmation = () => setStage("sent");
22+
window.addEventListener(NOTIFICATIONS_ENABLED_EVENT, showConfirmation);
23+
return () => window.removeEventListener(NOTIFICATIONS_ENABLED_EVENT, showConfirmation);
24+
}, []);
1025

11-
if (!isVisible) return null;
26+
if (stage === "hidden") return null;
27+
28+
if (stage === "sent") {
29+
return (
30+
<div role="status" className={PANEL}>
31+
<Check className="w-5 h-5 mt-0.5 shrink-0 text-green-400" />
32+
<p className="flex-1 text-sm text-gray-300">
33+
Notifications are on, and a sample was just sent. Didn&apos;t see it? Allow notifications for your browser in your
34+
system settings and turn off Do Not Disturb or Focus mode.
35+
</p>
36+
<button onClick={() => setStage("hidden")} aria-label="Close" title="Close" className={CLOSE_BUTTON}>
37+
<X className="w-4 h-4" />
38+
</button>
39+
</div>
40+
);
41+
}
1242

1343
const allow = async () => {
14-
const permission = await requestNotificationPermission();
15-
// Closing the browser dialog leaves the permission at "default"; keep offering in that case.
16-
if (permission !== "default") setIsVisible(false);
44+
const status = await enableNotifications();
45+
if (status !== "on" && status !== "undecided") setStage("hidden");
1746
};
1847

1948
const notNow = () => {
20-
dismissNotificationOffer();
21-
setIsVisible(false);
49+
disableNotifications();
50+
setStage("hidden");
2251
};
2352

2453
return (
25-
<div
26-
role="dialog"
27-
aria-label="Enable notifications"
28-
className="fixed top-14 left-1/2 -translate-x-1/2 z-50 w-[calc(100%-1.5rem)] max-w-md flex items-center gap-3 px-4 py-3 bg-gray-900 border border-gray-700 rounded-xl shadow-2xl motion-safe:animate-[bft-sheet-in_200ms_ease-out]"
29-
>
54+
<div role="dialog" aria-label="Enable notifications" className={`${PANEL} items-center`}>
3055
<Bell className="w-5 h-5 shrink-0 text-blue-400" />
31-
<p className="flex-1 text-sm text-gray-300">Get a notification when a focus session or break ends.</p>
56+
<p className="flex-1 text-sm text-gray-300">Get a notification when a focus session or break ends?</p>
3257
<button
3358
onClick={() => void allow()}
3459
className="shrink-0 px-3 py-1.5 text-sm font-medium bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
3560
>
36-
Allow
61+
Turn on
3762
</button>
38-
<button
39-
onClick={notNow}
40-
aria-label="Not now"
41-
title="Not now"
42-
className="shrink-0 p-1.5 text-gray-400 hover:text-white hover:bg-gray-800 rounded-lg transition-colors"
43-
>
63+
<button onClick={notNow} aria-label="Not now" title="Not now" className={CLOSE_BUTTON}>
4464
<X className="w-4 h-4" />
4565
</button>
4666
</div>

‎src/components/shell/StartMenu.tsx‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"use client";
22

33
import { useEffect, useRef, useState, type ComponentType } from "react";
4-
import { notificationStatus, notify, requestNotificationPermission, type NotificationStatus } from "../focus/notifications";
4+
import { disableNotifications, enableNotifications, notificationStatus, type NotificationStatus } from "../focus/notifications";
55
import { Bell, ChevronDown, CircleUser, Menu, Settings, Tag } from "../icons";
66
import { useHotkey, useHotkeyLabel } from "../hotkeys/HotkeysProvider";
77
import type { Tab } from "../types";
@@ -17,27 +17,38 @@ const SETTINGS: readonly { label: string; Icon: ComponentType<{ className?: stri
1717
];
1818

1919
const NOTIFICATION_LABELS: Readonly<Record<Exclude<NotificationStatus, "unsupported">, string>> = {
20-
default: "Turn on notifications",
21-
granted: "Notifications on · test",
22-
denied: "Notifications blocked",
20+
on: "Notifications: On",
21+
off: "Notifications: Off",
22+
undecided: "Notifications: Off",
23+
blocked: "Notifications: Blocked",
24+
};
25+
26+
const NOTIFICATION_HINTS: Readonly<Record<Exclude<NotificationStatus, "unsupported">, string>> = {
27+
on: "Click to turn notifications off",
28+
off: "Click to turn notifications on",
29+
undecided: "Click to turn notifications on",
30+
blocked: "Click to see how to allow notifications",
2331
};
2432

2533
const BLOCKED_HELP =
2634
"Notifications are blocked for this site. Allow them in your browser's site settings (the icon left of the address bar), then reload.";
2735

28-
/** One menu row that shows the current permission and does the useful next step for it. */
36+
/** A switch row: shows the current state and flips it; a blocked browser gets instructions instead. */
2937
function NotificationsItem() {
3038
const [status, setStatus] = useState<NotificationStatus>(notificationStatus);
3139
if (status === "unsupported") return null;
3240

33-
const act = async () => {
34-
if (status === "default") setStatus((await requestNotificationPermission()) ?? notificationStatus());
35-
else if (status === "granted") notify("Notifications are on", "You'll get one when a focus session or break ends.");
36-
else alert(BLOCKED_HELP);
41+
const toggle = async () => {
42+
if (status === "blocked") return alert(BLOCKED_HELP);
43+
if (status === "on") {
44+
disableNotifications();
45+
return setStatus("off");
46+
}
47+
setStatus(await enableNotifications());
3748
};
3849

3950
return (
40-
<button onClick={() => void act()} className={SUB_ITEM}>
51+
<button onClick={() => void toggle()} title={NOTIFICATION_HINTS[status]} className={SUB_ITEM}>
4152
<Bell className="w-4 h-4" />
4253
<span>{NOTIFICATION_LABELS[status]}</span>
4354
</button>

0 commit comments

Comments
 (0)