Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/app/api/notifications/stream/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { NextRequest } from "next/server";

export const runtime = "edge";

/**
* GET /api/notifications/stream?address=<stellar_address>
*
* Server-Sent Events stream for real-time notifications.
* Emits contribution, payout, and dispute events.
*/
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const address = searchParams.get("address");

if (!address) {
return new Response("Missing address", { status: 400 });
}

const encoder = new TextEncoder();

const stream = new ReadableStream({
start(controller) {
// Send initial keep-alive comment
controller.enqueue(encoder.encode(": connected\n\n"));

// Keep-alive ping every 25 seconds to prevent proxy timeouts
const pingInterval = setInterval(() => {
try {
controller.enqueue(encoder.encode(": ping\n\n"));
} catch {
clearInterval(pingInterval);
}
}, 25000);

// In a real implementation, subscribe to on-chain events here.
// This scaffold emits a welcome event so the client can verify the stream works.
setTimeout(() => {
try {
const event = JSON.stringify({
groupId: null,
message: "Notifications connected. You will receive updates for contributions, payouts, and disputes.",
});
controller.enqueue(encoder.encode(`event: contribution\ndata: ${event}\n\n`));
} catch {}
}, 500);

req.signal.addEventListener("abort", () => {
clearInterval(pingInterval);
try {
controller.close();
} catch {}
});
},
});

return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
}
3 changes: 2 additions & 1 deletion src/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import React, { createContext, useContext, useState, useCallback, useEffect } from "react";
import { connectWallet, getPublicKey, isFreighterInstalled } from "@/lib/wallet";
import { NotificationProvider } from "@/components/NotificationProvider";

interface WalletContextType {
address: string | null;
Expand Down Expand Up @@ -54,7 +55,7 @@ export function Providers({ children }: { children: React.ReactNode }) {
disconnect,
}}
>
{children}
<NotificationProvider>{children}</NotificationProvider>
</WalletContext.Provider>
);
}
6 changes: 5 additions & 1 deletion src/components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import Link from "next/link";
import { ConnectWallet } from "./ConnectWallet";
import { NotificationBell } from "./NotificationBell";

export function Navbar() {
return (
Expand All @@ -27,7 +28,10 @@ export function Navbar() {
</Link>
</div>
</div>
<ConnectWallet />
<div className="flex items-center space-x-2">
<NotificationBell />
<ConnectWallet />
</div>
</div>
</div>
</nav>
Expand Down
135 changes: 135 additions & 0 deletions src/components/NotificationBell.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"use client";

import { useState, useRef, useEffect } from "react";
import Link from "next/link";
import { useNotifications, Notification } from "./NotificationProvider";

function timeAgo(date: Date): string {
const diff = Date.now() - date.getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
return `${Math.floor(hrs / 24)}d ago`;
}

function typeIcon(type: Notification["type"]) {
if (type === "contribution") return "💰";
if (type === "payout") return "🎉";
return "⚠️";
}

export function NotificationBell() {
const { notifications, unreadCount, markAsRead, markAllAsRead, clearAll } =
useNotifications();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);

useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
}
}
if (open) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [open]);

return (
<div className="relative" ref={ref}>
<button
onClick={() => setOpen((v) => !v)}
className="relative p-2 text-gray-600 hover:text-gray-900 focus:outline-none"
aria-label="Notifications"
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
/>
</svg>
{unreadCount > 0 && (
<span className="absolute top-1 right-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-xs text-white font-bold">
{unreadCount > 9 ? "9+" : unreadCount}
</span>
)}
</button>

{open && (
<div className="absolute right-0 mt-2 w-80 rounded-lg bg-white shadow-lg ring-1 ring-black ring-opacity-5 z-50">
<div className="flex items-center justify-between px-4 py-3 border-b">
<span className="text-sm font-semibold text-gray-900">Notifications</span>
<div className="flex space-x-2">
{unreadCount > 0 && (
<button
onClick={markAllAsRead}
className="text-xs text-primary-600 hover:text-primary-800"
>
Mark all read
</button>
)}
{notifications.length > 0 && (
<button
onClick={clearAll}
className="text-xs text-gray-400 hover:text-gray-600"
>
Clear
</button>
)}
</div>
</div>

<div className="max-h-96 overflow-y-auto divide-y divide-gray-100">
{notifications.length === 0 ? (
<p className="px-4 py-6 text-center text-sm text-gray-500">
No notifications yet
</p>
) : (
notifications.map((n) => (
<div
key={n.id}
className={`px-4 py-3 hover:bg-gray-50 cursor-pointer ${
!n.read ? "bg-blue-50" : ""
}`}
onClick={() => markAsRead(n.id)}
>
<div className="flex items-start space-x-2">
<span className="text-lg">{typeIcon(n.type)}</span>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-900">{n.title}</p>
<p className="text-xs text-gray-600 mt-0.5 truncate">{n.message}</p>
<div className="flex items-center justify-between mt-1">
<span className="text-xs text-gray-400">{timeAgo(n.timestamp)}</span>
{n.groupId && (
<Link
href={`/groups/${n.groupId}`}
className="text-xs text-primary-600 hover:underline"
onClick={(e) => e.stopPropagation()}
>
View group
</Link>
)}
</div>
</div>
{!n.read && (
<span className="mt-1 h-2 w-2 rounded-full bg-blue-500 flex-shrink-0" />
)}
</div>
</div>
))
)}
</div>
</div>
)}
</div>
);
}
140 changes: 140 additions & 0 deletions src/components/NotificationProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"use client";

