Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(notifications): add clear all and refine remove control (#8482)

Andrew Huangae32566aa75d
diff --git a/backend/src/server/routes/v1/notification-router.ts b/backend/src/server/routes/v1/notification-router.ts
index dddadafb8d..6bde703a60 100644
--- a/backend/src/server/routes/v1/notification-router.ts
+++ b/backend/src/server/routes/v1/notification-router.ts
@@ -38,6 +38,33 @@ export const registerNotificationRouter = async (server: FastifyZodProvider) =>
}
});
+ server.route({
+ url: "/user",
+ config: {
+ rateLimit: writeLimit
+ },
+ method: "DELETE",
+ schema: {
+ operationId: "deleteUserNotifications",
+ response: {
+ 204: z.string().length(0)
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req, reply) => {
+ if (req.auth.authMode !== AuthMode.JWT) {
+ throw new UnauthorizedError({ message: "This endpoint can only be accessed by users" });
+ }
+
+ await server.services.notification.deleteUserNotifications({
+ userId: req.auth.userId,
+ orgId: req.auth.orgId
+ });
+
+ return reply.code(204).send("");
+ }
+ });
+
server.route({
url: "/user/:notificationId",
config: {
diff --git a/backend/src/services/notification/notification-service.ts b/backend/src/services/notification/notification-service.ts
index ed50c3f1cf..ba0d9f5756 100644
--- a/backend/src/services/notification/notification-service.ts
+++ b/backend/src/services/notification/notification-service.ts
@@ -48,6 +48,10 @@ export const notificationServiceFactory = ({
await userNotificationDAL.markAllNotificationsAsRead(userId, orgId);
};
+ const deleteUserNotifications = async ({ userId, orgId }: { userId: string; orgId: string }) => {
+ await userNotificationDAL.deleteAllNotifications(userId, orgId);
+ };
+
const updateUserNotification = async ({
userId,
notificationId,
@@ -75,6 +79,7 @@ export const notificationServiceFactory = ({
listUserNotifications,
createUserNotifications,
deleteUserNotification,
+ deleteUserNotifications,
markUserNotificationsAsRead,
updateUserNotification
};
diff --git a/backend/src/services/notification/user-notification-dal.ts b/backend/src/services/notification/user-notification-dal.ts
index 334835de30..25d839f5f3 100644
--- a/backend/src/services/notification/user-notification-dal.ts
+++ b/backend/src/services/notification/user-notification-dal.ts
@@ -125,5 +125,18 @@ export const userNotificationDALFactory = (db: TDbClient) => {
.update({ isRead: true });
};
- return { ...notificationOrm, pruneNotifications, find, markAllNotificationsAsRead };
+ const deleteAllNotifications = async (userId: string, orgId: string) => {
+ try {
+ await db(TableName.UserNotifications)
+ .where({ userId, isRead: true })
+ .andWhere((qb) => {
+ void qb.where({ orgId }).orWhereNull("orgId");
+ })
+ .delete();
+ } catch (error) {
+ throw new DatabaseError({ error });
+ }
+ };
+
+ return { ...notificationOrm, pruneNotifications, find, markAllNotificationsAsRead, deleteAllNotifications };
};
diff --git a/frontend/src/hooks/api/notifications/mutations.tsx b/frontend/src/hooks/api/notifications/mutations.tsx
index 34ab7aa261..391ab2a303 100644
--- a/frontend/src/hooks/api/notifications/mutations.tsx
+++ b/frontend/src/hooks/api/notifications/mutations.tsx
@@ -68,3 +68,18 @@ export const useDeleteNotification = () => {
}
});
};
+
+export const useDeleteAllNotifications = () => {
+ const { currentOrg } = useOrganization();
+ const orgId = currentOrg.id || "";
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async () => {
+ await apiRequest.delete("/api/v1/notifications/user");
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: notificationKeys.list(orgId) });
+ }
+ });
+};
diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/Notification.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/Notification.tsx
index 40c2e177cd..6ef415b491 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/Notification.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/Notification.tsx
@@ -1,7 +1,6 @@
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 { Trash2 } from "lucide-react";
import { twMerge } from "tailwind-merge";
import { IconButton, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
@@ -28,9 +27,11 @@ export const Notification = ({ notification, onDelete }: Props) => {
<div className="flex items-start gap-2">
{!notification.isRead && (
<div className="flex h-5 items-center">
- <FontAwesomeIcon
- icon={faCircle}
- className={twMerge("size-2 shrink-0", isCritical ? "text-danger" : "text-warning")}
+ <span
+ className={twMerge(
+ "size-2 shrink-0 rounded-full",
+ isCritical ? "bg-danger" : "bg-warning"
+ )}
/>
</div>
)}
@@ -44,9 +45,24 @@ export const Notification = ({ notification, onDelete }: Props) => {
<Markdown>{notification.title}</Markdown>
</TooltipContent>
</Tooltip>
- <span className="mt-px ml-auto text-xs whitespace-nowrap text-muted">
- {formatDistance(notification.createdAt, new Date())} ago
- </span>
+ <div className="relative ml-auto shrink-0 pl-7">
+ <span className="inline-block text-xs leading-5 whitespace-nowrap text-muted transition-transform group-focus-within:-translate-x-7 group-hover:-translate-x-7 [@media(hover:none)]:-translate-x-7">
+ {formatDistance(notification.createdAt, new Date())} ago
+ </span>
+ <IconButton
+ aria-label="Delete notification"
+ variant="ghost-muted"
+ size="2xs"
+ className="absolute -top-0.5 right-0 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100"
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete(notification.id);
+ }}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <Trash2 />
+ </IconButton>
+ </div>
</div>
{notification.body && (
<div className="w-full overflow-hidden text-xs break-words text-accent">
@@ -54,19 +70,6 @@ export const Notification = ({ notification, onDelete }: Props) => {
</div>
)}
</div>
- <div className="mt-0.5 flex w-0 shrink-0 justify-end opacity-0 transition-all group-hover:w-[24px] group-hover:opacity-100">
- <IconButton
- aria-label="Delete notification"
- variant="danger"
- size="xs"
- onClick={(e) => {
- e.stopPropagation();
- onDelete(notification.id);
- }}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- </div>
</div>
);
};
diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/NotificationDropdown.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/NotificationDropdown.tsx
index d5ad92b2b7..6863fde7e5 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/NotificationDropdown.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/NotificationDropdown.tsx
@@ -1,10 +1,16 @@
-import { useMemo, useState } from "react";
-import { faBell } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useMemo, useRef, useState } from "react";
import { useRouter } from "@tanstack/react-router";
import { Bell, BellIcon } from "lucide-react";
import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
Badge,
DropdownMenu,
DropdownMenuContent,
@@ -14,6 +20,7 @@ import {
Loader
} from "@app/components/v3";
import {
+ useDeleteAllNotifications,
useDeleteNotification,
useMarkAllNotificationsAsRead,
useUpdateNotification
@@ -28,11 +35,14 @@ const NOTIFICATIONS_PER_PAGE = 20;
export const NotificationDropdown = () => {
const router = useRouter();
const [visibleNotificationCount, setVisibleNotificationCount] = useState(NOTIFICATIONS_PER_PAGE);
+ const [isClearAllOpen, setIsClearAllOpen] = useState(false);
+ const clearAllButtonRef = useRef<HTMLButtonElement>(null);
const { data: notifications, isLoading } = useGetMyNotifications();
const { mutate: markAllAsRead } = useMarkAllNotificationsAsRead();
const { mutate: updateNotification } = useUpdateNotification();
const { mutate: deleteNotification } = useDeleteNotification();
+ const { mutate: deleteAllNotifications, isPending: isClearingAll } = useDeleteAllNotifications();
// Links are stored server-side and may be site-relative or absolute, and may carry a query string. Passing them
// straight to `to` would resolve them against the current path and swallow the search params, so normalize to a
@@ -66,96 +76,140 @@ export const NotificationDropdown = () => {
const hasMoreNotifications = notifications && visibleNotificationCount < notifications.length;
return (
- <DropdownMenu
- modal={false}
- onOpenChange={(isOpen) => {
- if (isOpen) setVisibleNotificationCount(NOTIFICATIONS_PER_PAGE);
- }}
- >
- <DropdownMenuTrigger asChild>
- <IconButton variant="outline" size="sm" aria-label="Notifications" className="relative">
- {unreadCount > 0 ? <BellIcon className="text-warning" /> : <Bell />}
- {unreadCount > 0 && (
- <span
- aria-hidden="true"
- className="absolute -top-0.5 -right-0.5 z-10 size-2 rounded-full bg-warning ring-2 ring-background"
- />
- )}
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- side="bottom"
- className="flex h-[550px] w-[400px] overflow-hidden p-0"
+ <>
+ <DropdownMenu
+ modal={false}
+ onOpenChange={(isOpen) => {
+ if (isOpen) setVisibleNotificationCount(NOTIFICATIONS_PER_PAGE);
+ }}
>
- <div className="flex w-full flex-col">
- <div className="flex items-center justify-between border-b border-border px-3 py-2">
- <div className="flex items-center gap-2">
- <span className="font-medium text-foreground">Notifications</span>
- {hasCritical && (
- <Badge variant="danger">
- {criticalCount > 99 ? "99+" : criticalCount} Critical
- </Badge>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="outline" size="sm" aria-label="Notifications" className="relative">
+ {unreadCount > 0 ? <BellIcon className="text-warning" /> : <Bell />}
+ {unreadCount > 0 && (
+ <span
+ aria-hidden="true"
+ className="absolute -top-0.5 -right-0.5 z-10 size-2 rounded-full bg-warning ring-2 ring-background"
+ />
+ )}
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ side="bottom"
+ className="flex h-[550px] w-[400px] overflow-hidden p-0"
+ onInteractOutside={(e) => {
+ if (isClearAllOpen) e.preventDefault();
+ }}
+ >
+ <div className="flex w-full flex-col">
+ <div className="flex items-center justify-between border-b border-border px-3 py-2">
+ <div className="flex items-center gap-2">
+ <span className="font-medium text-foreground">Notifications</span>
+ {hasCritical && (
+ <Badge variant="danger">
+ {criticalCount > 99 ? "99+" : criticalCount} Critical
+ </Badge>
+ )}
+ </div>
+ <button
+ ref={clearAllButtonRef}
+ type="button"
+ className="text-xs font-medium text-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
+ onClick={(e) => {
+ e.preventDefault();
+ if (unreadCount > 0) markAllAsRead();
+ else setIsClearAllOpen(true);
+ }}
+ disabled={!notifications?.length || isClearingAll}
+ >
+ {unreadCount > 0 ? "Mark all as read" : "Clear All"}
+ </button>
+ </div>
+ <div className="flex h-full w-full overflow-auto">
+ {isLoading && (
+ <div className="flex h-full w-full items-center justify-center">
+ <Loader className="pointer-events-none" size="sm" />
+ </div>
+ )}
+ {!isLoading && notifications?.length === 0 && (
+ <div className="flex h-full w-full flex-col items-center justify-center">
+ <Bell className="size-10 text-muted" />
+ <span className="mt-4 text-sm text-accent">No new notifications</span>
+ <span className="text-xs text-muted">
+ We&apos;ll let you know when something important happens.
+ </span>
+ </div>
+ )}
+ {!isLoading && notifications && notifications.length > 0 && (
+ <div className="flex w-full flex-col">
+ {visibleNotifications?.map((notification) => (
+ <div
+ role="button"
+ tabIndex={0}
+ key={notification.id}
+ onClick={() => handleNotificationOpen(notification)}
+ onKeyDown={(e) => {
+ if (e.key !== "Enter") return;
+ handleNotificationOpen(notification);
+ }}
+ >
+ <Notification notification={notification} onDelete={deleteNotification} />
+ </div>
+ ))}
+ {hasMoreNotifications && (
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.preventDefault();
+ setVisibleNotificationCount((count) => count + NOTIFICATIONS_PER_PAGE);
+ }}
+ >
+ Show More
+ </DropdownMenuItem>
+ )}
+ </div>
)}
</div>
- <button
- type="button"
- className="text-xs font-medium text-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <AlertDialog open={isClearAllOpen} onOpenChange={setIsClearAllOpen}>
+ <AlertDialogContent
+ onCloseAutoFocus={(e) => {
+ e.preventDefault();
+ if (clearAllButtonRef.current && !clearAllButtonRef.current.disabled) {
+ clearAllButtonRef.current.focus();
+ } else {
+ clearAllButtonRef.current?.closest<HTMLElement>("[role='menu']")?.focus();
+ }
+ }}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>Clear All Notifications?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will remove all your read notifications for this organization, including account
+ notifications. This cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel variant="outline" disabled={isClearingAll}>
+ Cancel
+ </AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ isPending={isClearingAll}
onClick={(e) => {
e.preventDefault();
- markAllAsRead();
+ deleteAllNotifications(undefined, {
+ onSuccess: () => setIsClearAllOpen(false)
+ });
}}
- 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">
- <Loader className="pointer-events-none" size="sm" />
- </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-muted" />
- <span className="mt-4 text-sm text-accent">No new notifications</span>
- <span className="text-xs text-muted">
- We&apos;ll let you know when something important happens.
- </span>
- </div>
- )}
- {!isLoading && notifications && notifications.length > 0 && (
- <div className="flex w-full flex-col">
- {visibleNotifications?.map((notification) => (
- <div
- role="button"
- tabIndex={0}
- key={notification.id}
- onClick={() => handleNotificationOpen(notification)}
- onKeyDown={(e) => {
- if (e.key !== "Enter") return;
- handleNotificationOpen(notification);
- }}
- >
- <Notification notification={notification} onDelete={deleteNotification} />
- </div>
- ))}
- {hasMoreNotifications && (
- <DropdownMenuItem
- onSelect={(e) => {
- e.preventDefault();
- setVisibleNotificationCount((count) => count + NOTIFICATIONS_PER_PAGE);
- }}
- >
- Show More
- </DropdownMenuItem>
- )}
- </div>
- )}
- </div>
- </div>
- </DropdownMenuContent>
- </DropdownMenu>
+ Clear All
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
);
};