Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/pie-night

Pie night sign-ups: hosts start an event, guests add the pies they are bringing and watch the list fill in live. Installable, with optional push notifications.

FollowForkOpen app

Files

pwa.js

185 lines · 8.4 KB · JavaScript
// Pie Night PWA helpers shared by every page: service worker registration with a
// "Refresh" banner for updates, the install button, and push notification opt-in.
;(function () {
	'use strict'
	var boot = {}
	try { boot = JSON.parse(document.getElementById('boot').textContent || '{}') } catch (e) {}
	var base = boot.appBase || ''
	var local = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname)
	// Service workers stay off on localhost so dev reloads are honest; add ?sw=1 to test them.
	var swWanted = 'serviceWorker' in navigator && (!local || /[?&]sw=1/.test(location.search))
	var regPromise = null
	var currentEndpoint = ''
	var reloading = false

	function $(sel) { return document.querySelector(sel) }
	function el(html) { var d = document.createElement('div'); d.innerHTML = html; return d.firstElementChild }

	// ---------- Updates ----------
	// Lesson from the factory app: ask the registration for the worker waiting *now* when
	// Refresh is tapped, post both message shapes, reload on controllerchange, and fall back
	// to a plain reload so the button never looks dead.
	function showUpdate(reg) {
		var bar = $('#update-bar')
		if (!bar) return
		var waiting = reg.waiting
		bar.hidden = !(waiting && navigator.serviceWorker.controller && waiting !== navigator.serviceWorker.controller)
	}
	function applyUpdate() {
		if (!regPromise) return location.reload()
		var btn = $('#update-btn')
		if (btn) { btn.disabled = true; btn.textContent = 'Refreshing...' }
		regPromise.then(function (reg) {
			var waiting = reg && reg.waiting
			if (!waiting) { location.reload(); return }
			try { waiting.postMessage('SKIP_WAITING') } catch (e) {}
			try { waiting.postMessage({ type: 'SKIP_WAITING' }) } catch (e) {}
			setTimeout(function () { if (!reloading) { reloading = true; location.reload() } }, 4000)
		}, function () { location.reload() })
	}
	function registerSW() {
		if (!swWanted) return null
		regPromise = navigator.serviceWorker.register(base + '/sw.js', { scope: base + '/' }).then(function (reg) {
			showUpdate(reg)
			reg.addEventListener('updatefound', function () {
				var next = reg.installing
				if (!next) return
				next.addEventListener('statechange', function () { if (next.state === 'installed') showUpdate(reg) })
			})
			document.addEventListener('visibilitychange', function () { if (!document.hidden) reg.update().catch(function () {}) })
			return reg
		})
		regPromise.catch(function () {})
		var hadController = !!navigator.serviceWorker.controller
		navigator.serviceWorker.addEventListener('controllerchange', function () {
			if (!hadController) { hadController = true; return }
			if (reloading) return
			reloading = true
			location.reload()
		})
		return regPromise
	}

	// ---------- Install ----------
	var deferredInstall = null
	function isStandalone() { return window.matchMedia('(display-mode: standalone)').matches || navigator.standalone === true }
	function isIos() { return /iphone|ipad|ipod/i.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) }
	window.addEventListener('beforeinstallprompt', function (e) {
		e.preventDefault()
		deferredInstall = e
		var btn = $('#install-btn')
		if (btn) btn.hidden = false
	})
	function wireInstall() {
		var btn = $('#install-btn')
		if (!btn || isStandalone()) return
		if (isIos()) btn.hidden = false
		btn.addEventListener('click', function () {
			if (deferredInstall) {
				deferredInstall.prompt()
				deferredInstall.userChoice.finally(function () { deferredInstall = null; btn.hidden = true })
			} else if (isIos()) {
				alert('On iPhone or iPad: tap the Share button, then "Add to Home Screen".')
			}
		})
	}

	// ---------- Push ----------
	function keyBytes(b64) {
		var pad = '='.repeat((4 - (b64.length % 4)) % 4)
		var raw = atob((b64 + pad).replace(/-/g, '+').replace(/_/g, '/'))
		var out = new Uint8Array(raw.length)
		for (var i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i)
		return out
	}
	function pushSupported() { return swWanted && 'PushManager' in window && 'Notification' in window && !!boot.pushKey }
	function post(path, body) {
		return fetch(boot.api + path, { method: 'POST', headers: { 'content-type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify(body) }).then(function (r) {
			return r.json().catch(function () { return {} }).then(function (d) { if (!r.ok) throw new Error(d.error || 'Something went wrong.'); return d })
		})
	}
	function currentSub() {
		if (!regPromise) return Promise.resolve(null)
		return regPromise.then(function (reg) { return reg.pushManager.getSubscription() }).then(function (sub) {
			currentEndpoint = sub ? sub.endpoint : ''
			return sub
		}, function () { return null })
	}

	/** Draws a notify card into `box`. host=true subscribes as a host (and adds a test button). */
	function notifyCard(box, host) {
		if (!box || !boot.api) return
		if (!pushSupported()) {
			if (boot.pushKey && isIos() && !isStandalone()) {
				box.hidden = false
				box.innerHTML = '<p class="notify-text">🔔 Want a ping when pies are added? On iPhone, tap Share, then <b>Add to Home Screen</b>, and open Pie Night from there.</p>'
			} else {
				box.hidden = true
			}
			return
		}
		box.hidden = false
		function draw(on, note) {
			if (Notification.permission === 'denied' && !on) {
				box.innerHTML = '<p class="notify-text">🔕 Notifications are blocked for this site. You can allow them in your browser settings.</p>'
				return
			}
			box.innerHTML = on
				? '<p class="notify-text">🔔 ' + (host ? 'You will get a ping on this device when a guest adds a pie.' : 'You will get a ping when a pie is added.') + '</p>' +
					'<div class="notify-actions">' + (host ? '<button type="button" class="ghost-btn" data-act="test">Send a test</button>' : '') + '<button type="button" class="ghost-btn" data-act="off">Turn off</button></div>'
				: '<p class="notify-text">' + (host ? 'Get a notification on this device when a guest adds a pie.' : 'Want a heads up when someone adds a pie?') + '</p>' +
					'<div class="notify-actions"><button type="button" class="big-btn small" data-act="on">🔔 Notify me when a pie is added</button></div>'
			if (note) box.insertAdjacentHTML('beforeend', '<p class="notify-note">' + note + '</p>')
		}
		function busy(btn) { if (btn) { btn.disabled = true } }
		box.addEventListener('click', function (e) {
			var btn = e.target.closest('[data-act]')
			if (!btn) return
			var act = btn.getAttribute('data-act')
			busy(btn)
			if (act === 'on') {
				Notification.requestPermission().then(function (perm) {
					if (perm !== 'granted') { draw(false); return }
					return regPromise.then(function (reg) {
						return reg.pushManager.getSubscription().then(function (sub) {
							return sub || reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(boot.pushKey) })
						})
					}).then(function (sub) {
						currentEndpoint = sub.endpoint
						return post('/push', { subscription: sub.toJSON(), host: !!host })
					}).then(function () { draw(true) })
				}).catch(function (err) { draw(false, String((err && err.message) || err)) })
			} else if (act === 'off') {
				post('/push', { off: true, endpoint: currentEndpoint }).then(function () { draw(false) }, function (err) { draw(true, err.message) })
			} else if (act === 'test') {
				post('/admin/test-push', { endpoint: currentEndpoint }).then(function (d) {
					draw(true, d.ok ? 'Test sent. It should pop up in a moment.' : 'The test did not go through. Try turning notifications off and on again.')
				}, function (err) { draw(true, err.message) })
			}
		})
		draw(false)
		currentSub().then(function (sub) {
			if (!sub) return draw(false)
			return post('/push', { check: true, endpoint: sub.endpoint }).then(function (d) {
				draw(!!d.on && (!host || !!d.host))
			}, function () { draw(false) })
		})
	}

	// ---------- Code lookup (home and not-found pages) ----------
	function slugify(text) {
		return String(text || '').normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/g, '')
	}

	registerSW()
	if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', wireInstall)
	else wireInstall()
	document.addEventListener('click', function (e) { if (e.target && e.target.id === 'update-btn') applyUpdate() })

	window.PieNight = {
		endpoint: function () { return currentEndpoint },
		notifyCard: notifyCard,
		slugify: slugify,
		registration: function () { return regPromise },
	}
})()