import React, { createContext, useContext, useState, useEffect, useCallback, useRef } from "react";
import { useWallet } from "@/app/providers";

export type NotificationType = "contribution" | "payout" | "dispute";

export interface Notification {
id: string;
type: NotificationType;
title: string;
message: string;
groupId?: string;
timestamp: Date;
read: boolean;
}

interface NotificationContextType {
notifications: Notification[];
unreadCount: number;
markAsRead: (id: string) => void;
markAllAsRead: () => void;
clearAll: () => void;
}

const NotificationContext = createContext<NotificationContextType>({
notifications: [],
unreadCount: 0,
markAsRead: () => {},
markAllAsRead: () => {},
clearAll: () => {},
});

export function useNotifications() {
return useContext(NotificationContext);
}

function makeId() {
return Math.random().toString(36).slice(2) + Date.now().toString(36);
}

export function NotificationProvider({ children }: { children: React.ReactNode }) {
const { address, isConnected } = useWallet();
const [notifications, setNotifications] = useState<Notification[]>([]);
const eventSourceRef = useRef<EventSource | null>(null);

const addNotification = useCallback((data: Omit<Notification, "id" | "timestamp" | "read">) => {
const notification: Notification = {
...data,
id: makeId(),
timestamp: new Date(),
read: false,
};
setNotifications((prev) => [notification, ...prev].slice(0, 50));
}, []);

useEffect(() => {
if (!isConnected || !address) {
if (eventSourceRef.current) {
eventSourceRef.current.close();
eventSourceRef.current = null;
}
return;
}

const url = `/api/notifications/stream?address=${encodeURIComponent(address)}`;
const es = new EventSource(url);
eventSourceRef.current = es;

es.addEventListener("contribution", (e) => {
try {
const d = JSON.parse(e.data);
addNotification({
type: "contribution",
title: "Contribution Received",
message: d.message || `A contribution was made to group ${d.groupId}`,
groupId: d.groupId,
});
} catch {}
});

es.addEventListener("payout", (e) => {
try {
const d = JSON.parse(e.data);
addNotification({
type: "payout",
title: "Payout Distributed",
message: d.message || `Payout distributed for group ${d.groupId}`,
groupId: d.groupId,
});
} catch {}
});

es.addEventListener("dispute", (e) => {
try {
const d = JSON.parse(e.data);
addNotification({
type: "dispute",
title: "Dispute Raised",
message: d.message || `A dispute was raised in group ${d.groupId}`,
groupId: d.groupId,
});
} catch {}
});

es.onerror = () => {
es.close();
eventSourceRef.current = null;
};

return () => {
es.close();
eventSourceRef.current = null;
};
}, [isConnected, address, addNotification]);

const markAsRead = useCallback((id: string) => {
setNotifications((prev) =>
prev.map((n) => (n.id === id ? { ...n, read: true } : n))
);
}, []);

const markAllAsRead = useCallback(() => {
setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
}, []);

const clearAll = useCallback(() => {
setNotifications([]);
}, []);

const unreadCount = notifications.filter((n) => !n.read).length;

return (
<NotificationContext.Provider
value={{ notifications, unreadCount, markAsRead, markAllAsRead, clearAll }}
>
{children}
</NotificationContext.Provider>
);
}