@juice-js/notifications 0.0.0-stage → 2.1.0-alpha.1

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.
@@ -0,0 +1,1031 @@
1
+ import * as i0 from '@angular/core';
2
+ import { InjectionToken, makeEnvironmentProviders, inject, Injectable, signal, computed, input, output, ChangeDetectionStrategy, Component, DestroyRef, NgModule } from '@angular/core';
3
+ import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
4
+ import { OAuthService } from 'angular-oauth2-oidc';
5
+ import { throwError, firstValueFrom } from 'rxjs';
6
+ import { map } from 'rxjs/operators';
7
+ import { HubConnectionBuilder, LogLevel, HubConnectionState } from '@microsoft/signalr';
8
+ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
9
+ import * as i1 from '@angular/material/badge';
10
+ import { MatBadgeModule } from '@angular/material/badge';
11
+ import * as i2 from '@angular/material/button';
12
+ import { MatButtonModule } from '@angular/material/button';
13
+ import * as i3 from '@angular/material/icon';
14
+ import { MatIconModule } from '@angular/material/icon';
15
+ import * as i4$1 from '@angular/material/menu';
16
+ import { MatMenuModule } from '@angular/material/menu';
17
+ import { TranslatePipe } from '@ngx-translate/core';
18
+ import { DatePipe, JsonPipe } from '@angular/common';
19
+ import * as i2$1 from '@angular/material/button-toggle';
20
+ import { MatButtonToggleModule } from '@angular/material/button-toggle';
21
+ import * as i4 from '@angular/material/progress-bar';
22
+ import { MatProgressBarModule } from '@angular/material/progress-bar';
23
+ import * as i5 from '@angular/material/slide-toggle';
24
+ import { MatSlideToggleModule } from '@angular/material/slide-toggle';
25
+ import * as i6 from '@angular/material/tooltip';
26
+ import { MatTooltipModule } from '@angular/material/tooltip';
27
+ import * as i1$1 from '@angular/forms';
28
+ import { FormsModule } from '@angular/forms';
29
+ import * as i3$1 from '@angular/material/checkbox';
30
+ import { MatCheckboxModule } from '@angular/material/checkbox';
31
+ import * as i3$2 from '@angular/material/form-field';
32
+ import { MatFormFieldModule } from '@angular/material/form-field';
33
+ import * as i6$1 from '@angular/material/input';
34
+ import { MatInputModule } from '@angular/material/input';
35
+ import * as i7 from '@angular/material/select';
36
+ import { MatSelectModule } from '@angular/material/select';
37
+ import * as i1$2 from '@angular/router';
38
+ import { RouterModule } from '@angular/router';
39
+
40
+ /**
41
+ * The shapes of the Juice.Notifications person's API (`/api/v1/tenants/{tenantId}/me/…`), as it sends them: camelCase, enums as strings,
42
+ * times as ISO 8601 text.
43
+ */
44
+ /** Whether the item's actions can still be chosen: it has some, and its correlation (if any) is open or acknowledged. */
45
+ function canAct(item) {
46
+ return !!item.actions?.length && (!item.correlation || item.correlation.state === 'open' || item.correlation.state === 'acknowledged');
47
+ }
48
+ /** The action the person chose on the item, if any. */
49
+ function chosenAction(item) {
50
+ return item.interactions?.find((i) => i.kind === 'action')?.actionId ?? null;
51
+ }
52
+
53
+ const NOTIFICATIONS_CONFIG = new InjectionToken('NOTIFICATIONS_CONFIG');
54
+ /** Registers the configuration: `providers: [provideNotifications({ apiUrl: environment.notificationsApi })]`. */
55
+ function provideNotifications(config) {
56
+ return makeEnvironmentProviders([{ provide: NOTIFICATIONS_CONFIG, useValue: config }]);
57
+ }
58
+ /** A JWT's payload claim, or null when the token isn't a JWT or hasn't it. Reads; never verifies (the API does). */
59
+ function tokenClaim(token, claim) {
60
+ const payload = token?.split('.')[1];
61
+ if (!payload) {
62
+ return null;
63
+ }
64
+ try {
65
+ const json = atob(payload.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(payload.length / 4) * 4, '='));
66
+ const value = JSON.parse(decodeURIComponent(Array.from(json, (c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')).join('')))[claim];
67
+ return typeof value === 'string' && value.length > 0 ? value : null;
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ /** Thrown (as an observable error) when no tenant id can be found: the configuration has none and the token no `platform_tenant` claim. */
75
+ class NoTenantError extends Error {
76
+ constructor() {
77
+ super('[@juice-js/notifications] No tenant: configure tenantId, or sign in with a token that has a platform_tenant claim.');
78
+ }
79
+ }
80
+ /**
81
+ * The person's API of Juice.Notifications, one method per call. The bearer token comes from `@juice-js/auth`'s interceptor (list the API in
82
+ * `AuthModuleConfig.allowedUrls`); errors are the API's problem details ({@link NotificationsProblem}) in an `HttpErrorResponse`.
83
+ */
84
+ class NotificationsApi {
85
+ constructor() {
86
+ this.http = inject(HttpClient);
87
+ this.config = inject(NOTIFICATIONS_CONFIG);
88
+ this.oauth = inject(OAuthService, { optional: true });
89
+ }
90
+ /** The access token for the hub (REST calls get theirs from the interceptor). */
91
+ accessToken() {
92
+ return (this.config.accessToken ? this.config.accessToken() : this.oauth?.getAccessToken()) ?? null;
93
+ }
94
+ /** The tenant's id: configured, or the token's `platform_tenant` claim. */
95
+ tenantId() {
96
+ const configured = typeof this.config.tenantId === 'function' ? this.config.tenantId() : this.config.tenantId;
97
+ return configured || tokenClaim(this.accessToken(), 'platform_tenant');
98
+ }
99
+ get hubUrl() {
100
+ return this.config.hubUrl ?? `${this.config.apiUrl}/hubs/inbox`;
101
+ }
102
+ // The inbox.
103
+ inbox(query = {}) {
104
+ let params = new HttpParams();
105
+ for (const [key, value] of Object.entries(query)) {
106
+ if (value !== undefined && value !== null && value !== false) {
107
+ params = params.set(key, String(value));
108
+ }
109
+ }
110
+ return this.me((base) => this.http.get(`${base}/inbox`, { params }));
111
+ }
112
+ counts() {
113
+ return this.me((base) => this.http.get(`${base}/inbox/counts`));
114
+ }
115
+ item(id) {
116
+ return this.me((base) => this.http.get(`${base}/inbox/${encodeURIComponent(id)}`));
117
+ }
118
+ /** Marks an item read (`true`) or unread. */
119
+ read(id, read = true) {
120
+ const url = (base) => `${base}/inbox/${encodeURIComponent(id)}/read`;
121
+ return this.me((base) => read ? this.http.post(url(base), null) : this.http.delete(url(base)));
122
+ }
123
+ /** Archives an item (`true`, which also reads it) or puts it back. */
124
+ archive(id, archive = true) {
125
+ const url = (base) => `${base}/inbox/${encodeURIComponent(id)}/archive`;
126
+ return this.me((base) => archive ? this.http.post(url(base), null) : this.http.delete(url(base)));
127
+ }
128
+ /**
129
+ * Chooses one of the item's actions: the producer hears it and decides (the inbox decides nothing). Once per action; refused (409
130
+ * `correlation_closed`) once it has been decided.
131
+ */
132
+ act(id, actionId) {
133
+ return this.me((base) => this.http.post(`${base}/inbox/${encodeURIComponent(id)}/actions/${encodeURIComponent(actionId)}`, null));
134
+ }
135
+ /** Acknowledges the item: the producer hears it. */
136
+ acknowledge(id) {
137
+ return this.me((base) => this.http.post(`${base}/inbox/${encodeURIComponent(id)}/acknowledge`, null));
138
+ }
139
+ /** Marks every open item read, in one group or all; answers how many were. */
140
+ readAll(group) {
141
+ const params = group ? new HttpParams().set('group', group) : undefined;
142
+ return this.me((base) => this.http.post(`${base}/inbox/read-all`, null, { params }).pipe(map((r) => r.marked)));
143
+ }
144
+ // The person and their settings.
145
+ profile() {
146
+ return this.me((base) => this.http.get(base));
147
+ }
148
+ preferences() {
149
+ return this.me((base) => this.http.get(`${base}/preferences`));
150
+ }
151
+ /** Replaces all of the person's preferences (an empty list: everything on). */
152
+ savePreferences(preferences) {
153
+ const body = { preferences: preferences.map(({ category, channel, mode }) => ({ category, channel, mode })) };
154
+ return this.me((base) => this.http.put(`${base}/preferences`, body));
155
+ }
156
+ saveQuietHours(quiet) {
157
+ return this.me((base) => this.http.put(`${base}/quiet-hours`, quiet));
158
+ }
159
+ clearQuietHours() {
160
+ return this.me((base) => this.http.delete(`${base}/quiet-hours`));
161
+ }
162
+ contactPoints() {
163
+ return this.me((base) => this.http.get(`${base}/contact-points`));
164
+ }
165
+ addContactPoint(channel, address) {
166
+ return this.me((base) => this.http.post(`${base}/contact-points`, { channel, address }));
167
+ }
168
+ removeContactPoint(id) {
169
+ return this.me((base) => this.http.delete(`${base}/contact-points/${encodeURIComponent(id)}`));
170
+ }
171
+ /** Sends a verification code to the address. */
172
+ sendCode(id) {
173
+ return this.me((base) => this.http.post(`${base}/contact-points/${encodeURIComponent(id)}/verification`, null));
174
+ }
175
+ verify(id, code) {
176
+ return this.me((base) => this.http.post(`${base}/contact-points/${encodeURIComponent(id)}/verify`, { code }));
177
+ }
178
+ /** A code to link a chat account (`slack`, `telegram`): the person sends it to the tenant's bot from that account. */
179
+ linkCode(channel) {
180
+ return this.me((base) => this.http.post(`${base}/links`, { channel }));
181
+ }
182
+ devices() {
183
+ return this.me((base) => this.http.get(`${base}/devices`));
184
+ }
185
+ /** Registers this device for push (or refreshes its registration); see `enableWebPush` for browsers. */
186
+ registerDevice(device) {
187
+ return this.me((base) => this.http.post(`${base}/devices`, device));
188
+ }
189
+ removeDevice(id) {
190
+ return this.me((base) => this.http.delete(`${base}/devices/${encodeURIComponent(id)}`));
191
+ }
192
+ /** The types the tenant receives (tenant admins), for the template editor. */
193
+ tenantTypes() {
194
+ return this.tenant((base) => this.http.get(`${base}/types`));
195
+ }
196
+ template(type, channel) {
197
+ return this.tenant((base) => this.http.get(`${base}/types/${encodeURIComponent(type)}/templates/${encodeURIComponent(channel)}`));
198
+ }
199
+ /** Saves the tenant's own template for a type and channel, over the application's. */
200
+ saveTemplate(type, channel, body) {
201
+ return this.tenant((base) => this.http.put(`${base}/types/${encodeURIComponent(type)}/templates/${encodeURIComponent(channel)}`, { body }));
202
+ }
203
+ /** Removes the tenant's template: the application's is used again. */
204
+ removeTemplate(type, channel) {
205
+ return this.tenant((base) => this.http.delete(`${base}/types/${encodeURIComponent(type)}/templates/${encodeURIComponent(channel)}`));
206
+ }
207
+ /** Renders a template (the one in effect, without `body`) with `data` (a sample from the type's schema, without it). Nothing is stored. */
208
+ previewTemplate(type, channel, body, data) {
209
+ return this.tenant((base) => this.http.post(`${base}/templates/preview`, { type, channel, body, data }));
210
+ }
211
+ /** A call under `…/tenants/{tenantId}` (the tenant's admins), or {@link NoTenantError} when there's no tenant. */
212
+ tenant(call) {
213
+ const tenant = this.tenantId();
214
+ return tenant ? call(`${this.config.apiUrl}/api/v1/tenants/${encodeURIComponent(tenant)}`) : throwError(() => new NoTenantError());
215
+ }
216
+ /** A call under `…/tenants/{tenantId}/me`, or {@link NoTenantError} when there's no tenant. */
217
+ me(call) {
218
+ const tenant = this.tenantId();
219
+ return tenant
220
+ ? call(`${this.config.apiUrl}/api/v1/tenants/${encodeURIComponent(tenant)}/me`)
221
+ : throwError(() => new NoTenantError());
222
+ }
223
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsApi, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
224
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsApi, providedIn: 'root' }); }
225
+ }
226
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsApi, decorators: [{
227
+ type: Injectable,
228
+ args: [{ providedIn: 'root' }]
229
+ }] });
230
+
231
+ /**
232
+ * Opens the inbox hub (`/hubs/inbox?tenant=…`, the token as `access_token` in the query, as WebSockets need). It reconnects on its own, and
233
+ * after the server closes a session whose token expired it starts again with a fresh token. Replace it in tests.
234
+ */
235
+ class InboxHubConnector {
236
+ connect(url, tenantId, accessToken, handlers) {
237
+ const connection = new HubConnectionBuilder()
238
+ .withUrl(`${url}?tenant=${encodeURIComponent(tenantId)}`, { accessTokenFactory: () => accessToken() ?? '' })
239
+ .withAutomaticReconnect()
240
+ .configureLogging(LogLevel.Warning)
241
+ .build();
242
+ connection.on('inboxChanged', (change) => handlers.changed(change));
243
+ connection.onreconnected(() => handlers.reconnected());
244
+ let stopped = false;
245
+ let retry;
246
+ const start = (delay) => {
247
+ connection.start().then(() => delay > 1000 && handlers.reconnected()).catch(() => {
248
+ // Refused (an expired token, the server not up yet): try again, more slowly each time, up to a minute.
249
+ if (!stopped) {
250
+ retry = setTimeout(() => start(Math.min(delay * 2, 60_000)), delay);
251
+ }
252
+ });
253
+ };
254
+ // Closed for good (automatic reconnection gave up, or the server ended a session whose token expired): start again.
255
+ connection.onclose(() => {
256
+ if (!stopped && connection.state === HubConnectionState.Disconnected) {
257
+ retry = setTimeout(() => start(2000), 1000);
258
+ }
259
+ });
260
+ start(1000);
261
+ return {
262
+ stop: () => {
263
+ stopped = true;
264
+ clearTimeout(retry);
265
+ return connection.stop();
266
+ },
267
+ };
268
+ }
269
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: InboxHubConnector, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
270
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: InboxHubConnector, providedIn: 'root' }); }
271
+ }
272
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: InboxHubConnector, decorators: [{
273
+ type: Injectable,
274
+ args: [{ providedIn: 'root' }]
275
+ }] });
276
+
277
+ /**
278
+ * The person's inbox as signals, kept current by the hub: the counts (the bell's badge, the panel's tabs), and the items of the group and filter
279
+ * shown. Call {@link start} once signed in (the bell does); {@link stop} on sign-out.
280
+ */
281
+ class InboxService {
282
+ constructor() {
283
+ this.api = inject(NotificationsApi);
284
+ this.hub = inject(InboxHubConnector);
285
+ this.pageSize = Math.min(Math.max(inject(NOTIFICATIONS_CONFIG).pageSize ?? 20, 1), 100);
286
+ this._counts = signal(null, /* @ts-ignore */
287
+ ...(ngDevMode ? [{ debugName: "_counts" }] : /* istanbul ignore next */ []));
288
+ this._items = signal([], /* @ts-ignore */
289
+ ...(ngDevMode ? [{ debugName: "_items" }] : /* istanbul ignore next */ []));
290
+ this._group = signal(null, /* @ts-ignore */
291
+ ...(ngDevMode ? [{ debugName: "_group" }] : /* istanbul ignore next */ []));
292
+ this._actionable = signal(false, /* @ts-ignore */
293
+ ...(ngDevMode ? [{ debugName: "_actionable" }] : /* istanbul ignore next */ []));
294
+ this._loading = signal(false, /* @ts-ignore */
295
+ ...(ngDevMode ? [{ debugName: "_loading" }] : /* istanbul ignore next */ []));
296
+ this._more = signal(false, /* @ts-ignore */
297
+ ...(ngDevMode ? [{ debugName: "_more" }] : /* istanbul ignore next */ []));
298
+ this._error = signal(null, /* @ts-ignore */
299
+ ...(ngDevMode ? [{ debugName: "_error" }] : /* istanbul ignore next */ []));
300
+ this.counts = this._counts.asReadonly();
301
+ /** Unread in every group: the bell's badge. */
302
+ this.unread = computed(() => this._counts()?.unread ?? 0, /* @ts-ignore */
303
+ ...(ngDevMode ? [{ debugName: "unread" }] : /* istanbul ignore next */ []));
304
+ this.actionableOpen = computed(() => this._counts()?.actionableOpen ?? 0, /* @ts-ignore */
305
+ ...(ngDevMode ? [{ debugName: "actionableOpen" }] : /* istanbul ignore next */ []));
306
+ this.items = this._items.asReadonly();
307
+ /** The group shown (a key), or null for every group. */
308
+ this.group = this._group.asReadonly();
309
+ /** Only actionable and open items. */
310
+ this.actionableOnly = this._actionable.asReadonly();
311
+ this.loading = this._loading.asReadonly();
312
+ /** Whether there may be more items past the last one shown. */
313
+ this.hasMore = this._more.asReadonly();
314
+ /** The last load's error, until the next one succeeds. */
315
+ this.error = this._error.asReadonly();
316
+ this.connection = null;
317
+ this.listing = null;
318
+ this.started = false;
319
+ }
320
+ /** Loads the counts and the first page, and opens the hub. Again after {@link stop}; once otherwise. */
321
+ start() {
322
+ if (this.started) {
323
+ return;
324
+ }
325
+ const tenant = this.api.tenantId();
326
+ if (!tenant) {
327
+ return; // not signed in yet: the bell asks again when it is
328
+ }
329
+ this.started = true;
330
+ this.reload();
331
+ this.connection = this.hub.connect(this.api.hubUrl, tenant, () => this.api.accessToken(), {
332
+ changed: (change) => this.onChange(change),
333
+ reconnected: () => this.reload(),
334
+ });
335
+ }
336
+ stop() {
337
+ this.started = false;
338
+ this.listing?.unsubscribe();
339
+ void this.connection?.stop();
340
+ this.connection = null;
341
+ this._counts.set(null);
342
+ this._items.set([]);
343
+ }
344
+ ngOnDestroy() {
345
+ this.stop();
346
+ }
347
+ /** Shows one group (a key) or every group (null). */
348
+ showGroup(group) {
349
+ if (group !== this._group()) {
350
+ this._group.set(group);
351
+ this.loadItems();
352
+ }
353
+ }
354
+ showActionableOnly(only) {
355
+ if (only !== this._actionable()) {
356
+ this._actionable.set(only);
357
+ this.loadItems();
358
+ }
359
+ }
360
+ /** The page after the last item shown. */
361
+ loadMore() {
362
+ const last = this._items().at(-1);
363
+ if (last && this._more() && !this._loading()) {
364
+ this.loadItems(last.id);
365
+ }
366
+ }
367
+ /** Counts and the first page again. */
368
+ reload() {
369
+ this.loadCounts();
370
+ this.loadItems();
371
+ }
372
+ /** Marks an item read (or unread), here at once and then as the API answers. */
373
+ async markRead(item, read = true) {
374
+ if (!!item.readAt === read) {
375
+ return;
376
+ }
377
+ this.replace({ ...item, readAt: read ? new Date().toISOString() : null });
378
+ await this.apply(this.api.read(item.id, read), item);
379
+ }
380
+ /** Archives an item (or restores one): it leaves (or joins) the open items. */
381
+ async archive(item, archive = true) {
382
+ this._items.update((items) => items.filter((i) => i.id !== item.id));
383
+ await this.apply(this.api.archive(item.id, archive), item);
384
+ }
385
+ /** Chooses one of the item's actions; the item comes back with the choice recorded (and the correlation as it stands). */
386
+ async act(item, actionId) {
387
+ await this.apply(this.api.act(item.id, actionId), item);
388
+ }
389
+ /** Marks every open item read, in the group shown or all. */
390
+ async readAll() {
391
+ const group = this._group();
392
+ this._items.update((items) => items.map((i) => i.readAt ? i : { ...i, readAt: new Date().toISOString() }));
393
+ try {
394
+ await firstValueFrom(this.api.readAll(group ?? undefined));
395
+ }
396
+ catch (error) {
397
+ this._error.set(error);
398
+ }
399
+ this.loadCounts();
400
+ }
401
+ async apply(call, before) {
402
+ try {
403
+ const after = await firstValueFrom(call);
404
+ this.replace(after);
405
+ this._error.set(null);
406
+ }
407
+ catch (error) {
408
+ this._error.set(error);
409
+ this.loadItems(); // back to what the server has
410
+ }
411
+ this.loadCounts();
412
+ }
413
+ /** An item as it now is: replaced where shown, or dropped if it no longer belongs to the listing. */
414
+ replace(item) {
415
+ const fits = !item.archivedAt && (this._group() === null || item.group === this._group()) && (!this._actionable() || canAct(item));
416
+ this._items.update((items) => fits ? items.map((i) => i.id === item.id ? item : i) : items.filter((i) => i.id !== item.id));
417
+ }
418
+ onChange(change) {
419
+ this.loadCounts();
420
+ if (change.kind === 'changed') {
421
+ // Only the items shown matter here; any other changed item shows up when its page loads.
422
+ for (const id of change.items.filter((id) => this._items().some((i) => i.id === id))) {
423
+ firstValueFrom(this.api.item(id)).then((item) => this.replace(item), () => this._items.update((items) => items.filter((i) => i.id !== id)));
424
+ }
425
+ return;
426
+ }
427
+ // Added (newest first, so at the top) or reset: the first page again.
428
+ this.loadItems();
429
+ }
430
+ loadCounts() {
431
+ this.api.counts().subscribe({ next: (counts) => this._counts.set(counts), error: (error) => this._error.set(error) });
432
+ }
433
+ loadItems(before) {
434
+ this.listing?.unsubscribe();
435
+ const query = { group: this._group() ?? undefined, actionable: this._actionable(), before, limit: this.pageSize };
436
+ this._loading.set(true);
437
+ this.listing = this.api.inbox(query).subscribe({
438
+ next: (page) => {
439
+ this._items.update((items) => before ? [...items, ...page.filter((p) => !items.some((i) => i.id === p.id))] : page);
440
+ this._more.set(page.length === this.pageSize);
441
+ this._loading.set(false);
442
+ this._error.set(null);
443
+ },
444
+ error: (error) => {
445
+ this._loading.set(false);
446
+ this._error.set(error);
447
+ },
448
+ });
449
+ }
450
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: InboxService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
451
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: InboxService, providedIn: 'root' }); }
452
+ }
453
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: InboxService, decorators: [{
454
+ type: Injectable,
455
+ args: [{ providedIn: 'root' }]
456
+ }] });
457
+
458
+ /** Web Push isn't available here: no service workers, no Push API, or the person said no. */
459
+ class WebPushUnavailableError extends Error {
460
+ }
461
+ /** Whether this browser can take Web Push at all. */
462
+ function webPushSupported() {
463
+ return typeof navigator !== 'undefined' && 'serviceWorker' in navigator && typeof window !== 'undefined' && 'PushManager' in window;
464
+ }
465
+ function fromBase64Url(text) {
466
+ const base64 = text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=');
467
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
468
+ }
469
+ function toBase64Url(buffer) {
470
+ const bytes = new Uint8Array(buffer ?? new ArrayBuffer(0));
471
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
472
+ }
473
+ /**
474
+ * Subscribes this browser to push (asking the person, when they haven't answered yet) and registers the subscription with the service, so
475
+ * notifications of types with a `push` template reach it. Call it again on each start: registering an existing subscription only refreshes it.
476
+ */
477
+ async function enableWebPush(api, options) {
478
+ if (!webPushSupported()) {
479
+ throw new WebPushUnavailableError('This browser has no Web Push.');
480
+ }
481
+ if ((await Notification.requestPermission()) !== 'granted') {
482
+ throw new WebPushUnavailableError('Notifications are not allowed for this site.');
483
+ }
484
+ const registration = await navigator.serviceWorker.register(options.serviceWorkerUrl ?? '/juice-push-sw.js');
485
+ await navigator.serviceWorker.ready;
486
+ const subscription = (await registration.pushManager.getSubscription())
487
+ ?? (await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: fromBase64Url(options.vapidPublicKey) }));
488
+ return firstValueFrom(api.registerDevice({
489
+ platform: 'webpush',
490
+ appId: options.appId ?? 'web',
491
+ subscription: { endpoint: subscription.endpoint, p256dh: toBase64Url(subscription.getKey('p256dh')), auth: toBase64Url(subscription.getKey('auth')) },
492
+ locale: options.locale ?? null,
493
+ }));
494
+ }
495
+ /** On sign-out: removes the registration from the service and unsubscribes this browser. */
496
+ async function disableWebPush(api, deviceId, serviceWorkerUrl = '/juice-push-sw.js') {
497
+ await firstValueFrom(api.removeDevice(deviceId));
498
+ if (!webPushSupported()) {
499
+ return;
500
+ }
501
+ const registration = await navigator.serviceWorker.getRegistration(serviceWorkerUrl);
502
+ await (await registration?.pushManager.getSubscription())?.unsubscribe();
503
+ }
504
+
505
+ /**
506
+ * The person's inbox: a tab per display group with its unread count, an "actionable and open" filter, the items newest first (unread ones
507
+ * marked), and per item read and archive. Opening an item reads it and follows its link (`links.self`) unless {@link opened} is handled
508
+ * (`followLinks` false).
509
+ */
510
+ class InboxPanelComponent {
511
+ constructor() {
512
+ this.inbox = inject(InboxService);
513
+ /** Whether opening an item follows its link; when false, handle {@link opened}. */
514
+ this.followLinks = input(true, /* @ts-ignore */
515
+ ...(ngDevMode ? [{ debugName: "followLinks" }] : /* istanbul ignore next */ []));
516
+ /** An item was opened (after it was marked read). */
517
+ this.opened = output();
518
+ this.canAct = canAct;
519
+ this.chosen = chosenAction;
520
+ }
521
+ open(item) {
522
+ void this.inbox.markRead(item);
523
+ this.opened.emit(item);
524
+ if (this.followLinks() && item.url && /^https?:\/\//i.test(item.url)) {
525
+ window.location.assign(item.url);
526
+ }
527
+ }
528
+ toggleRead(item, event) {
529
+ event.stopPropagation();
530
+ void this.inbox.markRead(item, !item.readAt);
531
+ }
532
+ archive(item, event) {
533
+ event.stopPropagation();
534
+ void this.inbox.archive(item);
535
+ }
536
+ act(item, actionId, event) {
537
+ event.stopPropagation();
538
+ void this.inbox.act(item, actionId);
539
+ }
540
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: InboxPanelComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
541
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.6", type: InboxPanelComponent, isStandalone: true, selector: "juice-inbox-panel", inputs: { followLinks: { classPropertyName: "followLinks", publicName: "followLinks", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { opened: "opened" }, ngImport: i0, template: "<section class=\"inbox\" (click)=\"$event.stopPropagation()\" (keydown)=\"$event.stopPropagation()\">\n <header class=\"inbox-header\">\n <h2 class=\"inbox-title\">{{ 'Notifications' | translate }}</h2>\n <mat-slide-toggle class=\"inbox-actionable\" [checked]=\"inbox.actionableOnly()\" (change)=\"inbox.showActionableOnly($event.checked)\">\n {{ 'Needs action' | translate }} ({{ inbox.actionableOpen() }})\n </mat-slide-toggle>\n <button mat-icon-button type=\"button\" (click)=\"inbox.readAll()\" [disabled]=\"!inbox.unread()\"\n [matTooltip]=\"'Mark all as read' | translate\" [attr.aria-label]=\"'Mark all as read' | translate\">\n <mat-icon>done_all</mat-icon>\n </button>\n </header>\n\n <mat-button-toggle-group class=\"inbox-groups\" hideSingleSelectionIndicator [value]=\"inbox.group()\" (change)=\"inbox.showGroup($event.value)\"\n [attr.aria-label]=\"'Groups' | translate\">\n <mat-button-toggle [value]=\"null\">{{ 'All' | translate }}@if (inbox.unread()) { <span class=\"unread-count\">{{ inbox.unread() }}</span> }</mat-button-toggle>\n @for (group of inbox.counts()?.groups ?? []; track group.key) {\n <mat-button-toggle [value]=\"group.key\">{{ group.name }}@if (group.unread) { <span class=\"unread-count\">{{ group.unread }}</span> }</mat-button-toggle>\n }\n </mat-button-toggle-group>\n\n @if (inbox.loading()) {\n <mat-progress-bar mode=\"indeterminate\"></mat-progress-bar>\n }\n @if (inbox.error()) {\n <p class=\"inbox-error\" role=\"alert\">{{ 'Notifications could not be loaded.' | translate }}\n <button mat-button type=\"button\" (click)=\"inbox.reload()\">{{ 'Try again' | translate }}</button></p>\n }\n\n <ul class=\"inbox-items\" role=\"list\">\n @for (item of inbox.items(); track item.id) {\n <li class=\"inbox-item\" [class.unread]=\"!item.readAt\" [class.urgent]=\"item.priority === 'high' || item.priority === 'critical'\">\n <button type=\"button\" class=\"inbox-item-open\" (click)=\"open(item)\">\n <span class=\"inbox-item-title\">{{ item.title }}</span>\n @if (item.body) { <span class=\"inbox-item-body\">{{ item.body }}</span> }\n @if (item.correlation?.state === 'resolved' || item.correlation?.state === 'cancelled') {\n <span class=\"inbox-item-outcome\">{{ item.correlation!.outcome || (item.correlation!.state === 'resolved' ? 'Done' : 'Cancelled') | translate }}</span>\n }\n <time class=\"inbox-item-time\" [attr.datetime]=\"item.createdAt\">{{ item.createdAt | date: 'short' }}</time>\n </button>\n @if (canAct(item)) {\n <span class=\"inbox-item-actions\">\n @for (action of item.actions; track action.id) {\n <button mat-stroked-button type=\"button\" class=\"inbox-item-action\" [class.chosen]=\"chosen(item) === action.id\"\n [disabled]=\"chosen(item) === action.id\" (click)=\"act(item, action.id, $event)\">{{ action.label }}</button>\n }\n </span>\n }\n <span class=\"inbox-item-tools\">\n <button mat-icon-button type=\"button\" (click)=\"toggleRead(item, $event)\"\n [matTooltip]=\"(item.readAt ? 'Mark as unread' : 'Mark as read') | translate\"\n [attr.aria-label]=\"(item.readAt ? 'Mark as unread' : 'Mark as read') | translate\">\n <mat-icon>{{ item.readAt ? 'mark_email_unread' : 'mark_email_read' }}</mat-icon>\n </button>\n <button mat-icon-button type=\"button\" (click)=\"archive(item, $event)\" [matTooltip]=\"'Archive' | translate\" [attr.aria-label]=\"'Archive' | translate\">\n <mat-icon>archive</mat-icon>\n </button>\n </span>\n </li>\n } @empty {\n @if (!inbox.loading()) {\n <li class=\"inbox-empty\">{{ 'Nothing here.' | translate }}</li>\n }\n }\n </ul>\n\n @if (inbox.hasMore()) {\n <button mat-button type=\"button\" class=\"inbox-more\" (click)=\"inbox.loadMore()\" [disabled]=\"inbox.loading()\">{{ 'Show more' | translate }}</button>\n }\n</section>\n", styles: [":host{display:block}.inbox{display:flex;flex-direction:column;gap:8px;width:min(420px,100vw - 32px);max-height:min(600px,80vh);padding:8px 12px;box-sizing:border-box}.inbox-header{display:flex;align-items:center;gap:8px}.inbox-title{flex:1;margin:0;font-size:1.1rem;font-weight:500}.inbox-groups{flex-wrap:wrap;font-size:.85rem}.unread-count{margin-left:6px;padding:0 6px;border-radius:10px;background:var(--mat-sys-primary, #3f51b5);color:var(--mat-sys-on-primary, #fff);font-size:.75rem}.inbox-items{flex:1;overflow-y:auto;margin:0;padding:0;list-style:none}.inbox-item{display:flex;align-items:flex-start;gap:4px;border-bottom:1px solid var(--mat-sys-outline-variant, rgba(0, 0, 0, .12))}.inbox-item.unread .inbox-item-title{font-weight:600}.inbox-item.unread .inbox-item-open:before{content:\"\";position:absolute;left:0;top:14px;width:8px;height:8px;border-radius:50%;background:var(--mat-sys-primary, #3f51b5)}.inbox-item.urgent .inbox-item-title{color:var(--mat-sys-error, #b00020)}.inbox-item-open{position:relative;flex:1;display:flex;flex-direction:column;gap:2px;min-width:0;padding:8px 4px 8px 16px;border:0;background:none;color:inherit;font:inherit;text-align:left;cursor:pointer}.inbox-item-body{overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;opacity:.8;font-size:.875rem}.inbox-item-actions{display:flex;flex-wrap:wrap;gap:4px}.inbox-item-actions{padding:0 4px 8px 16px}.inbox-item-action.chosen{font-weight:600}.inbox-item-outcome{font-size:.8rem;font-style:italic}.inbox-item{flex-wrap:wrap}.inbox-item-time{opacity:.6;font-size:.75rem}.inbox-item-tools{display:flex}.inbox-empty,.inbox-error{padding:16px 4px;opacity:.7;text-align:center}\n"], dependencies: [{ kind: "ngmodule", type: MatButtonModule }, { kind: "component", type: i2.MatButton, selector: " button[matButton], a[matButton], button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button], a[mat-button], a[mat-raised-button], a[mat-flat-button], a[mat-stroked-button] ", inputs: ["matButton"], exportAs: ["matButton", "matAnchor"] }, { kind: "component", type: i2.MatIconButton, selector: "button[mat-icon-button], a[mat-icon-button], button[matIconButton], a[matIconButton]", exportAs: ["matButton", "matAnchor"] }, { kind: "ngmodule", type: MatButtonToggleModule }, { kind: "directive", type: i2$1.MatButtonToggleGroup, selector: "mat-button-toggle-group", inputs: ["appearance", "name", "vertical", "value", "multiple", "disabled", "disabledInteractive", "hideSingleSelectionIndicator", "hideMultipleSelectionIndicator"], outputs: ["valueChange", "change"], exportAs: ["matButtonToggleGroup"] }, { kind: "component", type: i2$1.MatButtonToggle, selector: "mat-button-toggle", inputs: ["aria-label", "aria-labelledby", "id", "name", "value", "tabIndex", "disableRipple", "appearance", "checked", "disabled", "disabledInteractive"], outputs: ["change"], exportAs: ["matButtonToggle"] }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i3.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatProgressBarModule }, { kind: "component", type: i4.MatProgressBar, selector: "mat-progress-bar", inputs: ["color", "value", "bufferValue", "mode"], outputs: ["animationEnd"], exportAs: ["matProgressBar"] }, { kind: "ngmodule", type: MatSlideToggleModule }, { kind: "component", type: i5.MatSlideToggle, selector: "mat-slide-toggle", inputs: ["name", "id", "labelPosition", "aria-label", "aria-labelledby", "aria-describedby", "required", "color", "disabled", "disableRipple", "tabIndex", "checked", "hideIcon", "disabledInteractive"], outputs: ["change", "toggleChange"], exportAs: ["matSlideToggle"] }, { kind: "ngmodule", type: MatTooltipModule }, { kind: "directive", type: i6.MatTooltip, selector: "[matTooltip]", inputs: ["matTooltipPosition", "matTooltipPositionAtOrigin", "matTooltipDisabled", "matTooltipShowDelay", "matTooltipHideDelay", "matTooltipTouchGestures", "matTooltip", "matTooltipClass"], exportAs: ["matTooltip"] }, { kind: "pipe", type: DatePipe, name: "date" }, { kind: "pipe", type: TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
542
+ }
543
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: InboxPanelComponent, decorators: [{
544
+ type: Component,
545
+ args: [{ selector: 'juice-inbox-panel', standalone: true, imports: [DatePipe, MatButtonModule, MatButtonToggleModule, MatIconModule, MatProgressBarModule, MatSlideToggleModule, MatTooltipModule, TranslatePipe], changeDetection: ChangeDetectionStrategy.OnPush, template: "<section class=\"inbox\" (click)=\"$event.stopPropagation()\" (keydown)=\"$event.stopPropagation()\">\n <header class=\"inbox-header\">\n <h2 class=\"inbox-title\">{{ 'Notifications' | translate }}</h2>\n <mat-slide-toggle class=\"inbox-actionable\" [checked]=\"inbox.actionableOnly()\" (change)=\"inbox.showActionableOnly($event.checked)\">\n {{ 'Needs action' | translate }} ({{ inbox.actionableOpen() }})\n </mat-slide-toggle>\n <button mat-icon-button type=\"button\" (click)=\"inbox.readAll()\" [disabled]=\"!inbox.unread()\"\n [matTooltip]=\"'Mark all as read' | translate\" [attr.aria-label]=\"'Mark all as read' | translate\">\n <mat-icon>done_all</mat-icon>\n </button>\n </header>\n\n <mat-button-toggle-group class=\"inbox-groups\" hideSingleSelectionIndicator [value]=\"inbox.group()\" (change)=\"inbox.showGroup($event.value)\"\n [attr.aria-label]=\"'Groups' | translate\">\n <mat-button-toggle [value]=\"null\">{{ 'All' | translate }}@if (inbox.unread()) { <span class=\"unread-count\">{{ inbox.unread() }}</span> }</mat-button-toggle>\n @for (group of inbox.counts()?.groups ?? []; track group.key) {\n <mat-button-toggle [value]=\"group.key\">{{ group.name }}@if (group.unread) { <span class=\"unread-count\">{{ group.unread }}</span> }</mat-button-toggle>\n }\n </mat-button-toggle-group>\n\n @if (inbox.loading()) {\n <mat-progress-bar mode=\"indeterminate\"></mat-progress-bar>\n }\n @if (inbox.error()) {\n <p class=\"inbox-error\" role=\"alert\">{{ 'Notifications could not be loaded.' | translate }}\n <button mat-button type=\"button\" (click)=\"inbox.reload()\">{{ 'Try again' | translate }}</button></p>\n }\n\n <ul class=\"inbox-items\" role=\"list\">\n @for (item of inbox.items(); track item.id) {\n <li class=\"inbox-item\" [class.unread]=\"!item.readAt\" [class.urgent]=\"item.priority === 'high' || item.priority === 'critical'\">\n <button type=\"button\" class=\"inbox-item-open\" (click)=\"open(item)\">\n <span class=\"inbox-item-title\">{{ item.title }}</span>\n @if (item.body) { <span class=\"inbox-item-body\">{{ item.body }}</span> }\n @if (item.correlation?.state === 'resolved' || item.correlation?.state === 'cancelled') {\n <span class=\"inbox-item-outcome\">{{ item.correlation!.outcome || (item.correlation!.state === 'resolved' ? 'Done' : 'Cancelled') | translate }}</span>\n }\n <time class=\"inbox-item-time\" [attr.datetime]=\"item.createdAt\">{{ item.createdAt | date: 'short' }}</time>\n </button>\n @if (canAct(item)) {\n <span class=\"inbox-item-actions\">\n @for (action of item.actions; track action.id) {\n <button mat-stroked-button type=\"button\" class=\"inbox-item-action\" [class.chosen]=\"chosen(item) === action.id\"\n [disabled]=\"chosen(item) === action.id\" (click)=\"act(item, action.id, $event)\">{{ action.label }}</button>\n }\n </span>\n }\n <span class=\"inbox-item-tools\">\n <button mat-icon-button type=\"button\" (click)=\"toggleRead(item, $event)\"\n [matTooltip]=\"(item.readAt ? 'Mark as unread' : 'Mark as read') | translate\"\n [attr.aria-label]=\"(item.readAt ? 'Mark as unread' : 'Mark as read') | translate\">\n <mat-icon>{{ item.readAt ? 'mark_email_unread' : 'mark_email_read' }}</mat-icon>\n </button>\n <button mat-icon-button type=\"button\" (click)=\"archive(item, $event)\" [matTooltip]=\"'Archive' | translate\" [attr.aria-label]=\"'Archive' | translate\">\n <mat-icon>archive</mat-icon>\n </button>\n </span>\n </li>\n } @empty {\n @if (!inbox.loading()) {\n <li class=\"inbox-empty\">{{ 'Nothing here.' | translate }}</li>\n }\n }\n </ul>\n\n @if (inbox.hasMore()) {\n <button mat-button type=\"button\" class=\"inbox-more\" (click)=\"inbox.loadMore()\" [disabled]=\"inbox.loading()\">{{ 'Show more' | translate }}</button>\n }\n</section>\n", styles: [":host{display:block}.inbox{display:flex;flex-direction:column;gap:8px;width:min(420px,100vw - 32px);max-height:min(600px,80vh);padding:8px 12px;box-sizing:border-box}.inbox-header{display:flex;align-items:center;gap:8px}.inbox-title{flex:1;margin:0;font-size:1.1rem;font-weight:500}.inbox-groups{flex-wrap:wrap;font-size:.85rem}.unread-count{margin-left:6px;padding:0 6px;border-radius:10px;background:var(--mat-sys-primary, #3f51b5);color:var(--mat-sys-on-primary, #fff);font-size:.75rem}.inbox-items{flex:1;overflow-y:auto;margin:0;padding:0;list-style:none}.inbox-item{display:flex;align-items:flex-start;gap:4px;border-bottom:1px solid var(--mat-sys-outline-variant, rgba(0, 0, 0, .12))}.inbox-item.unread .inbox-item-title{font-weight:600}.inbox-item.unread .inbox-item-open:before{content:\"\";position:absolute;left:0;top:14px;width:8px;height:8px;border-radius:50%;background:var(--mat-sys-primary, #3f51b5)}.inbox-item.urgent .inbox-item-title{color:var(--mat-sys-error, #b00020)}.inbox-item-open{position:relative;flex:1;display:flex;flex-direction:column;gap:2px;min-width:0;padding:8px 4px 8px 16px;border:0;background:none;color:inherit;font:inherit;text-align:left;cursor:pointer}.inbox-item-body{overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;opacity:.8;font-size:.875rem}.inbox-item-actions{display:flex;flex-wrap:wrap;gap:4px}.inbox-item-actions{padding:0 4px 8px 16px}.inbox-item-action.chosen{font-weight:600}.inbox-item-outcome{font-size:.8rem;font-style:italic}.inbox-item{flex-wrap:wrap}.inbox-item-time{opacity:.6;font-size:.75rem}.inbox-item-tools{display:flex}.inbox-empty,.inbox-error{padding:16px 4px;opacity:.7;text-align:center}\n"] }]
546
+ }], propDecorators: { followLinks: [{ type: i0.Input, args: [{ isSignal: true, alias: "followLinks", required: false }] }], opened: [{ type: i0.Output, args: ["opened"] }] } });
547
+
548
+ /**
549
+ * The bell for a toolbar: the person's unread count as its badge, and the inbox panel when clicked. It starts the inbox once the person is
550
+ * signed in (and again after a new sign-in), and stops it on sign-out.
551
+ */
552
+ class NotificationBellComponent {
553
+ constructor() {
554
+ this.inbox = inject(InboxService);
555
+ this.oauth = inject(OAuthService, { optional: true });
556
+ this.destroyRef = inject(DestroyRef);
557
+ /** Whether opening an item follows its link. */
558
+ this.followLinks = input(true, /* @ts-ignore */
559
+ ...(ngDevMode ? [{ debugName: "followLinks" }] : /* istanbul ignore next */ []));
560
+ }
561
+ badge() {
562
+ const unread = this.inbox.unread();
563
+ return unread > 99 ? '99+' : String(unread);
564
+ }
565
+ ngOnInit() {
566
+ this.inbox.start();
567
+ this.oauth?.events.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((event) => {
568
+ if (event.type === 'token_received') {
569
+ this.inbox.start();
570
+ }
571
+ else if (event.type === 'logout' || event.type === 'session_terminated') {
572
+ this.inbox.stop();
573
+ }
574
+ });
575
+ }
576
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationBellComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
577
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "22.0.6", type: NotificationBellComponent, isStandalone: true, selector: "juice-notification-bell", inputs: { followLinks: { classPropertyName: "followLinks", publicName: "followLinks", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `
578
+ <button mat-icon-button type="button" [matMenuTriggerFor]="panel" (menuOpened)="inbox.start()"
579
+ [attr.aria-label]="'Notifications' | translate" [title]="'Notifications' | translate">
580
+ <mat-icon [matBadge]="badge()" [matBadgeHidden]="!inbox.unread()" matBadgeSize="small" matBadgeColor="warn"
581
+ [attr.aria-hidden]="true">{{ inbox.unread() ? 'notifications_active' : 'notifications' }}</mat-icon>
582
+ </button>
583
+ <mat-menu #panel="matMenu" class="juice-inbox-menu" xPosition="before">
584
+ <juice-inbox-panel [followLinks]="followLinks()"></juice-inbox-panel>
585
+ </mat-menu>
586
+ `, isInline: true, dependencies: [{ kind: "ngmodule", type: MatBadgeModule }, { kind: "directive", type: i1.MatBadge, selector: "[matBadge]", inputs: ["matBadgeColor", "matBadgeOverlap", "matBadgeDisabled", "matBadgePosition", "matBadge", "matBadgeDescription", "matBadgeSize", "matBadgeHidden"] }, { kind: "ngmodule", type: MatButtonModule }, { kind: "component", type: i2.MatIconButton, selector: "button[mat-icon-button], a[mat-icon-button], button[matIconButton], a[matIconButton]", exportAs: ["matButton", "matAnchor"] }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i3.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatMenuModule }, { kind: "component", type: i4$1.MatMenu, selector: "mat-menu", inputs: ["backdropClass", "aria-label", "aria-labelledby", "aria-describedby", "xPosition", "yPosition", "overlapTrigger", "hasBackdrop", "class", "classList"], outputs: ["closed", "close"], exportAs: ["matMenu"] }, { kind: "directive", type: i4$1.MatMenuTrigger, selector: "[mat-menu-trigger-for], [matMenuTriggerFor]", inputs: ["mat-menu-trigger-for", "matMenuTriggerFor", "matMenuTriggerData", "matMenuTriggerRestoreFocus"], outputs: ["menuOpened", "onMenuOpen", "menuClosed", "onMenuClose"], exportAs: ["matMenuTrigger"] }, { kind: "component", type: InboxPanelComponent, selector: "juice-inbox-panel", inputs: ["followLinks"], outputs: ["opened"] }, { kind: "pipe", type: TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
587
+ }
588
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationBellComponent, decorators: [{
589
+ type: Component,
590
+ args: [{
591
+ selector: 'juice-notification-bell',
592
+ standalone: true,
593
+ imports: [MatBadgeModule, MatButtonModule, MatIconModule, MatMenuModule, TranslatePipe, InboxPanelComponent],
594
+ template: `
595
+ <button mat-icon-button type="button" [matMenuTriggerFor]="panel" (menuOpened)="inbox.start()"
596
+ [attr.aria-label]="'Notifications' | translate" [title]="'Notifications' | translate">
597
+ <mat-icon [matBadge]="badge()" [matBadgeHidden]="!inbox.unread()" matBadgeSize="small" matBadgeColor="warn"
598
+ [attr.aria-hidden]="true">{{ inbox.unread() ? 'notifications_active' : 'notifications' }}</mat-icon>
599
+ </button>
600
+ <mat-menu #panel="matMenu" class="juice-inbox-menu" xPosition="before">
601
+ <juice-inbox-panel [followLinks]="followLinks()"></juice-inbox-panel>
602
+ </mat-menu>
603
+ `,
604
+ changeDetection: ChangeDetectionStrategy.OnPush,
605
+ }]
606
+ }], propDecorators: { followLinks: [{ type: i0.Input, args: [{ isSignal: true, alias: "followLinks", required: false }] }] } });
607
+
608
+ /** A message for the person from an API error: the problem's field errors, else its detail, else a general one. */
609
+ function problemMessage(error, fallback = 'Something went wrong. Try again.') {
610
+ if (error instanceof NoTenantError) {
611
+ return 'Sign in to see your notifications.';
612
+ }
613
+ if (error instanceof HttpErrorResponse && error.error && typeof error.error === 'object') {
614
+ const problem = error.error;
615
+ if (problem.errors?.length) {
616
+ return problem.errors.map((e) => e.message).join(' ');
617
+ }
618
+ if (problem.detail) {
619
+ return problem.detail;
620
+ }
621
+ }
622
+ return fallback;
623
+ }
624
+
625
+ /** Days as the API names them, Monday first. */
626
+ const WEEK_DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
627
+ /**
628
+ * The person's notification preferences (a mode per category and channel; `*` for every one; the most specific wins) and quiet hours, when
629
+ * personal channels wait and the inbox doesn't. A mandatory type reaches the person anyway, in the inbox at least.
630
+ */
631
+ class PreferencesComponent {
632
+ constructor() {
633
+ this.api = inject(NotificationsApi);
634
+ this.channels = ['*', 'inbox', 'email', 'push', 'sms', 'slack', 'teams'];
635
+ this.modes = ['on', 'off', 'digest'];
636
+ this.days = WEEK_DAYS;
637
+ this.rows = signal([], /* @ts-ignore */
638
+ ...(ngDevMode ? [{ debugName: "rows" }] : /* istanbul ignore next */ []));
639
+ this.quiet = signal(null, /* @ts-ignore */
640
+ ...(ngDevMode ? [{ debugName: "quiet" }] : /* istanbul ignore next */ []));
641
+ this.quietOn = signal(false, /* @ts-ignore */
642
+ ...(ngDevMode ? [{ debugName: "quietOn" }] : /* istanbul ignore next */ []));
643
+ this.busy = signal(false, /* @ts-ignore */
644
+ ...(ngDevMode ? [{ debugName: "busy" }] : /* istanbul ignore next */ []));
645
+ this.message = signal(null, /* @ts-ignore */
646
+ ...(ngDevMode ? [{ debugName: "message" }] : /* istanbul ignore next */ []));
647
+ this.error = signal(null, /* @ts-ignore */
648
+ ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
649
+ }
650
+ async ngOnInit() {
651
+ await this.run(async () => {
652
+ const [preferences, me] = await Promise.all([firstValueFrom(this.api.preferences()), firstValueFrom(this.api.profile())]);
653
+ this.rows.set(preferences.map((p) => ({ ...p })));
654
+ this.quietOn.set(!!me.quietHours);
655
+ this.quiet.set(me.quietHours ?? { days: null, start: '22:00', end: '07:00', timeZone: me.timeZone ?? browserZone() });
656
+ });
657
+ }
658
+ add() {
659
+ this.rows.update((rows) => [...rows, { category: '*', channel: '*', mode: 'on' }]);
660
+ }
661
+ remove(index) {
662
+ this.rows.update((rows) => rows.filter((_, i) => i !== index));
663
+ }
664
+ update(index, change) {
665
+ this.rows.update((rows) => rows.map((row, i) => i === index ? { ...row, ...change } : row));
666
+ }
667
+ async savePreferences() {
668
+ await this.run(async () => {
669
+ this.rows.set(await firstValueFrom(this.api.savePreferences(this.rows())));
670
+ this.message.set('Preferences saved.');
671
+ });
672
+ }
673
+ quietDay(day) {
674
+ return this.quiet()?.days?.includes(day) ?? true;
675
+ }
676
+ setQuiet(change) {
677
+ this.quiet.update((q) => q ? { ...q, ...change } : q);
678
+ }
679
+ toggleDay(day, on) {
680
+ const current = this.quiet()?.days ?? [...WEEK_DAYS];
681
+ const days = WEEK_DAYS.filter((d) => d === day ? on : current.includes(d));
682
+ // Every day is no list at all.
683
+ this.setQuiet({ days: days.length === WEEK_DAYS.length ? null : days });
684
+ }
685
+ async saveQuietHours() {
686
+ await this.run(async () => {
687
+ if (this.quietOn() && this.quiet()) {
688
+ this.quiet.set(await firstValueFrom(this.api.saveQuietHours(this.quiet())));
689
+ }
690
+ else {
691
+ await firstValueFrom(this.api.clearQuietHours());
692
+ }
693
+ this.message.set('Quiet hours saved.');
694
+ });
695
+ }
696
+ async run(work) {
697
+ this.busy.set(true);
698
+ this.message.set(null);
699
+ this.error.set(null);
700
+ try {
701
+ await work();
702
+ }
703
+ catch (error) {
704
+ this.error.set(problemMessage(error));
705
+ }
706
+ finally {
707
+ this.busy.set(false);
708
+ }
709
+ }
710
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: PreferencesComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
711
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.6", type: PreferencesComponent, isStandalone: true, selector: "juice-notification-preferences", ngImport: i0, template: "<section class=\"juice-notification-settings\">\n <h2>{{ 'Notification preferences' | translate }}</h2>\n <p>{{ 'Choose how you hear about each category. The most specific choice wins; * means every category or channel. Required notifications still reach your inbox.' | translate }}</p>\n\n @if (error()) { <p class=\"error\" role=\"alert\">{{ error()! | translate }}</p> }\n @if (message()) { <p class=\"message\" role=\"status\">{{ message()! | translate }}</p> }\n\n <table class=\"preferences\">\n <thead>\n <tr><th>{{ 'Category' | translate }}</th><th>{{ 'Channel' | translate }}</th><th>{{ 'Mode' | translate }}</th><th></th></tr>\n </thead>\n <tbody>\n @for (row of rows(); track $index; let i = $index) {\n <tr>\n <td>\n <mat-form-field subscriptSizing=\"dynamic\">\n <input matInput [ngModel]=\"row.category\" (ngModelChange)=\"update(i, { category: $event })\" [attr.aria-label]=\"'Category' | translate\" required>\n </mat-form-field>\n </td>\n <td>\n <mat-form-field subscriptSizing=\"dynamic\">\n <mat-select [ngModel]=\"row.channel\" (ngModelChange)=\"update(i, { channel: $event })\" [attr.aria-label]=\"'Channel' | translate\">\n @for (channel of channels; track channel) { <mat-option [value]=\"channel\">{{ channel }}</mat-option> }\n </mat-select>\n </mat-form-field>\n </td>\n <td>\n <mat-form-field subscriptSizing=\"dynamic\">\n <mat-select [ngModel]=\"row.mode\" (ngModelChange)=\"update(i, { mode: $event })\" [attr.aria-label]=\"'Mode' | translate\">\n @for (mode of modes; track mode) { <mat-option [value]=\"mode\">{{ mode | translate }}</mat-option> }\n </mat-select>\n </mat-form-field>\n </td>\n <td>\n <button mat-icon-button type=\"button\" (click)=\"remove(i)\" [attr.aria-label]=\"'Remove' | translate\"><mat-icon>delete</mat-icon></button>\n </td>\n </tr>\n } @empty {\n <tr><td colspan=\"4\">{{ 'Everything is on.' | translate }}</td></tr>\n }\n </tbody>\n </table>\n <div class=\"buttons\">\n <button mat-button type=\"button\" (click)=\"add()\" [disabled]=\"busy()\"><mat-icon>add</mat-icon> {{ 'Add a preference' | translate }}</button>\n <button mat-flat-button type=\"button\" (click)=\"savePreferences()\" [disabled]=\"busy()\">{{ 'Save preferences' | translate }}</button>\n </div>\n\n <h3>{{ 'Quiet hours' | translate }}</h3>\n <p>{{ 'During quiet hours email and other personal channels wait until they end; your inbox still gets everything.' | translate }}</p>\n <mat-slide-toggle [checked]=\"quietOn()\" (change)=\"quietOn.set($event.checked)\">{{ 'Use quiet hours' | translate }}</mat-slide-toggle>\n @if (quietOn() && quiet(); as q) {\n <div class=\"quiet\">\n <mat-form-field>\n <mat-label>{{ 'From' | translate }}</mat-label>\n <input matInput type=\"time\" [ngModel]=\"q.start\" (ngModelChange)=\"setQuiet({ start: $event })\" required>\n </mat-form-field>\n <mat-form-field>\n <mat-label>{{ 'Until' | translate }}</mat-label>\n <input matInput type=\"time\" [ngModel]=\"q.end\" (ngModelChange)=\"setQuiet({ end: $event })\" required>\n </mat-form-field>\n <mat-form-field>\n <mat-label>{{ 'Time zone' | translate }}</mat-label>\n <input matInput [ngModel]=\"q.timeZone\" (ngModelChange)=\"setQuiet({ timeZone: $event || null })\" placeholder=\"Europe/Paris\">\n </mat-form-field>\n <div class=\"days\" role=\"group\" [attr.aria-label]=\"'Days' | translate\">\n @for (day of days; track day) {\n <mat-checkbox [checked]=\"quietDay(day)\" (change)=\"toggleDay(day, $event.checked)\">{{ day | translate }}</mat-checkbox>\n }\n </div>\n </div>\n }\n <div class=\"buttons\">\n <button mat-flat-button type=\"button\" (click)=\"saveQuietHours()\" [disabled]=\"busy()\">{{ 'Save quiet hours' | translate }}</button>\n </div>\n</section>\n", dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox]):not([ngNoCva])[formControlName],textarea:not([ngNoCva])[formControlName],input:not([type=checkbox]):not([ngNoCva])[formControl],textarea:not([ngNoCva])[formControl],input:not([type=checkbox]):not([ngNoCva])[ngModel],textarea:not([ngNoCva])[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i1$1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "ngmodule", type: MatButtonModule }, { kind: "component", type: i2.MatButton, selector: " button[matButton], a[matButton], button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button], a[mat-button], a[mat-raised-button], a[mat-flat-button], a[mat-stroked-button] ", inputs: ["matButton"], exportAs: ["matButton", "matAnchor"] }, { kind: "component", type: i2.MatIconButton, selector: "button[mat-icon-button], a[mat-icon-button], button[matIconButton], a[matIconButton]", exportAs: ["matButton", "matAnchor"] }, { kind: "ngmodule", type: MatCheckboxModule }, { kind: "component", type: i3$1.MatCheckbox, selector: "mat-checkbox", inputs: ["aria-label", "aria-labelledby", "aria-describedby", "aria-expanded", "aria-controls", "aria-owns", "id", "required", "labelPosition", "name", "value", "disableRipple", "tabIndex", "color", "disabledInteractive", "checked", "disabled", "indeterminate"], outputs: ["change", "indeterminateChange"], exportAs: ["matCheckbox"] }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "component", type: i3$2.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3$2.MatLabel, selector: "mat-label" }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i3.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatInputModule }, { kind: "directive", type: i6$1.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly", "disabledInteractive"], exportAs: ["matInput"] }, { kind: "ngmodule", type: MatSelectModule }, { kind: "component", type: i7.MatSelect, selector: "mat-select", inputs: ["aria-describedby", "panelClass", "disabled", "disableRipple", "tabIndex", "hideSingleSelectionIndicator", "placeholder", "required", "multiple", "disableOptionCentering", "compareWith", "value", "aria-label", "aria-labelledby", "errorStateMatcher", "typeaheadDebounceInterval", "sortComparator", "id", "panelWidth", "canSelectNullableOptions"], outputs: ["openedChange", "opened", "closed", "selectionChange", "valueChange"], exportAs: ["matSelect"] }, { kind: "component", type: i7.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "ngmodule", type: MatSlideToggleModule }, { kind: "component", type: i5.MatSlideToggle, selector: "mat-slide-toggle", inputs: ["name", "id", "labelPosition", "aria-label", "aria-labelledby", "aria-describedby", "required", "color", "disabled", "disableRipple", "tabIndex", "checked", "hideIcon", "disabledInteractive"], outputs: ["change", "toggleChange"], exportAs: ["matSlideToggle"] }, { kind: "pipe", type: TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
712
+ }
713
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: PreferencesComponent, decorators: [{
714
+ type: Component,
715
+ args: [{ selector: 'juice-notification-preferences', standalone: true, imports: [FormsModule, MatButtonModule, MatCheckboxModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule, MatSlideToggleModule,
716
+ TranslatePipe], changeDetection: ChangeDetectionStrategy.OnPush, template: "<section class=\"juice-notification-settings\">\n <h2>{{ 'Notification preferences' | translate }}</h2>\n <p>{{ 'Choose how you hear about each category. The most specific choice wins; * means every category or channel. Required notifications still reach your inbox.' | translate }}</p>\n\n @if (error()) { <p class=\"error\" role=\"alert\">{{ error()! | translate }}</p> }\n @if (message()) { <p class=\"message\" role=\"status\">{{ message()! | translate }}</p> }\n\n <table class=\"preferences\">\n <thead>\n <tr><th>{{ 'Category' | translate }}</th><th>{{ 'Channel' | translate }}</th><th>{{ 'Mode' | translate }}</th><th></th></tr>\n </thead>\n <tbody>\n @for (row of rows(); track $index; let i = $index) {\n <tr>\n <td>\n <mat-form-field subscriptSizing=\"dynamic\">\n <input matInput [ngModel]=\"row.category\" (ngModelChange)=\"update(i, { category: $event })\" [attr.aria-label]=\"'Category' | translate\" required>\n </mat-form-field>\n </td>\n <td>\n <mat-form-field subscriptSizing=\"dynamic\">\n <mat-select [ngModel]=\"row.channel\" (ngModelChange)=\"update(i, { channel: $event })\" [attr.aria-label]=\"'Channel' | translate\">\n @for (channel of channels; track channel) { <mat-option [value]=\"channel\">{{ channel }}</mat-option> }\n </mat-select>\n </mat-form-field>\n </td>\n <td>\n <mat-form-field subscriptSizing=\"dynamic\">\n <mat-select [ngModel]=\"row.mode\" (ngModelChange)=\"update(i, { mode: $event })\" [attr.aria-label]=\"'Mode' | translate\">\n @for (mode of modes; track mode) { <mat-option [value]=\"mode\">{{ mode | translate }}</mat-option> }\n </mat-select>\n </mat-form-field>\n </td>\n <td>\n <button mat-icon-button type=\"button\" (click)=\"remove(i)\" [attr.aria-label]=\"'Remove' | translate\"><mat-icon>delete</mat-icon></button>\n </td>\n </tr>\n } @empty {\n <tr><td colspan=\"4\">{{ 'Everything is on.' | translate }}</td></tr>\n }\n </tbody>\n </table>\n <div class=\"buttons\">\n <button mat-button type=\"button\" (click)=\"add()\" [disabled]=\"busy()\"><mat-icon>add</mat-icon> {{ 'Add a preference' | translate }}</button>\n <button mat-flat-button type=\"button\" (click)=\"savePreferences()\" [disabled]=\"busy()\">{{ 'Save preferences' | translate }}</button>\n </div>\n\n <h3>{{ 'Quiet hours' | translate }}</h3>\n <p>{{ 'During quiet hours email and other personal channels wait until they end; your inbox still gets everything.' | translate }}</p>\n <mat-slide-toggle [checked]=\"quietOn()\" (change)=\"quietOn.set($event.checked)\">{{ 'Use quiet hours' | translate }}</mat-slide-toggle>\n @if (quietOn() && quiet(); as q) {\n <div class=\"quiet\">\n <mat-form-field>\n <mat-label>{{ 'From' | translate }}</mat-label>\n <input matInput type=\"time\" [ngModel]=\"q.start\" (ngModelChange)=\"setQuiet({ start: $event })\" required>\n </mat-form-field>\n <mat-form-field>\n <mat-label>{{ 'Until' | translate }}</mat-label>\n <input matInput type=\"time\" [ngModel]=\"q.end\" (ngModelChange)=\"setQuiet({ end: $event })\" required>\n </mat-form-field>\n <mat-form-field>\n <mat-label>{{ 'Time zone' | translate }}</mat-label>\n <input matInput [ngModel]=\"q.timeZone\" (ngModelChange)=\"setQuiet({ timeZone: $event || null })\" placeholder=\"Europe/Paris\">\n </mat-form-field>\n <div class=\"days\" role=\"group\" [attr.aria-label]=\"'Days' | translate\">\n @for (day of days; track day) {\n <mat-checkbox [checked]=\"quietDay(day)\" (change)=\"toggleDay(day, $event.checked)\">{{ day | translate }}</mat-checkbox>\n }\n </div>\n </div>\n }\n <div class=\"buttons\">\n <button mat-flat-button type=\"button\" (click)=\"saveQuietHours()\" [disabled]=\"busy()\">{{ 'Save quiet hours' | translate }}</button>\n </div>\n</section>\n" }]
717
+ }] });
718
+ function browserZone() {
719
+ try {
720
+ return Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
721
+ }
722
+ catch {
723
+ return null;
724
+ }
725
+ }
726
+
727
+ /**
728
+ * The person's email addresses: add one, have a code sent to it and enter the code, or remove one. Only a verified address that hasn't failed
729
+ * is ever used; one your organization's directory vouches for arrives verified. And their chat accounts (`linkChannels`): a chat account is
730
+ * never typed in; the person asks for a code and sends it to the tenant's bot from that account, which links it.
731
+ */
732
+ class ContactPointsComponent {
733
+ constructor() {
734
+ this.api = inject(NotificationsApi);
735
+ this.config = inject(NOTIFICATIONS_CONFIG);
736
+ this.points = signal([], /* @ts-ignore */
737
+ ...(ngDevMode ? [{ debugName: "points" }] : /* istanbul ignore next */ []));
738
+ this.emails = computed(() => this.points().filter((p) => p.channel === 'email' || p.channel === 'sms'), /* @ts-ignore */
739
+ ...(ngDevMode ? [{ debugName: "emails" }] : /* istanbul ignore next */ []));
740
+ this.accounts = computed(() => this.points().filter((p) => p.channel !== 'email' && p.channel !== 'sms'), /* @ts-ignore */
741
+ ...(ngDevMode ? [{ debugName: "accounts" }] : /* istanbul ignore next */ []));
742
+ this.phoneNumbers = this.config.phoneNumbers ?? false;
743
+ this.phone = signal('', /* @ts-ignore */
744
+ ...(ngDevMode ? [{ debugName: "phone" }] : /* istanbul ignore next */ []));
745
+ this.linkChannels = this.config.linkChannels ?? [];
746
+ /** The code being shown, for the channel it links. */
747
+ this.link = signal(null, /* @ts-ignore */
748
+ ...(ngDevMode ? [{ debugName: "link" }] : /* istanbul ignore next */ []));
749
+ this.address = signal('', /* @ts-ignore */
750
+ ...(ngDevMode ? [{ debugName: "address" }] : /* istanbul ignore next */ []));
751
+ /** Codes being typed, by contact point. */
752
+ this.codes = signal({}, /* @ts-ignore */
753
+ ...(ngDevMode ? [{ debugName: "codes" }] : /* istanbul ignore next */ []));
754
+ /** Contact points a code was sent to, with when it expires. */
755
+ this.sent = signal({}, /* @ts-ignore */
756
+ ...(ngDevMode ? [{ debugName: "sent" }] : /* istanbul ignore next */ []));
757
+ this.busy = signal(false, /* @ts-ignore */
758
+ ...(ngDevMode ? [{ debugName: "busy" }] : /* istanbul ignore next */ []));
759
+ this.error = signal(null, /* @ts-ignore */
760
+ ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
761
+ }
762
+ async ngOnInit() {
763
+ await this.run(() => this.load());
764
+ }
765
+ async add(channel = 'email') {
766
+ const field = channel === 'sms' ? this.phone : this.address;
767
+ const address = field().trim();
768
+ if (!address) {
769
+ return;
770
+ }
771
+ await this.run(async () => {
772
+ const point = await firstValueFrom(this.api.addContactPoint(channel, address));
773
+ field.set('');
774
+ await this.load();
775
+ await this.sendCode(point, false);
776
+ });
777
+ }
778
+ async sendCode(point, alone = true) {
779
+ const send = async () => {
780
+ const sent = await firstValueFrom(this.api.sendCode(point.id));
781
+ this.sent.update((s) => ({ ...s, [point.id]: sent.expiresAt }));
782
+ };
783
+ await (alone ? this.run(send) : send());
784
+ }
785
+ setCode(id, code) {
786
+ this.codes.update((c) => ({ ...c, [id]: code }));
787
+ }
788
+ async verify(point) {
789
+ const code = (this.codes()[point.id] ?? '').trim();
790
+ if (!code) {
791
+ return;
792
+ }
793
+ await this.run(async () => {
794
+ await firstValueFrom(this.api.verify(point.id, code));
795
+ this.sent.update(({ [point.id]: _, ...rest }) => rest);
796
+ this.codes.update(({ [point.id]: _, ...rest }) => rest);
797
+ await this.load();
798
+ });
799
+ }
800
+ async linkAccount(channel) {
801
+ await this.run(async () => this.link.set(await firstValueFrom(this.api.linkCode(channel))));
802
+ }
803
+ /** Telegram's deep link, which opens the bot with the code (`/start`), when the bot's name is configured. */
804
+ telegramLink(code) {
805
+ const bot = this.config.telegramBot;
806
+ return code.channel === 'telegram' && bot ? `https://t.me/${encodeURIComponent(bot)}?start=${code.code.replace('-', '')}` : null;
807
+ }
808
+ /** After sending the code: the linked account shows up in the list. */
809
+ async linked() {
810
+ await this.run(async () => {
811
+ await this.load();
812
+ this.link.set(null);
813
+ });
814
+ }
815
+ async remove(point) {
816
+ await this.run(async () => {
817
+ await firstValueFrom(this.api.removeContactPoint(point.id));
818
+ await this.load();
819
+ });
820
+ }
821
+ async load() {
822
+ this.points.set(await firstValueFrom(this.api.contactPoints()));
823
+ }
824
+ async run(work) {
825
+ this.busy.set(true);
826
+ this.error.set(null);
827
+ try {
828
+ await work();
829
+ }
830
+ catch (error) {
831
+ this.error.set(problemMessage(error));
832
+ }
833
+ finally {
834
+ this.busy.set(false);
835
+ }
836
+ }
837
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: ContactPointsComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
838
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.6", type: ContactPointsComponent, isStandalone: true, selector: "juice-contact-points", ngImport: i0, template: "<section class=\"juice-notification-settings\">\n <h2>{{ (phoneNumbers ? 'Email addresses and phone numbers' : 'Email addresses') | translate }}</h2>\n <p>{{ 'Notifications are sent only to addresses you have verified.' | translate }}</p>\n\n @if (error()) { <p class=\"error\" role=\"alert\">{{ error()! | translate }}</p> }\n\n <ul class=\"contact-points\" role=\"list\">\n @for (point of emails(); track point.id) {\n <li class=\"contact-point\">\n <span class=\"contact-point-address\">{{ point.address }}</span>\n @if (point.health === 'failed') {\n <span class=\"contact-point-state failed\">{{ 'Not delivering: verify it again' | translate }}</span>\n } @else if (point.verified) {\n <span class=\"contact-point-state verified\"><mat-icon inline>verified</mat-icon> {{ 'Verified' | translate }}</span>\n } @else {\n <span class=\"contact-point-state\">{{ 'Not verified' | translate }}</span>\n }\n @if (!point.verified || point.health === 'failed') {\n @if (sent()[point.id]; as expires) {\n <mat-form-field subscriptSizing=\"dynamic\" class=\"contact-point-code\">\n <mat-label>{{ 'Code' | translate }}</mat-label>\n <input matInput inputmode=\"numeric\" autocomplete=\"one-time-code\" maxlength=\"6\" [ngModel]=\"codes()[point.id] ?? ''\"\n (ngModelChange)=\"setCode(point.id, $event)\" (keyup.enter)=\"verify(point)\">\n <mat-hint>{{ 'Valid until' | translate }} {{ expires | date: 'shortTime' }}</mat-hint>\n </mat-form-field>\n <button mat-flat-button type=\"button\" (click)=\"verify(point)\" [disabled]=\"busy()\">{{ 'Verify' | translate }}</button>\n }\n <button mat-button type=\"button\" (click)=\"sendCode(point)\" [disabled]=\"busy()\">\n {{ (sent()[point.id] ? 'Send another code' : 'Send a code') | translate }}\n </button>\n }\n <button mat-icon-button type=\"button\" (click)=\"remove(point)\" [disabled]=\"busy()\" [attr.aria-label]=\"'Remove' | translate\"><mat-icon>delete</mat-icon></button>\n </li>\n } @empty {\n <li>{{ 'No addresses yet.' | translate }}</li>\n }\n </ul>\n\n <form class=\"contact-point-add\" (ngSubmit)=\"add()\">\n <mat-form-field>\n <mat-label>{{ 'Add an email address' | translate }}</mat-label>\n <input matInput type=\"email\" name=\"address\" autocomplete=\"email\" [ngModel]=\"address()\" (ngModelChange)=\"address.set($event)\" required>\n </mat-form-field>\n <button mat-flat-button type=\"submit\" [disabled]=\"busy() || !address().trim()\">{{ 'Add' | translate }}</button>\n </form>\n @if (phoneNumbers) {\n <form class=\"contact-point-add\" (ngSubmit)=\"add('sms')\">\n <mat-form-field>\n <mat-label>{{ 'Add a phone number for SMS' | translate }}</mat-label>\n <input matInput type=\"tel\" name=\"phone\" autocomplete=\"tel\" placeholder=\"+84 90 123 4567\" [ngModel]=\"phone()\" (ngModelChange)=\"phone.set($event)\" required>\n <mat-hint>{{ 'With the country code, starting with +' | translate }}</mat-hint>\n </mat-form-field>\n <button mat-flat-button type=\"submit\" [disabled]=\"busy() || !phone().trim()\">{{ 'Add' | translate }}</button>\n </form>\n }\n</section>\n\n@if (linkChannels.length > 0) {\n <section class=\"juice-notification-settings juice-chat-accounts\">\n <h2>{{ 'Chat accounts' | translate }}</h2>\n <p>{{ 'Link an account to get notifications there. You prove it is yours by sending a code to the bot from it.' | translate }}</p>\n <ul class=\"contact-points\" role=\"list\">\n @for (point of accounts(); track point.id) {\n <li class=\"contact-point\">\n <span class=\"contact-point-channel\">{{ point.channel }}</span>\n <span class=\"contact-point-address\">{{ point.address }}</span>\n @if (point.health === 'failed') {\n <span class=\"contact-point-state failed\">{{ 'Not delivering: link it again' | translate }}</span>\n } @else {\n <span class=\"contact-point-state verified\"><mat-icon inline>link</mat-icon> {{ 'Linked' | translate }}</span>\n }\n <button mat-icon-button type=\"button\" (click)=\"remove(point)\" [disabled]=\"busy()\" [attr.aria-label]=\"'Remove' | translate\"><mat-icon>delete</mat-icon></button>\n </li>\n } @empty {\n <li>{{ 'No chat accounts yet.' | translate }}</li>\n }\n </ul>\n @if (link(); as code) {\n <div class=\"link-code\" role=\"status\">\n <p>\n @if (code.channel === 'telegram') {\n {{ 'Send this to the bot in Telegram:' | translate }} <code>/start {{ code.code }}</code>\n } @else {\n {{ 'Send this code to the app in a direct message:' | translate }} <code>{{ code.code }}</code>\n }\n </p>\n @if (telegramLink(code); as url) {\n <a mat-stroked-button [href]=\"url\" target=\"_blank\" rel=\"noopener\">{{ 'Open Telegram' | translate }}</a>\n }\n <p class=\"hint\">{{ 'Valid until' | translate }} {{ code.expiresAt | date: 'shortTime' }}</p>\n <button mat-flat-button type=\"button\" (click)=\"linked()\" [disabled]=\"busy()\">{{ 'I sent it' | translate }}</button>\n </div>\n }\n <div class=\"link-actions\">\n @for (channel of linkChannels; track channel) {\n <button mat-button type=\"button\" (click)=\"linkAccount(channel)\" [disabled]=\"busy()\">{{ 'Link' | translate }} {{ channel }}</button>\n }\n </div>\n </section>\n}\n", dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1$1.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox]):not([ngNoCva])[formControlName],textarea:not([ngNoCva])[formControlName],input:not([type=checkbox]):not([ngNoCva])[formControl],textarea:not([ngNoCva])[formControl],input:not([type=checkbox]):not([ngNoCva])[ngModel],textarea:not([ngNoCva])[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],[formArray],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i1$1.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i1$1.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { kind: "directive", type: i1$1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i1$1.NgForm, selector: "form:not([ngNoForm]):not([formGroup]):not([formArray]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "ngmodule", type: MatButtonModule }, { kind: "component", type: i2.MatButton, selector: " button[matButton], a[matButton], button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button], a[mat-button], a[mat-raised-button], a[mat-flat-button], a[mat-stroked-button] ", inputs: ["matButton"], exportAs: ["matButton", "matAnchor"] }, { kind: "component", type: i2.MatIconButton, selector: "button[mat-icon-button], a[mat-icon-button], button[matIconButton], a[matIconButton]", exportAs: ["matButton", "matAnchor"] }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "component", type: i3$2.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3$2.MatLabel, selector: "mat-label" }, { kind: "directive", type: i3$2.MatHint, selector: "mat-hint", inputs: ["align", "id"] }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i3.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatInputModule }, { kind: "directive", type: i6$1.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly", "disabledInteractive"], exportAs: ["matInput"] }, { kind: "pipe", type: DatePipe, name: "date" }, { kind: "pipe", type: TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
839
+ }
840
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: ContactPointsComponent, decorators: [{
841
+ type: Component,
842
+ args: [{ selector: 'juice-contact-points', standalone: true, imports: [DatePipe, FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, TranslatePipe], changeDetection: ChangeDetectionStrategy.OnPush, template: "<section class=\"juice-notification-settings\">\n <h2>{{ (phoneNumbers ? 'Email addresses and phone numbers' : 'Email addresses') | translate }}</h2>\n <p>{{ 'Notifications are sent only to addresses you have verified.' | translate }}</p>\n\n @if (error()) { <p class=\"error\" role=\"alert\">{{ error()! | translate }}</p> }\n\n <ul class=\"contact-points\" role=\"list\">\n @for (point of emails(); track point.id) {\n <li class=\"contact-point\">\n <span class=\"contact-point-address\">{{ point.address }}</span>\n @if (point.health === 'failed') {\n <span class=\"contact-point-state failed\">{{ 'Not delivering: verify it again' | translate }}</span>\n } @else if (point.verified) {\n <span class=\"contact-point-state verified\"><mat-icon inline>verified</mat-icon> {{ 'Verified' | translate }}</span>\n } @else {\n <span class=\"contact-point-state\">{{ 'Not verified' | translate }}</span>\n }\n @if (!point.verified || point.health === 'failed') {\n @if (sent()[point.id]; as expires) {\n <mat-form-field subscriptSizing=\"dynamic\" class=\"contact-point-code\">\n <mat-label>{{ 'Code' | translate }}</mat-label>\n <input matInput inputmode=\"numeric\" autocomplete=\"one-time-code\" maxlength=\"6\" [ngModel]=\"codes()[point.id] ?? ''\"\n (ngModelChange)=\"setCode(point.id, $event)\" (keyup.enter)=\"verify(point)\">\n <mat-hint>{{ 'Valid until' | translate }} {{ expires | date: 'shortTime' }}</mat-hint>\n </mat-form-field>\n <button mat-flat-button type=\"button\" (click)=\"verify(point)\" [disabled]=\"busy()\">{{ 'Verify' | translate }}</button>\n }\n <button mat-button type=\"button\" (click)=\"sendCode(point)\" [disabled]=\"busy()\">\n {{ (sent()[point.id] ? 'Send another code' : 'Send a code') | translate }}\n </button>\n }\n <button mat-icon-button type=\"button\" (click)=\"remove(point)\" [disabled]=\"busy()\" [attr.aria-label]=\"'Remove' | translate\"><mat-icon>delete</mat-icon></button>\n </li>\n } @empty {\n <li>{{ 'No addresses yet.' | translate }}</li>\n }\n </ul>\n\n <form class=\"contact-point-add\" (ngSubmit)=\"add()\">\n <mat-form-field>\n <mat-label>{{ 'Add an email address' | translate }}</mat-label>\n <input matInput type=\"email\" name=\"address\" autocomplete=\"email\" [ngModel]=\"address()\" (ngModelChange)=\"address.set($event)\" required>\n </mat-form-field>\n <button mat-flat-button type=\"submit\" [disabled]=\"busy() || !address().trim()\">{{ 'Add' | translate }}</button>\n </form>\n @if (phoneNumbers) {\n <form class=\"contact-point-add\" (ngSubmit)=\"add('sms')\">\n <mat-form-field>\n <mat-label>{{ 'Add a phone number for SMS' | translate }}</mat-label>\n <input matInput type=\"tel\" name=\"phone\" autocomplete=\"tel\" placeholder=\"+84 90 123 4567\" [ngModel]=\"phone()\" (ngModelChange)=\"phone.set($event)\" required>\n <mat-hint>{{ 'With the country code, starting with +' | translate }}</mat-hint>\n </mat-form-field>\n <button mat-flat-button type=\"submit\" [disabled]=\"busy() || !phone().trim()\">{{ 'Add' | translate }}</button>\n </form>\n }\n</section>\n\n@if (linkChannels.length > 0) {\n <section class=\"juice-notification-settings juice-chat-accounts\">\n <h2>{{ 'Chat accounts' | translate }}</h2>\n <p>{{ 'Link an account to get notifications there. You prove it is yours by sending a code to the bot from it.' | translate }}</p>\n <ul class=\"contact-points\" role=\"list\">\n @for (point of accounts(); track point.id) {\n <li class=\"contact-point\">\n <span class=\"contact-point-channel\">{{ point.channel }}</span>\n <span class=\"contact-point-address\">{{ point.address }}</span>\n @if (point.health === 'failed') {\n <span class=\"contact-point-state failed\">{{ 'Not delivering: link it again' | translate }}</span>\n } @else {\n <span class=\"contact-point-state verified\"><mat-icon inline>link</mat-icon> {{ 'Linked' | translate }}</span>\n }\n <button mat-icon-button type=\"button\" (click)=\"remove(point)\" [disabled]=\"busy()\" [attr.aria-label]=\"'Remove' | translate\"><mat-icon>delete</mat-icon></button>\n </li>\n } @empty {\n <li>{{ 'No chat accounts yet.' | translate }}</li>\n }\n </ul>\n @if (link(); as code) {\n <div class=\"link-code\" role=\"status\">\n <p>\n @if (code.channel === 'telegram') {\n {{ 'Send this to the bot in Telegram:' | translate }} <code>/start {{ code.code }}</code>\n } @else {\n {{ 'Send this code to the app in a direct message:' | translate }} <code>{{ code.code }}</code>\n }\n </p>\n @if (telegramLink(code); as url) {\n <a mat-stroked-button [href]=\"url\" target=\"_blank\" rel=\"noopener\">{{ 'Open Telegram' | translate }}</a>\n }\n <p class=\"hint\">{{ 'Valid until' | translate }} {{ code.expiresAt | date: 'shortTime' }}</p>\n <button mat-flat-button type=\"button\" (click)=\"linked()\" [disabled]=\"busy()\">{{ 'I sent it' | translate }}</button>\n </div>\n }\n <div class=\"link-actions\">\n @for (channel of linkChannels; track channel) {\n <button mat-button type=\"button\" (click)=\"linkAccount(channel)\" [disabled]=\"busy()\">{{ 'Link' | translate }} {{ channel }}</button>\n }\n </div>\n </section>\n}\n" }]
843
+ }] });
844
+
845
+ /**
846
+ * The tenant's own templates (Juice.Notifications D22): pick a type and a channel, edit the text (Scriban), preview it with the type's sample
847
+ * data or your own, save it over the application's template, or remove it to use the application's again. For the tenant's admins.
848
+ */
849
+ class TemplatesComponent {
850
+ constructor() {
851
+ this.api = inject(NotificationsApi);
852
+ this.types = signal([], /* @ts-ignore */
853
+ ...(ngDevMode ? [{ debugName: "types" }] : /* istanbul ignore next */ []));
854
+ this.type = signal(null, /* @ts-ignore */
855
+ ...(ngDevMode ? [{ debugName: "type" }] : /* istanbul ignore next */ []));
856
+ this.channel = signal(null, /* @ts-ignore */
857
+ ...(ngDevMode ? [{ debugName: "channel" }] : /* istanbul ignore next */ []));
858
+ this.template = signal(null, /* @ts-ignore */
859
+ ...(ngDevMode ? [{ debugName: "template" }] : /* istanbul ignore next */ []));
860
+ this.body = signal('', /* @ts-ignore */
861
+ ...(ngDevMode ? [{ debugName: "body" }] : /* istanbul ignore next */ []));
862
+ this.data = signal('', /* @ts-ignore */
863
+ ...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
864
+ this.preview = signal(null, /* @ts-ignore */
865
+ ...(ngDevMode ? [{ debugName: "preview" }] : /* istanbul ignore next */ []));
866
+ this.busy = signal(false, /* @ts-ignore */
867
+ ...(ngDevMode ? [{ debugName: "busy" }] : /* istanbul ignore next */ []));
868
+ this.error = signal(null, /* @ts-ignore */
869
+ ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
870
+ this.saved = signal(false, /* @ts-ignore */
871
+ ...(ngDevMode ? [{ debugName: "saved" }] : /* istanbul ignore next */ []));
872
+ /** The chosen type's channels with a template (the application's or the tenant's). */
873
+ this.channels = computed(() => this.types().find((t) => t.key === this.type())?.channels.filter((c) => c.declared || c.overridden) ?? [], /* @ts-ignore */
874
+ ...(ngDevMode ? [{ debugName: "channels" }] : /* istanbul ignore next */ []));
875
+ }
876
+ async ngOnInit() {
877
+ await this.run(async () => this.types.set(await firstValueFrom(this.api.tenantTypes())));
878
+ }
879
+ async pickType(key) {
880
+ this.type.set(key);
881
+ const first = this.channels()[0]?.channel ?? null;
882
+ await this.pickChannel(first);
883
+ }
884
+ async pickChannel(channel) {
885
+ this.channel.set(channel);
886
+ this.template.set(null);
887
+ this.preview.set(null);
888
+ this.data.set('');
889
+ this.saved.set(false);
890
+ const type = this.type();
891
+ if (!type || !channel) {
892
+ return;
893
+ }
894
+ await this.run(async () => {
895
+ const template = await firstValueFrom(this.api.template(type, channel));
896
+ this.template.set(template);
897
+ this.body.set(template.tenant ?? template.application ?? '');
898
+ await this.render();
899
+ });
900
+ }
901
+ async previewNow() {
902
+ await this.run(() => this.render());
903
+ }
904
+ /** Saves the text as the tenant's template (refused with the reason when it doesn't parse, as a producer's would be). */
905
+ async save() {
906
+ const type = this.type();
907
+ const channel = this.channel();
908
+ if (!type || !channel || !this.body().trim()) {
909
+ return;
910
+ }
911
+ await this.run(async () => {
912
+ this.template.set(await firstValueFrom(this.api.saveTemplate(type, channel, this.body())));
913
+ this.saved.set(true);
914
+ this.types.update((all) => all.map((t) => t.key !== type ? t
915
+ : { ...t, channels: t.channels.map((c) => (c.channel === channel ? { ...c, overridden: true } : c)) }));
916
+ });
917
+ }
918
+ /** Removes the tenant's template: the application's is used again. */
919
+ async remove() {
920
+ const type = this.type();
921
+ const channel = this.channel();
922
+ if (!type || !channel || !this.template()?.tenant) {
923
+ return;
924
+ }
925
+ await this.run(async () => {
926
+ await firstValueFrom(this.api.removeTemplate(type, channel));
927
+ this.types.update((all) => all.map((t) => t.key !== type ? t
928
+ : { ...t, channels: t.channels.map((c) => (c.channel === channel ? { ...c, overridden: false } : c)) }));
929
+ });
930
+ await this.pickChannel(channel);
931
+ }
932
+ async render() {
933
+ const type = this.type();
934
+ const channel = this.channel();
935
+ if (!type || !channel) {
936
+ return;
937
+ }
938
+ let data = null;
939
+ if (this.data().trim()) {
940
+ try {
941
+ data = JSON.parse(this.data());
942
+ }
943
+ catch {
944
+ this.error.set('The data is not JSON.');
945
+ return;
946
+ }
947
+ }
948
+ const preview = await firstValueFrom(this.api.previewTemplate(type, channel, this.body(), data));
949
+ this.preview.set(preview);
950
+ if (!this.data().trim()) {
951
+ this.data.set(JSON.stringify(preview.data, null, 2));
952
+ }
953
+ }
954
+ async run(work) {
955
+ this.busy.set(true);
956
+ this.error.set(null);
957
+ try {
958
+ await work();
959
+ }
960
+ catch (error) {
961
+ this.error.set(problemMessage(error));
962
+ }
963
+ finally {
964
+ this.busy.set(false);
965
+ }
966
+ }
967
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: TemplatesComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
968
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.6", type: TemplatesComponent, isStandalone: true, selector: "juice-notification-templates", ngImport: i0, template: "<section class=\"juice-notification-settings juice-notification-templates\">\n <h2>{{ 'Notification templates' | translate }}</h2>\n <p>{{ \"Change what a notification says for your organization. Your template is used instead of the application's until you remove it.\" | translate }}</p>\n\n @if (error()) { <p class=\"error\" role=\"alert\">{{ error()! | translate }}</p> }\n\n <div class=\"template-pick\">\n <mat-form-field>\n <mat-label>{{ 'Type' | translate }}</mat-label>\n <mat-select [value]=\"type()\" (selectionChange)=\"pickType($event.value)\">\n @for (t of types(); track t.key) {\n <mat-option [value]=\"t.key\">{{ t.name }} ({{ t.key }} v{{ t.version }})</mat-option>\n }\n </mat-select>\n </mat-form-field>\n <mat-form-field>\n <mat-label>{{ 'Channel' | translate }}</mat-label>\n <mat-select [value]=\"channel()\" (selectionChange)=\"pickChannel($event.value)\" [disabled]=\"!type()\">\n @for (c of channels(); track c.channel) {\n <mat-option [value]=\"c.channel\">{{ c.channel }}@if (c.overridden) { ({{ 'yours' | translate }}) }</mat-option>\n }\n </mat-select>\n </mat-form-field>\n </div>\n\n @if (template(); as t) {\n <div class=\"template-edit\">\n <div class=\"template-source\">\n <mat-form-field class=\"template-body\">\n <mat-label>{{ (t.tenant ? \"Your template\" : \"The application's template (edit to make it yours)\") | translate }}</mat-label>\n <textarea matInput rows=\"14\" spellcheck=\"false\" [ngModel]=\"body()\" (ngModelChange)=\"body.set($event); saved.set(false)\"></textarea>\n <mat-hint>Scriban: <code ngNonBindable>{{ data.field }}</code>. {{ \"A first line Subject: (email) or Title: (inbox, chat, push) sets the heading.\" | translate }}</mat-hint>\n </mat-form-field>\n <mat-form-field class=\"template-data\">\n <mat-label>{{ 'Sample data (JSON)' | translate }}</mat-label>\n <textarea matInput rows=\"8\" spellcheck=\"false\" [ngModel]=\"data()\" (ngModelChange)=\"data.set($event)\"></textarea>\n </mat-form-field>\n <div class=\"template-actions\">\n <button mat-button type=\"button\" (click)=\"previewNow()\" [disabled]=\"busy()\">{{ 'Preview' | translate }}</button>\n <button mat-flat-button type=\"button\" (click)=\"save()\" [disabled]=\"busy() || !body().trim()\">{{ 'Save' | translate }}</button>\n @if (t.tenant) {\n <button mat-button type=\"button\" (click)=\"remove()\" [disabled]=\"busy()\">{{ \"Use the application's template\" | translate }}</button>\n }\n @if (saved()) { <span role=\"status\">{{ 'Saved' | translate }}</span> }\n </div>\n </div>\n <div class=\"template-preview\" aria-live=\"polite\">\n <h3>{{ 'Preview' | translate }}</h3>\n @if (preview(); as p) {\n @if (p.error) {\n <p class=\"error\">{{ p.error }}</p>\n } @else {\n <pre>{{ p.content | json }}</pre>\n }\n }\n </div>\n </div>\n }\n</section>\n", dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox]):not([ngNoCva])[formControlName],textarea:not([ngNoCva])[formControlName],input:not([type=checkbox]):not([ngNoCva])[formControl],textarea:not([ngNoCva])[formControl],input:not([type=checkbox]):not([ngNoCva])[ngModel],textarea:not([ngNoCva])[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "ngmodule", type: MatButtonModule }, { kind: "component", type: i2.MatButton, selector: " button[matButton], a[matButton], button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button], a[mat-button], a[mat-raised-button], a[mat-flat-button], a[mat-stroked-button] ", inputs: ["matButton"], exportAs: ["matButton", "matAnchor"] }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "component", type: i3$2.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3$2.MatLabel, selector: "mat-label" }, { kind: "directive", type: i3$2.MatHint, selector: "mat-hint", inputs: ["align", "id"] }, { kind: "ngmodule", type: MatInputModule }, { kind: "directive", type: i6$1.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly", "disabledInteractive"], exportAs: ["matInput"] }, { kind: "ngmodule", type: MatSelectModule }, { kind: "component", type: i7.MatSelect, selector: "mat-select", inputs: ["aria-describedby", "panelClass", "disabled", "disableRipple", "tabIndex", "hideSingleSelectionIndicator", "placeholder", "required", "multiple", "disableOptionCentering", "compareWith", "value", "aria-label", "aria-labelledby", "errorStateMatcher", "typeaheadDebounceInterval", "sortComparator", "id", "panelWidth", "canSelectNullableOptions"], outputs: ["openedChange", "opened", "closed", "selectionChange", "valueChange"], exportAs: ["matSelect"] }, { kind: "component", type: i7.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "pipe", type: JsonPipe, name: "json" }, { kind: "pipe", type: TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
969
+ }
970
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: TemplatesComponent, decorators: [{
971
+ type: Component,
972
+ args: [{ selector: 'juice-notification-templates', standalone: true, imports: [JsonPipe, FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule, TranslatePipe], changeDetection: ChangeDetectionStrategy.OnPush, template: "<section class=\"juice-notification-settings juice-notification-templates\">\n <h2>{{ 'Notification templates' | translate }}</h2>\n <p>{{ \"Change what a notification says for your organization. Your template is used instead of the application's until you remove it.\" | translate }}</p>\n\n @if (error()) { <p class=\"error\" role=\"alert\">{{ error()! | translate }}</p> }\n\n <div class=\"template-pick\">\n <mat-form-field>\n <mat-label>{{ 'Type' | translate }}</mat-label>\n <mat-select [value]=\"type()\" (selectionChange)=\"pickType($event.value)\">\n @for (t of types(); track t.key) {\n <mat-option [value]=\"t.key\">{{ t.name }} ({{ t.key }} v{{ t.version }})</mat-option>\n }\n </mat-select>\n </mat-form-field>\n <mat-form-field>\n <mat-label>{{ 'Channel' | translate }}</mat-label>\n <mat-select [value]=\"channel()\" (selectionChange)=\"pickChannel($event.value)\" [disabled]=\"!type()\">\n @for (c of channels(); track c.channel) {\n <mat-option [value]=\"c.channel\">{{ c.channel }}@if (c.overridden) { ({{ 'yours' | translate }}) }</mat-option>\n }\n </mat-select>\n </mat-form-field>\n </div>\n\n @if (template(); as t) {\n <div class=\"template-edit\">\n <div class=\"template-source\">\n <mat-form-field class=\"template-body\">\n <mat-label>{{ (t.tenant ? \"Your template\" : \"The application's template (edit to make it yours)\") | translate }}</mat-label>\n <textarea matInput rows=\"14\" spellcheck=\"false\" [ngModel]=\"body()\" (ngModelChange)=\"body.set($event); saved.set(false)\"></textarea>\n <mat-hint>Scriban: <code ngNonBindable>{{ data.field }}</code>. {{ \"A first line Subject: (email) or Title: (inbox, chat, push) sets the heading.\" | translate }}</mat-hint>\n </mat-form-field>\n <mat-form-field class=\"template-data\">\n <mat-label>{{ 'Sample data (JSON)' | translate }}</mat-label>\n <textarea matInput rows=\"8\" spellcheck=\"false\" [ngModel]=\"data()\" (ngModelChange)=\"data.set($event)\"></textarea>\n </mat-form-field>\n <div class=\"template-actions\">\n <button mat-button type=\"button\" (click)=\"previewNow()\" [disabled]=\"busy()\">{{ 'Preview' | translate }}</button>\n <button mat-flat-button type=\"button\" (click)=\"save()\" [disabled]=\"busy() || !body().trim()\">{{ 'Save' | translate }}</button>\n @if (t.tenant) {\n <button mat-button type=\"button\" (click)=\"remove()\" [disabled]=\"busy()\">{{ \"Use the application's template\" | translate }}</button>\n }\n @if (saved()) { <span role=\"status\">{{ 'Saved' | translate }}</span> }\n </div>\n </div>\n <div class=\"template-preview\" aria-live=\"polite\">\n <h3>{{ 'Preview' | translate }}</h3>\n @if (preview(); as p) {\n @if (p.error) {\n <p class=\"error\">{{ p.error }}</p>\n } @else {\n <pre>{{ p.content | json }}</pre>\n }\n }\n </div>\n </div>\n }\n</section>\n" }]
973
+ }] });
974
+
975
+ /**
976
+ * For NgModule apps: `NotificationsModule.forRoot({ apiUrl })` once, then `<juice-notification-bell>` in the toolbar. Standalone apps use
977
+ * `provideNotifications` and import the components directly.
978
+ */
979
+ class NotificationsModule {
980
+ static forRoot(config) {
981
+ return { ngModule: NotificationsModule, providers: [{ provide: NOTIFICATIONS_CONFIG, useValue: config }] };
982
+ }
983
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
984
+ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "22.0.6", ngImport: i0, type: NotificationsModule, imports: [NotificationBellComponent, InboxPanelComponent], exports: [NotificationBellComponent, InboxPanelComponent] }); }
985
+ static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsModule, imports: [NotificationBellComponent, InboxPanelComponent] }); }
986
+ }
987
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsModule, decorators: [{
988
+ type: NgModule,
989
+ args: [{
990
+ imports: [NotificationBellComponent, InboxPanelComponent],
991
+ exports: [NotificationBellComponent, InboxPanelComponent],
992
+ }]
993
+ }] });
994
+
995
+ /**
996
+ * The settings pages, for `loadChildren`: `preferences` and `contact-points` (the person's), `templates` (the tenant's admins). Guard the
997
+ * route with the app's `AuthGuard`.
998
+ */
999
+ const routes = [
1000
+ { path: 'preferences', component: PreferencesComponent, title: 'Notification preferences',
1001
+ data: { menuDisplay: true, menuIcon: 'tune', menuTitle: 'Notification preferences', menuOrder: 10 } },
1002
+ { path: 'contact-points', component: ContactPointsComponent, title: 'Email addresses',
1003
+ data: { menuDisplay: true, menuIcon: 'alternate_email', menuTitle: 'Email addresses', menuOrder: 11 } },
1004
+ // For the tenant's admins (the API refuses others): the tenant's own templates, with a preview.
1005
+ { path: 'templates', component: TemplatesComponent, title: 'Notification templates',
1006
+ data: { menuDisplay: false, menuIcon: 'edit_note', menuTitle: 'Notification templates', menuOrder: 20 } },
1007
+ { path: '', redirectTo: 'preferences', pathMatch: 'full' },
1008
+ ];
1009
+ class NotificationsRoutingModule {
1010
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsRoutingModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
1011
+ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "22.0.6", ngImport: i0, type: NotificationsRoutingModule, imports: [i1$2.RouterModule], exports: [RouterModule] }); }
1012
+ static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsRoutingModule, imports: [RouterModule.forChild(routes), RouterModule] }); }
1013
+ }
1014
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: NotificationsRoutingModule, decorators: [{
1015
+ type: NgModule,
1016
+ args: [{
1017
+ imports: [RouterModule.forChild(routes)],
1018
+ exports: [RouterModule],
1019
+ }]
1020
+ }] });
1021
+
1022
+ /*
1023
+ * Public API Surface of notifications
1024
+ */
1025
+
1026
+ /**
1027
+ * Generated bundle index. Do not edit.
1028
+ */
1029
+
1030
+ export { ContactPointsComponent, InboxHubConnector, InboxPanelComponent, InboxService, NOTIFICATIONS_CONFIG, NoTenantError, NotificationBellComponent, NotificationsApi, NotificationsModule, NotificationsRoutingModule, PreferencesComponent, TemplatesComponent, WEEK_DAYS, WebPushUnavailableError, canAct, chosenAction, disableWebPush, enableWebPush, provideNotifications, tokenClaim, webPushSupported };
1031
+ //# sourceMappingURL=juice-js-notifications.mjs.map