Spaces:
Sleeping
Sleeping
Download apps/web/src/components/notifications/NotificationBell.tsx from Benaah/MicProtocol: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/web/src/components/notifications/NotificationBell.tsx
- Command line
-
hf download hf://spaces/Benaah/MicProtocol/apps/web/src/components/notifications/NotificationBell.tsx
-
curl -L -o NotificationBell.tsx https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/web/src/components/notifications/NotificationBell.tsx
10 kB
| "use client"; | |
| import React, { useEffect, useState } from "react"; | |
| import { Bell } from "lucide-react"; | |
| import { trpc } from "@/lib/trpc"; | |
| import Link from "next/link"; | |
| import { formatDistanceToNow } from "date-fns"; | |
| import * as Popover from "@radix-ui/react-popover"; | |
| type Notification = { | |
| id: string; | |
| title: string; | |
| message: string; | |
| isRead: boolean; | |
| createdAt: string; | |
| link?: string | null; | |
| }; | |
| /** Convert a base64-encoded VAPID public key to a Uint8Array for the Push API. */ | |
| function urlBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer> { | |
| const padding = "=".repeat((4 - (base64String.length % 4)) % 4); | |
| const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/"); | |
| const raw = atob(base64); | |
| const buffer = new ArrayBuffer(raw.length); | |
| const output = new Uint8Array(buffer); | |
| for (let i = 0; i < raw.length; i++) { | |
| output[i] = raw.charCodeAt(i); | |
| } | |
| return output; | |
| } | |
| export function NotificationBell() { | |
| const [open, setOpen] = useState(false); | |
| const [mounted] = useState(true); | |
| const [pushSubscribed, setPushSubscribed] = useState(false); | |
| const [isSubscribing, setIsSubscribing] = useState(false); | |
| const vapidKeyQuery = trpc.notifications.webPushVapidKey.useQuery(undefined, { | |
| retry: false, | |
| }); | |
| const subscribeMutation = trpc.notifications.webPushSubscribe.useMutation(); | |
| const unsubscribeMutation = trpc.notifications.webPushUnsubscribe.useMutation(); | |
| const { data: notifications } = trpc.notifications.list.useQuery(undefined, { | |
| retry: false, | |
| }); | |
| const markAllAsRead = trpc.notifications.markAllAsRead.useMutation(); | |
| const markAsRead = trpc.notifications.markAsRead.useMutation(); | |
| // ββ Register service worker + check existing push subscription ββ | |
| useEffect(() => { | |
| let cancelled = false; | |
| async function initPush() { | |
| if (typeof window === "undefined" || !("PushManager" in window)) return; | |
| if (!("serviceWorker" in navigator)) return; | |
| try { | |
| const registration = await navigator.serviceWorker.register("/sw.js", { | |
| scope: "/", | |
| }); | |
| const subscription = await registration.pushManager.getSubscription(); | |
| if (!cancelled) setPushSubscribed(!!subscription); | |
| } catch { | |
| // Service worker registration failed β push unavailable | |
| } | |
| } | |
| initPush(); | |
| return () => { | |
| cancelled = true; | |
| }; | |
| }, []); | |
| // ββ Subscribe the current browser to push notifications ββ | |
| async function subscribeToPush() { | |
| if (!vapidKeyQuery.data?.vapidPublicKey) return; | |
| setIsSubscribing(true); | |
| try { | |
| const registration = await navigator.serviceWorker.ready; | |
| const applicationServerKey = urlBase64ToUint8Array( | |
| vapidKeyQuery.data.vapidPublicKey, | |
| ); | |
| const subscription = await registration.pushManager.subscribe({ | |
| userVisibleOnly: true, | |
| applicationServerKey, | |
| }); | |
| const key = subscription.getKey?.("p256dh"); | |
| const auth = subscription.getKey?.("auth"); | |
| if (!key || !auth) throw new Error("Unable to get push subscription keys"); | |
| const p256dhKey = btoa( | |
| String.fromCharCode(...new Uint8Array(key as ArrayBuffer)), | |
| ); | |
| const authKey = btoa( | |
| String.fromCharCode(...new Uint8Array(auth as ArrayBuffer)), | |
| ); | |
| await subscribeMutation.mutateAsync({ | |
| endpoint: subscription.endpoint, | |
| p256dhKey, | |
| authKey, | |
| deviceInfo: navigator.userAgent, | |
| }); | |
| setPushSubscribed(true); | |
| } catch (err) { | |
| console.error("Failed to subscribe to push notifications", err); | |
| } finally { | |
| setIsSubscribing(false); | |
| } | |
| } | |
| // ββ Unsubscribe the current browser from push notifications ββ | |
| async function unsubscribeFromPush() { | |
| setIsSubscribing(true); | |
| try { | |
| const registration = await navigator.serviceWorker.ready; | |
| const subscription = await registration.pushManager.getSubscription(); | |
| if (subscription) { | |
| await unsubscribeMutation.mutateAsync({ endpoint: subscription.endpoint }); | |
| await subscription.unsubscribe(); | |
| } | |
| setPushSubscribed(false); | |
| } catch (err) { | |
| console.error("Failed to unsubscribe from push notifications", err); | |
| } finally { | |
| setIsSubscribing(false); | |
| } | |
| } | |
| const unreadCount = notifications?.items?.filter((n: any) => !n.isRead).length || 0; | |
| if (!mounted) { | |
| return ( | |
| <button | |
| className="btn btn-ghost" | |
| style={{ position: "relative", padding: "var(--space-2)" }} | |
| aria-label="Notifications" | |
| type="button" | |
| > | |
| <Bell size={18} /> | |
| </button> | |
| ); | |
| } | |
| return ( | |
| <Popover.Root open={open} onOpenChange={setOpen}> | |
| <Popover.Trigger asChild> | |
| <button | |
| className="btn btn-ghost" | |
| style={{ position: "relative", padding: "var(--space-2)" }} | |
| aria-label="Notifications" | |
| type="button" | |
| > | |
| <Bell size={18} /> | |
| {unreadCount > 0 && ( | |
| <span | |
| className="notification-dot animate-pulse-dot" | |
| aria-hidden="true" | |
| /> | |
| )} | |
| </button> | |
| </Popover.Trigger> | |
| <Popover.Portal> | |
| <Popover.Content | |
| className="radix-popover-content" | |
| align="end" | |
| sideOffset={5} | |
| style={{ | |
| width: "350px", | |
| maxHeight: "80vh", | |
| overflowY: "auto", | |
| backgroundColor: "var(--surface-color)", | |
| border: "1px solid var(--border-color)", | |
| borderRadius: "var(--radius-lg)", | |
| boxShadow: "0 10px 30px -10px rgba(0,0,0,0.5)", | |
| padding: "var(--space-4)", | |
| zIndex: 100, | |
| }} | |
| > | |
| <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--space-4)" }}> | |
| <h3 style={{ margin: 0, fontSize: "16px", fontWeight: "600" }}>Notifications</h3> | |
| {unreadCount > 0 && ( | |
| <button | |
| onClick={() => markAllAsRead.mutate()} | |
| style={{ fontSize: "12px", background: "none", border: "none", color: "var(--primary-color)", cursor: "pointer" }} | |
| type="button" | |
| > | |
| Mark all as read | |
| </button> | |
| )} | |
| </div> | |
| {/* Browser push notifications toggle */} | |
| <div | |
| style={{ | |
| display: "flex", | |
| alignItems: "center", | |
| justifyContent: "space-between", | |
| gap: "var(--space-2)", | |
| marginBottom: "var(--space-4)", | |
| paddingTop: "var(--space-2)", | |
| borderTop: "1px solid var(--border-color)", | |
| }} | |
| > | |
| <span style={{ fontSize: "13px", color: "var(--text-secondary)" }}> | |
| Browser notifications | |
| </span> | |
| <label | |
| style={{ | |
| display: "flex", | |
| alignItems: "center", | |
| gap: "var(--space-2)", | |
| cursor: | |
| vapidKeyQuery.data && !isSubscribing ? "pointer" : "not-allowed", | |
| fontSize: "13px", | |
| color: "var(--text-secondary)", | |
| }} | |
| > | |
| <input | |
| type="checkbox" | |
| checked={pushSubscribed} | |
| onChange={() => | |
| pushSubscribed | |
| ? unsubscribeFromPush() | |
| : subscribeToPush() | |
| } | |
| disabled={!vapidKeyQuery.data || isSubscribing} | |
| /> | |
| {isSubscribing | |
| ? "Subscribing..." | |
| : pushSubscribed | |
| ? "On" | |
| : "Off"} | |
| </label> | |
| </div> | |
| <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-3)" }}> | |
| {!notifications?.items?.length ? ( | |
| <p style={{ textAlign: "center", color: "var(--text-tertiary)", fontSize: "14px", padding: "var(--space-4) 0" }}> | |
| No new notifications | |
| </p> | |
| ) : ( | |
| notifications?.items?.map((notification: any) => ( | |
| <div | |
| key={notification.id} | |
| style={{ | |
| padding: "var(--space-3)", | |
| borderRadius: "var(--radius-md)", | |
| backgroundColor: notification.isRead ? "transparent" : "var(--surface-sunken)", | |
| display: "flex", | |
| flexDirection: "column", | |
| gap: "var(--space-1)", | |
| borderLeft: notification.isRead ? "none" : "3px solid var(--primary-color)", | |
| cursor: "pointer", | |
| }} | |
| onClick={() => { | |
| if (!notification.isRead) markAsRead.mutate({ id: notification.id }); | |
| }} | |
| > | |
| <div style={{ display: "flex", justifyContent: "space-between" }}> | |
| <span style={{ fontWeight: 600, fontSize: "14px" }}>{notification.title}</span> | |
| <span style={{ fontSize: "12px", color: "var(--text-tertiary)" }}> | |
| {formatDistanceToNow(new Date(notification.createdAt), { addSuffix: true })} | |
| </span> | |
| </div> | |
| <p style={{ margin: 0, fontSize: "13px", color: "var(--text-secondary)", lineHeight: 1.4 }}> | |
| {notification.message} | |
| </p> | |
| {notification.link && ( | |
| <Link href={notification.link} style={{ fontSize: "12px", color: "var(--primary-color)", marginTop: "var(--space-1)", display: "inline-block" }}> | |
| View Details → | |
| </Link> | |
| )} | |
| </div> | |
| )) | |
| )} | |
| </div> | |
| </Popover.Content> | |
| </Popover.Portal> | |
| </Popover.Root> | |
| ); | |
| } | |