Merge pull request #4448 from Infisical/ENG-3586

feat(notifications): User Notifications
This commit is contained in:
x032205
2025-09-08 14:22:58 -04:00
committed by GitHub
24 changed files with 5595 additions and 4601 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,70 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { useOrganization } from "@app/context";
import { notificationKeys } from "./queries";
import { TUserNotification } from "./types";
export const useMarkAllNotificationsAsRead = () => {
const { currentOrg } = useOrganization();
const orgId = currentOrg.id || "";
const queryClient = useQueryClient();
return useMutation({
mutationFn: async () => {
await apiRequest.post("/api/v1/notifications/user/mark-as-read");
},
onSuccess: () => {
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(orgId), (oldData) => {
if (!oldData) return oldData;
return oldData.map((notification) => ({
...notification,
isRead: true
}));
});
}
});
};
export const useUpdateNotification = () => {
const { currentOrg } = useOrganization();
const orgId = currentOrg.id || "";
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ notificationId, isRead }: { notificationId: string; isRead: boolean }) => {
const { data } = await apiRequest.patch<{ notification: TUserNotification }>(
`/api/v1/notifications/user/${notificationId}`,
{ isRead }
);
return data.notification;
},
onSuccess: (updatedNotification) => {
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(orgId), (oldData) => {
if (!oldData) return oldData;
return oldData.map((notification) =>
notification.id === updatedNotification.id ? updatedNotification : notification
);
});
}
});
};
export const useDeleteNotification = () => {
const { currentOrg } = useOrganization();
const orgId = currentOrg.id || "";
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (notificationId: string) => {
await apiRequest.delete(`/api/v1/notifications/user/${notificationId}`);
},
onSuccess: (_, notificationId) => {
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(orgId), (oldData) => {
if (!oldData) return oldData;
return oldData.filter((notification) => notification.id !== notificationId);
});
}
});
};
@@ -0,0 +1,29 @@
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { useOrganization } from "@app/context";
import { TUserNotification } from "./types";
export const notificationKeys = {
all: ["notifications"] as const,
list: (orgId: string) => [...notificationKeys.all, "list", { orgId }] as const
};
export const useGetMyNotifications = () => {
const { currentOrg } = useOrganization();
const orgId = currentOrg.id || "";
return useQuery({
queryKey: notificationKeys.list(orgId),
queryFn: async () => {
const {
data: { notifications }
} = await apiRequest.get<{ notifications: TUserNotification[] }>(
"/api/v1/notifications/user"
);
return notifications;
},
refetchInterval: 30 * 1000 // Poll every 30 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: string;
}
@@ -48,6 +48,7 @@ import { AuthMethod } from "@app/hooks/api/users/types";
import { navigateUserToOrg } from "@app/pages/auth/LoginPage/Login.utils";
import { ServerAdminsPanel } from "../ServerAdminsPanel/ServerAdminsPanel";
import { NotificationDropdown } from "./NotificationDropdown";
const getPlan = (subscription: SubscriptionPlan) => {
if (subscription.groups) return "Enterprise";
@@ -118,6 +119,7 @@ export const Navbar = () => {
const [shouldShowMfa, toggleShowMfa] = useToggle(false);
const router = useRouter();
const queryClient = useQueryClient();
const location = useLocation();
const matches = useRouterState({ select: (s) => s.matches.at(-1)?.context });
const breadcrumbs = matches && "breadcrumbs" in matches ? matches.breadcrumbs : undefined;
@@ -304,7 +306,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>
@@ -358,9 +360,10 @@ export const Navbar = () => {
)}
</DropdownMenuContent>
</DropdownMenu>
<NotificationDropdown />
<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,60 @@
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={<Markdown>{notification.title}</Markdown>} delayDuration={300}>
<span className="overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-5 text-mineshaft-100">
<Markdown components={{ p: "span" }}>{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-xs 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"
colorSchema="danger"
size="sm"
onClick={(e) => {
e.stopPropagation();
onDelete(notification.id);
}}
>
<FontAwesomeIcon icon={faTrash} />
</IconButton>
</div>
</div>
);
};
@@ -0,0 +1,116 @@
import { useMemo } from "react";
import { faBell } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useRouter } from "@tanstack/react-router";
import {
ContentLoader,
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger
} from "@app/components/v2";
import {
useDeleteNotification,
useMarkAllNotificationsAsRead,
useUpdateNotification
} from "@app/hooks/api/notifications/mutations";
import { useGetMyNotifications } from "@app/hooks/api/notifications/queries";
import { Notification } from "./Notification";
export const NotificationDropdown = () => {
const router = useRouter();
const { data: notifications, isLoading } = useGetMyNotifications();
const { mutate: markAllAsRead } = useMarkAllNotificationsAsRead();
const { mutate: updateNotification } = useUpdateNotification();
const { mutate: deleteNotification } = useDeleteNotification();
const unreadCount = useMemo(
() => notifications?.filter((n) => !n.isRead).length || 0,
[notifications]
);
return (
<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-3 py-2">
<span className="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) {
updateNotification({ notificationId: notification.id, isRead: true });
}
if (notification.link) {
router.navigate({ to: notification.link });
}
}}
onKeyDown={(e) => {
if (e.key !== "Enter") return;
if (!notification.isRead) {
updateNotification({ notificationId: notification.id, isRead: true });
}
if (notification.link) {
router.navigate({ to: notification.link });
}
}}
>
<Notification notification={notification} onDelete={deleteNotification} />
</div>
))}
</div>
)}
</div>
</div>
</DropdownMenuContent>
</DropdownMenu>
);
};
+4726 -4564
View File
File diff suppressed because it is too large Load Diff