Skip to content

Commit

Permalink
Merge pull request #42 from icssc/webpush-api-client
Browse files Browse the repository at this point in the history
added a page to test webpush
  • Loading branch information
NwinNwin authored Feb 27, 2024
2 parents 6442cac + 3cc4539 commit abea63e
Show file tree
Hide file tree
Showing 6 changed files with 167 additions and 10 deletions.
11 changes: 5 additions & 6 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@
<html lang="en">
<head>
<style>
@media (min-resolution: 120dpi) {
html {
font-size: 14px;
}
html {
font-size: 16px; /* Base font size */
}
@media (min-resolution: 144dpi) {

@media (min-resolution: 120dpi) {
html {
font-size: 12px;
font-size: 13px; /* Keep the base size or adjust as needed */
}
}
</style>
Expand Down
7 changes: 7 additions & 0 deletions public/serviceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,10 @@ this.addEventListener("activate", (event) => {
)
);
});

self.addEventListener("push", function (e) {
const data = e.data.json();
self.registration.showNotification(data.title, {
body: data.body,
});
});
2 changes: 2 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import "./App.css";
import Login from "./components/Login/Login";
import Home from "./components/Home/Home";
import UpdatePage from "./components/UpdatePage/UpdatePage";
import Playground from "./components/Playground/Playground";

import { ChakraProvider } from "@chakra-ui/react";
import "leaflet/dist/leaflet.css";
Expand Down Expand Up @@ -33,6 +34,7 @@ function App() {
<Route path="/" element={<Home />} />
<Route path="/:id" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/playground" element={<Playground />} />
</Routes>
</div>
</ChakraProvider>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Home/DateRangeFilter.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from "../../utils/HomeUtils";

export default function DateRangeFilter() {
const [DateRangeFilter, setDateRangeFilter] = useState("Date Range Filter");
const [DateRangeFilter, setDateRangeFilter] = useState("Date Range");
const { setLoading, setData } = useContext(DataContext);

return (
Expand Down
6 changes: 3 additions & 3 deletions src/components/Home/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -527,15 +527,15 @@ export default function Home() {
<ButtonGroup
variant="outline"
colorScheme="twitter"
color="#74a2fa"
spacing={6}
color="#5f85cf"
spacing={3}
boxShadow="5px 2px 9px rgba(0, 0, 0, 0.2);"
>
<Button
backgroundColor="white"
onClick={onOpen}
size="lg"
gap={2}
gap={1}
fontSize={{ base: "xl", md: "2xl" }}
borderRadius={"lg"}
borderWidth={2}
Expand Down
149 changes: 149 additions & 0 deletions src/components/Playground/Playground.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import { Text, Center, Button, Stack, Flex } from "@chakra-ui/react";
import axios from "axios";
import { useState } from "react";

import React from "react";

function Playground() {
const [reg, setReg] = useState(null);
const [sub, setSub] = useState(null);
const [routeText, setRouteText] = useState("");
const [registrationText, setRegistrationText] = useState("");
const [subscribed, setSubscribed] = useState(false);
// const [regular, setRegular] = useState(false);
const publicVapidKey =
"BGn0m4u5g8DQZXChgsgqwzg7vKkdfgQT29g-gB9HjYSsCwRKwuL9oKfdO8NsROpQV5jCBsqs_e1ETsvH6r9G1Vw";

const testRouting = async () => {
const test = await axios.get("http://localhost:3001/notification/test");
setRouteText(test.data.message);
};

/*
Registers the service worker, asks users to enable notifications on their browser
*/
const registerServiceWorker = async () => {
console.log("Registering!");
const register = await navigator.serviceWorker.register(
"serviceWorker.js",
{
scope: "/",
}
);
setReg(register);
setRegistrationText("Service Worker Registered to scope '/'");
};
console.log(reg);

/*
Calls subscribe route to subscribe a user to push notifications
right now, just happens when the user presses the button
*/
const subscribeUser = async () => {
const subscription = await reg?.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicVapidKey,
});
console.log("Successfully Subscribed");
setSub(subscription || null);
setSubscribed(true);
};

/*
Unsubscribes a subscribed user from push notifications
*/
const unsubscribeUser = async () => {
navigator.serviceWorker.ready.then(() => {
// makes sure the service worker is active
if (sub) {
sub
.unsubscribe()
.then(() => {
console.log("Successfully Unsubscribed");
setSubscribed(false);
})
.catch(() => {
// Unsubscribing failed
console.log(
"Unsubscribing Failed, perhaps you did not subscribe yet?"
);
});
}
});
};

/*
Send a push notification to subscribed users
*/
const sendNotification = async () => {
await fetch("http://localhost:3001/notification", {
method: "POST",
body: JSON.stringify(sub),
headers: {
"Content-Type": "application/json",
},
});
};

/*
Sends 5 push notifications
*/
const setNotificationsRegularly = async () => {
const sleep = (delay) =>
new Promise((resolve) => setTimeout(resolve, delay));
// setRegular(true);
while (5) {
await sleep(10000);
console.log("Sending!");
await fetch("http://localhost:3001/notification", {
method: "POST",
body: JSON.stringify(sub),
headers: {
"Content-Type": "application/json",
},
});
}
};
console.log(JSON.stringify(sub));

return (
<React.Fragment>
<Stack>
<Center>
<Text fontSize="4xl" mb="5rem">
Webpush Demo
</Text>
</Center>
<Button onClick={() => testRouting()} mt={3}>
test routing
</Button>
<Text>{routeText}</Text>
<Button onClick={() => registerServiceWorker()} mt={3}>
register for push notifications
</Button>
<Text>{registrationText}</Text>
<Flex gap={3}>
<Button onClick={() => subscribeUser()} mt={3}>
subscribe for push notifications
</Button>
<Button onClick={() => unsubscribeUser()} mt={3}>
unsubscribe from push notifications
</Button>
</Flex>
{subscribed ? (
<Text>Currently Subscribed to Push Notifications</Text>
) : (
<Text>Currently Unsubscribed from Push Notifications</Text>
)}
<Button onClick={() => sendNotification()} mt={3}>
send push notifications to subscribers
</Button>
<Button onClick={() => setNotificationsRegularly()} mt={3}>
send five push notifications every 10 seconds
</Button>
</Stack>
</React.Fragment>
);
}

export default Playground;

0 comments on commit abea63e

Please sign in to comment.