Skip to content

Commit

Permalink
Simple notifications on message
Browse files Browse the repository at this point in the history
  • Loading branch information
KomelT committed Sep 18, 2024
1 parent 57d0d27 commit 65f695c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { useAppStore } from "@core/stores/appStore.js";
import { useDeviceStore } from "@core/stores/deviceStore.js";
import { Dashboard } from "@pages/Dashboard/index.js";
import { MapProvider } from "react-map-gl";
import { Notifications } from "./components/Notifications";

export const App = (): JSX.Element => {
const { getDevice } = useDeviceStore();
Expand Down Expand Up @@ -39,6 +40,7 @@ export const App = (): JSX.Element => {
<DialogManager />
<CommandPalette />
<PageRouter />
<Notifications />
</div>
) : (
<>
Expand Down
40 changes: 40 additions & 0 deletions src/components/Notifications.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useDevice } from "@app/core/stores/deviceStore";
import type { Types } from "@meshtastic/js";
import { numberToHexUnpadded } from "@noble/curves/abstract/utils";
import { useCallback, useEffect } from "react";

export const Notifications = (): JSX.Element | null => {
const { nodes, connection, channels } = useDevice();
let notificationPermission = Notification.permission;

useEffect(() => {
if (!("Notification" in window)) {
console.log("This browser does not support notifications.");
notificationPermission = "denied";
return;
}
Notification.requestPermission().then(() => notificationPermission);
connection?.events.onMessagePacket.subscribe(messageHandler);
return () => connection?.events.onMessagePacket.unsubscribe(messageHandler);
}, [notificationPermission, connection]);

const messageHandler = useCallback(
(packet: Types.PacketMetadata<string>) => {
if (notificationPermission !== "granted") return;

const notificationBody = packet.data;
let notificationTitle = `New Message from ${nodes.get(packet.from)?.user?.longName ?? `!${numberToHexUnpadded(packet.from)}`}`;

if (packet.type === "broadcast") {
notificationTitle = `New Message in ${channels.get(packet.channel)?.settings?.name ?? "Broadcast"}, from ${nodes.get(packet.from)?.user?.longName ?? `!${numberToHexUnpadded(packet.from)}`}`;
}

new Notification(notificationTitle, {
body: notificationBody,
icon: "/favicon.ico",
});
},
[notificationPermission, nodes, channels],
);
return null;
};

0 comments on commit 65f695c

Please sign in to comment.