staging-tester / ocean-landing-serve / src/ lib/ live/ notifications.svelte.ts

import { request } from './http.js';

// In-app alerts: today only mirrors that stopped (diverged, refused, expired, disconnected, paused by the server).
export type Notice = { id: string; kind: 'mirror'; state: string; title: string; body: string; link: string; at: string; read: boolean };

export const notices = $state<{ items: Notice[]; unread: number; state: 'loading' | 'ready' | 'failed'; error: string | null }>({
	items: [],
	unread: 0,
	state: 'loading',
	error: null
});

export async function loadNotices() {
	try {
		const listing = await request<{ items: Notice[]; unread: number }>('GET', '/api/me/notifications');
		notices.items = listing.items;
		notices.unread = listing.unread;
		notices.state = 'ready';
		notices.error = null;
	} catch (err) {
		notices.state = 'failed';
		notices.error = err instanceof Error ? err.message : 'Something went wrong.';
	}
}

// Marks read here at once and tells the server; a refusal puts them back. No ids marks every unread one.
export async function markRead(ids?: string[]) {
	const before = $state.snapshot(notices);
	const hit = (n: Notice) => !n.read && (!ids || ids.includes(n.id));
	const marked = notices.items.filter(hit).length;
	notices.items = notices.items.map((n) => (hit(n) ? { ...n, read: true } : n));
	notices.unread = ids ? Math.max(0, notices.unread - marked) : 0;
	try {
		await request<void>('POST', '/api/me/notifications/read', ids ? { ids } : {});
	} catch (err) {
		notices.items = before.items;
		notices.unread = before.unread;
		notices.error = err instanceof Error ? err.message : 'Something went wrong.';
	}
}

// Checks every minute while the tab is visible, and at once when it becomes visible again.
export function watchNotices() {
	void loadNotices();
	const timer = setInterval(() => {
		if (document.visibilityState === 'visible') void loadNotices();
	}, 60_000);
	const visible = () => {
		if (document.visibilityState === 'visible') void loadNotices();
	};
	document.addEventListener('visibilitychange', visible);
	return () => {
		clearInterval(timer);
		document.removeEventListener('visibilitychange', visible);
	};
}