patch-testing-coworker / web /src /notify /useNotifications.ts
EnergyVenom's picture
Deploy notifications bf2e614: event outbox, Telegram channel, bell, Settings > Notifications
92d45ee verified
Raw History Blame Contribute Delete
5.8 kB
import { useQuery } from '@tanstack/react-query';
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { useNavigate } from 'react-router-dom';
import { getJson } from '../api/client';
import { useAuthOptional } from '../auth/AuthContext';
/** One thing a coworker wants you to know (GET /api/notifications), newest first. */
export interface Notice {
id: number;
kind: string;
title: string;
body: string;
coworker: string;
run_id: string | null;
link: string;
created_at: string;
}
const store = {
get(k: string) { try { return window.localStorage.getItem(k); } catch { return null; } },
set(k: string, v: string) { try { window.localStorage.setItem(k, v); } catch { /* private mode: not remembered */ } },
};
/** The notices newer than the last one the person has seen. */
export const unreadOf = (items: Notice[], lastSeen: number) => items.filter((n) => n.id > lastSeen);
/** A same-origin link as a router path (the server sends absolute links for chat apps); other links stay as they are. */
export function toPath(link: string): { path: string; external: boolean } {
if (link.startsWith('/')) return { path: link, external: false };
try {
const u = new URL(link);
if (typeof window !== 'undefined' && u.origin === window.location.origin) return { path: `${u.pathname}${u.search}${u.hash}`, external: false };
} catch { /* not a URL: treat as a path */ }
return { path: link, external: true };
}
/** "just now", "5 min ago", "3 h ago", then the date. */
export function whenWords(iso: string, now = Date.now()): string {
const t = Date.parse(iso);
if (Number.isNaN(t)) return '';
const min = Math.round((now - t) / 60000);
if (min < 1) return 'just now';
if (min < 60) return `${min} min ago`;
if (min < 24 * 60) return `${Math.round(min / 60)} h ago`;
return new Date(t).toLocaleDateString(undefined, { day: 'numeric', month: 'short' });
}
/* "Tell me in this browser too": remembered per person in this browser, shared by the bell and Settings. */
const PREF_EVENT = 'pw-notify-pref';
const prefKey = (user: string) => `pw-notify-browser:${user}`;
export function useBrowserPref() {
const user = useAuthOptional()?.user?.username ?? '';
const key = prefKey(user);
const on = useSyncExternalStore(
(cb) => { window.addEventListener('storage', cb); window.addEventListener(PREF_EVENT, cb); return () => { window.removeEventListener('storage', cb); window.removeEventListener(PREF_EVENT, cb); }; },
() => store.get(key) === '1',
() => false,
);
const supported = typeof window !== 'undefined' && 'Notification' in window;
const blocked = supported && Notification.permission === 'denied';
/** Turning it on asks the browser for permission first; it stays off when the browser says no. */
const setOn = useCallback(async (v: boolean) => {
if (v && supported && Notification.permission !== 'granted') {
const p = await Notification.requestPermission().catch(() => 'denied' as NotificationPermission);
if (p !== 'granted') v = false;
}
store.set(key, v ? '1' : '0');
window.dispatchEvent(new Event(PREF_EVENT));
}, [key, supported]);
return { on: on && supported && !blocked, setOn, supported, blocked };
}
/**
* The person's notices: refreshed every 20 seconds while the tab is visible (and in the background too when browser
* notifications are on, so they can arrive). Unread = newer than the last notice the person marked as seen.
*/
export function useNotifications() {
const user = useAuthOptional()?.user?.username ?? '';
const seenKey = `pw-notify-seen:${user}`;
const browser = useBrowserPref();
const q = useQuery({
queryKey: ['notifications'],
queryFn: () => getJson<{ items?: Notice[] }>('/api/notifications?limit=30'),
refetchInterval: 20_000,
refetchIntervalInBackground: browser.on,
retry: false,
});
const items = Array.isArray(q.data?.items) ? q.data.items : [];
const [lastSeen, setLastSeen] = useState(() => Number(store.get(seenKey) ?? 0) || 0);
useEffect(() => { setLastSeen(Number(store.get(seenKey) ?? 0) || 0); }, [seenKey]);
const unread = unreadOf(items, lastSeen);
const newest = items.reduce((m, n) => Math.max(m, n.id), 0);
const markAllSeen = useCallback(() => {
if (!newest) return;
store.set(seenKey, String(newest));
setLastSeen(newest);
}, [newest, seenKey]);
useBrowserNotices(items, browser.on);
return { items, unread, lastSeen, markAllSeen, isLoading: q.isLoading, error: q.error };
}
/** Shows a system notification for each new notice while the app is in the background (and only if turned on). */
function useBrowserNotices(items: Notice[], on: boolean) {
const nav = useNavigate();
const shownUpTo = useRef<number | null>(null);
useEffect(() => {
const newest = items.reduce((m, n) => Math.max(m, n.id), 0);
if (shownUpTo.current === null) { shownUpTo.current = newest; return; } // the first load is history, not news
const fresh = items.filter((n) => n.id > (shownUpTo.current ?? 0));
shownUpTo.current = Math.max(shownUpTo.current, newest);
if (!on || !fresh.length || typeof document === 'undefined' || !document.hidden || !('Notification' in window) || Notification.permission !== 'granted') return;
for (const n of fresh.slice(0, 3)) {
const note = new Notification(n.title, { body: n.body, tag: `patchwise-${n.id}` });
note.onclick = () => {
window.focus();
const { path, external } = toPath(n.link);
if (external) window.open(path, '_blank', 'noopener'); else nav(path);
note.close();
};
}
}, [items, on, nav]);
}