Raw
1 import {
2 BellAlert,
3 BellAlertDone,
4 InformationCircleSolid,
5 } from "@medusajs/icons"
6 import { HttpTypes } from "@medusajs/types"
7 import { clx, Drawer, Heading, IconButton, Text } from "@medusajs/ui"
8 import { formatDistance } from "date-fns"
9 import { TFunction } from "i18next"
10 import { useEffect, useState } from "react"
11 import { useTranslation } from "react-i18next"
12 import {
13 notificationQueryKeys,
14 useMe,
15 useNotifications,
16 } from "../../../hooks/api"
17 import { sdk } from "../../../lib/client"
18 import { FilePreview } from "../../common/file-preview"
19 import { InfiniteList } from "../../common/infinite-list"
20
21 interface NotificationData {
22 title: string
23 description?: string
24 file?: {
25 filename?: string
26 url?: string
27 mimeType?: string
28 }
29 }
30
31 const LAST_READ_NOTIFICATION_KEY = "notificationsLastReadAt"
32
33 export const Notifications = () => {
34 const { t } = useTranslation()
35 const [open, setOpen] = useState(false)
36 const [hasUnread, setHasUnread] = useUnreadNotifications()
37 // This is used to show the unread icon on the notification when the drawer is open,
38 // so it should lag behind the local storage data and should only be reset on close
39 const [lastReadAt, setLastReadAt] = useState(
40 localStorage.getItem(LAST_READ_NOTIFICATION_KEY)
41 )
42 const { user: me } = useMe()
43
44 useEffect(() => {
45 const onKeyDown = (e: KeyboardEvent) => {
46 if (e.key === "n" && (e.metaKey || e.ctrlKey)) {
47 setOpen((prev) => !prev)
48 }
49 }
50
51 document.addEventListener("keydown", onKeyDown)
52
53 return () => {
54 document.removeEventListener("keydown", onKeyDown)
55 }
56 }, [])
57
58 const handleOnOpen = (shouldOpen: boolean) => {
59 if (shouldOpen) {
60 setHasUnread(false)
61 setOpen(true)
62 localStorage.setItem(LAST_READ_NOTIFICATION_KEY, new Date().toISOString())
63 } else {
64 setOpen(false)
65 setLastReadAt(localStorage.getItem(LAST_READ_NOTIFICATION_KEY))
66 }
67 }
68
69 return (
70 <Drawer open={open} onOpenChange={handleOnOpen}>
71 <Drawer.Trigger asChild>
72 <IconButton
73 variant="transparent"
74 size="small"
75 className="text-ui-fg-muted hover:text-ui-fg-subtle"
76 >
77 {hasUnread ? <BellAlertDone /> : <BellAlert />}
78 </IconButton>
79 </Drawer.Trigger>
80 <Drawer.Content>
81 <Drawer.Header>
82 <Drawer.Title asChild>
83 <Heading>{t("notifications.domain")}</Heading>
84 </Drawer.Title>
85 <Drawer.Description className="sr-only">
86 {t("notifications.accessibility.description")}
87 </Drawer.Description>
88 </Drawer.Header>
89 <Drawer.Body className="overflow-y-auto px-0">
90 <InfiniteList<
91 HttpTypes.AdminNotificationListResponse,
92 HttpTypes.AdminNotification,
93 HttpTypes.AdminNotificationListParams
94 >
95 responseKey="notifications"
96 queryKey={notificationQueryKeys.all}
97 queryFn={(params) =>
98 sdk.admin.notification.list({
99 ...params,
100 to: [me?.id, me?.email, ""].filter((v) => v !== undefined),
101 channel: "feed",
102 })
103 }
104 queryOptions={{ enabled: open }}
105 renderEmpty={() => <NotificationsEmptyState t={t} />}
106 renderItem={(notification) => {
107 return (
108 <Notification
109 key={notification.id}
110 notification={notification}
111 unread={
112 Date.parse(notification.created_at) >
113 (lastReadAt ? Date.parse(lastReadAt) : 0)
114 }
115 />
116 )
117 }}
118 />
119 </Drawer.Body>
120 </Drawer.Content>
121 </Drawer>
122 )
123 }
124
125 const Notification = ({
126 notification,
127 unread,
128 }: {
129 notification: HttpTypes.AdminNotification
130 unread?: boolean
131 }) => {
132 const data = notification.data as unknown as NotificationData | undefined
133
134 // We need at least the title to render a notification in the feed
135 if (!data?.title) {
136 return null
137 }
138
139 return (
140 <>
141 <div className="relative flex items-start justify-center gap-3 border-b p-6">
142 <div className="text-ui-fg-muted flex size-5 items-center justify-center">
143 <InformationCircleSolid />
144 </div>
145 <div className="flex w-full flex-col gap-y-3">
146 <div className="flex flex-col">
147 <div className="flex items-center justify-between">
148 <Text size="small" leading="compact" weight="plus">
149 {data.title}
150 </Text>
151 <div className="align-center flex items-center justify-center gap-2">
152 <Text
153 as={"span"}
154 className={clx("text-ui-fg-subtle", {
155 "text-ui-fg-base": unread,
156 })}
157 size="small"
158 leading="compact"
159 weight="plus"
160 >
161 {formatDistance(notification.created_at, new Date(), {
162 addSuffix: true,
163 })}
164 </Text>
165 {unread && (
166 <div
167 className="bg-ui-bg-interactive h-2 w-2 rounded"
168 role="status"
169 />
170 )}
171 </div>
172 </div>
173 {!!data.description && (
174 <Text
175 className="text-ui-fg-subtle whitespace-pre-line"
176 size="small"
177 >
178 {data.description}
179 </Text>
180 )}
181 </div>
182 {!!data?.file?.url && (
183 <FilePreview
184 filename={data.file.filename ?? ""}
185 url={data.file.url}
186 hideThumbnail
187 />
188 )}
189 </div>
190 </div>
191 </>
192 )
193 }
194
195 const NotificationsEmptyState = ({ t }: { t: TFunction }) => {
196 return (
197 <div className="flex h-full flex-col items-center justify-center">
198 <BellAlertDone />
199 <Text size="small" leading="compact" weight="plus" className="mt-3">
200 {t("notifications.emptyState.title")}
201 </Text>
202 <Text
203 size="small"
204 className="text-ui-fg-muted mt-1 max-w-[294px] text-center"
205 >
206 {t("notifications.emptyState.description")}
207 </Text>
208 </div>
209 )
210 }
211
212 const useUnreadNotifications = () => {
213 const [hasUnread, setHasUnread] = useState(false)
214 const { notifications } = useNotifications(
215 { limit: 1, offset: 0, fields: "created_at" },
216 { refetchInterval: 60_000 }
217 )
218 const lastNotification = notifications?.[0]
219
220 useEffect(() => {
221 if (!lastNotification) {
222 return
223 }
224
225 const lastNotificationAsTimestamp = Date.parse(lastNotification.created_at)
226
227 const lastReadDatetime = localStorage.getItem(LAST_READ_NOTIFICATION_KEY)
228 const lastReadAsTimestamp = lastReadDatetime
229 ? Date.parse(lastReadDatetime)
230 : 0
231
232 if (lastNotificationAsTimestamp > lastReadAsTimestamp) {
233 setHasUnread(true)
234 }
235 }, [lastNotification])
236
237 return [hasUnread, setHasUnread] as const
238 }