DiffWeave / studio /src /components /NotificationsCenter.jsx
shak3008's picture
feat(notifications): add dynamic bell notification center with collaborator request approval and fix profile workspace privacy
36d7087
Raw History Blame Contribute Delete
17.2 kB
import React, { useState, useEffect, useRef } from 'react';
import {
Bell,
Check,
X,
CheckCheck,
UserCheck,
UserX,
FileText,
GitPullRequest,
CheckCircle2,
Clock,
Layers,
Sparkles,
ExternalLink
} from 'lucide-react';
import { api } from '../api/client';
export default function NotificationsCenter({ onSelectWorkspace, onOpenProfile, showToast = () => {} }) {
const [isOpen, setIsOpen] = useState(false);
const [notifications, setNotifications] = useState([]);
const [unreadCount, setUnreadCount] = useState(0);
const [filter, setFilter] = useState('ALL'); // 'ALL' | 'REQUESTS' | 'ACTIVITY'
const [actionInProgress, setActionInProgress] = useState({}); // { [memberId]: 'APPROVE' | 'REJECT' }
const [resolvedActions, setResolvedActions] = useState({}); // { [memberId]: 'APPROVED' | 'REJECTED' }
const dropdownRef = useRef(null);
// Poll for notifications every 8 seconds
const fetchNotifications = async () => {
try {
const data = await api.getNotifications();
if (data && Array.isArray(data.notifications)) {
setNotifications(data.notifications);
setUnreadCount(data.unread_count || 0);
}
} catch (err) {
// Quiet fail on network hiccups
}
};
useEffect(() => {
fetchNotifications();
const interval = setInterval(fetchNotifications, 8000);
return () => clearInterval(interval);
}, []);
// Close dropdown on click outside
useEffect(() => {
function handleClickOutside(e) {
if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
setIsOpen(false);
}
}
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
}
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [isOpen]);
const handleMarkAllRead = async () => {
try {
await api.markAllNotificationsRead();
setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
setUnreadCount(0);
showToast('All notifications marked as read.', 'info');
} catch (err) {
showToast('Failed to mark notifications read.', 'error');
}
};
const handleMarkRead = async (notifId) => {
try {
await api.markNotificationRead(notifId);
setNotifications((prev) =>
prev.map((n) => (n.id === notifId ? { ...n, is_read: true } : n))
);
setUnreadCount((prev) => Math.max(0, prev - 1));
} catch {
// Ignore
}
};
const handleRespondRequest = async (workspaceId, memberId, decision) => {
setActionInProgress((prev) => ({ ...prev, [memberId]: decision }));
try {
await api.respondWorkspaceRequest(workspaceId, memberId, decision, 'EDITOR');
setResolvedActions((prev) => ({ ...prev, [memberId]: decision === 'APPROVE' ? 'APPROVED' : 'REJECTED' }));
setUnreadCount((prev) => Math.max(0, prev - 1));
showToast(
decision === 'APPROVE'
? 'Collaborator request approved! They can now collaborate.'
: 'Collaborator request declined.',
decision === 'APPROVE' ? 'success' : 'info'
);
setTimeout(fetchNotifications, 1000);
} catch (err) {
showToast(`Error responding to request: ${err.message || err}`, 'error');
} finally {
setActionInProgress((prev) => {
const next = { ...prev };
delete next[memberId];
return next;
});
}
};
const filteredNotifs = notifications.filter((n) => {
if (filter === 'REQUESTS') return n.type === 'ACCESS_REQUEST';
if (filter === 'ACTIVITY') return n.type !== 'ACCESS_REQUEST';
return true;
});
const requestsCount = notifications.filter((n) => n.type === 'ACCESS_REQUEST').length;
return (
<div className="relative" ref={dropdownRef}>
{/* Bell Button */}
<button
onClick={() => {
setIsOpen(!isOpen);
if (!isOpen && unreadCount > 0) {
fetchNotifications();
}
}}
className="relative p-2 rounded-lg text-slate-300 hover:text-white hover:bg-slate-800/80 transition-all border border-transparent hover:border-slate-700/60 focus:outline-none focus:ring-2 focus:ring-teal-500/40"
title="Notifications"
id="notifications-bell-btn"
>
<Bell className={`w-5 h-5 transition-transform ${isOpen ? 'scale-110 text-teal-400' : ''}`} />
{/* Dynamic Glowing Notification Counter Badge (YouTube style) */}
{unreadCount > 0 && (
<span className="absolute -top-1 -right-1 flex h-5 min-w-[20px] px-1 items-center justify-center rounded-full bg-gradient-to-r from-teal-500 to-cyan-500 text-[11px] font-bold text-slate-950 shadow-lg shadow-teal-500/40 animate-pulse">
{unreadCount > 99 ? '99+' : unreadCount}
</span>
)}
</button>
{/* Floating Notifications Dropdown Popover */}
{isOpen && (
<div className="absolute right-0 mt-2 w-96 max-w-[calc(100vw-2rem)] bg-slate-900/95 backdrop-blur-xl border border-slate-700/80 rounded-2xl shadow-2xl shadow-black/80 z-50 overflow-hidden flex flex-col max-h-[540px] animate-in fade-in zoom-in-95 duration-150">
{/* Header */}
<div className="p-4 border-b border-slate-800/80 bg-slate-950/40 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="w-7 h-7 rounded-lg bg-teal-500/10 border border-teal-500/30 flex items-center justify-center text-teal-400">
<Bell className="w-4 h-4" />
</div>
<h3 className="font-semibold text-slate-100 text-sm">Notifications</h3>
{unreadCount > 0 && (
<span className="text-[10px] font-semibold bg-teal-500/20 text-teal-300 border border-teal-500/30 px-2 py-0.5 rounded-full">
{unreadCount} new
</span>
)}
</div>
{unreadCount > 0 && (
<button
onClick={handleMarkAllRead}
className="text-xs text-slate-400 hover:text-teal-400 flex items-center gap-1 transition-colors px-2 py-1 rounded hover:bg-slate-800/50"
title="Mark all as read"
>
<CheckCheck className="w-3.5 h-3.5" />
<span>Mark all read</span>
</button>
)}
</div>
{/* Filter Pills */}
<div className="px-4 py-2 border-b border-slate-800/60 bg-slate-950/20 flex items-center gap-1.5 text-xs">
<button
onClick={() => setFilter('ALL')}
className={`px-2.5 py-1 rounded-md font-medium transition-all ${
filter === 'ALL'
? 'bg-slate-800 text-teal-300 border border-teal-500/30 shadow-sm'
: 'text-slate-400 hover:text-slate-200'
}`}
>
All ({notifications.length})
</button>
<button
onClick={() => setFilter('REQUESTS')}
className={`px-2.5 py-1 rounded-md font-medium transition-all flex items-center gap-1 ${
filter === 'REQUESTS'
? 'bg-slate-800 text-teal-300 border border-teal-500/30 shadow-sm'
: 'text-slate-400 hover:text-slate-200'
}`}
>
Requests
{requestsCount > 0 && (
<span className="text-[10px] bg-amber-500/20 text-amber-300 px-1.5 py-0.2 rounded-full font-bold">
{requestsCount}
</span>
)}
</button>
<button
onClick={() => setFilter('ACTIVITY')}
className={`px-2.5 py-1 rounded-md font-medium transition-all ${
filter === 'ACTIVITY'
? 'bg-slate-800 text-teal-300 border border-teal-500/30 shadow-sm'
: 'text-slate-400 hover:text-slate-200'
}`}
>
Activity
</button>
</div>
{/* Notifications Items List */}
<div className="overflow-y-auto flex-1 divide-y divide-slate-800/50">
{filteredNotifs.length === 0 ? (
<div className="p-8 text-center flex flex-col items-center justify-center text-slate-500">
<div className="w-12 h-12 rounded-full bg-slate-800/50 flex items-center justify-center mb-3 text-slate-400">
<CheckCircle2 className="w-6 h-6 text-teal-500/60" />
</div>
<p className="text-sm font-medium text-slate-300">All caught up!</p>
<p className="text-xs text-slate-500 mt-1">No notifications matching this filter.</p>
</div>
) : (
filteredNotifs.map((notif) => {
const isActionable = notif.is_actionable && notif.type === 'ACCESS_REQUEST';
const resolvedStatus = notif.member_id ? resolvedActions[notif.member_id] : null;
const inProgress = notif.member_id ? actionInProgress[notif.member_id] : null;
return (
<div
key={notif.id}
onClick={() => {
if (!notif.is_read) handleMarkRead(notif.id);
}}
className={`p-3.5 transition-colors hover:bg-slate-800/40 relative ${
!notif.is_read ? 'bg-teal-950/15' : ''
}`}
>
{/* Unread indicator dot */}
{!notif.is_read && (
<span className="absolute top-4 right-3 w-2 h-2 rounded-full bg-teal-400 ring-2 ring-teal-400/30" />
)}
<div className="flex items-start gap-3">
{/* Icon */}
<div className="mt-0.5 shrink-0">
{notif.type === 'ACCESS_REQUEST' && (
<div className="w-8 h-8 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center justify-center text-amber-400">
<UserCheck className="w-4 h-4" />
</div>
)}
{notif.type === 'ACCESS_APPROVED' && (
<div className="w-8 h-8 rounded-lg bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center text-emerald-400">
<CheckCircle2 className="w-4 h-4" />
</div>
)}
{notif.type === 'DOCUMENT_STATUS' && (
<div className="w-8 h-8 rounded-lg bg-cyan-500/10 border border-cyan-500/30 flex items-center justify-center text-cyan-400">
<FileText className="w-4 h-4" />
</div>
)}
{notif.type === 'PR_UPDATE' && (
<div className="w-8 h-8 rounded-lg bg-purple-500/10 border border-purple-500/30 flex items-center justify-center text-purple-400">
<GitPullRequest className="w-4 h-4" />
</div>
)}
</div>
{/* Content */}
<div className="flex-1 min-w-0 pr-4">
<div className="flex items-center gap-2 mb-1 flex-wrap">
<span className="text-xs font-semibold text-slate-200 truncate">
{notif.title}
</span>
{notif.workspace_name && (
<span className="text-[10px] bg-slate-800 text-slate-400 px-1.5 py-0.5 rounded border border-slate-700/60 font-mono">
{notif.workspace_name}
</span>
)}
</div>
<p className="text-xs text-slate-300 leading-relaxed mb-2">
{notif.message}
</p>
{/* Interactive Approval / Rejection Actions for Access Requests */}
{isActionable && (
<div className="mt-2.5 pt-2 border-t border-slate-800/80">
{resolvedStatus ? (
<div
className={`text-xs font-medium px-2.5 py-1 rounded inline-flex items-center gap-1.5 ${
resolvedStatus === 'APPROVED'
? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
: 'bg-rose-500/20 text-rose-300 border border-rose-500/30'
}`}
>
{resolvedStatus === 'APPROVED' ? (
<>
<Check className="w-3.5 h-3.5" />
<span>Approved as Editor</span>
</>
) : (
<>
<X className="w-3.5 h-3.5" />
<span>Request Declined</span>
</>
)}
</div>
) : (
<div className="flex items-center gap-2">
<button
onClick={(e) => {
e.stopPropagation();
handleRespondRequest(notif.workspace_id, notif.member_id, 'APPROVE');
}}
disabled={Boolean(inProgress)}
className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-xs font-medium flex items-center gap-1.5 shadow-sm transition-all disabled:opacity-50"
>
<Check className="w-3.5 h-3.5" />
<span>{inProgress === 'APPROVE' ? 'Approving...' : 'Approve as Editor'}</span>
</button>
<button
onClick={(e) => {
e.stopPropagation();
handleRespondRequest(notif.workspace_id, notif.member_id, 'REJECT');
}}
disabled={Boolean(inProgress)}
className="px-3 py-1.5 bg-slate-800 hover:bg-rose-950/60 text-slate-300 hover:text-rose-400 border border-slate-700/80 rounded-lg text-xs font-medium flex items-center gap-1.5 transition-all disabled:opacity-50"
>
<X className="w-3.5 h-3.5" />
<span>{inProgress === 'REJECT' ? 'Declining...' : 'Decline'}</span>
</button>
</div>
)}
</div>
)}
{/* Navigation link if workspace actionable */}
{!isActionable && notif.workspace_id && onSelectWorkspace && (
<button
onClick={(e) => {
e.stopPropagation();
setIsOpen(false);
onSelectWorkspace({ id: notif.workspace_id, name: notif.workspace_name });
}}
className="mt-1 text-[11px] text-teal-400 hover:text-teal-300 flex items-center gap-1 transition-colors"
>
<span>Open in Workspace</span>
<ExternalLink className="w-3 h-3" />
</button>
)}
{/* Time */}
{notif.created_at && (
<span className="block mt-1 text-[10px] text-slate-500 font-mono">
{new Date(notif.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} ·{' '}
{new Date(notif.created_at).toLocaleDateString([], { month: 'short', day: 'numeric' })}
</span>
)}
</div>
</div>
</div>
);
})
)}
</div>
{/* Footer */}
<div className="p-2.5 border-t border-slate-800/80 bg-slate-950/60 text-center">
<span className="text-[11px] text-slate-500 font-mono">
DiffWeave Live Notification Stream
</span>
</div>
</div>
)}
</div>
);
}