stacker.news/components/serviceworker.js

112 lines
3.9 KiB
JavaScript
Raw Normal View History

Service worker rework, Web Target Share API & Web Push API (#324) * npm uninstall next-pwa next-pwa was last updated in August 2022. There is also an issue which mentions that next-pwa is abandoned (?): https://github.com/shadowwalker/next-pwa/issues/482 But the main reason for me uninstalling it is that it adds a lot of preconfigured stuff which is not necessary for us. It even lead to a bug since pages were cached without our knowledge. So I will go with a different PWA approach. This different approach should do the following: - make it more transparent what the service worker is doing - gives us more control to configure the service worker and thus making it easier * Use workbox-webpack-plugin Every other plugin (`next-offline`, `next-workbox-webpack-plugin`, `next-with-workbox`, ...) added unnecessary configuration which felt contrary to how PWAs should be built. (PWAs should progressivly enhance the website in small steps, see https://web.dev/learn/pwa/getting-started/#focus-on-a-feature) These default configurations even lead to worse UX since they made invalid assumptions about stacker.news: We _do not_ want to cache our start url and we _do not_ want to cache anything unless explicitly told to. Almost every page on SN should be fresh for the best UX. To achieve this, by default, the service worker falls back to the network (as if the service worker wasn't there). Therefore, this should be the simplest configuration with a valid precache and cache busting support. In the future, we can try to use prefetching to improve performance of navigation requests. * Add support for Web Share Target API See https://developer.chrome.com/articles/web-share-target/ * Use Web Push API for push notifications I followed this (very good!) guide: https://web.dev/notifications/ * Refactor code related to Web Push * Send push notification to users on events * Merge notifications * Send notification to author of every parent recursively * Remove unused userId param in savePushSubscription As it should be, the user id is retrieved from the authenticated user in the backend. * Resubscribe user if push subscription changed * Update old subscription if oldEndpoint was given * Allow users to unsubscribe * Use LTREE operator instead of recursive query * Always show checkbox for push notifications * Justify checkbox to end * Update title of first push notification * Fix warning from uncontrolled to controlled * Add comment about Notification.requestPermission * Fix timestamp * Catch error on push subscription toggle * Wrap function bodies in try/catch * Use Promise.allSettled * Filter subscriptions by user notification settings * Fix user notification filter * Use skipWaiting --------- Co-authored-by: ekzyis <ek@stacker.news>
2023-07-04 19:36:07 +00:00
import { createContext, useContext, useEffect, useState, useCallback } from 'react'
import { Workbox } from 'workbox-window'
import { gql, useMutation } from '@apollo/client'
const applicationServerKey = process.env.NEXT_PUBLIC_VAPID_PUBKEY
const ServiceWorkerContext = createContext()
export const ServiceWorkerProvider = ({ children }) => {
const [registration, setRegistration] = useState(null)
const [support, setSupport] = useState({ serviceWorker: undefined, pushManager: undefined })
const [permission, setPermission] = useState({ notification: undefined })
const [savePushSubscription] = useMutation(
gql`
mutation savePushSubscription(
$endpoint: String!
$p256dh: String!
$auth: String!
) {
savePushSubscription(
endpoint: $endpoint
p256dh: $p256dh
auth: $auth
) {
id
}
}
`)
const [deletePushSubscription] = useMutation(
gql`
mutation deletePushSubscription($endpoint: String!) {
deletePushSubscription(endpoint: $endpoint) {
id
}
}
`)
// I am not entirely sure if this is needed since at least in Brave,
// using `registration.pushManager.subscribe` also prompts the user.
// However, I am keeping this here since that's how it's done in most guides.
// Could be that this is required for the `registration.showNotification` call
// to work or that some browsers will break without this.
const requestNotificationPermission = useCallback(() => {
// https://web.dev/push-notifications-subscribing-a-user/#requesting-permission
return new Promise(function (resolve, reject) {
2023-07-25 14:14:45 +00:00
const permission = window.Notification.requestPermission(function (result) {
Service worker rework, Web Target Share API & Web Push API (#324) * npm uninstall next-pwa next-pwa was last updated in August 2022. There is also an issue which mentions that next-pwa is abandoned (?): https://github.com/shadowwalker/next-pwa/issues/482 But the main reason for me uninstalling it is that it adds a lot of preconfigured stuff which is not necessary for us. It even lead to a bug since pages were cached without our knowledge. So I will go with a different PWA approach. This different approach should do the following: - make it more transparent what the service worker is doing - gives us more control to configure the service worker and thus making it easier * Use workbox-webpack-plugin Every other plugin (`next-offline`, `next-workbox-webpack-plugin`, `next-with-workbox`, ...) added unnecessary configuration which felt contrary to how PWAs should be built. (PWAs should progressivly enhance the website in small steps, see https://web.dev/learn/pwa/getting-started/#focus-on-a-feature) These default configurations even lead to worse UX since they made invalid assumptions about stacker.news: We _do not_ want to cache our start url and we _do not_ want to cache anything unless explicitly told to. Almost every page on SN should be fresh for the best UX. To achieve this, by default, the service worker falls back to the network (as if the service worker wasn't there). Therefore, this should be the simplest configuration with a valid precache and cache busting support. In the future, we can try to use prefetching to improve performance of navigation requests. * Add support for Web Share Target API See https://developer.chrome.com/articles/web-share-target/ * Use Web Push API for push notifications I followed this (very good!) guide: https://web.dev/notifications/ * Refactor code related to Web Push * Send push notification to users on events * Merge notifications * Send notification to author of every parent recursively * Remove unused userId param in savePushSubscription As it should be, the user id is retrieved from the authenticated user in the backend. * Resubscribe user if push subscription changed * Update old subscription if oldEndpoint was given * Allow users to unsubscribe * Use LTREE operator instead of recursive query * Always show checkbox for push notifications * Justify checkbox to end * Update title of first push notification * Fix warning from uncontrolled to controlled * Add comment about Notification.requestPermission * Fix timestamp * Catch error on push subscription toggle * Wrap function bodies in try/catch * Use Promise.allSettled * Filter subscriptions by user notification settings * Fix user notification filter * Use skipWaiting --------- Co-authored-by: ekzyis <ek@stacker.news>
2023-07-04 19:36:07 +00:00
resolve(result)
})
if (permission) {
permission.then(resolve, reject)
}
}).then(function (permission) {
setPermission({ notification: permission })
if (permission === 'granted') return subscribeToPushNotifications()
})
})
const subscribeToPushNotifications = async () => {
const subscribeOptions = { userVisibleOnly: true, applicationServerKey }
// Brave users must enable a flag in brave://settings/privacy first
// see https://stackoverflow.com/a/69624651
let pushSubscription = await registration.pushManager.subscribe(subscribeOptions)
// convert keys from ArrayBuffer to string
pushSubscription = JSON.parse(JSON.stringify(pushSubscription))
const variables = {
endpoint: pushSubscription.endpoint,
p256dh: pushSubscription.keys.p256dh,
auth: pushSubscription.keys.auth
}
await savePushSubscription({ variables })
}
const unsubscribeFromPushNotifications = async (subscription) => {
await subscription.unsubscribe()
const { endpoint } = subscription
await deletePushSubscription({ variables: { endpoint } })
}
const togglePushSubscription = useCallback(async () => {
const pushSubscription = await registration.pushManager.getSubscription()
if (pushSubscription) return unsubscribeFromPushNotifications(pushSubscription)
return subscribeToPushNotifications()
})
useEffect(() => {
setSupport({
serviceWorker: 'serviceWorker' in navigator,
notification: 'Notification' in window,
pushManager: 'PushManager' in window
})
2023-07-25 14:14:45 +00:00
setPermission({ notification: 'Notification' in window ? window.Notification.permission : 'denied' })
Service worker rework, Web Target Share API & Web Push API (#324) * npm uninstall next-pwa next-pwa was last updated in August 2022. There is also an issue which mentions that next-pwa is abandoned (?): https://github.com/shadowwalker/next-pwa/issues/482 But the main reason for me uninstalling it is that it adds a lot of preconfigured stuff which is not necessary for us. It even lead to a bug since pages were cached without our knowledge. So I will go with a different PWA approach. This different approach should do the following: - make it more transparent what the service worker is doing - gives us more control to configure the service worker and thus making it easier * Use workbox-webpack-plugin Every other plugin (`next-offline`, `next-workbox-webpack-plugin`, `next-with-workbox`, ...) added unnecessary configuration which felt contrary to how PWAs should be built. (PWAs should progressivly enhance the website in small steps, see https://web.dev/learn/pwa/getting-started/#focus-on-a-feature) These default configurations even lead to worse UX since they made invalid assumptions about stacker.news: We _do not_ want to cache our start url and we _do not_ want to cache anything unless explicitly told to. Almost every page on SN should be fresh for the best UX. To achieve this, by default, the service worker falls back to the network (as if the service worker wasn't there). Therefore, this should be the simplest configuration with a valid precache and cache busting support. In the future, we can try to use prefetching to improve performance of navigation requests. * Add support for Web Share Target API See https://developer.chrome.com/articles/web-share-target/ * Use Web Push API for push notifications I followed this (very good!) guide: https://web.dev/notifications/ * Refactor code related to Web Push * Send push notification to users on events * Merge notifications * Send notification to author of every parent recursively * Remove unused userId param in savePushSubscription As it should be, the user id is retrieved from the authenticated user in the backend. * Resubscribe user if push subscription changed * Update old subscription if oldEndpoint was given * Allow users to unsubscribe * Use LTREE operator instead of recursive query * Always show checkbox for push notifications * Justify checkbox to end * Update title of first push notification * Fix warning from uncontrolled to controlled * Add comment about Notification.requestPermission * Fix timestamp * Catch error on push subscription toggle * Wrap function bodies in try/catch * Use Promise.allSettled * Filter subscriptions by user notification settings * Fix user notification filter * Use skipWaiting --------- Co-authored-by: ekzyis <ek@stacker.news>
2023-07-04 19:36:07 +00:00
}, [])
useEffect(() => {
if (!support.serviceWorker) return
const wb = new Workbox('/sw.js', { scope: '/' })
wb.register().then(registration => {
setRegistration(registration)
})
}, [support.serviceWorker])
return (
<ServiceWorkerContext.Provider value={{ registration, support, permission, requestNotificationPermission, togglePushSubscription }}>
{children}
</ServiceWorkerContext.Provider>
)
}
export function useServiceWorker () {
return useContext(ServiceWorkerContext)
}