~james/core

core/web/src/lib/notifications.svelte.ts -rw-r--r-- 5.3 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
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
import { getContext, untrack } from "svelte";
import { SvelteMap } from "svelte/reactivity";
import { createBobbinClient } from "#lib/api/client.ts";
import { createDeliberiClient, type DeliberiContext } from "#lib/api/deliberi.ts";
import {
	getUnreadCount,
	hydrateNotifications,
	listNotifications,
	markAllNotificationsRead,
	markEntityNotificationsRead,
	updateNotificationSeen
} from "#lib/api/notifications.ts";
import type {
	CategoryFilter,
	NotificationSummary,
	ReadFilter
} from "#lib/components/notifications/types.ts";
import type { Auth } from "#lib/auth.svelte.ts";

export const NOTIFICATIONS_KEY = Symbol("notifications");

export interface NotificationQuery {
	read?: ReadFilter;
	category?: CategoryFilter;
	limit?: number;
}

export interface Notifications {
	readonly unread: number;
	overlay(rows: NotificationSummary[]): NotificationSummary[];
	/** rows as the server returned them, empty when signed out or deliberi is unconfigured */
	list(query?: NotificationQuery): Promise<NotificationSummary[]>;
	setRead(uri: string, read: boolean): Promise<void>;
	markAllRead(): Promise<void>;
	markEntityVisited(entityUri: string): Promise<void>;
}

const unreadOf = (rows: NotificationSummary[]) => rows.filter((row) => !row.read).length;

// the account-wide count and the per-row read state move together here, so no
// caller can advance one without the other
const createReadState = (initial: number) => {
	let unread = $state(initial);
	const reads = new SvelteMap<string, boolean>();

	return {
		get unread() {
			return unread;
		},
		overlay: (rows: NotificationSummary[]): NotificationSummary[] =>
			rows.map((row) => {
				const read = reads.get(row.uri) ?? row.read;
				return read === row.read ? row : { ...row, read };
			}),
		seed: (rows: NotificationSummary[], total: number) => {
			unread = total;
			for (const row of rows) reads.set(row.uri, row.read);
		},
		mark: (uri: string, read: boolean): boolean => {
			if (reads.get(uri) === read) return false;
			reads.set(uri, read);
			unread = Math.max(0, unread + (read ? -1 : 1));
			return true;
		},
		markAll: () => {
			for (const uri of reads.keys()) reads.set(uri, true);
			unread = 0;
		},
		resync: async (deliberi: DeliberiContext) => {
			unread = await getUnreadCount(deliberi)
				.then((r) => r.count)
				.catch(() => unread);
		}
	};
};

export const createNotifications = (
	auth: Auth,
	deliberiUrl: string | undefined,
	bobbinUrl: string
): Notifications => {
	const state = createReadState(0);

	const client = async (): Promise<DeliberiContext | null> => {
		const did = auth.currentDid;
		if (!did || !deliberiUrl) return null;
		// the agent lands after the did and shouldn't load the list again
		const agent = await untrack(
			() => auth.agent ?? auth.agentFor(did, { relogin: false }).catch(() => null)
		);
		return agent ? createDeliberiClient({ deliberiUrl, agent }) : null;
	};

	// the bell and a page's own list load together and share one count
	let counting: { did: string; count: Promise<{ count: number }> } | null = null;
	const unreadCount = (deliberi: DeliberiContext) => {
		const did = deliberi.agent.sub;
		if (counting?.did !== did) {
			const count = getUnreadCount(deliberi).finally(() => {
				if (counting?.count === count) counting = null;
			});
			counting = { did, count };
		}
		return counting.count;
	};

	const list = async (query: NotificationQuery = {}): Promise<NotificationSummary[]> => {
		const deliberi = await client();
		if (!deliberi) return [];
		const [count, page] = await Promise.all([
			unreadCount(deliberi),
			listNotifications(deliberi, {
				read: query.read,
				category: query.category === "all" ? undefined : query.category,
				limit: query.limit
			})
		]);
		const rows = await hydrateNotifications(
			createBobbinClient({ serviceUrl: bobbinUrl }),
			page.notifications
		);
		state.seed(rows, count.count);
		return rows;
	};

	const setRead = async (uri: string, read: boolean): Promise<void> => {
		if (!state.mark(uri, read)) return;
		const deliberi = await client();
		if (!deliberi) return;
		await updateNotificationSeen(deliberi, { uri, read }).catch(() => state.resync(deliberi));
	};

	const markAllRead = async (): Promise<void> => {
		state.markAll();
		const deliberi = await client();
		if (!deliberi) return;
		await markAllNotificationsRead(deliberi).catch(() => state.resync(deliberi));
	};

	const markEntityVisited = async (entityUri: string): Promise<void> => {
		// yield first so the call lands outside the $effect that invoked it
		await Promise.resolve();
		const deliberi = await client();
		if (!deliberi) return;
		await markEntityNotificationsRead(deliberi, entityUri).catch(() => {});
		await state.resync(deliberi);
	};

	return {
		get unread() {
			return state.unread;
		},
		overlay: state.overlay,
		list,
		setRead,
		markAllRead,
		markEntityVisited
	};
};

/** storybook and tests: same surface, no network */
export const createFixtureNotifications = (rows: NotificationSummary[]): Notifications => {
	const state = createReadState(unreadOf(rows));
	state.seed(rows, unreadOf(rows));

	return {
		get unread() {
			return state.unread;
		},
		overlay: state.overlay,
		list: async () => rows,
		setRead: async (uri, read) => void state.mark(uri, read),
		markAllRead: async () => state.markAll(),
		markEntityVisited: async () => {}
	};
};

export const getNotifications = () => getContext<Notifications>(NOTIFICATIONS_KEY);