@nr-connect/node-red 0.0.0-stage → 1.0.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,1173 @@
1
+ import { h, nextTick, resolveComponent, Teleport } from "vue";
2
+
3
+ const STYLE_TAG_ID = "ui-nr-connect-profile-styles";
4
+ const FIREBASE_SDK_VERSION = "13.3.0";
5
+ const FIREBASE_APP_NAME = "nr-connect-push";
6
+ const PROFILE_CACHE_TTL_MS = 60 * 1000;
7
+ const PUSH_SYNC_TTL_MS = 12 * 60 * 60 * 1000;
8
+ const SIGN_OUT_UNREGISTER_TIMEOUT_MS = 1500;
9
+ const BLOCKED_STATUS_MESSAGE =
10
+ "Notifications blocked in browser settings — allow in site settings";
11
+
12
+ const profileCache = new Map();
13
+ const profileInFlight = new Map();
14
+
15
+ export function resetProfileWidgetCaches() {
16
+ profileCache.clear();
17
+ profileInFlight.clear();
18
+ }
19
+
20
+ function injectProfileStyles() {
21
+ if (typeof document === "undefined" || document.getElementById(STYLE_TAG_ID)) {
22
+ return;
23
+ }
24
+ const style = document.createElement("style");
25
+ style.id = STYLE_TAG_ID;
26
+ style.textContent = `
27
+ .nrc-profile {
28
+ display: flex;
29
+ flex-direction: column;
30
+ min-width: 0;
31
+ width: 100%;
32
+ }
33
+ .nrc-profile--group {
34
+ gap: 10px;
35
+ padding: 2px 0;
36
+ }
37
+ .nrc-profile--menu {
38
+ gap: 0;
39
+ }
40
+ .nrc-profile-menu-card {
41
+ overflow: hidden;
42
+ border: 1px solid rgba(var(--v-border-color, 128, 128, 128), var(--v-border-opacity, 0.14));
43
+ }
44
+ .nrc-profile-header {
45
+ display: flex;
46
+ align-items: center;
47
+ gap: 12px;
48
+ min-width: 0;
49
+ width: 100%;
50
+ }
51
+ .nrc-profile--menu .nrc-profile-header {
52
+ padding: 14px 14px 12px;
53
+ }
54
+ .nrc-profile-text {
55
+ display: flex;
56
+ flex-direction: column;
57
+ gap: 2px;
58
+ min-width: 0;
59
+ flex: 1 1 auto;
60
+ }
61
+ .nrc-profile-name-row {
62
+ display: flex;
63
+ align-items: center;
64
+ gap: 6px;
65
+ min-width: 0;
66
+ }
67
+ .nrc-profile-name {
68
+ font-weight: 600;
69
+ font-size: 0.92rem;
70
+ line-height: 1.25;
71
+ overflow: hidden;
72
+ text-overflow: ellipsis;
73
+ white-space: nowrap;
74
+ }
75
+ .nrc-profile-email {
76
+ opacity: 0.7;
77
+ font-size: 0.8rem;
78
+ line-height: 1.3;
79
+ overflow: hidden;
80
+ text-overflow: ellipsis;
81
+ white-space: nowrap;
82
+ }
83
+ .nrc-profile-local {
84
+ opacity: 0.68;
85
+ font-size: 0.78rem;
86
+ line-height: 1.3;
87
+ }
88
+ .nrc-profile-role {
89
+ flex: 0 0 auto;
90
+ font-weight: 600;
91
+ letter-spacing: 0.01em;
92
+ }
93
+ .nrc-profile-divider {
94
+ height: 1px;
95
+ width: 100%;
96
+ background: rgba(var(--v-border-color, 128, 128, 128), var(--v-border-opacity, 0.12));
97
+ }
98
+ .nrc-profile-actions {
99
+ display: flex;
100
+ flex-direction: column;
101
+ gap: 4px;
102
+ }
103
+ .nrc-profile--menu .nrc-profile-actions {
104
+ padding: 6px;
105
+ }
106
+ .nrc-profile-push-btn {
107
+ display: flex;
108
+ align-items: center;
109
+ gap: 10px;
110
+ width: 100%;
111
+ padding: 8px 10px;
112
+ border: 1px solid rgba(var(--v-border-color, 128, 128, 128), var(--v-border-opacity, 0.12));
113
+ border-radius: 10px;
114
+ background: transparent;
115
+ color: inherit;
116
+ text-align: left;
117
+ cursor: pointer;
118
+ transition: background-color 140ms ease, border-color 140ms ease, opacity 140ms ease;
119
+ font: inherit;
120
+ }
121
+ .nrc-profile--menu .nrc-profile-push-btn {
122
+ border-color: transparent;
123
+ border-radius: 8px;
124
+ }
125
+ .nrc-profile-push-btn:hover:not(:disabled) {
126
+ background: rgba(var(--v-theme-on-surface, 128, 128, 128), 0.06);
127
+ }
128
+ .nrc-profile-push-btn:focus-visible {
129
+ outline: 2px solid rgb(var(--v-theme-primary, 25, 118, 210));
130
+ outline-offset: -2px;
131
+ }
132
+ .nrc-profile-push-btn:disabled {
133
+ opacity: 0.6;
134
+ cursor: not-allowed;
135
+ }
136
+ .nrc-profile-bell-badge {
137
+ display: inline-flex;
138
+ align-items: center;
139
+ justify-content: center;
140
+ width: 32px;
141
+ height: 32px;
142
+ border-radius: 999px;
143
+ flex: 0 0 32px;
144
+ background: rgba(var(--v-theme-on-surface, 128, 128, 128), 0.08);
145
+ color: inherit;
146
+ transition: background-color 140ms ease, color 140ms ease;
147
+ }
148
+ .nrc-profile-push-btn--on .nrc-profile-bell-badge {
149
+ background: rgba(var(--v-theme-primary, 25, 118, 210), 0.14);
150
+ color: rgb(var(--v-theme-primary, 25, 118, 210));
151
+ }
152
+ .nrc-profile-push-btn--blocked .nrc-profile-bell-badge {
153
+ background: rgba(var(--v-theme-error, 176, 0, 32), 0.12);
154
+ color: rgb(var(--v-theme-error, 176, 0, 32));
155
+ }
156
+ .nrc-profile-push-copy {
157
+ display: flex;
158
+ flex-direction: column;
159
+ gap: 1px;
160
+ min-width: 0;
161
+ flex: 1 1 auto;
162
+ }
163
+ .nrc-profile-push-label {
164
+ font-size: 0.85rem;
165
+ font-weight: 500;
166
+ line-height: 1.25;
167
+ overflow: hidden;
168
+ text-overflow: ellipsis;
169
+ white-space: nowrap;
170
+ }
171
+ .nrc-profile-push-status {
172
+ font-size: 0.74rem;
173
+ line-height: 1.25;
174
+ opacity: 0.68;
175
+ overflow: hidden;
176
+ text-overflow: ellipsis;
177
+ display: -webkit-box;
178
+ -webkit-line-clamp: 2;
179
+ -webkit-box-orient: vertical;
180
+ }
181
+ .nrc-profile-push-pill {
182
+ display: inline-flex;
183
+ align-items: center;
184
+ justify-content: center;
185
+ min-width: 34px;
186
+ height: 22px;
187
+ padding: 0 8px;
188
+ border-radius: 999px;
189
+ font-size: 0.72rem;
190
+ font-weight: 600;
191
+ letter-spacing: 0.02em;
192
+ flex: 0 0 auto;
193
+ background: rgba(var(--v-theme-on-surface, 128, 128, 128), 0.09);
194
+ color: inherit;
195
+ opacity: 0.82;
196
+ }
197
+ .nrc-profile-push-btn--on .nrc-profile-push-pill {
198
+ background: rgba(var(--v-theme-primary, 25, 118, 210), 0.15);
199
+ color: rgb(var(--v-theme-primary, 25, 118, 210));
200
+ opacity: 1;
201
+ }
202
+ .nrc-profile-push-btn--blocked .nrc-profile-push-pill {
203
+ background: rgba(var(--v-theme-error, 176, 0, 32), 0.12);
204
+ color: rgb(var(--v-theme-error, 176, 0, 32));
205
+ opacity: 1;
206
+ }
207
+ .nrc-profile-spinner {
208
+ width: 12px;
209
+ height: 12px;
210
+ border: 2px solid currentColor;
211
+ border-right-color: transparent;
212
+ border-radius: 999px;
213
+ animation: nrc-spin 650ms linear infinite;
214
+ }
215
+ @keyframes nrc-spin {
216
+ to { transform: rotate(360deg); }
217
+ }
218
+ .nrc-profile-signout-row {
219
+ padding: 6px;
220
+ }
221
+ .nrc-profile-signout {
222
+ justify-content: flex-start;
223
+ text-transform: none;
224
+ letter-spacing: 0;
225
+ font-weight: 500;
226
+ }
227
+ .nrc-profile--group .nrc-profile-signout {
228
+ align-self: flex-start;
229
+ }
230
+ .nrc-profile-initials {
231
+ font-weight: 600;
232
+ font-size: 0.85rem;
233
+ color: rgb(var(--v-theme-on-primary, 255, 255, 255));
234
+ }
235
+ .nrc-profile-trigger {
236
+ position: relative;
237
+ }
238
+ `;
239
+ document.head.appendChild(style);
240
+ }
241
+
242
+ export function getInitials(name, email) {
243
+ const trimmedName = typeof name === "string" ? name.trim() : "";
244
+ if (trimmedName) {
245
+ const words = trimmedName.split(/\s+/).filter(Boolean);
246
+ if (words.length === 1) {
247
+ return words[0].charAt(0).toUpperCase();
248
+ }
249
+ if (words.length > 1) {
250
+ return (words[0].charAt(0) + words[words.length - 1].charAt(0)).toUpperCase();
251
+ }
252
+ }
253
+ const trimmedEmail = typeof email === "string" ? email.trim() : "";
254
+ if (trimmedEmail) {
255
+ return trimmedEmail.charAt(0).toUpperCase();
256
+ }
257
+ return "";
258
+ }
259
+
260
+ function requestNotificationPermission() {
261
+ if (
262
+ typeof Notification === "undefined" ||
263
+ typeof Notification.requestPermission !== "function"
264
+ ) {
265
+ return Promise.resolve("denied");
266
+ }
267
+ try {
268
+ let settled = false;
269
+ let resolvePermission;
270
+ const permissionPromise = new Promise((resolve) => {
271
+ resolvePermission = (value) => {
272
+ if (!settled) {
273
+ settled = true;
274
+ resolve(value || Notification.permission || "default");
275
+ }
276
+ };
277
+ });
278
+
279
+ const maybePromise = Notification.requestPermission((cbPermission) => {
280
+ resolvePermission(cbPermission);
281
+ });
282
+ if (maybePromise && typeof maybePromise.then === "function") {
283
+ maybePromise.then(
284
+ (resolved) => resolvePermission(resolved),
285
+ () => resolvePermission(Notification.permission === "granted" ? "granted" : "denied")
286
+ );
287
+ }
288
+ return permissionPromise;
289
+ } catch {
290
+ return Promise.resolve("denied");
291
+ }
292
+ }
293
+
294
+ function getPushSyncStorageKey(basePath) {
295
+ const origin = typeof window !== "undefined" ? window.location.origin : "";
296
+ return `nrc_push_sync_v1:${origin}${basePath}`;
297
+ }
298
+
299
+ function readPushSyncCache(basePath) {
300
+ try {
301
+ if (typeof localStorage === "undefined") return null;
302
+ const raw = localStorage.getItem(getPushSyncStorageKey(basePath));
303
+ if (!raw) return null;
304
+ const parsed = JSON.parse(raw);
305
+ if (parsed && typeof parsed.token === "string" && typeof parsed.syncedAt === "number") {
306
+ return parsed;
307
+ }
308
+ } catch {
309
+ // Ignore storage access/parse errors (e.g. private browsing)
310
+ }
311
+ return null;
312
+ }
313
+
314
+ function writePushSyncCache(basePath, token, email) {
315
+ try {
316
+ if (typeof localStorage === "undefined") return;
317
+ localStorage.setItem(
318
+ getPushSyncStorageKey(basePath),
319
+ JSON.stringify({ token, email: email || "", syncedAt: Date.now() })
320
+ );
321
+ } catch {
322
+ // Ignore storage write errors
323
+ }
324
+ }
325
+
326
+ function clearPushSyncCache(basePath) {
327
+ try {
328
+ if (typeof localStorage === "undefined") return;
329
+ localStorage.removeItem(getPushSyncStorageKey(basePath));
330
+ } catch {
331
+ // Ignore storage removal errors
332
+ }
333
+ }
334
+
335
+ export default {
336
+ name: "UINrConnectProfile",
337
+ inject: {
338
+ $socket: { default: null },
339
+ },
340
+ props: {
341
+ id: { type: String, required: true },
342
+ props: { type: Object, default: () => ({}) },
343
+ state: { type: Object, default: () => ({ enabled: true, visible: true }) },
344
+ },
345
+ data() {
346
+ return {
347
+ loading: true,
348
+ user: null,
349
+ local: true,
350
+ signOutBaseUrl: null,
351
+ imgFailed: false,
352
+ basePath: "/dashboard",
353
+ teleportReady: false,
354
+ loadError: false,
355
+ isUnmounted: false,
356
+
357
+ // Integrated Push Notification reactive UI state
358
+ pushConfig: null,
359
+ pushConfigLoaded: false,
360
+ pushConfigured: null,
361
+ pushSupported: true,
362
+ pushState: false,
363
+ pushEnabled: false,
364
+ pushLoading: false,
365
+ pushStatus: "",
366
+ currentToken: null,
367
+ signingOut: false,
368
+ };
369
+ },
370
+ computed: {
371
+ displayName() {
372
+ if (this.loadError) return "Profile unavailable";
373
+ return this.user?.name || this.user?.email || "Local access";
374
+ },
375
+ initials() {
376
+ return getInitials(this.user?.name, this.user?.email);
377
+ },
378
+ showPhoto() {
379
+ return Boolean(this.user?.photoUrl) && !this.imgFailed;
380
+ },
381
+ signOutHref() {
382
+ if (this.local || !this.signOutBaseUrl || this.props.showSignOut === false) {
383
+ return null;
384
+ }
385
+ const origin = typeof window !== "undefined" ? window.location.origin : "";
386
+ return `${this.signOutBaseUrl}?redirect=${encodeURIComponent(origin + this.basePath)}`;
387
+ },
388
+ roleLabel() {
389
+ const role = this.user?.role;
390
+ if (typeof role !== "string" || !role) return "";
391
+ return role.charAt(0).toUpperCase() + role.slice(1);
392
+ },
393
+ pushFeatureEnabled() {
394
+ return this.props.showPushToggle !== false && !this.loading && Boolean(this.user?.email);
395
+ },
396
+ showPushSection() {
397
+ if (!this.pushFeatureEnabled) return false;
398
+ if (!this.pushSupported) return true;
399
+ return this.pushConfigured === true;
400
+ },
401
+ pushLabel() {
402
+ return this.props.pushLabel || "Push Notifications";
403
+ },
404
+ displayedPushStatus() {
405
+ return this.props.showPushStatus !== false ? this.pushStatus : "";
406
+ },
407
+ pushBlocked() {
408
+ if (!this.pushSupported) return true;
409
+ if (typeof Notification !== "undefined" && Notification.permission === "denied") {
410
+ return true;
411
+ }
412
+ return this.pushStatus === BLOCKED_STATUS_MESSAGE;
413
+ },
414
+ pushBellIcon() {
415
+ if (this.pushBlocked) return "mdi-bell-off-outline";
416
+ return this.pushState ? "mdi-bell-ring" : "mdi-bell-outline";
417
+ },
418
+ pushPillText() {
419
+ if (!this.pushSupported) return "N/A";
420
+ if (this.pushBlocked) return "Blocked";
421
+ return this.pushState ? "On" : "Off";
422
+ },
423
+ },
424
+ async mounted() {
425
+ injectProfileStyles();
426
+ this.basePath = this.resolveBasePath();
427
+ if (this.props.placement === "appbar") {
428
+ await nextTick();
429
+ if (this.isUnmounted) return;
430
+ this.checkOrObserveAppBar();
431
+ }
432
+ await this.loadProfile();
433
+ if (this.isUnmounted) return;
434
+ if (this.pushFeatureEnabled) {
435
+ await this.initializePush();
436
+ }
437
+ },
438
+ unmounted() {
439
+ this.isUnmounted = true;
440
+ if (this._teleportObserver) {
441
+ this._teleportObserver.disconnect();
442
+ this._teleportObserver = null;
443
+ }
444
+ if (typeof this._unsubscribeOnMessage === "function") {
445
+ this._unsubscribeOnMessage();
446
+ this._unsubscribeOnMessage = null;
447
+ }
448
+ if (this._permissionStatus) {
449
+ this._permissionStatus.onchange = null;
450
+ this._permissionStatus = null;
451
+ }
452
+ },
453
+ methods: {
454
+ resolveBasePath() {
455
+ const socketPath = this.$store?.state?.setup?.setup?.socketio?.path;
456
+ if (typeof socketPath === "string" && socketPath.includes("/socket.io")) {
457
+ const prefix = socketPath.replace(/\/socket\.io.*$/, "");
458
+ if (prefix) return prefix;
459
+ }
460
+ if (typeof window !== "undefined" && window.location.pathname.startsWith("/ui")) {
461
+ return "/ui";
462
+ }
463
+ return "/dashboard";
464
+ },
465
+ send(msg) {
466
+ this.$socket?.emit?.("widget-action", this.id, msg);
467
+ },
468
+ checkOrObserveAppBar() {
469
+ if (typeof document === "undefined") return;
470
+ if (document.querySelector("#app-bar-actions")) {
471
+ this.teleportReady = true;
472
+ return;
473
+ }
474
+ if (typeof MutationObserver === "undefined" || !document.body) {
475
+ console.warn("[NR Connect] #app-bar-actions not found; is the dashboard title bar hidden?");
476
+ return;
477
+ }
478
+ const observer = new MutationObserver(() => {
479
+ if (this.isUnmounted) return;
480
+ if (document.querySelector("#app-bar-actions")) {
481
+ this.teleportReady = true;
482
+ observer.disconnect();
483
+ this._teleportObserver = null;
484
+ }
485
+ });
486
+ this._teleportObserver = observer;
487
+ observer.observe(document.body, { childList: true, subtree: true });
488
+ },
489
+ async fetchProfileData() {
490
+ const cached = profileCache.get(this.basePath);
491
+ if (cached && Date.now() - cached.fetchedAt < PROFILE_CACHE_TTL_MS) {
492
+ return cached.data;
493
+ }
494
+
495
+ if (profileInFlight.has(this.basePath)) {
496
+ return profileInFlight.get(this.basePath);
497
+ }
498
+
499
+ const promise = (async () => {
500
+ const res = await fetch(`${this.basePath}/_nrc/me`, {
501
+ credentials: "same-origin",
502
+ cache: "no-store",
503
+ });
504
+ if (!res.ok) {
505
+ throw new Error(`HTTP ${res.status}`);
506
+ }
507
+ const data = await res.json();
508
+ profileCache.set(this.basePath, { fetchedAt: Date.now(), data });
509
+ return data;
510
+ })();
511
+
512
+ profileInFlight.set(this.basePath, promise);
513
+ try {
514
+ return await promise;
515
+ } finally {
516
+ profileInFlight.delete(this.basePath);
517
+ }
518
+ },
519
+ async loadProfile() {
520
+ try {
521
+ const data = await this.fetchProfileData();
522
+ if (this.isUnmounted) return;
523
+ this.user = data?.user || null;
524
+ this.local = Boolean(data?.local ?? !this.user);
525
+ this.signOutBaseUrl = data?.signOutBaseUrl || null;
526
+ this.imgFailed = false;
527
+ this.loadError = false;
528
+ } catch {
529
+ if (this.isUnmounted) return;
530
+ this.loadError = true;
531
+ this.user = null;
532
+ this.local = true;
533
+ this.signOutBaseUrl = null;
534
+ } finally {
535
+ if (!this.isUnmounted) {
536
+ this.loading = false;
537
+ }
538
+ }
539
+ },
540
+ async loadFirebaseModules() {
541
+ if (this._firebaseModules) return this._firebaseModules;
542
+ const [appMod, msgMod] = await Promise.all([
543
+ import(
544
+ /* @vite-ignore */ `https://www.gstatic.com/firebasejs/${FIREBASE_SDK_VERSION}/firebase-app.js`
545
+ ),
546
+ import(
547
+ /* @vite-ignore */ `https://www.gstatic.com/firebasejs/${FIREBASE_SDK_VERSION}/firebase-messaging.js`
548
+ ),
549
+ ]);
550
+ this._firebaseModules = { appMod, msgMod };
551
+ return this._firebaseModules;
552
+ },
553
+ async ensureFirebaseMessaging() {
554
+ const { appMod, msgMod } = await this.loadFirebaseModules();
555
+ const supported = await msgMod.isSupported();
556
+ if (!supported) {
557
+ throw new Error("Push notifications are not supported in this browser");
558
+ }
559
+
560
+ const existing = appMod
561
+ .getApps()
562
+ .find((app) => app.name === FIREBASE_APP_NAME);
563
+ const app =
564
+ existing ||
565
+ appMod.initializeApp(this.pushConfig.firebaseConfig, FIREBASE_APP_NAME);
566
+
567
+ if (!this._messaging) {
568
+ this._messaging = msgMod.getMessaging(app);
569
+ }
570
+ return { msgMod, messaging: this._messaging };
571
+ },
572
+ getServiceWorkerScope() {
573
+ return `${this.basePath}/nr-connect-push-scope`;
574
+ },
575
+ async getExistingServiceWorkerRegistration() {
576
+ if (this._swRegistration) return this._swRegistration;
577
+ if (typeof navigator === "undefined" || !navigator.serviceWorker) return null;
578
+ if (typeof navigator.serviceWorker.getRegistration !== "function") return null;
579
+ try {
580
+ const reg = await navigator.serviceWorker.getRegistration(this.getServiceWorkerScope());
581
+ if (reg && reg.active) {
582
+ this._swRegistration = reg;
583
+ return reg;
584
+ }
585
+ } catch {
586
+ // Ignore lookup error and fall back to registration on demand
587
+ }
588
+ return null;
589
+ },
590
+ async ensureServiceWorker() {
591
+ if (this._swRegistration) return this._swRegistration;
592
+ const swUrl = `${this.basePath}/nr-connect-push-sw.js`;
593
+ const scope = this.getServiceWorkerScope();
594
+ const reg = await navigator.serviceWorker.register(swUrl, { scope });
595
+
596
+ if (!reg.active) {
597
+ await new Promise((resolve, reject) => {
598
+ const worker = reg.installing || reg.waiting;
599
+ if (!worker) {
600
+ resolve();
601
+ return;
602
+ }
603
+ const timer = setTimeout(() => {
604
+ reject(new Error("Push notification setup timed out"));
605
+ }, 10000);
606
+ worker.addEventListener("statechange", () => {
607
+ if (worker.state === "activated") {
608
+ clearTimeout(timer);
609
+ resolve();
610
+ } else if (worker.state === "redundant") {
611
+ clearTimeout(timer);
612
+ reject(new Error("Push notification setup failed"));
613
+ }
614
+ });
615
+ });
616
+ }
617
+
618
+ this._swRegistration = reg;
619
+ return reg;
620
+ },
621
+ async ensurePushConfigLoaded() {
622
+ if (this.pushConfigLoaded) {
623
+ return this.pushConfigured === true;
624
+ }
625
+ try {
626
+ const res = await fetch(`${this.basePath}/_fcm/config`, {
627
+ credentials: "same-origin",
628
+ });
629
+ const cfg = await res.json();
630
+ if (this.isUnmounted) return false;
631
+ this.pushConfigLoaded = true;
632
+ if (!res.ok || !cfg?.configured || !cfg?.firebaseConfig || !cfg?.vapidKey) {
633
+ this.pushConfigured = false;
634
+ this.pushConfig = null;
635
+ return false;
636
+ }
637
+ this.pushConfig = cfg;
638
+ this.pushConfigured = true;
639
+ return true;
640
+ } catch {
641
+ if (this.isUnmounted) return false;
642
+ this.pushConfigLoaded = false;
643
+ this.pushConfigured = false;
644
+ this.pushStatus = "Unable to load push configuration";
645
+ return false;
646
+ }
647
+ },
648
+ async initializePush() {
649
+ if (typeof window === "undefined") return;
650
+
651
+ if (!window.isSecureContext) {
652
+ this.pushSupported = false;
653
+ this.pushEnabled = false;
654
+ this.pushStatus = "Push notifications require HTTPS";
655
+ return;
656
+ }
657
+ if (
658
+ !("serviceWorker" in navigator) ||
659
+ !("PushManager" in window) ||
660
+ !("Notification" in window)
661
+ ) {
662
+ this.pushSupported = false;
663
+ this.pushEnabled = false;
664
+ this.pushStatus = "Push notifications are not supported in this browser";
665
+ return;
666
+ }
667
+
668
+ this.pushSupported = true;
669
+
670
+ if (Notification.permission === "denied") {
671
+ this.pushStatus = BLOCKED_STATUS_MESSAGE;
672
+ this.pushState = false;
673
+ this.pushEnabled = true;
674
+ void this.watchPermissionChanges();
675
+ if (this.props.placement !== "appbar") {
676
+ await this.ensurePushConfigLoaded();
677
+ }
678
+ return;
679
+ }
680
+
681
+ // If permission is already granted, check for an existing browser push subscription
682
+ // without loading Firebase CDN or registering a new SW unless a subscription is active.
683
+ if (Notification.permission === "granted") {
684
+ const existingReg = await this.getExistingServiceWorkerRegistration();
685
+ if (this.isUnmounted) return;
686
+ const existingSub = existingReg
687
+ ? await existingReg.pushManager?.getSubscription?.().catch(() => null)
688
+ : null;
689
+ if (this.isUnmounted) return;
690
+
691
+ if (existingSub) {
692
+ const configured = await this.ensurePushConfigLoaded();
693
+ if (this.isUnmounted || !configured) return;
694
+
695
+ try {
696
+ const { msgMod, messaging } = await this.ensureFirebaseMessaging();
697
+ if (this.isUnmounted) return;
698
+ this.attachForegroundListener(msgMod, messaging);
699
+ this.pushEnabled = true;
700
+ this.pushState = true;
701
+ this.pushStatus = "Subscribed for push alerts";
702
+ void this.watchPermissionChanges();
703
+
704
+ if (this.props.autoSyncPush !== false) {
705
+ const token = await msgMod.getToken(messaging, {
706
+ vapidKey: this.pushConfig.vapidKey,
707
+ serviceWorkerRegistration: existingReg,
708
+ });
709
+ if (this.isUnmounted) return;
710
+ if (token) {
711
+ this.currentToken = token;
712
+ const cached = readPushSyncCache(this.basePath);
713
+ const email = this.user?.email || "";
714
+ const cacheFresh =
715
+ cached &&
716
+ cached.token === token &&
717
+ cached.email === email &&
718
+ Date.now() - cached.syncedAt < PUSH_SYNC_TTL_MS;
719
+ if (!cacheFresh) {
720
+ await this.syncTokenWithServer(token, "POST");
721
+ if (this.isUnmounted) return;
722
+ writePushSyncCache(this.basePath, token, email);
723
+ }
724
+ }
725
+ }
726
+ } catch (err) {
727
+ if (this.isUnmounted) return;
728
+ this.pushState = false;
729
+ this.pushEnabled = true;
730
+ this.pushStatus = err?.message || "Push initialization failed";
731
+ }
732
+ return;
733
+ }
734
+ }
735
+
736
+ // Not currently subscribed: defer Firebase SDK + SW registration until the user toggles ON.
737
+ this.pushState = false;
738
+ this.pushStatus = "Off — toggle to enable push alerts";
739
+ if (this.props.placement !== "appbar") {
740
+ const configured = await this.ensurePushConfigLoaded();
741
+ if (this.isUnmounted || !configured) return;
742
+ this.pushEnabled = true;
743
+ void this.watchPermissionChanges();
744
+ }
745
+ },
746
+ async ensurePushReadyForMenu() {
747
+ if (!this.pushFeatureEnabled || !this.pushSupported) return;
748
+ if (!this.pushConfigLoaded) {
749
+ const configured = await this.ensurePushConfigLoaded();
750
+ if (this.isUnmounted || !configured) return;
751
+ this.pushEnabled = true;
752
+ if (!this.pushStatus) {
753
+ this.pushStatus =
754
+ Notification.permission === "denied"
755
+ ? BLOCKED_STATUS_MESSAGE
756
+ : "Off — toggle to enable push alerts";
757
+ }
758
+ void this.watchPermissionChanges();
759
+ }
760
+ },
761
+ attachForegroundListener(msgMod, messaging) {
762
+ if (this._unsubscribeOnMessage) {
763
+ this._unsubscribeOnMessage();
764
+ }
765
+ this._unsubscribeOnMessage = msgMod.onMessage(messaging, (payload) => {
766
+ this.send({ topic: "push", payload });
767
+ });
768
+ },
769
+ async syncTokenWithServer(token, method) {
770
+ const res = await fetch(`${this.basePath}/_fcm/register`, {
771
+ method,
772
+ credentials: "same-origin",
773
+ headers: { "Content-Type": "application/json" },
774
+ body: JSON.stringify({ token }),
775
+ });
776
+ const data = await res.json().catch(() => ({}));
777
+ if (!res.ok) {
778
+ throw new Error(data?.error || `Server returned HTTP ${res.status}`);
779
+ }
780
+ return data;
781
+ },
782
+ async watchPermissionChanges() {
783
+ if (
784
+ typeof navigator === "undefined" ||
785
+ !navigator.permissions ||
786
+ typeof navigator.permissions.query !== "function" ||
787
+ this._permissionStatus
788
+ ) {
789
+ return;
790
+ }
791
+ try {
792
+ const status = await navigator.permissions.query({ name: "notifications" });
793
+ if (this.isUnmounted) return;
794
+ this._permissionStatus = status;
795
+ status.onchange = () => {
796
+ this.syncPermissionState();
797
+ };
798
+ } catch {
799
+ // Permissions API for "notifications" is optional across browsers
800
+ }
801
+ },
802
+ syncPermissionState() {
803
+ if (typeof Notification === "undefined") return;
804
+ if (Notification.permission === "denied") {
805
+ this.pushState = false;
806
+ this.currentToken = null;
807
+ clearPushSyncCache(this.basePath);
808
+ this.pushStatus = BLOCKED_STATUS_MESSAGE;
809
+ } else if (!this.pushState) {
810
+ this.pushStatus = "Off — toggle to enable push alerts";
811
+ }
812
+ },
813
+ async unregisterCurrentBrowserPush() {
814
+ let tokenToRemove = this.currentToken;
815
+ let fb = null;
816
+ if (this.pushConfig && (this._messaging || tokenToRemove || Notification.permission === "granted")) {
817
+ fb = await this.ensureFirebaseMessaging().catch(() => null);
818
+ }
819
+ const reg = this._swRegistration || (await this.getExistingServiceWorkerRegistration());
820
+
821
+ if (!tokenToRemove && fb && reg && Notification.permission === "granted") {
822
+ tokenToRemove = await fb.msgMod
823
+ .getToken(fb.messaging, {
824
+ vapidKey: this.pushConfig.vapidKey,
825
+ serviceWorkerRegistration: reg,
826
+ })
827
+ .catch(() => null);
828
+ }
829
+
830
+ if (tokenToRemove) {
831
+ await this.syncTokenWithServer(tokenToRemove, "DELETE").catch(() => {});
832
+ }
833
+ if (fb) {
834
+ await fb.msgMod.deleteToken(fb.messaging).catch(() => {});
835
+ }
836
+ if (reg) {
837
+ const sub = await reg.pushManager?.getSubscription?.().catch(() => null);
838
+ if (sub) {
839
+ await sub.unsubscribe().catch(() => {});
840
+ }
841
+ }
842
+ clearPushSyncCache(this.basePath);
843
+ this.currentToken = null;
844
+ },
845
+ async onPushToggle(nextValue) {
846
+ if (this.pushLoading) return;
847
+ const wantsEnable = Boolean(nextValue);
848
+
849
+ // Call Notification.requestPermission() synchronously inside the user
850
+ // gesture before any `await` so browsers preserve transient user activation.
851
+ let permissionPromise = null;
852
+ if (wantsEnable) {
853
+ if (
854
+ typeof Notification === "undefined" ||
855
+ typeof Notification.requestPermission !== "function"
856
+ ) {
857
+ this.pushState = false;
858
+ this.pushStatus = "Push notifications are not supported in this browser";
859
+ return;
860
+ }
861
+ permissionPromise = requestNotificationPermission();
862
+ }
863
+
864
+ this.pushLoading = true;
865
+ this.pushEnabled = false;
866
+ this.pushStatus = wantsEnable
867
+ ? "Requesting notification permission..."
868
+ : "Updating push subscription...";
869
+
870
+ try {
871
+ if (wantsEnable) {
872
+ const permission = await permissionPromise;
873
+ if (this.isUnmounted) return;
874
+ if (permission !== "granted") {
875
+ this.pushState = false;
876
+ this.pushStatus =
877
+ permission === "denied"
878
+ ? BLOCKED_STATUS_MESSAGE
879
+ : "Permission prompt dismissed";
880
+ return;
881
+ }
882
+ }
883
+
884
+ const configured = await this.ensurePushConfigLoaded();
885
+ if (this.isUnmounted) return;
886
+ if (!configured) {
887
+ throw new Error("Push notifications are not configured on the portal");
888
+ }
889
+
890
+ if (wantsEnable) {
891
+ const { msgMod, messaging } = await this.ensureFirebaseMessaging();
892
+ if (this.isUnmounted) return;
893
+ const reg = await this.ensureServiceWorker();
894
+ if (this.isUnmounted) return;
895
+ this.attachForegroundListener(msgMod, messaging);
896
+
897
+ const token = await msgMod.getToken(messaging, {
898
+ vapidKey: this.pushConfig.vapidKey,
899
+ serviceWorkerRegistration: reg,
900
+ });
901
+ if (this.isUnmounted) return;
902
+ if (!token) {
903
+ throw new Error("Could not register this browser for push notifications");
904
+ }
905
+
906
+ await this.syncTokenWithServer(token, "POST");
907
+ if (this.isUnmounted) return;
908
+ writePushSyncCache(this.basePath, token, this.user?.email || "");
909
+ this.currentToken = token;
910
+ this.pushState = true;
911
+ this.pushStatus = "Subscribed for push alerts";
912
+ this.send({ topic: "push_subscribed", payload: { subscribed: true } });
913
+ } else {
914
+ await this.unregisterCurrentBrowserPush();
915
+ if (this.isUnmounted) return;
916
+ this.pushState = false;
917
+ this.pushStatus = "Unsubscribed from push alerts";
918
+ this.send({ topic: "push_unsubscribed", payload: { subscribed: false } });
919
+ }
920
+ } catch (err) {
921
+ if (this.isUnmounted) return;
922
+ this.pushState = !wantsEnable;
923
+ this.pushStatus = err?.message || "Failed to update push subscription";
924
+ } finally {
925
+ if (!this.isUnmounted) {
926
+ this.pushLoading = false;
927
+ this.pushEnabled = true;
928
+ }
929
+ }
930
+ },
931
+ async onSignOutClick(event) {
932
+ if (!this.signOutHref || this.signingOut) return;
933
+ if (!this.pushState && !this.currentToken) {
934
+ return;
935
+ }
936
+ if (event && typeof event.preventDefault === "function") {
937
+ event.preventDefault();
938
+ }
939
+ this.signingOut = true;
940
+ try {
941
+ await Promise.race([
942
+ this.unregisterCurrentBrowserPush().catch(() => {}),
943
+ new Promise((resolve) => setTimeout(resolve, SIGN_OUT_UNREGISTER_TIMEOUT_MS)),
944
+ ]);
945
+ } finally {
946
+ if (typeof window !== "undefined" && window.location) {
947
+ window.location.assign(this.signOutHref);
948
+ }
949
+ }
950
+ },
951
+ renderAvatar(size) {
952
+ const VAvatar = resolveComponent("v-avatar");
953
+ const VIcon = resolveComponent("v-icon");
954
+
955
+ return h(VAvatar, { size, color: "primary" }, () => {
956
+ if (this.loading) {
957
+ return h("span", { class: "nrc-profile-initials" }, "");
958
+ }
959
+ if (this.showPhoto) {
960
+ return h("img", {
961
+ src: this.user.photoUrl,
962
+ alt: "",
963
+ referrerpolicy: "no-referrer",
964
+ onError: () => {
965
+ this.imgFailed = true;
966
+ },
967
+ style: "width:100%;height:100%;object-fit:cover",
968
+ });
969
+ }
970
+ if (this.initials) {
971
+ return h("span", { class: "nrc-profile-initials" }, this.initials);
972
+ }
973
+ return h(VIcon, { icon: "mdi-account" });
974
+ });
975
+ },
976
+ renderIdentityDetails() {
977
+ const VChip = resolveComponent("v-chip");
978
+ const nameRowChildren = [h("div", { class: "nrc-profile-name" }, this.displayName)];
979
+
980
+ if (this.props.showRole !== false && this.user?.role && !this.local) {
981
+ nameRowChildren.push(
982
+ h(
983
+ VChip,
984
+ {
985
+ size: "x-small",
986
+ variant: "tonal",
987
+ color: "primary",
988
+ label: true,
989
+ class: "nrc-profile-role",
990
+ },
991
+ () => this.roleLabel
992
+ )
993
+ );
994
+ }
995
+
996
+ const items = [h("div", { class: "nrc-profile-name-row" }, nameRowChildren)];
997
+
998
+ if (this.props.showEmail !== false && this.user?.email) {
999
+ items.push(h("div", { class: "nrc-profile-email" }, this.user.email));
1000
+ }
1001
+
1002
+ if (this.loadError) {
1003
+ items.push(
1004
+ h("div", { class: "nrc-profile-local" }, "Could not load account details")
1005
+ );
1006
+ } else if (this.local && !this.user) {
1007
+ items.push(h("div", { class: "nrc-profile-local" }, "Direct connection"));
1008
+ }
1009
+
1010
+ return items;
1011
+ },
1012
+ renderPushSwitch() {
1013
+ if (!this.showPushSection) return null;
1014
+ const VIcon = resolveComponent("v-icon");
1015
+ const disabled =
1016
+ !this.pushEnabled ||
1017
+ !this.pushSupported ||
1018
+ this.pushLoading ||
1019
+ this.state?.enabled === false;
1020
+
1021
+ const copyChildren = [h("span", { class: "nrc-profile-push-label" }, this.pushLabel)];
1022
+ if (this.displayedPushStatus) {
1023
+ copyChildren.push(
1024
+ h("span", { class: "nrc-profile-push-status" }, this.displayedPushStatus)
1025
+ );
1026
+ }
1027
+
1028
+ const btnClasses = [
1029
+ "nrc-profile-push-btn",
1030
+ this.pushState ? "nrc-profile-push-btn--on" : "",
1031
+ this.pushBlocked ? "nrc-profile-push-btn--blocked" : "",
1032
+ ].filter(Boolean);
1033
+
1034
+ return h("div", { class: "nrc-profile-push" }, [
1035
+ h(
1036
+ "button",
1037
+ {
1038
+ type: "button",
1039
+ role: "switch",
1040
+ "aria-checked": String(this.pushState),
1041
+ "aria-busy": String(this.pushLoading),
1042
+ "aria-label": `${this.pushLabel}: ${this.pushPillText}`,
1043
+ disabled,
1044
+ class: btnClasses,
1045
+ onClick: () => {
1046
+ if (disabled) return;
1047
+ const nextVal = !this.pushState;
1048
+ this.pushState = nextVal;
1049
+ void this.onPushToggle(nextVal);
1050
+ },
1051
+ },
1052
+ [
1053
+ h("span", { class: "nrc-profile-bell-badge", "aria-hidden": "true" }, [
1054
+ h(VIcon, { icon: this.pushBellIcon, size: 18 }),
1055
+ ]),
1056
+ h("span", { class: "nrc-profile-push-copy" }, copyChildren),
1057
+ h("span", { class: "nrc-profile-push-pill" }, [
1058
+ this.pushLoading
1059
+ ? h("span", { class: "nrc-profile-spinner", "aria-hidden": "true" })
1060
+ : this.pushPillText,
1061
+ ]),
1062
+ ]
1063
+ ),
1064
+ ]);
1065
+ },
1066
+ renderSignOutButton(inMenu = false) {
1067
+ if (!this.signOutHref) return null;
1068
+ const VBtn = resolveComponent("v-btn");
1069
+ return h(
1070
+ VBtn,
1071
+ {
1072
+ href: this.signOutHref,
1073
+ variant: inMenu ? "text" : "tonal",
1074
+ size: "small",
1075
+ block: inMenu,
1076
+ rounded: "lg",
1077
+ prependIcon: "mdi-logout",
1078
+ loading: this.signingOut,
1079
+ class: "nrc-profile-signout",
1080
+ onClick: (e) => this.onSignOutClick(e),
1081
+ },
1082
+ () => "Sign out"
1083
+ );
1084
+ },
1085
+ },
1086
+ render() {
1087
+ if (this.state?.visible === false) {
1088
+ return null;
1089
+ }
1090
+
1091
+ if (this.props.placement === "appbar") {
1092
+ if (!this.teleportReady) {
1093
+ return null;
1094
+ }
1095
+ const VMenu = resolveComponent("v-menu");
1096
+ const VBtn = resolveComponent("v-btn");
1097
+ const VCard = resolveComponent("v-card");
1098
+
1099
+ const menuChildren = [
1100
+ h("div", { class: "nrc-profile-header" }, [
1101
+ this.renderAvatar(44),
1102
+ h("div", { class: "nrc-profile-text" }, this.loading ? [] : this.renderIdentityDetails()),
1103
+ ]),
1104
+ ];
1105
+ if (!this.loading) {
1106
+ const pushEl = this.renderPushSwitch();
1107
+ if (pushEl) {
1108
+ menuChildren.push(h("div", { class: "nrc-profile-divider" }));
1109
+ menuChildren.push(h("div", { class: "nrc-profile-actions" }, [pushEl]));
1110
+ }
1111
+ const signOutEl = this.renderSignOutButton(true);
1112
+ if (signOutEl) {
1113
+ menuChildren.push(h("div", { class: "nrc-profile-divider" }));
1114
+ menuChildren.push(h("div", { class: "nrc-profile-signout-row" }, [signOutEl]));
1115
+ }
1116
+ }
1117
+
1118
+ const menu = h(
1119
+ VMenu,
1120
+ {
1121
+ location: "bottom end",
1122
+ offset: 8,
1123
+ closeOnContentClick: false,
1124
+ "onUpdate:modelValue": (open) => {
1125
+ if (open) void this.ensurePushReadyForMenu();
1126
+ },
1127
+ },
1128
+ {
1129
+ activator: ({ props: act }) =>
1130
+ h(
1131
+ VBtn,
1132
+ {
1133
+ ...act,
1134
+ icon: true,
1135
+ variant: "text",
1136
+ "aria-label": `Account: ${this.displayName}`,
1137
+ class: "nrc-profile-trigger",
1138
+ },
1139
+ () => this.renderAvatar(32)
1140
+ ),
1141
+ default: () =>
1142
+ h(
1143
+ VCard,
1144
+ {
1145
+ width: 280,
1146
+ rounded: "lg",
1147
+ elevation: 6,
1148
+ class: "nrc-profile-menu nrc-profile-menu-card",
1149
+ },
1150
+ () => h("div", { class: "nrc-profile nrc-profile--menu" }, menuChildren)
1151
+ ),
1152
+ }
1153
+ );
1154
+
1155
+ return h(Teleport, { to: "#app-bar-actions" }, [menu]);
1156
+ }
1157
+
1158
+ const groupChildren = [
1159
+ h("div", { class: "nrc-profile-header" }, [
1160
+ this.renderAvatar(40),
1161
+ h("div", { class: "nrc-profile-text" }, this.loading ? [] : this.renderIdentityDetails()),
1162
+ ]),
1163
+ ];
1164
+ if (!this.loading) {
1165
+ const pushEl = this.renderPushSwitch();
1166
+ if (pushEl) groupChildren.push(pushEl);
1167
+ const signOutEl = this.renderSignOutButton(false);
1168
+ if (signOutEl) groupChildren.push(signOutEl);
1169
+ }
1170
+
1171
+ return h("div", { class: "nrc-profile nrc-profile--group" }, groupChildren);
1172
+ },
1173
+ };