feat(notifications): User Notifications

This commit is contained in:
x032205
2025-08-31 22:53:12 -04:00
parent 29dd49d696
commit 542cc0f93c
22 changed files with 756 additions and 15 deletions
@@ -11,9 +11,10 @@ type Props = {
text?: string | string[];
frequency?: number;
className?: string;
lottieClassName?: string;
};
export const ContentLoader = ({ text, frequency = 2000, className }: Props) => {
export const ContentLoader = ({ text, frequency = 2000, className, lottieClassName }: Props) => {
const [pos, setPos] = useState(0);
const isTextArray = Array.isArray(text);
useEffect(() => {
@@ -33,7 +34,11 @@ export const ContentLoader = ({ text, frequency = 2000, className }: Props) => {
className
)}
>
<Lottie isAutoPlay icon="infisical_loading" className="h-32 w-32" />
<Lottie
isAutoPlay
icon="infisical_loading"
className={twMerge("h-32 w-32", lottieClassName)}
/>
{text && isTextArray && (
<AnimatePresence mode="wait">
<motion.div
@@ -16,6 +16,7 @@ export type TooltipProps = Omit<TooltipPrimitive.TooltipContentProps, "open" | "
center?: boolean;
size?: "sm" | "md";
rootProps?: RootProps;
delayDuration?: number;
};
export const Tooltip = ({
@@ -31,12 +32,13 @@ export const Tooltip = ({
position = "top",
size = "md",
rootProps,
delayDuration = 50,
...props
}: TooltipProps) =>
// just render children if tooltip content is empty
content ? (
<TooltipPrimitive.Root
delayDuration={50}
delayDuration={delayDuration}
{...rootProps}
open={isOpen}
defaultOpen={defaultOpen}
@@ -0,0 +1,56 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { notificationKeys } from "./queries";
import { TUserNotification } from "./types";
export const useMarkAllNotificationsAsRead = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async () => {
await apiRequest.post("/api/v1/notifications/user/mark-as-read");
},
onSuccess: () => {
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(), (oldData) => {
if (!oldData) return oldData;
return oldData.map((notification) => ({
...notification,
isRead: true
}));
});
}
});
};
export const useMarkNotificationAsRead = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (notificationId: string) => {
await apiRequest.post(`/api/v1/notifications/user/${notificationId}/mark-as-read`);
},
onSuccess: (_, notificationId) => {
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(), (oldData) => {
if (!oldData) return oldData;
return oldData.map((notification) =>
notification.id === notificationId ? { ...notification, isRead: true } : notification
);
});
}
});
};
export const useDeleteNotification = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (notificationId: string) => {
await apiRequest.delete(`/api/v1/notifications/user/${notificationId}`);
},
onSuccess: (_, notificationId) => {
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(), (oldData) => {
if (!oldData) return oldData;
return oldData.filter((notification) => notification.id !== notificationId);
});
}
});
};
@@ -0,0 +1,25 @@
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TUserNotification } from "./types";
export const notificationKeys = {
all: ["notifications"] as const,
list: () => [...notificationKeys.all, "list"] as const
};
export const useGetMyNotifications = () => {
return useQuery({
queryKey: notificationKeys.list(),
queryFn: async () => {
const {
data: { notifications }
} = await apiRequest.get<{ notifications: TUserNotification[] }>(
"/api/v1/notifications/user"
);
return notifications;
},
refetchInterval: 10 * 1000 // Poll every 10 seconds
});
};
@@ -0,0 +1,10 @@
export interface TUserNotification {
id: string;
userId: string;
type: string;
title: string;
body?: string | null;
link?: string | null;
isRead: boolean;
createdAt: Date;
}
@@ -1,6 +1,6 @@
import { useState } from "react";
import { useMemo, useState } from "react";
import { faGithub, faSlack } from "@fortawesome/free-brands-svg-icons";
import { faCircleQuestion, faUserCircle } from "@fortawesome/free-regular-svg-icons";
import { faBell, faCircleQuestion, faUserCircle } from "@fortawesome/free-regular-svg-icons";
import {
faArrowUpRightFromSquare,
faBook,
@@ -24,6 +24,7 @@ import SecurityClient from "@app/components/utilities/SecurityClient";
import {
BreadcrumbContainer,
Button,
ContentLoader,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -41,12 +42,19 @@ import { useToggle } from "@app/hooks";
import { useGetOrganizations, useLogoutUser, workspaceKeys } from "@app/hooks/api";
import { authKeys, selectOrganization } from "@app/hooks/api/auth/queries";
import { MfaMethod } from "@app/hooks/api/auth/types";
import {
useDeleteNotification,
useMarkAllNotificationsAsRead,
useMarkNotificationAsRead
} from "@app/hooks/api/notifications/mutations";
import { useGetMyNotifications } from "@app/hooks/api/notifications/queries";
import { getAuthToken } from "@app/hooks/api/reactQuery";
import { SubscriptionPlan } from "@app/hooks/api/types";
import { AuthMethod } from "@app/hooks/api/users/types";
import { navigateUserToOrg } from "@app/pages/auth/LoginPage/Login.utils";
import { ServerAdminsPanel } from "../ServerAdminsPanel/ServerAdminsPanel";
import { Notification } from "./Notification";
const getPlan = (subscription: SubscriptionPlan) => {
if (subscription.groups) return "Enterprise";
@@ -118,6 +126,16 @@ export const Navbar = () => {
const router = useRouter();
const queryClient = useQueryClient();
const { data: notifications, isLoading } = useGetMyNotifications();
const { mutate: markAllAsRead } = useMarkAllNotificationsAsRead();
const { mutate: markNotificationAsRead } = useMarkNotificationAsRead();
const { mutate: deleteNotification } = useDeleteNotification();
const unreadCount = useMemo(
() => notifications?.filter((n) => !n.isRead).length || 0,
[notifications]
);
const matches = useRouterState({ select: (s) => s.matches.at(-1)?.context });
const breadcrumbs = matches && "breadcrumbs" in matches ? matches.breadcrumbs : undefined;
@@ -280,7 +298,7 @@ export const Navbar = () => {
<div className="flex-grow" />
<DropdownMenu modal={false}>
<DropdownMenuTrigger>
<div className="rounded-l-md border border-r-0 border-mineshaft-500 px-2 py-1 hover:bg-mineshaft-600">
<div className="rounded-l-md border border-r-0 border-mineshaft-500 px-2.5 py-1 hover:bg-mineshaft-600">
<FontAwesomeIcon icon={faCircleQuestion} className="text-mineshaft-200" />
</div>
</DropdownMenuTrigger>
@@ -334,9 +352,89 @@ export const Navbar = () => {
)}
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu modal={false}>
<DropdownMenuTrigger>
<div className="relative border border-r-0 border-mineshaft-500 px-2.5 py-1 hover:bg-mineshaft-600">
<FontAwesomeIcon icon={faBell} className="text-mineshaft-200" />
{unreadCount > 0 && (
<span className="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-yellow-400 px-1 text-[10px] text-black">
{unreadCount > 99 ? "99+" : unreadCount}
</span>
)}
</div>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
side="bottom"
className="mt-3 flex h-[550px] w-[400px] overflow-hidden rounded-lg"
>
<div className="flex w-full flex-col">
<div className="flex items-center justify-between border-b border-mineshaft-500 px-4 py-2">
<span className="text-xl font-semibold text-white">Notifications</span>
<button
type="button"
className="text-xs font-medium text-mineshaft-300 hover:text-primary-400 disabled:pointer-events-none disabled:opacity-50"
onClick={(e) => {
e.preventDefault();
markAllAsRead();
}}
disabled={unreadCount === 0}
>
Mark all as read
</button>
</div>
<div className="flex h-full w-full overflow-auto">
{isLoading && (
<div className="flex h-full w-full items-center justify-center">
<ContentLoader className="pointer-events-none" lottieClassName="size-10" />
</div>
)}
{!isLoading && notifications?.length === 0 && (
<div className="flex h-full w-full flex-col items-center justify-center">
<FontAwesomeIcon icon={faBell} size="3x" className="text-mineshaft-400" />
<span className="mt-4 text-sm text-mineshaft-300">No new notifications</span>
<span className="text-xs text-mineshaft-400">
We&apos;ll let you know when something important happens.
</span>
</div>
)}
{!isLoading && notifications && notifications.length > 0 && (
<div className="flex w-full flex-col">
{notifications.map((notification) => (
<div
role="button"
tabIndex={0}
key={notification.id}
onClick={() => {
if (!notification.isRead) {
markNotificationAsRead(notification.id);
}
if (notification.link) {
router.navigate({ to: notification.link });
}
}}
onKeyDown={(e) => {
if (e.key !== "Enter") return;
if (!notification.isRead) {
markNotificationAsRead(notification.id);
}
if (notification.link) {
router.navigate({ to: notification.link });
}
}}
>
<Notification notification={notification} onDelete={deleteNotification} />
</div>
))}
</div>
)}
</div>
</div>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<div className="rounded-r-md border border-mineshaft-500 px-2 py-1 hover:bg-mineshaft-600">
<div className="rounded-r-md border border-mineshaft-500 px-2.5 py-1 hover:bg-mineshaft-600">
<FontAwesomeIcon icon={faUserCircle} className="text-mineshaft-200" />
</div>
</DropdownMenuTrigger>
@@ -0,0 +1,59 @@
import Markdown from "react-markdown";
import { faCircle, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { formatDistance } from "date-fns";
import { twMerge } from "tailwind-merge";
import { IconButton, Tooltip } from "@app/components/v2";
import { TUserNotification } from "@app/hooks/api/notifications/types";
type Props = {
notification: TUserNotification;
onDelete: (notificationId: string) => void;
};
export const Notification = ({ notification, onDelete }: Props) => {
return (
<div
className={twMerge(
"group relative flex cursor-pointer items-start border-b border-mineshaft-600 p-3 transition-colors",
notification.link ? "hover:bg-mineshaft-700" : "cursor-default",
!notification.isRead && "bg-mineshaft-800"
)}
>
<div className="flex w-full min-w-0 flex-col">
<div className="flex gap-2">
{!notification.isRead && (
<FontAwesomeIcon icon={faCircle} className="mt-1.5 size-2 text-yellow-400" />
)}
<Tooltip content={notification.title} delayDuration={300}>
<span className="overflow-hidden text-ellipsis whitespace-nowrap font-medium leading-5 text-mineshaft-100">
<Markdown>{notification.title}</Markdown>
</span>
</Tooltip>
<span className="ml-auto mt-px whitespace-nowrap text-xs text-mineshaft-400">
{formatDistance(notification.createdAt, new Date())} ago
</span>
</div>
{notification.body && (
<span className="max-w-[350px] text-sm text-mineshaft-300">
<Markdown>{notification.body}</Markdown>
</span>
)}
</div>
<div className="flex w-0 flex-shrink-0 justify-end opacity-0 transition-all group-hover:w-[24px] group-hover:opacity-100">
<IconButton
ariaLabel="delete"
variant="plain"
size="sm"
onClick={(e) => {
e.stopPropagation();
onDelete(notification.id);
}}
>
<FontAwesomeIcon icon={faTrash} />
</IconButton>
</div>
</div>
);
};