Skip to content

Web Notifications #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: release/v0.2.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion frontend/src/components/layout/header/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import NotificationBadge from "@components/layout/header/NotificationBadge"
import SearchBox from "@components/layout/header/SearchBox"
import WSStatus from "@components/layout/header/WSStatus"
import { DRAWER_WIDTH } from "@components/layout/menu/Menu"
import NotificationBadge from "@components/notifications/NotificationBadge"
import AppBar from "@mui/material/AppBar"
import Box from "@mui/material/Box"
import Slide from "@mui/material/Slide"
Expand Down
13 changes: 0 additions & 13 deletions frontend/src/components/layout/header/NotificationBadge.tsx

This file was deleted.

93 changes: 93 additions & 0 deletions frontend/src/components/notifications/NotificationBadge.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import NotificationItem from "@components/notifications/NotificationItem"
import ClearAllIcon from "@mui/icons-material/ClearAll"
import NotificationsIcon from "@mui/icons-material/Notifications"
import NotificationsOffIcon from "@mui/icons-material/NotificationsOff"
import Badge from "@mui/material/Badge"
import IconButton from "@mui/material/IconButton"
import List from "@mui/material/List"
import ListItem from "@mui/material/ListItem"
import ListItemSecondaryAction from "@mui/material/ListItemSecondaryAction"
import ListItemText from "@mui/material/ListItemText"
import Popover from "@mui/material/Popover"
import Switch from "@mui/material/Switch"
import Tooltip from "@mui/material/Tooltip"
import {
addNotification,
clearNotifications,
toggleNotifications,
useNotificationStore,
} from "@stores/useNotifications"
import React, { useEffect, useMemo } from "react"

const NotificationBadge: React.FC = () => {
const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(null)

const notifications = useNotificationStore((state) => state.notifications)
const unseenNotifications = useMemo(
() => notifications.filter((notification) => !notification.seen),
[notifications]
)
const enabled = useNotificationStore((state) => state.enabled)
const id = anchorEl ? "notification-popover" : undefined

useEffect(() => {
// Create fake notifications when dropdown is open
if (anchorEl) {
const token = setInterval(
() =>
addNotification({
type: "info",
message: "Hello world!",
}),
5 * 1000
)
return () => clearInterval(token)
}
}, [anchorEl])

return (
<>
<IconButton size="large" aria-describedby={id} onClick={(event) => setAnchorEl(event.currentTarget)}>
<Badge badgeContent={unseenNotifications.length} color="error">
{enabled ? <NotificationsIcon /> : <NotificationsOffIcon />}
</Badge>
</IconButton>
<Popover
id={id}
open={Boolean(anchorEl)}
anchorEl={anchorEl}
anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
onClose={() => setAnchorEl(null)}
>
<List
sx={{ width: "450px", maxHeight: "70vh", overflowY: "scroll" }}
subheader={
<ListItem>
<ListItemText primary="Notifications"></ListItemText>
<ListItemSecondaryAction>
<Tooltip title={enabled ? "Disable notifications" : "Enable notifications"} arrow>
<Switch checked={enabled} onChange={async () => await toggleNotifications()} />
</Tooltip>
<Tooltip title="Clear all" arrow>
<IconButton onClick={() => clearNotifications()}>
<ClearAllIcon />
</IconButton>
</Tooltip>
</ListItemSecondaryAction>
</ListItem>
}
>
{notifications.map((notification) => (
<NotificationItem key={notification.id} notification={notification} />
))}
{notifications.length === 0 && (
<ListItem>
<ListItemText primary="No new notifications" primaryTypographyProps={{ align: "center" }} />
</ListItem>
)}
</List>
</Popover>
</>
)
}
export default NotificationBadge
26 changes: 26 additions & 0 deletions frontend/src/components/notifications/NotificationItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import ListItem from "@mui/material/ListItem"
import ListItemText from "@mui/material/ListItemText"
import { Notification, setNotificationSeen } from "@stores/useNotifications"
import React, { useEffect } from "react"

interface NotificationItemProps {
notification: Notification
}

const NotificationItem: React.FC<NotificationItemProps> = ({ notification }) => {
useEffect(() => {
// Automatically mark notification as seen after 5 seconds
const token = setTimeout(() => {
if (!notification.seen) {
setNotificationSeen(notification.id)
}
}, 1000)
return () => clearTimeout(token)
}, [notification.id, notification.seen])
return (
<ListItem>
<ListItemText primary={notification.type} secondary={notification.message} />
</ListItem>
)
}
export default NotificationItem
83 changes: 83 additions & 0 deletions frontend/src/stores/useNotifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import create from "zustand"

type NotificationType = "error" | "info" | "success"

export interface Notification {
id: number
timestamp: Date
seen: boolean
icon?: string
link?: string
message: string
type: NotificationType
}

interface NotificationStore {
notifications: Notification[]
enabled: boolean
limit: number
}

export const useNotificationStore = create<NotificationStore>(() => ({
notifications: [],
enabled: Notification.permission === "granted",
limit: 30,
}))

export const addNotification = (notification: Omit<Notification, "id" | "timestamp" | "seen">) => {
const enabled = useNotificationStore.getState().enabled

if (enabled && Notification.permission === "granted") {
const notificationOptions = {
body: notification.message,
icon: notification.icon,
data: {
url: notification.link,
},
}

new Notification(notification.type, notificationOptions)
useNotificationStore.setState((state) => ({
notifications: [
{
id: state.notifications.length + 1,
timestamp: new Date(),
seen: false,
...notification,
},
...state.notifications.slice(0, state.limit - 1),
],
}))
}
}

export const toggleNotifications = async () => {
const enabled = useNotificationStore.getState().enabled

if (enabled) {
useNotificationStore.setState({ enabled: false })
} else {
if (Notification.permission === "granted") {
useNotificationStore.setState({ enabled: true })
} else if (Notification.permission !== "denied") {
const permission = await Notification.requestPermission()
if (permission === "granted") {
useNotificationStore.setState({ enabled: true })
}
}
}
}

export const clearNotifications = () => useNotificationStore.setState({ notifications: [] })

export const setNotificationSeen = (notificationId: number) =>
useNotificationStore.setState((state) => {
const notifications = state.notifications.map((notification) => {
if (notification.id === notificationId) {
return { ...notification, seen: true }
} else {
return notification
}
})
return { notifications, enabled: state.enabled }
})