80 lines
2.0 KiB
TypeScript
80 lines
2.0 KiB
TypeScript
import React, { useState } from "react"
|
|
import { useEffect } from "react"
|
|
import { usePush } from "../usePush"
|
|
import { request } from "http"
|
|
import urlB64ToUint8Array from "../../b64ToUInt8"
|
|
import pushPublicKey from "../../pushPublicKey"
|
|
|
|
export default function EnableNotifications({
|
|
onSubscribe,
|
|
}: {
|
|
onSubscribe: () => void
|
|
}) {
|
|
return (
|
|
<div>
|
|
<h1>Allow Notifications</h1>
|
|
<div>
|
|
Tack Up Now requires your permission to send notifications in order to
|
|
function properly
|
|
</div>
|
|
<EnableButton onSubscribe={onSubscribe} />
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function EnableButton({ onSubscribe }: { onSubscribe: () => void }) {
|
|
const { subscribeToPush, requestPermission, canSendPush } = usePush()
|
|
|
|
const [error, setError] = useState<Error>()
|
|
const [log, setLog] = useState<string[]>([])
|
|
|
|
function subscribe() {
|
|
requestPermission()
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (!canSendPush) return
|
|
|
|
setLog((prev) => [...prev, "Subscribing to push notifications"])
|
|
|
|
subscribeToPush(
|
|
urlB64ToUint8Array(pushPublicKey) as any,
|
|
(subscription) => {
|
|
setLog((prev) => [
|
|
...prev,
|
|
`controller is undefined? ${navigator.serviceWorker.controller === undefined}`,
|
|
])
|
|
setLog((prev) => [
|
|
...prev,
|
|
`subscriptions: ${JSON.stringify(subscription.toJSON())}`,
|
|
])
|
|
try {
|
|
navigator.serviceWorker.ready.then((registration) => {
|
|
registration.active?.postMessage({
|
|
type: "subscribed",
|
|
subscription: subscription.toJSON(),
|
|
})
|
|
setLog((prev) => [...prev, "After post message"])
|
|
})
|
|
// onSubscribe()
|
|
} catch (error) {
|
|
setError(error as Error)
|
|
}
|
|
},
|
|
(error) => {
|
|
setError(error)
|
|
}
|
|
)
|
|
}, [canSendPush])
|
|
|
|
return (
|
|
<>
|
|
<button onClick={subscribe}>Enable Notifications</button>
|
|
<div>{error?.toString()}</div>
|
|
{log.map((log, index) => (
|
|
<div key={index}>{log}</div>
|
|
))}
|
|
</>
|
|
)
|
|
}
|