@dovetail-ts/notifications 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +139 -2
- package/addon-main.cjs +4 -0
- package/declarations/activity.d.ts +43 -0
- package/declarations/activity.d.ts.map +1 -0
- package/declarations/components/dovetail/activity-feed.d.ts +34 -0
- package/declarations/components/dovetail/activity-feed.d.ts.map +1 -0
- package/declarations/components/dovetail/inbox-button.d.ts +19 -0
- package/declarations/components/dovetail/inbox-button.d.ts.map +1 -0
- package/declarations/components/dovetail/inbox.d.ts +33 -0
- package/declarations/components/dovetail/inbox.d.ts.map +1 -0
- package/declarations/components/dovetail/toast-bridge.d.ts +24 -0
- package/declarations/components/dovetail/toast-bridge.d.ts.map +1 -0
- package/declarations/format.d.ts +3 -0
- package/declarations/format.d.ts.map +1 -0
- package/declarations/inbox.d.ts +99 -0
- package/declarations/inbox.d.ts.map +1 -0
- package/declarations/index.d.ts +15 -0
- package/declarations/index.d.ts.map +1 -0
- package/declarations/toasts.d.ts +31 -0
- package/declarations/toasts.d.ts.map +1 -0
- package/declarations/when-visible.d.ts +9 -0
- package/declarations/when-visible.d.ts.map +1 -0
- package/dist/_app_/components/dovetail/activity-feed.js +1 -0
- package/dist/_app_/components/dovetail/inbox-button.js +1 -0
- package/dist/_app_/components/dovetail/inbox.js +1 -0
- package/dist/_app_/components/dovetail/toast-bridge.js +1 -0
- package/dist/activity-feed-CO_8ZYII.js +165 -0
- package/dist/activity-feed-CO_8ZYII.js.map +1 -0
- package/dist/components/dovetail/activity-feed.js +10 -0
- package/dist/components/dovetail/activity-feed.js.map +1 -0
- package/dist/components/dovetail/inbox-button.js +32 -0
- package/dist/components/dovetail/inbox-button.js.map +1 -0
- package/dist/components/dovetail/inbox.js +88 -0
- package/dist/components/dovetail/inbox.js.map +1 -0
- package/dist/components/dovetail/toast-bridge.js +7 -0
- package/dist/components/dovetail/toast-bridge.js.map +1 -0
- package/dist/format-CnYSfbv5.js +8 -0
- package/dist/format-CnYSfbv5.js.map +1 -0
- package/dist/index.js +406 -0
- package/dist/index.js.map +1 -0
- package/dist/toast-bridge-CJ7iWI9Q.js +95 -0
- package/dist/toast-bridge-CJ7iWI9Q.js.map +1 -0
- package/package.json +99 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
import { tracked } from '@glimmer/tracking';
|
|
2
|
+
import { NOTIFICATION_TYPE, userRoom } from '@dovetail-ts/protocol';
|
|
3
|
+
import { g, i } from 'decorator-transforms/runtime';
|
|
4
|
+
export { A as ActivityFeed, a as ActivityLog, d as describeGroup, g as groupActivity, n as notificationActivity } from './activity-feed-CO_8ZYII.js';
|
|
5
|
+
export { T as ToastBridge, b as bridgeToasts } from './toast-bridge-CJ7iWI9Q.js';
|
|
6
|
+
export { default as Inbox } from './components/dovetail/inbox.js';
|
|
7
|
+
export { default as InboxButton } from './components/dovetail/inbox-button.js';
|
|
8
|
+
|
|
9
|
+
// The inbox model (ADR 0009, ADR 0016, ADR 0025). It is a plain tracked model that the store sink
|
|
10
|
+
// feeds: the host gives `inbox.sink(inner)` to its SyncClient, so the feed of the per-user room and
|
|
11
|
+
// the optimistic changes of the ledger both arrive here. The sink gets the ops of all rooms, so
|
|
12
|
+
// only the feed of the per-user room and the HTTP pages can add a notification. Mark read and archive are writes through the
|
|
13
|
+
// SyncClient, so they are optimistic and queue offline.
|
|
14
|
+
const isNotification = r => r.type === NOTIFICATION_TYPE && typeof r.attributes?.['verb'] === 'string';
|
|
15
|
+
|
|
16
|
+
/** `before` with the read, seen and archived times of `resource`, and no other change. */
|
|
17
|
+
function withTimes(before, resource) {
|
|
18
|
+
const attributes = {
|
|
19
|
+
...before.attributes
|
|
20
|
+
};
|
|
21
|
+
for (const key of ['readAt', 'seenAt', 'archivedAt']) {
|
|
22
|
+
if (key in resource.attributes) attributes[key] = resource.attributes[key] ?? null;
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
...before,
|
|
26
|
+
attributes
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function toItem(resource) {
|
|
30
|
+
const {
|
|
31
|
+
verb,
|
|
32
|
+
createdAt,
|
|
33
|
+
readAt,
|
|
34
|
+
archivedAt
|
|
35
|
+
} = resource.attributes;
|
|
36
|
+
return {
|
|
37
|
+
id: resource.id,
|
|
38
|
+
verb,
|
|
39
|
+
actor: resource.relationships.actor.data,
|
|
40
|
+
target: resource.relationships.target.data,
|
|
41
|
+
createdAt,
|
|
42
|
+
readAt,
|
|
43
|
+
archivedAt: archivedAt ?? null,
|
|
44
|
+
read: readAt !== null,
|
|
45
|
+
resource
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The notifications of one user: the loaded pages and the live feed, the unread count, and the
|
|
51
|
+
* actions mark read, archive and mark all read.
|
|
52
|
+
*/
|
|
53
|
+
class NotificationInbox {
|
|
54
|
+
static {
|
|
55
|
+
g(this.prototype, "records", [tracked], function () {
|
|
56
|
+
return new Map();
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
#records = (i(this, "records"), void 0);
|
|
60
|
+
static {
|
|
61
|
+
g(this.prototype, "hiddenUnread", [tracked], function () {
|
|
62
|
+
return 0;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
#hiddenUnread = (i(this, "hiddenUnread"), void 0);
|
|
66
|
+
/** The unread notifications on the server that are not loaded. */
|
|
67
|
+
static {
|
|
68
|
+
g(this.prototype, "next", [tracked], function () {
|
|
69
|
+
return undefined;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
#next = (i(this, "next"), void 0);
|
|
73
|
+
/** The cursor of the next page: undefined before the first page, null after the last page. */
|
|
74
|
+
static {
|
|
75
|
+
g(this.prototype, "state", [tracked], function () {
|
|
76
|
+
return 'idle';
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
#state = (i(this, "state"), void 0);
|
|
80
|
+
static {
|
|
81
|
+
g(this.prototype, "error", [tracked], function () {
|
|
82
|
+
return undefined;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
#error = (i(this, "error"), void 0);
|
|
86
|
+
/** The message of the last error, or undefined. */
|
|
87
|
+
#options;
|
|
88
|
+
#client;
|
|
89
|
+
#paging = false;
|
|
90
|
+
/** True while an op of the per-user room feed or of an HTTP page goes through the ledger. */
|
|
91
|
+
#trusted = false;
|
|
92
|
+
#oldest;
|
|
93
|
+
#listeners = new Set();
|
|
94
|
+
/** The request that failed last, for `retry()`. */
|
|
95
|
+
#failedRequest;
|
|
96
|
+
/** Stops the wait of an offline "mark all as read" for the connection. */
|
|
97
|
+
#stopReadAll;
|
|
98
|
+
constructor(options) {
|
|
99
|
+
this.#options = options;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The notifications that are not archived, the newest first. */
|
|
103
|
+
get items() {
|
|
104
|
+
return [...this.records.values()].filter(r => !r.attributes.archivedAt).sort((a, b) => b.attributes.createdAt.localeCompare(a.attributes.createdAt)).map(toItem);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The unread items that are loaded. */
|
|
108
|
+
get unreadItems() {
|
|
109
|
+
return this.items.filter(item => !item.read);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The number of unread notifications on the server, with the local changes. */
|
|
113
|
+
get unread() {
|
|
114
|
+
return this.unreadItems.length + this.hiddenUnread;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** True when the server has older pages. */
|
|
118
|
+
get hasMore() {
|
|
119
|
+
return typeof this.next === 'string';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** True after the first page loaded. */
|
|
123
|
+
get loaded() {
|
|
124
|
+
return this.next !== undefined;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The text of an item. An arrow function, so a template can call `@inbox.describe`. */
|
|
128
|
+
describe = item => this.#options.describe?.(item) ?? `${item.actor.id} ${item.verb} on ${item.target.type} ${item.target.id}`;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The sink to give the SyncClient. It keeps the notifications, and gives each op to `inner`
|
|
132
|
+
* too (for example `storeSink(store)` of `@dovetail-ts/warp-drive`).
|
|
133
|
+
*/
|
|
134
|
+
sink(inner) {
|
|
135
|
+
return {
|
|
136
|
+
apply: op => {
|
|
137
|
+
this.#apply(op);
|
|
138
|
+
inner?.apply(op);
|
|
139
|
+
},
|
|
140
|
+
peek: ref => ref.type === NOTIFICATION_TYPE ? this.records.get(ref.id) : inner?.peek?.(ref)
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Joins the per-user room on `client`, and loads the first page. Returns a function that stops
|
|
146
|
+
* it.
|
|
147
|
+
*/
|
|
148
|
+
connect(client) {
|
|
149
|
+
this.#client = client;
|
|
150
|
+
const room = userRoom(this.#options.userId);
|
|
151
|
+
const release = client.connection.retain(room);
|
|
152
|
+
const stopFeed = client.connection.onFeed(room, message => this.#trust(() => {
|
|
153
|
+
for (const op of message.ops) client.ledger.receive(op);
|
|
154
|
+
}));
|
|
155
|
+
// A reset join lost the changes after the cursor of the client (ADR 0024): load again.
|
|
156
|
+
const stopReset = client.connection.onReset(room, () => void this.load());
|
|
157
|
+
void this.load();
|
|
158
|
+
return () => {
|
|
159
|
+
stopFeed();
|
|
160
|
+
stopReset();
|
|
161
|
+
release();
|
|
162
|
+
this.#stopReadAll?.();
|
|
163
|
+
this.#stopReadAll = undefined;
|
|
164
|
+
if (this.#client === client) this.#client = undefined;
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Calls `listener` for each new notification of the live feed. Returns a function that stops it. */
|
|
169
|
+
onNotification(listener) {
|
|
170
|
+
this.#listeners.add(listener);
|
|
171
|
+
return () => this.#listeners.delete(listener);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Loads the first page again. */
|
|
175
|
+
load() {
|
|
176
|
+
return this.#page(undefined);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Loads the next older page. */
|
|
180
|
+
async loadMore() {
|
|
181
|
+
if (typeof this.next === 'string') await this.#page(this.next);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Sends the request that failed last again, or loads the first page. */
|
|
185
|
+
retry() {
|
|
186
|
+
const request = this.#failedRequest ?? (() => this.load());
|
|
187
|
+
this.#failedRequest = undefined;
|
|
188
|
+
return request();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Marks one notification as read. Optimistic: it queues while offline. */
|
|
192
|
+
async markRead(id) {
|
|
193
|
+
const record = this.records.get(id);
|
|
194
|
+
if (!record || record.attributes.readAt) return;
|
|
195
|
+
await this.#write(id, {
|
|
196
|
+
readAt: this.#now()
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Archives one notification. Optimistic: it queues while offline. */
|
|
201
|
+
async archive(id) {
|
|
202
|
+
if (!this.records.has(id)) return;
|
|
203
|
+
await this.#write(id, {
|
|
204
|
+
archivedAt: this.#now()
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Marks each unread notification as read, with `POST /notifications/read-all`. The change shows
|
|
210
|
+
* at once, and rolls back when the request fails. Offline, each loaded unread item gets a
|
|
211
|
+
* queued mark read, and the request goes when the connection opens again.
|
|
212
|
+
*/
|
|
213
|
+
async markAllRead() {
|
|
214
|
+
const connection = this.#client?.connection;
|
|
215
|
+
if (connection && !connection.isOnline) {
|
|
216
|
+
const at = this.#now();
|
|
217
|
+
for (const item of this.unreadItems) await this.#write(item.id, {
|
|
218
|
+
readAt: at
|
|
219
|
+
});
|
|
220
|
+
this.hiddenUnread = 0;
|
|
221
|
+
this.#stopReadAll ??= connection.onStateChange(() => {
|
|
222
|
+
if (!connection.isOpen) return;
|
|
223
|
+
this.#stopReadAll?.();
|
|
224
|
+
this.#stopReadAll = undefined;
|
|
225
|
+
void this.markAllRead();
|
|
226
|
+
});
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const before = this.unreadItems.map(item => item.resource);
|
|
230
|
+
const hidden = this.hiddenUnread;
|
|
231
|
+
const at = this.#now();
|
|
232
|
+
this.#receive(before.map(r => ({
|
|
233
|
+
...r,
|
|
234
|
+
attributes: {
|
|
235
|
+
...r.attributes,
|
|
236
|
+
readAt: at
|
|
237
|
+
}
|
|
238
|
+
})));
|
|
239
|
+
this.hiddenUnread = 0;
|
|
240
|
+
try {
|
|
241
|
+
await this.#request('POST', '/notifications/read-all');
|
|
242
|
+
this.error = undefined;
|
|
243
|
+
this.state = 'idle';
|
|
244
|
+
} catch (error) {
|
|
245
|
+
this.#receive(before);
|
|
246
|
+
this.hiddenUnread = hidden;
|
|
247
|
+
this.#failed(error, () => this.markAllRead());
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
#now() {
|
|
251
|
+
return new Date((this.#options.now ?? Date.now)()).toISOString();
|
|
252
|
+
}
|
|
253
|
+
async #write(id, attributes) {
|
|
254
|
+
const client = this.#client;
|
|
255
|
+
if (!client) throw new Error('NotificationInbox: call connect(client) first');
|
|
256
|
+
if (!this.records.has(id)) return;
|
|
257
|
+
// A partial notification (ADR 0024): only the time that changes. The server sets a time only
|
|
258
|
+
// when it is null, and acks with the full record. The ledger merges the time into the local
|
|
259
|
+
// record, so the change shows at once.
|
|
260
|
+
const data = {
|
|
261
|
+
type: NOTIFICATION_TYPE,
|
|
262
|
+
id,
|
|
263
|
+
attributes
|
|
264
|
+
};
|
|
265
|
+
await client.write(userRoom(this.#options.userId), {
|
|
266
|
+
op: 'upsert',
|
|
267
|
+
document: {
|
|
268
|
+
data
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
async #page(before) {
|
|
273
|
+
this.state = 'loading';
|
|
274
|
+
try {
|
|
275
|
+
const query = new URLSearchParams({
|
|
276
|
+
filter: 'all',
|
|
277
|
+
limit: String(this.#options.pageSize ?? 20)
|
|
278
|
+
});
|
|
279
|
+
if (before) query.set('before', before);
|
|
280
|
+
const page = await (await this.#request('GET', `/notifications?${query}`)).json();
|
|
281
|
+
this.#receive(page.data);
|
|
282
|
+
const last = page.data.at(-1);
|
|
283
|
+
if (last) this.#oldest = last.attributes.createdAt;
|
|
284
|
+
this.next = page.meta.next;
|
|
285
|
+
this.hiddenUnread = page.meta.next ? Math.max(0, page.meta.unread - this.unreadItems.length) : 0;
|
|
286
|
+
this.error = undefined;
|
|
287
|
+
this.state = 'idle';
|
|
288
|
+
} catch (error) {
|
|
289
|
+
this.#failed(error, () => this.#page(before));
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Puts server records through the ledger, so they rebase on the pending writes. */
|
|
294
|
+
#receive(resources) {
|
|
295
|
+
this.#paging = true;
|
|
296
|
+
try {
|
|
297
|
+
this.#trust(() => {
|
|
298
|
+
for (const data of resources) {
|
|
299
|
+
const op = {
|
|
300
|
+
op: 'upsert',
|
|
301
|
+
document: {
|
|
302
|
+
data
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
if (this.#client) this.#client.ledger.receive(op);else this.#apply(op);
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
} finally {
|
|
309
|
+
this.#paging = false;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Runs `work` with the trust of the per-user room: it can add and delete notifications. */
|
|
314
|
+
#trust(work) {
|
|
315
|
+
const before = this.#trusted;
|
|
316
|
+
this.#trusted = true;
|
|
317
|
+
try {
|
|
318
|
+
work();
|
|
319
|
+
} finally {
|
|
320
|
+
this.#trusted = before;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** The unread count of the server, after a change to a notification that is not loaded. */
|
|
325
|
+
async #refreshCount() {
|
|
326
|
+
try {
|
|
327
|
+
const page = await (await this.#request('GET', '/notifications?filter=unread&limit=1')).json();
|
|
328
|
+
this.hiddenUnread = Math.max(0, page.meta.unread - this.unreadItems.length);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
this.#failed(error, () => this.#refreshCount());
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
async #request(method, path) {
|
|
334
|
+
const token = await this.#options.getToken?.();
|
|
335
|
+
const fetch = this.#options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
336
|
+
const response = await fetch(`${this.#options.url ?? ''}${path}`, {
|
|
337
|
+
method,
|
|
338
|
+
headers: {
|
|
339
|
+
accept: 'application/vnd.api+json',
|
|
340
|
+
...(token ? {
|
|
341
|
+
authorization: `Bearer ${token}`
|
|
342
|
+
} : {})
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
if (!response.ok) throw new Error(`The server answered ${response.status}.`);
|
|
346
|
+
return response;
|
|
347
|
+
}
|
|
348
|
+
#failed(error, request) {
|
|
349
|
+
this.#failedRequest = request;
|
|
350
|
+
this.error = error instanceof Error ? error.message : String(error);
|
|
351
|
+
this.state = 'error';
|
|
352
|
+
}
|
|
353
|
+
#apply(op) {
|
|
354
|
+
const trusted = this.#trusted;
|
|
355
|
+
if (op.op === 'delete') {
|
|
356
|
+
if (!trusted || op.ref.type !== NOTIFICATION_TYPE || !this.records.has(op.ref.id)) return;
|
|
357
|
+
const records = new Map(this.records);
|
|
358
|
+
records.delete(op.ref.id);
|
|
359
|
+
this.records = records;
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
const {
|
|
363
|
+
data,
|
|
364
|
+
included
|
|
365
|
+
} = op.document;
|
|
366
|
+
const resources = [...(Array.isArray(data) ? data : data ? [data] : []), ...(included ?? [])];
|
|
367
|
+
const records = new Map(this.records);
|
|
368
|
+
const added = [];
|
|
369
|
+
let changed = false;
|
|
370
|
+
for (const resource of resources.filter(isNotification)) {
|
|
371
|
+
const before = records.get(resource.id);
|
|
372
|
+
// Another room can send a notification resource too. It cannot add one.
|
|
373
|
+
if (!before && !trusted) continue;
|
|
374
|
+
if (!before && !this.#paging && this.#isOld(resource)) {
|
|
375
|
+
// A change to a notification of a page that is not loaded: only the count changes.
|
|
376
|
+
void this.#refreshCount();
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
// Outside the trust, only the times change: the local writes, their acks and rollbacks
|
|
380
|
+
// change nothing more. Another room cannot change the text of a notification.
|
|
381
|
+
records.set(resource.id, trusted || !before ? {
|
|
382
|
+
...before,
|
|
383
|
+
...resource,
|
|
384
|
+
attributes: {
|
|
385
|
+
...before?.attributes,
|
|
386
|
+
...resource.attributes
|
|
387
|
+
}
|
|
388
|
+
} : withTimes(before, resource));
|
|
389
|
+
changed = true;
|
|
390
|
+
if (!before && !this.#paging) added.push(resource);
|
|
391
|
+
}
|
|
392
|
+
if (!changed) return;
|
|
393
|
+
this.records = records;
|
|
394
|
+
for (const resource of added) {
|
|
395
|
+
for (const listener of [...this.#listeners]) listener(toItem(resource));
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** True when `resource` is older than the loaded pages, and older pages exist. */
|
|
400
|
+
#isOld(resource) {
|
|
401
|
+
return this.hasMore && this.#oldest !== undefined && resource.attributes.createdAt < this.#oldest;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export { NotificationInbox };
|
|
406
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/inbox.ts"],"sourcesContent":["// The inbox model (ADR 0009, ADR 0016, ADR 0025). It is a plain tracked model that the store sink\n// feeds: the host gives `inbox.sink(inner)` to its SyncClient, so the feed of the per-user room and\n// the optimistic changes of the ledger both arrive here. The sink gets the ops of all rooms, so\n// only the feed of the per-user room and the HTTP pages can add a notification. Mark read and archive are writes through the\n// SyncClient, so they are optimistic and queue offline.\nimport { tracked } from '@glimmer/tracking'\nimport { NOTIFICATION_TYPE, userRoom } from '@dovetail-ts/protocol'\nimport type {\n NotificationResource,\n Resource,\n ResourceIdentifier,\n StoreOp,\n} from '@dovetail-ts/protocol'\nimport type { StoreSink, SyncClient } from '@dovetail-ts/core'\n\n/** One notification, as the UI shows it. */\nexport interface NotificationItem {\n id: string\n verb: string\n actor: ResourceIdentifier\n target: ResourceIdentifier\n /** An ISO 8601 date-time. */\n createdAt: string\n readAt: string | null\n archivedAt: string | null\n /** True when `readAt` has a value. */\n read: boolean\n /** The JSON:API resource, with all its attributes. */\n resource: NotificationResource\n}\n\nexport interface InboxOptions {\n /** The id of the user. The inbox subscribes to the per-user room (`user:<id>`). */\n userId: string\n /**\n * Sends the HTTP requests (`GET /notifications`, `POST /notifications/read-all`). The default\n * is the global `fetch`.\n */\n fetch?: (url: string, init?: RequestInit) => Promise<Response>\n /** The base URL of the HTTP routes of the server. The default is `''` (the same origin). */\n url?: string\n /**\n * The token of the user. The inbox calls it before each HTTP request, and sends the token as\n * `Authorization: Bearer <token>`. It is necessary when the server has an `authenticate` hook:\n * such a server refuses a request with no token with 401, unless it sets `allowAnonymous`.\n */\n getToken?: () => string | undefined | Promise<string | undefined>\n /** The size of a page. The default is 20. */\n pageSize?: number\n /** The clock of the read and archive times. The default is `Date.now`. */\n now?: () => number\n /** The text of a notification. The default is `<actor id> <verb> on <target type> <target id>`. */\n describe?: (item: NotificationItem) => string\n}\n\n/** `idle`, `loading` (a page or a request is in progress) or `error` (the last request failed). */\nexport type InboxState = 'idle' | 'loading' | 'error'\n\ninterface Page {\n data: NotificationResource[]\n meta: { next: string | null; unread: number }\n}\n\nconst isNotification = (r: Resource): r is NotificationResource =>\n r.type === NOTIFICATION_TYPE && typeof r.attributes?.['verb'] === 'string'\n\n/** `before` with the read, seen and archived times of `resource`, and no other change. */\nfunction withTimes(\n before: NotificationResource,\n resource: NotificationResource,\n): NotificationResource {\n const attributes = { ...before.attributes }\n for (const key of ['readAt', 'seenAt', 'archivedAt'] as const) {\n if (key in resource.attributes) attributes[key] = resource.attributes[key] ?? null\n }\n return { ...before, attributes }\n}\n\nfunction toItem(resource: NotificationResource): NotificationItem {\n const { verb, createdAt, readAt, archivedAt } = resource.attributes\n return {\n id: resource.id,\n verb,\n actor: resource.relationships.actor.data,\n target: resource.relationships.target.data,\n createdAt,\n readAt,\n archivedAt: archivedAt ?? null,\n read: readAt !== null,\n resource,\n }\n}\n\n/**\n * The notifications of one user: the loaded pages and the live feed, the unread count, and the\n * actions mark read, archive and mark all read.\n */\nexport class NotificationInbox {\n @tracked private records = new Map<string, NotificationResource>()\n /** The unread notifications on the server that are not loaded. */\n @tracked private hiddenUnread = 0\n /** The cursor of the next page: undefined before the first page, null after the last page. */\n @tracked private next: string | null | undefined = undefined\n @tracked state: InboxState = 'idle'\n /** The message of the last error, or undefined. */\n @tracked error: string | undefined = undefined\n\n readonly #options: InboxOptions\n #client: SyncClient | undefined\n #paging = false\n /** True while an op of the per-user room feed or of an HTTP page goes through the ledger. */\n #trusted = false\n #oldest: string | undefined\n #listeners = new Set<(item: NotificationItem) => void>()\n /** The request that failed last, for `retry()`. */\n #failedRequest: (() => Promise<void>) | undefined\n /** Stops the wait of an offline \"mark all as read\" for the connection. */\n #stopReadAll: (() => void) | undefined\n\n constructor(options: InboxOptions) {\n this.#options = options\n }\n\n /** The notifications that are not archived, the newest first. */\n get items(): NotificationItem[] {\n return [...this.records.values()]\n .filter(r => !r.attributes.archivedAt)\n .sort((a, b) => b.attributes.createdAt.localeCompare(a.attributes.createdAt))\n .map(toItem)\n }\n\n /** The unread items that are loaded. */\n get unreadItems(): NotificationItem[] {\n return this.items.filter(item => !item.read)\n }\n\n /** The number of unread notifications on the server, with the local changes. */\n get unread(): number {\n return this.unreadItems.length + this.hiddenUnread\n }\n\n /** True when the server has older pages. */\n get hasMore(): boolean {\n return typeof this.next === 'string'\n }\n\n /** True after the first page loaded. */\n get loaded(): boolean {\n return this.next !== undefined\n }\n\n /** The text of an item. An arrow function, so a template can call `@inbox.describe`. */\n describe = (item: NotificationItem): string =>\n this.#options.describe?.(item) ??\n `${item.actor.id} ${item.verb} on ${item.target.type} ${item.target.id}`\n\n /**\n * The sink to give the SyncClient. It keeps the notifications, and gives each op to `inner`\n * too (for example `storeSink(store)` of `@dovetail-ts/warp-drive`).\n */\n sink(inner?: StoreSink): StoreSink {\n return {\n apply: op => {\n this.#apply(op)\n inner?.apply(op)\n },\n peek: ref => (ref.type === NOTIFICATION_TYPE ? this.records.get(ref.id) : inner?.peek?.(ref)),\n }\n }\n\n /**\n * Joins the per-user room on `client`, and loads the first page. Returns a function that stops\n * it.\n */\n connect(client: SyncClient): () => void {\n this.#client = client\n const room = userRoom(this.#options.userId)\n const release = client.connection.retain(room)\n const stopFeed = client.connection.onFeed(room, message =>\n this.#trust(() => {\n for (const op of message.ops) client.ledger.receive(op)\n }),\n )\n // A reset join lost the changes after the cursor of the client (ADR 0024): load again.\n const stopReset = client.connection.onReset(room, () => void this.load())\n void this.load()\n return () => {\n stopFeed()\n stopReset()\n release()\n this.#stopReadAll?.()\n this.#stopReadAll = undefined\n if (this.#client === client) this.#client = undefined\n }\n }\n\n /** Calls `listener` for each new notification of the live feed. Returns a function that stops it. */\n onNotification(listener: (item: NotificationItem) => void): () => void {\n this.#listeners.add(listener)\n return () => this.#listeners.delete(listener)\n }\n\n /** Loads the first page again. */\n load(): Promise<void> {\n return this.#page(undefined)\n }\n\n /** Loads the next older page. */\n async loadMore(): Promise<void> {\n if (typeof this.next === 'string') await this.#page(this.next)\n }\n\n /** Sends the request that failed last again, or loads the first page. */\n retry(): Promise<void> {\n const request = this.#failedRequest ?? (() => this.load())\n this.#failedRequest = undefined\n return request()\n }\n\n /** Marks one notification as read. Optimistic: it queues while offline. */\n async markRead(id: string): Promise<void> {\n const record = this.records.get(id)\n if (!record || record.attributes.readAt) return\n await this.#write(id, { readAt: this.#now() })\n }\n\n /** Archives one notification. Optimistic: it queues while offline. */\n async archive(id: string): Promise<void> {\n if (!this.records.has(id)) return\n await this.#write(id, { archivedAt: this.#now() })\n }\n\n /**\n * Marks each unread notification as read, with `POST /notifications/read-all`. The change shows\n * at once, and rolls back when the request fails. Offline, each loaded unread item gets a\n * queued mark read, and the request goes when the connection opens again.\n */\n async markAllRead(): Promise<void> {\n const connection = this.#client?.connection\n if (connection && !connection.isOnline) {\n const at = this.#now()\n for (const item of this.unreadItems) await this.#write(item.id, { readAt: at })\n this.hiddenUnread = 0\n this.#stopReadAll ??= connection.onStateChange(() => {\n if (!connection.isOpen) return\n this.#stopReadAll?.()\n this.#stopReadAll = undefined\n void this.markAllRead()\n })\n return\n }\n const before = this.unreadItems.map(item => item.resource)\n const hidden = this.hiddenUnread\n const at = this.#now()\n this.#receive(before.map(r => ({ ...r, attributes: { ...r.attributes, readAt: at } })))\n this.hiddenUnread = 0\n try {\n await this.#request('POST', '/notifications/read-all')\n this.error = undefined\n this.state = 'idle'\n } catch (error) {\n this.#receive(before)\n this.hiddenUnread = hidden\n this.#failed(error, () => this.markAllRead())\n }\n }\n\n #now(): string {\n return new Date((this.#options.now ?? Date.now)()).toISOString()\n }\n\n async #write(id: string, attributes: Record<string, string>): Promise<void> {\n const client = this.#client\n if (!client) throw new Error('NotificationInbox: call connect(client) first')\n if (!this.records.has(id)) return\n // A partial notification (ADR 0024): only the time that changes. The server sets a time only\n // when it is null, and acks with the full record. The ledger merges the time into the local\n // record, so the change shows at once.\n const data = { type: NOTIFICATION_TYPE, id, attributes }\n await client.write(userRoom(this.#options.userId), { op: 'upsert', document: { data } })\n }\n\n async #page(before: string | undefined): Promise<void> {\n this.state = 'loading'\n try {\n const query = new URLSearchParams({\n filter: 'all',\n limit: String(this.#options.pageSize ?? 20),\n })\n if (before) query.set('before', before)\n const page = (await (await this.#request('GET', `/notifications?${query}`)).json()) as Page\n this.#receive(page.data)\n const last = page.data.at(-1)\n if (last) this.#oldest = last.attributes.createdAt\n this.next = page.meta.next\n this.hiddenUnread = page.meta.next\n ? Math.max(0, page.meta.unread - this.unreadItems.length)\n : 0\n this.error = undefined\n this.state = 'idle'\n } catch (error) {\n this.#failed(error, () => this.#page(before))\n }\n }\n\n /** Puts server records through the ledger, so they rebase on the pending writes. */\n #receive(resources: NotificationResource[]): void {\n this.#paging = true\n try {\n this.#trust(() => {\n for (const data of resources) {\n const op: StoreOp = { op: 'upsert', document: { data } }\n if (this.#client) this.#client.ledger.receive(op)\n else this.#apply(op)\n }\n })\n } finally {\n this.#paging = false\n }\n }\n\n /** Runs `work` with the trust of the per-user room: it can add and delete notifications. */\n #trust(work: () => void): void {\n const before = this.#trusted\n this.#trusted = true\n try {\n work()\n } finally {\n this.#trusted = before\n }\n }\n\n /** The unread count of the server, after a change to a notification that is not loaded. */\n async #refreshCount(): Promise<void> {\n try {\n const page = (await (\n await this.#request('GET', '/notifications?filter=unread&limit=1')\n ).json()) as Page\n this.hiddenUnread = Math.max(0, page.meta.unread - this.unreadItems.length)\n } catch (error) {\n this.#failed(error, () => this.#refreshCount())\n }\n }\n\n async #request(method: string, path: string): Promise<Response> {\n const token = await this.#options.getToken?.()\n const fetch = this.#options.fetch ?? globalThis.fetch.bind(globalThis)\n const response = await fetch(`${this.#options.url ?? ''}${path}`, {\n method,\n headers: {\n accept: 'application/vnd.api+json',\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n })\n if (!response.ok) throw new Error(`The server answered ${response.status}.`)\n return response\n }\n\n #failed(error: unknown, request: () => Promise<void>): void {\n this.#failedRequest = request\n this.error = error instanceof Error ? error.message : String(error)\n this.state = 'error'\n }\n\n #apply(op: StoreOp): void {\n const trusted = this.#trusted\n if (op.op === 'delete') {\n if (!trusted || op.ref.type !== NOTIFICATION_TYPE || !this.records.has(op.ref.id)) return\n const records = new Map(this.records)\n records.delete(op.ref.id)\n this.records = records\n return\n }\n const { data, included } = op.document\n const resources = [...(Array.isArray(data) ? data : data ? [data] : []), ...(included ?? [])]\n const records = new Map(this.records)\n const added: NotificationResource[] = []\n let changed = false\n for (const resource of resources.filter(isNotification)) {\n const before = records.get(resource.id)\n // Another room can send a notification resource too. It cannot add one.\n if (!before && !trusted) continue\n if (!before && !this.#paging && this.#isOld(resource)) {\n // A change to a notification of a page that is not loaded: only the count changes.\n void this.#refreshCount()\n continue\n }\n // Outside the trust, only the times change: the local writes, their acks and rollbacks\n // change nothing more. Another room cannot change the text of a notification.\n records.set(\n resource.id,\n trusted || !before\n ? {\n ...before,\n ...resource,\n attributes: { ...before?.attributes, ...resource.attributes },\n }\n : withTimes(before, resource),\n )\n changed = true\n if (!before && !this.#paging) added.push(resource)\n }\n if (!changed) return\n this.records = records\n for (const resource of added) {\n for (const listener of [...this.#listeners]) listener(toItem(resource))\n }\n }\n\n /** True when `resource` is older than the loaded pages, and older pages exist. */\n #isOld(resource: NotificationResource): boolean {\n return (\n this.hasMore && this.#oldest !== undefined && resource.attributes.createdAt < this.#oldest\n )\n }\n}\n"],"names":["isNotification","r","type","NOTIFICATION_TYPE","attributes","withTimes","before","resource","key","toItem","verb","createdAt","readAt","archivedAt","id","actor","relationships","data","target","read","NotificationInbox","g","prototype","tracked","Map","i","undefined","Set","constructor","options","items","records","values","filter","sort","a","b","localeCompare","map","unreadItems","item","unread","length","hiddenUnread","hasMore","next","loaded","describe","sink","inner","apply","op","peek","ref","get","connect","client","room","userRoom","userId","release","connection","retain","stopFeed","onFeed","message","ops","ledger","receive","stopReset","onReset","load","onNotification","listener","add","delete","loadMore","retry","request","markRead","record","archive","has","markAllRead","isOnline","at","onStateChange","isOpen","hidden","error","state","#now","Date","now","toISOString","#write","Error","write","document","#page","query","URLSearchParams","limit","String","pageSize","set","page","json","last","meta","Math","max","#receive","resources","#trust","work","#refreshCount","#request","method","path","token","getToken","fetch","globalThis","bind","response","url","headers","accept","authorization","ok","status","#failed","#apply","trusted","included","Array","isArray","added","changed","push","#isOld"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AA2DA,MAAMA,cAAc,GAAIC,CAAW,IACjCA,CAAC,CAACC,IAAI,KAAKC,iBAAi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Q;AACXH,QAAAA,UAAU,EAAE;UAAE,GAAGE,MAAM,EAAEF,UAAU;AAAE,UAAA,GAAGG,QAAQ,CAACH;AAAW;AAC9D,OAAC,GACDC,SAAS,CAACC,MAAM,EAAEC,QAAQ,CAChC,CAAC;AACDoI,MAAAA,OAAO,GAAG,IAAI;AACd,MAAA,IAAI,CAACrI,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,EAAEoI,KAAK,CAACE,IAAI,CAACrI,QAAQ,CAAC;AACpD,IAAA;IACA,IAAI,CAACoI,OAAO,EAAE;IACd,IAAI,CAAC5G,OAAO,GAAGA,OAAO;AACtB,IAAA,KAAK,MAAMxB,QAAQ,IAAImI,KAAK,EAAE;AAC5B,MAAA,KAAK,MAAMjE,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,EAAEA,QAAQ,CAAChE,MAAM,CAACF,QAAQ,CAAC,CAAC;AACzE,IAAA;AACF,EAAA;;AAEA;EACA,MAAMsI,CAACtI,QAA8B,EAAW;IAC9C,OACE,IAAI,CAACqC,OAAO,IAAI,IAAI,CAAC,OAAO,KAAKlB,SAAS,IAAInB,QAAQ,CAACH,UAAU,CAACO,SAAS,GAAG,IAAI,CAAC,OAAO;AAE9F,EAAA;AACF;;"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import Component from '@glimmer/component';
|
|
2
|
+
import { registerDestructor } from '@ember/destroyable';
|
|
3
|
+
import { toastsFor } from '@ember-joinery/ember';
|
|
4
|
+
import { precompileTemplate } from '@ember/template-compilation';
|
|
5
|
+
import { setComponentTemplate } from '@ember/component';
|
|
6
|
+
|
|
7
|
+
// The toast bridge (ADR 0009). It shows new notifications and sync events in the Joinery
|
|
8
|
+
// Toaster. Dovetail has no toast component: the bridge calls the toast functions of the host.
|
|
9
|
+
|
|
10
|
+
/** The options of one toast: a subset of the `ExternalToast` of Joinery. */
|
|
11
|
+
|
|
12
|
+
/** The toast functions that the bridge uses. `toastsFor(owner)` of `@ember-joinery/ember` fits. */
|
|
13
|
+
|
|
14
|
+
/** The sync events that make a toast. Put a name in `mute` to stop its toasts. */
|
|
15
|
+
|
|
16
|
+
/** Shows the toasts. Returns a function that stops the bridge. */
|
|
17
|
+
function bridgeToasts({
|
|
18
|
+
toasts,
|
|
19
|
+
inbox,
|
|
20
|
+
client,
|
|
21
|
+
types,
|
|
22
|
+
mute = []
|
|
23
|
+
}) {
|
|
24
|
+
const on = name => !mute.includes(name);
|
|
25
|
+
const stops = [];
|
|
26
|
+
if (inbox) {
|
|
27
|
+
stops.push(inbox.onNotification(item => {
|
|
28
|
+
if (item.read || !on(item.verb) || types && !types.includes(item.verb)) return;
|
|
29
|
+
toasts.message(inbox.describe(item), {
|
|
30
|
+
id: `dovetail-notification-${item.id}`
|
|
31
|
+
});
|
|
32
|
+
}));
|
|
33
|
+
}
|
|
34
|
+
if (client) {
|
|
35
|
+
let online = client.state.online;
|
|
36
|
+
const shown = new Set([...client.state.errors.map(e => e.id), ...client.state.deadLetters.map(d => d.id)]);
|
|
37
|
+
const changed = state => {
|
|
38
|
+
if (state.online !== online) {
|
|
39
|
+
online = state.online;
|
|
40
|
+
const id = 'dovetail-network';
|
|
41
|
+
if (!online && on('offline')) {
|
|
42
|
+
toasts.warning('You are offline. Your changes will sync when you are back online.', {
|
|
43
|
+
id
|
|
44
|
+
});
|
|
45
|
+
} else if (online && on('online')) {
|
|
46
|
+
toasts.success('You are back online.', {
|
|
47
|
+
id
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
for (const error of state.errors) {
|
|
52
|
+
if (shown.has(error.id)) continue;
|
|
53
|
+
shown.add(error.id);
|
|
54
|
+
if (!on('rollback')) continue;
|
|
55
|
+
toasts.error('A change was rejected and rolled back.', {
|
|
56
|
+
id: `dovetail-write-${error.id}`
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
for (const letter of state.deadLetters) {
|
|
60
|
+
if (shown.has(letter.id)) continue;
|
|
61
|
+
shown.add(letter.id);
|
|
62
|
+
if (!on('dead-letter')) continue;
|
|
63
|
+
toasts.error('A change could not be saved.', {
|
|
64
|
+
id: `dovetail-write-${letter.id}`
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
stops.push(client.onChange(changed));
|
|
69
|
+
}
|
|
70
|
+
return () => {
|
|
71
|
+
for (const stop of stops.splice(0)) stop();
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Shows notifications and sync events in the Joinery `<Toaster>` of the app. It renders
|
|
77
|
+
* nothing. It reads its arguments once, when it renders.
|
|
78
|
+
*/
|
|
79
|
+
class ToastBridge extends Component {
|
|
80
|
+
constructor(owner, args) {
|
|
81
|
+
super(owner, args);
|
|
82
|
+
registerDestructor(this, bridgeToasts({
|
|
83
|
+
toasts: toastsFor(this),
|
|
84
|
+
...args
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
static {
|
|
88
|
+
setComponentTemplate(precompileTemplate("", {
|
|
89
|
+
strictMode: true
|
|
90
|
+
}), this);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export { ToastBridge as T, bridgeToasts as b };
|
|
95
|
+
//# sourceMappingURL=toast-bridge-CJ7iWI9Q.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"toast-bridge-CJ7iWI9Q.js","sources":["../src/toasts.ts","../src/components/dovetail/toast-bridge.gts"],"sourcesContent":["// The toast bridge (ADR 0009). It shows new notifications and sync events in the Joinery\n// Toaster. Dovetail has no toast component: the bridge calls the toast functions of the host.\nimport type { SyncClient, SyncState } from '@dovetail-ts/core'\nimport type { NotificationInbox } from './inbox.ts'\n\n/** The options of one toast: a subset of the `ExternalToast` of Joinery. */\nexport interface ToastOptions {\n id?: string | number\n}\n\ntype Show = (title: string, options?: ToastOptions) => string | number\n\n/** The toast functions that the bridge uses. `toastsFor(owner)` of `@ember-joinery/ember` fits. */\nexport interface ToastSink {\n message: Show\n success: Show\n warning: Show\n error: Show\n}\n\n/** The sync events that make a toast. Put a name in `mute` to stop its toasts. */\nexport type SyncEvent = 'offline' | 'online' | 'dead-letter' | 'rollback'\n\nexport interface ToastBridgeOptions {\n toasts: ToastSink\n /** The new notifications of this inbox make toasts. */\n inbox?: NotificationInbox\n /** The sync events of this client make toasts. */\n client?: SyncClient\n /** The notification verbs that make a toast. The default is all verbs. */\n types?: readonly string[]\n /** The notification verbs and the sync events that never make a toast. */\n mute?: readonly string[]\n}\n\n/** Shows the toasts. Returns a function that stops the bridge. */\nexport function bridgeToasts({ toasts, inbox, client, types, mute = [] }: ToastBridgeOptions) {\n const on = (name: string) => !mute.includes(name)\n const stops: (() => void)[] = []\n\n if (inbox) {\n stops.push(\n inbox.onNotification(item => {\n if (item.read || !on(item.verb) || (types && !types.includes(item.verb))) return\n toasts.message(inbox.describe(item), { id: `dovetail-notification-${item.id}` })\n }),\n )\n }\n\n if (client) {\n let online = client.state.online\n const shown = new Set<string>([\n ...client.state.errors.map(e => e.id),\n ...client.state.deadLetters.map(d => d.id),\n ])\n const changed = (state: SyncState) => {\n if (state.online !== online) {\n online = state.online\n const id = 'dovetail-network'\n if (!online && on('offline')) {\n toasts.warning('You are offline. Your changes will sync when you are back online.', {\n id,\n })\n } else if (online && on('online')) {\n toasts.success('You are back online.', { id })\n }\n }\n for (const error of state.errors) {\n if (shown.has(error.id)) continue\n shown.add(error.id)\n if (!on('rollback')) continue\n toasts.error('A change was rejected and rolled back.', { id: `dovetail-write-${error.id}` })\n }\n for (const letter of state.deadLetters) {\n if (shown.has(letter.id)) continue\n shown.add(letter.id)\n if (!on('dead-letter')) continue\n toasts.error('A change could not be saved.', { id: `dovetail-write-${letter.id}` })\n }\n }\n stops.push(client.onChange(changed))\n }\n\n return () => {\n for (const stop of stops.splice(0)) stop()\n }\n}\n","import Component from '@glimmer/component'\nimport type Owner from '@ember/owner'\nimport { registerDestructor } from '@ember/destroyable'\nimport { toastsFor } from '@ember-joinery/ember'\nimport type { SyncClient } from '@dovetail-ts/core'\nimport type { NotificationInbox } from '../../inbox.ts'\nimport { bridgeToasts } from '../../toasts.ts'\n\nexport interface ToastBridgeSignature {\n Args: {\n /** The new notifications of this inbox make toasts. */\n inbox?: NotificationInbox\n /** The sync events of this client (offline, back online, dead letter, rollback) make toasts. */\n client?: SyncClient\n /** The notification verbs that make a toast. The default is all verbs. */\n types?: readonly string[]\n /** The notification verbs and the sync events that never make a toast. */\n mute?: readonly string[]\n }\n}\n\n/**\n * Shows notifications and sync events in the Joinery `<Toaster>` of the app. It renders\n * nothing. It reads its arguments once, when it renders.\n */\nexport default class ToastBridge extends Component<ToastBridgeSignature> {\n constructor(owner: Owner, args: ToastBridgeSignature['Args']) {\n super(owner, args)\n registerDestructor(this, bridgeToasts({ toasts: toastsFor(this), ...args }))\n }\n\n <template></template>\n}\n"],"names":["bridgeToasts","toasts","inbox","client","types","mute","on","name","includes","stops","push","onNotification","item","read","verb","message","describe","id","online","state","shown","Set","errors","map","e","deadLetters","d","changed","warning","success","error","has","add","letter","onChange","stop","splice","ToastBridge","Component","constructor","owner","args","registerDestructor","toastsFor","setComponentTemplate","precompileTemplate","strictMode"],"mappings":";;;;;;AAAA;AACA;;AAIA;;AAOA;;AAQA;;AAeA;AACO,SAASA,YAAYA,CAAC;EAAEC,MAAM;EAAEC,KAAK;EAAEC,MAAM;EAAEC,KAAK;AAAEC,EAAAA,IAAI,GAAG;AAAuB,CAAC,EAAE;EAC5F,MAAMC,EAAE,GAAIC,IAAY,IAAK,CAACF,IAAI,CAACG,QAAQ,CAACD,IAAI,CAAC;EACjD,MAAME,KAAqB,GAAG,EAAE;AAEhC,EAAA,IAAIP,KAAK,EAAE;IACTO,KAAK,CAACC,IAAI,CACRR,KAAK,CAACS,cAAc,CAACC,IAAI,IAAI;MAC3B,IAAIA,IAAI,CAACC,IAAI,IAAI,CAACP,EAAE,CAACM,IAAI,CAACE,IAAI,CAAC,IA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