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

app.js

597 lines · 25.5 KB · JavaScript
;(function () {
	'use strict'
	var boot = JSON.parse(document.getElementById('boot').textContent)
	var base = boot.appBase || ''
	var apiBase = boot.api
	var pies = boot.pies || []
	var event = boot.event
	var NAME_KEY = 'pie-night:who'
	var freshIds = {}
	var presenceId = (window.crypto && crypto.randomUUID) ? crypto.randomUUID() : 'p-' + Math.random().toString(36).slice(2) + Date.now().toString(36)

	var $ = function (sel, root) { return (root || document).querySelector(sel) }
	var list = $('#pie-list')
	var form = $('#pie-form')
	var dialog = $('#edit-dialog')
	var editForm = $('#edit-form')
	var toastEl = $('#toast')
	var toastTimer = 0

	function esc(value) {
		return String(value == null ? '' : value).replace(/[&<>"']/g, function (c) {
			return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
		})
	}

	function toast(text) {
		toastEl.textContent = text
		toastEl.hidden = false
		clearTimeout(toastTimer)
		toastTimer = setTimeout(function () { toastEl.hidden = true }, 2600)
	}

	function api(method, path, body) {
		var opts = { method: method, headers: { accept: 'application/json', 'x-pie-tab': presenceId }, credentials: 'same-origin' }
		if (body !== undefined) {
			opts.headers['content-type'] = 'application/json'
			opts.body = JSON.stringify(body)
		}
		return fetch(apiBase + path, opts).then(function (res) {
			return res.json().catch(function () { return {} }).then(function (data) {
				if (!res.ok) {
					var err = new Error(data.error || 'Something went wrong. Try again?')
					err.data = data
					throw err
				}
				return data
			})
		}, function () {
			throw new Error('Could not reach the pie table. Check your connection?')
		})
	}

	function pieSvg(color) {
		return '<svg viewBox="0 0 64 64" aria-hidden="true">' +
			'<circle cx="32" cy="33" r="29" fill="#b9692e"/>' +
			'<circle cx="32" cy="31" r="28" fill="#d98a43"/>' +
			'<circle cx="32" cy="31" r="22" fill="' + esc(color) + '"/>' +
			'<g stroke="#f7cf8c" stroke-width="4.5" stroke-linecap="round" opacity=".95">' +
			'<path d="M22 13v36M32 10v42M42 13v36M14 21h36M11 31h42M14 41h36"/></g>' +
			'<circle cx="32" cy="31" r="26" fill="none" stroke="#e7a45c" stroke-width="4" stroke-dasharray="3 4"/>' +
			'</svg>'
	}

	function renderCount() {
		var n = pies.length
		var el = $('#pie-count')
		el.textContent = n === 0 ? '' : n === 1 ? '1 pie so far!' : n + ' pies and counting!'
	}

	function familyKey(who) {
		return String(who || '').trim().toLowerCase().replace(/\s+/g, ' ')
	}

	// Group pies by family, ordered by each family's first pie.
	function groups() {
		var map = Object.create(null)
		var order = []
		pies.forEach(function (p) {
			var key = familyKey(p.who)
			if (!map[key]) { map[key] = { who: p.who, pies: [] }; order.push(key) }
			map[key].pies.push(p)
		})
		return order.map(function (k) { return map[k] })
	}

	function pieRowHtml(p) {
		return '<li class="pie-item' + (freshIds[p.id] ? ' fresh' : '') + '" data-id="' + esc(p.id) + '">' +
			'<div class="pie-art">' + pieSvg(p.look.filling) + '<span class="emoji" aria-hidden="true">' + esc(p.look.emoji) + '</span></div>' +
			'<div class="pie-body"><div class="pie-name">' + esc(p.pie) + '</div>' +
			(p.note ? '<div class="pie-note">' + esc(p.note) + '</div>' : '') + '</div>' +
			'<div class="pie-actions"><button type="button" data-edit aria-label="Change ' + esc(p.pie) + '">✏️ Change</button>' +
			'<button type="button" class="danger" data-remove aria-label="Remove ' + esc(p.pie) + '">Remove</button></div>' +
			'</li>'
	}

	function render() {
		renderCount()
		if (!pies.length) {
			list.innerHTML = '<li class="empty"><span class="big">🥧</span>No pies yet. Be the first to add one!</li>'
			return
		}
		list.innerHTML = groups().map(function (g) {
			var names = g.pies.map(function (p) { return p.pie }).join(', ')
			return '<li class="family">' +
				'<div class="family-head"><span class="family-name">' + esc(g.who) + '</span>' +
				'<span class="family-count">' + (g.pies.length === 1 ? '1 pie' : g.pies.length + ' pies') + '</span></div>' +
				'<p class="family-sum">' + esc(names) + '</p>' +
				'<ul class="family-pies">' + g.pies.map(pieRowHtml).join('') + '</ul></li>'
		}).join('')
	}

	function setError(f, text) {
		var el = f.querySelector('.form-error')
		el.textContent = text || ''
		el.hidden = !text
	}

	function values(f) {
		return { who: f.who.value, pie: f.pie.value, note: f.note.value, website: f.website.value }
	}

	function burst(x, y) {
		var bits = ['🥧', '🍂', '🧡', '✨', '💛', '🍁']
		for (var i = 0; i < 12; i++) {
			var s = document.createElement('span')
			s.className = 'burst'
			s.textContent = bits[i % bits.length]
			s.style.left = x + 'px'
			s.style.top = y + 'px'
			var a = Math.random() * Math.PI * 2
			var d = 80 + Math.random() * 90
			s.style.setProperty('--dx', Math.cos(a) * d + 'px')
			s.style.setProperty('--dy', Math.sin(a) * d - 40 + 'px')
			s.style.setProperty('--r', (Math.random() * 360 - 180) + 'deg')
			document.body.appendChild(s)
			setTimeout(function (n) { n.remove() }.bind(null, s), 1200)
		}
	}

	// Pie rows: one name, then as many pies as they are bringing (up to the batch limit).
	var rowsEl = $('#pie-rows')
	var addRowBtn = $('#add-row')
	var doneEl = $('#form-done')
	var MAX_ROWS = (boot.limits && boot.limits.batch) || 6
	var CHIPS = [['Apple', '🍎 Apple'], ['Pumpkin', '🍂 Pumpkin'], ['Pecan', '🌰 Pecan'], ['Cherry', '🍒 Cherry'], ['Banana cream', '🍌 Banana cream'], ['Chocolate cream', '🍫 Chocolate'], ['Key lime', '🍈 Key lime'], ['Lemon meringue', '🍋 Lemon']]
	var PLACEHOLDERS = ['Apple crumble', 'Pumpkin', 'Chocolate cream', 'Cherry', 'Pecan', 'Key lime']

	function rows() { return Array.prototype.slice.call(rowsEl.querySelectorAll('.pie-row')) }

	function renumber() {
		var all = rows()
		all.forEach(function (row, i) {
			row.querySelector('.row-label').textContent = all.length > 1 ? 'Pie ' + (i + 1) : 'What pie?'
			row.querySelector('.row-x').hidden = all.length < 2
		})
		addRowBtn.hidden = all.length >= MAX_ROWS
		var filled = all.filter(function (r) { return r.querySelector('[name=pie]').value.trim() }).length
		$('#submit-label').textContent = filled > 1 ? 'Add my ' + filled + ' pies' : 'Add my pie'
	}

	function addRow(focus) {
		if (rows().length >= MAX_ROWS) return
		var i = rows().length
		var row = document.createElement('div')
		row.className = 'pie-row'
		row.innerHTML =
			'<div class="row-top"><span class="row-label">What pie?</span>' +
			'<button type="button" class="row-x" aria-label="Remove this pie row" hidden>×</button></div>' +
			'<input name="pie" maxlength="' + esc(rowsEl.getAttribute('data-pie-max')) + '" placeholder="' + esc(PLACEHOLDERS[i % PLACEHOLDERS.length]) + '" autocomplete="off" enterkeyhint="next" aria-label="Pie" />' +
			'<div class="quick" role="group" aria-label="Quick pie ideas">' +
			CHIPS.map(function (c) { return '<button type="button" data-pie="' + esc(c[0]) + '">' + esc(c[1]) + '</button>' }).join('') + '</div>' +
			'<input name="note" class="note-input" maxlength="' + esc(rowsEl.getAttribute('data-note-max')) + '" placeholder="Note (optional): gluten free..." autocomplete="off" enterkeyhint="done" aria-label="Note (optional)" />'
		rowsEl.appendChild(row)
		renumber()
		if (focus) {
			var input = row.querySelector('[name=pie]')
			input.focus({ preventScroll: true })
			row.scrollIntoView({ behavior: 'smooth', block: 'center' })
		}
		return row
	}

	function resetRows() {
		rowsEl.innerHTML = ''
		addRow(false)
	}

	resetRows()
	addRowBtn.addEventListener('click', function () { addRow(true) })

	rowsEl.addEventListener('click', function (e) {
		var row = e.target.closest('.pie-row')
		if (!row) return
		if (e.target.closest('.row-x')) {
			row.remove()
			renumber()
			return
		}
		var chip = e.target.closest('[data-pie]')
		if (!chip) return
		row.querySelector('[name=pie]').value = chip.getAttribute('data-pie')
		Array.prototype.forEach.call(row.querySelectorAll('.quick button'), function (b) { b.classList.toggle('on', b === chip) })
		renumber()
	})
	rowsEl.addEventListener('input', renumber)

	// Remember the name on this device so the next pie is one less thing to type.
	try { var saved = localStorage.getItem(NAME_KEY); if (saved) form.who.value = saved } catch (e) {}

	form.addEventListener('submit', function (e) {
		e.preventDefault()
		setError(form, '')
		var who = form.who.value
		var batch = rows().map(function (r) {
			return { pie: r.querySelector('[name=pie]').value, note: r.querySelector('[name=note]').value }
		})
		var filled = batch.filter(function (p) { return p.pie.trim() || p.note.trim() })
		if (!who.trim()) { setError(form, 'Please add your name or family name.'); form.who.focus(); return }
		if (!filled.length) { setError(form, 'What pie are you bringing?'); rows()[0].querySelector('[name=pie]').focus(); return }
		var missing = rows().filter(function (r) { return !r.querySelector('[name=pie]').value.trim() && r.querySelector('[name=note]').value.trim() })[0]
		if (missing) { setError(form, 'One of your notes is missing its pie.'); missing.querySelector('[name=pie]').focus(); return }
		var btn = $('#submit-btn')
		btn.disabled = true
		api('POST', '/pies', { who: who, pies: filled, website: form.website.value, pushEndpoint: window.PieNight && PieNight.endpoint() }).then(function (data) {
			pies = data.pies || pies
			freshIds = {}
			;(data.added || []).forEach(function (p) { freshIds[p.id] = true })
			var count = (data.added || []).length || filled.length
			try { localStorage.setItem(NAME_KEY, who.trim()) } catch (err) {}
			render()
			var r = btn.getBoundingClientRect()
			burst(r.left + r.width / 2, r.top)
			form.hidden = true
			$('#done-title').textContent = count > 1 ? 'Yum! Your ' + count + ' pies are on the list.' : 'Yum! Your pie is on the list.'
			$('#done-sub').textContent = 'Thanks, ' + who.trim() + '!'
			doneEl.querySelector('.done-pies').textContent = new Array(Math.min(count, 6) + 1).join('🥧')
			doneEl.hidden = false
			resetRows()
		}).catch(function (err) {
			setError(form, err.message)
		}).then(function () { btn.disabled = false })
	})

	$('#add-more').addEventListener('click', function () {
		doneEl.hidden = true
		form.hidden = false
		resetRows()
		var first = rows()[0].querySelector('[name=pie]')
		first.focus({ preventScroll: true })
		$('#form-title').scrollIntoView({ behavior: 'smooth', block: 'start' })
	})

	var editingId = null
	var confirmTimer = 0
	list.addEventListener('click', function (e) {
		var item = e.target.closest('.pie-item')
		if (!item) return
		var id = item.getAttribute('data-id')
		var pie = pies.filter(function (p) { return p.id === id })[0]
		if (!pie) return
		if (e.target.closest('[data-edit]')) {
			editingId = id
			editForm.who.value = pie.who
			editForm.pie.value = pie.pie
			editForm.note.value = pie.note || ''
			setError(editForm, '')
			if (dialog.showModal) dialog.showModal(); else dialog.setAttribute('open', '')
			return
		}
		var rm = e.target.closest('[data-remove]')
		if (rm) {
			if (!rm.classList.contains('confirming')) {
				rm.classList.add('confirming')
				rm.textContent = 'Tap again to remove'
				clearTimeout(confirmTimer)
				confirmTimer = setTimeout(function () { rm.classList.remove('confirming'); rm.textContent = 'Remove' }, 4000)
				return
			}
			rm.disabled = true
			api('DELETE', '/pies/' + id).then(function (data) {
				pies = data.pies || pies.filter(function (p) { return p.id !== id })
				render()
				toast('Pie removed')
			}).catch(function (err) { toast(err.message); rm.disabled = false })
		}
	})

	dialog.addEventListener('click', function (e) {
		if (e.target === dialog || e.target.closest('[data-close]')) dialog.close()
	})

	editForm.addEventListener('submit', function (e) {
		e.preventDefault()
		setError(editForm, '')
		var btn = editForm.querySelector('[type=submit]')
		btn.disabled = true
		api('PATCH', '/pies/' + editingId, values(editForm)).then(function (data) {
			pies = data.pies || pies
			freshIds = {}
			freshIds[editingId] = true
			render()
			dialog.close()
			toast('Saved! 🥧')
		}).catch(function (err) {
			if (err.data && err.data.pies) { pies = err.data.pies; render() }
			setError(editForm, err.message)
		}).then(function () { btn.disabled = false })
	})

	function setEvent(next) {
		event = next
		$('#event-title').textContent = next.title
		$('#event-day').textContent = next.when.day
		$('#event-time').textContent = next.when.time
		$('#event-blurb').textContent = next.blurb
		$('#event-where').textContent = next.place || ''
		$('#event-where-chip').hidden = !next.place
		document.body.setAttribute('data-theme', next.theme || 'harvest')
		document.title = next.title + ' 🥧 ' + next.when.day
	}

	// Live updates: Kody realtime pushes every change to open pages. Polling stays on as a
	// fallback (faster while the socket is down) so the page always catches up.
	var liveOpen = false
	var lastRefresh = 0
	var lastBeat = 0

	function refresh() {
		if (document.hidden || dialog.open) return
		lastRefresh = Date.now()
		api('GET', '/pies').then(function (data) {
			if (data.event && data.event.night !== event.night) freshIds = {}
			if (data.event) setEvent(data.event)
			if (JSON.stringify(data.pies) !== JSON.stringify(pies)) applyPies(data.pies, null)
		}).catch(function () {})
	}

	function listText(items) {
		if (!items || !items.length) return 'a pie'
		if (items.length === 1) return items[0]
		if (items.length === 2) return items[0] + ' and ' + items[1]
		return items.length + ' pies'
	}

	function applyPies(next, newIds) {
		freshIds = {}
		;(newIds || []).forEach(function (id) { freshIds[id] = true })
		pies = next || []
		if (dialog.open && editingId && !pies.some(function (p) { return p.id === editingId })) dialog.close()
		render()
	}

	function handleLive(msg) {
		if (!msg || typeof msg !== 'object') return
		var mine = msg.from && msg.from === presenceId.slice(0, 8)
		if (msg.type === 'pies' && msg.refetch) {
			refresh()
			if (!mine && msg.change === 'added') toast(msg.who + ' just added ' + listText(msg.items) + '! 🥧')
			return
		}
		if (msg.type === 'event' && msg.refetch) { if (msg.event) setEvent(msg.event); refresh(); return }
		if (msg.type === 'pies' && Array.isArray(msg.pies)) {
			if (mine) { if (JSON.stringify(msg.pies) !== JSON.stringify(pies)) applyPies(msg.pies, msg.ids); return }
			applyPies(msg.pies, msg.change === 'added' || msg.change === 'edited' ? msg.ids : null)
			if (msg.change === 'added') toast(msg.who + ' just added ' + listText(msg.items) + '! 🥧')
			else if (msg.change === 'edited') toast(listText(msg.items) + ' from ' + msg.who + ' was just updated')
			return
		}
		if (msg.type === 'event' && msg.event) {
			setEvent(msg.event)
			if (Array.isArray(msg.pies)) applyPies(msg.pies, null)
			return
		}
		if (msg.type === 'presence' && Array.isArray(msg.people)) renderPresence(msg.people)
	}

	function unwrap(raw) {
		var d = raw
		for (var i = 0; i < 3 && d && typeof d === 'object'; i++) {
			if (d.type === 'pies' || d.type === 'event' || d.type === 'presence') return d
			d = d.data || d.payload || d.message
			if (typeof d === 'string') { try { d = JSON.parse(d) } catch (e) { return null } }
		}
		return null
	}

	var socketTries = 0
	var pingTimer = 0
	var reconnectTimer = 0
	function setLive(on) {
		liveOpen = on
		var badge = $('#live-badge')
		if (badge) badge.hidden = !on
	}
	function connect() {
		if (!('WebSocket' in window) || document.hidden) return
		var url = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + base + '/ws/' + boot.slug
		var ws
		try { ws = new WebSocket(url) } catch (e) { scheduleReconnect(); return }
		ws.onopen = function () {
			socketTries = 0
			setLive(true)
			refresh()
			beat()
			clearInterval(pingTimer)
			pingTimer = setInterval(function () { try { ws.send('kody:ping') } catch (e) {} }, 25000)
		}
		ws.onmessage = function (m) {
			if (typeof m.data !== 'string' || m.data === 'kody:pong') return
			var parsed
			try { parsed = JSON.parse(m.data) } catch (e) { return }
			handleLive(unwrap(parsed))
		}
		ws.onclose = function () {
			setLive(false)
			clearInterval(pingTimer)
			scheduleReconnect()
		}
	}
	function scheduleReconnect() {
		clearTimeout(reconnectTimer)
		socketTries++
		var delay = Math.min(60000, 1000 * Math.pow(2, Math.min(socketTries, 6))) + Math.random() * 1000
		reconnectTimer = setTimeout(connect, delay)
	}

	render()

	// Presence: a random id per open tab, remembered name only (no accounts or location).
	// Heartbeats keep you listed (40-second expiry); changes are pushed live to everyone.
	var lastTyping = 0
	var heartbeatBusy = false
	var lastPresence = ''
	var AVATARS = ['🥧', '🍂', '🍁', '🍎', '🍒', '🍋']
	function nameNow() { return (form.who.value || '').trim() }
	function initials(name) {
		return name.split(/\s+/).filter(Boolean).slice(0, 2).map(function (w) { return w.charAt(0).toUpperCase() }).join('')
	}
	function presenceColor(id) {
		var n = 0
		for (var i = 0; i < id.length; i++) n += id.charCodeAt(i)
		return n % AVATARS.length
	}
	function renderPresence(people) {
		var me = presenceId.slice(0, 8)
		people = people.map(function (p) { return { id: p.id, name: p.name, typing: p.typing, me: p.id === me } })
		var signature = JSON.stringify(people)
		if (signature === lastPresence) return
		lastPresence = signature
		var box = $('#presence')
		if (!people.length) { box.hidden = true; return }
		box.hidden = false
		$('#presence-people').innerHTML = people.slice(0, 8).map(function (p) {
			var n = presenceColor(p.id)
			var label = p.name || 'Hungry guest'
			return '<span class="person" title="' + esc(label) + (p.me ? ' (you)' : '') + '">' +
				'<span class="avatar color-' + n + '" aria-hidden="true">' + (p.name ? esc(initials(p.name)) : AVATARS[n]) + '</span>' +
				'<span class="person-name">' + esc(p.name || 'Hungry guest') + (p.me ? ' (you)' : '') + '</span></span>'
		}).join('')
		$('#presence-caption').textContent = people.length === 1 ? 'Just you at the pie table right now' : people.length + ' people here now'
		var typing = people.filter(function (p) { return p.typing && !p.me })
		$('#typing-caption').textContent = typing.length ? (typing[0].name || 'A hungry guest') + ' is adding a pie...' : ''
	}
	function beat() {
		if (document.hidden || heartbeatBusy) return
		heartbeatBusy = true
		lastBeat = Date.now()
		api('POST', '/presence', { sid: presenceId, name: nameNow(), typing: !form.hidden && Date.now() - lastTyping < 10000 }).then(function (data) {
			renderPresence(data.people || [])
		}).catch(function () {}).then(function () { heartbeatBusy = false })
	}
	var typingDebounce = 0
	var typingDone = 0
	function noteTyping() {
		var wasTyping = Date.now() - lastTyping < 10000
		lastTyping = Date.now()
		clearTimeout(typingDebounce)
		typingDebounce = setTimeout(beat, wasTyping ? 2500 : 300)
		clearTimeout(typingDone)
		typingDone = setTimeout(beat, 10500)
	}
	form.addEventListener('input', noteTyping)
	form.addEventListener('click', function (e) { if (e.target.closest('[data-pie], #add-row')) noteTyping() })
	form.addEventListener('submit', function () { lastTyping = 0; setTimeout(beat, 600) })
	function leavePresence() {
		if (navigator.sendBeacon) navigator.sendBeacon(apiBase + '/presence', new Blob([JSON.stringify({ sid: presenceId, leave: true })], { type: 'application/json' }))
	}
	window.addEventListener('pagehide', leavePresence)
	document.addEventListener('visibilitychange', function () {
		if (document.hidden) { leavePresence(); return }
		beat()
		refresh()
		if (!liveOpen) { clearTimeout(reconnectTimer); connect() }
	})
	// Fallback timers: list every 20s and presence every 10s while the socket is down;
	// with a live socket, a slow catch-up every 60s and a heartbeat every 25s.
	setInterval(function () {
		var now = Date.now()
		if (now - lastRefresh > (liveOpen ? 60000 : 20000)) refresh()
		if (now - lastBeat > (liveOpen ? 25000 : 10000)) beat()
	}, 2000)
	lastRefresh = Date.now()
	beat()
	connect()

	// Hosts area (only on /admin).
	var admin = $('#admin')
	if (boot.mode === 'sign-in') {
		admin.hidden = false
		var loginUrl = boot.loginUrl
		admin.innerHTML = '<h2>Hosts only 🔑</h2><p>Sign in with Kody to change the date, bring back removed pies, or start a new pie night.</p>' +
			'<a class="big-btn alt" style="display:block;text-align:center;text-decoration:none" href="' + esc(loginUrl) + '">Sign in</a>'
	} else if (boot.mode === 'not-admin') {
		admin.hidden = false
		admin.innerHTML = '<h2>Hosts only 🔑</h2><p>You are signed in as <b>' + esc(boot.visitor && boot.visitor.username) + '</b>, but you are not a host for this pie night. Ask a host to add you.</p>'
	} else if (boot.mode === 'admin') {
		admin.hidden = false
		loadAdmin()
	}

	function loadAdmin() {
		api('GET', '/admin/state').then(renderAdmin).catch(function (err) {
			admin.innerHTML = '<p>' + esc(err.message) + '</p>'
		})
	}

	function renderAdmin(data) {
		var ev = data.event
		admin.innerHTML =
			'<span class="admin-badge">Host mode' + (data.visitor ? ': ' + esc(data.visitor.username) : '') + '</span>' +
			'<h2>Pie night details</h2>' +
			'<form id="event-form" novalidate>' +
			'<label class="field"><span>Title</span><input name="title" maxlength="' + boot.limits.title + '" value="' + esc(ev.title) + '"/></label>' +
			'<div class="row"><label class="field"><span>Date</span><input type="date" name="date" value="' + esc(ev.date) + '"/></label>' +
			'<label class="field"><span>Time</span><input type="time" name="time" value="' + esc(ev.time) + '"/></label></div>' +
			'<label class="field"><span>Where <em>(a friendly label, not an address)</em></span><input name="place" maxlength="' + boot.limits.place + '" value="' + esc(ev.place) + '" placeholder="At our house"/></label>' +
			'<label class="field"><span>Message</span><textarea name="blurb" rows="3" maxlength="' + boot.limits.blurb + '">' + esc(ev.blurb) + '</textarea></label>' +
			'<label class="field"><span>Theme</span><select name="theme">' + [['harvest', 'Harvest orange'], ['berry', 'Berry pink'], ['evergreen', 'Evergreen']].map(function (t) { return '<option value="' + t[0] + '"' + (ev.theme === t[0] ? ' selected' : '') + '>' + t[1] + '</option>' }).join('') + '</select></label>' +
			'<p class="form-error" role="alert" hidden></p>' +
			'<div class="sheet-actions"><button class="big-btn small alt" type="submit" data-action="save">Save details</button></div>' +
			'<hr/><h3>Start a new pie night</h3>' +
			'<p>Clears the list for a future night using the details above. The old list is kept, just hidden.</p>' +
			'<div class="sheet-actions"><button class="ghost-btn" type="button" data-action="reset">Start fresh</button></div>' +
			'</form>' +
			'<hr/><h3>Recently removed</h3>' +
			(data.removed.length ? '<ul class="removed">' + data.removed.map(function (p) {
				return '<li><span>' + esc(p.look.emoji + ' ' + p.pie) + ' <small>from ' + esc(p.who) + '</small></span><button type="button" data-restore="' + esc(p.id) + '">Bring back</button></li>'
			}).join('') + '</ul>' : '<p>Nothing removed yet.</p>') +
			'<hr/><h3>Co-hosts</h3>' +
			'<p><b>' + esc(ev.creator) + '</b> started this pie night. Co-hosts can change everything here too. Add Kody usernames, separated by commas.</p>' +
			'<form id="admins-form"><label class="field"><input name="usernames" value="' + esc((ev.hosts || []).join(', ')) + '" placeholder="username" autocapitalize="none"/></label>' +
			'<button class="ghost-btn" type="submit">Save co-hosts</button></form>' +
			'<hr/><h3>Notifications</h3>' +
			'<div id="host-notify"></div>' +
			'<hr/><h3>Share</h3>' +
			'<p>Send your guests this link. Codes are forgiving about capitals and spaces.</p>' +
			'<p class="share-link"><code>' + esc(location.origin + boot.eventPath) + '</code></p>' +
			'<p><img class="og-preview" alt="Share preview" src="' + esc(boot.eventPath + '/og.png?v=' + ev.version) + '" width="600" height="315"/></p>'

		var evForm = $('#event-form', admin)
		function evBody() { return { title: evForm.title.value, date: evForm.date.value, time: evForm.time.value, place: evForm.place.value, theme: evForm.theme.value, blurb: evForm.blurb.value } }
		evForm.addEventListener('submit', function (e) {
			e.preventDefault()
			setError(evForm, '')
			api('POST', '/admin/event', evBody()).then(function (d) { setEvent(d.event); toast('Details saved') }).catch(function (err) { setError(evForm, err.message) })
		})
		evForm.querySelector('[data-action=reset]').addEventListener('click', function (e) {
			var b = e.currentTarget
			if (!b.classList.contains('confirming')) {
				b.classList.add('confirming')
				b.textContent = 'Tap again to clear the list'
				setTimeout(function () { b.classList.remove('confirming'); b.textContent = 'Start fresh' }, 5000)
				return
			}
			api('POST', '/admin/reset', evBody()).then(function (d) {
				setEvent(d.event); pies = d.pies || []; render(); toast('Fresh pie night ready!'); loadAdmin()
			}).catch(function (err) { setError(evForm, err.message) })
		})
		Array.prototype.forEach.call(admin.querySelectorAll('[data-restore]'), function (b) {
			b.addEventListener('click', function () {
				api('POST', '/admin/restore/' + b.getAttribute('data-restore'), {}).then(function (d) {
					pies = d.pies; render(); toast('Pie is back!'); loadAdmin()
				}).catch(function (err) { toast(err.message) })
			})
		})
		$('#admins-form', admin).addEventListener('submit', function (e) {
			e.preventDefault()
			var names = e.currentTarget.usernames.value.split(/[\s,]+/).filter(Boolean)
			api('POST', '/admin/hosts', { usernames: names }).then(function () { toast('Co-hosts saved'); loadAdmin() }).catch(function (err) { toast(err.message) })
		})
		var hostNotify = $('#host-notify', admin)
		if (window.PieNight && data.pushReady) PieNight.notifyCard(hostNotify, true)
		else hostNotify.innerHTML = '<p>Notifications are not set up for this app yet.</p>'
	}

	if (window.PieNight) PieNight.notifyCard($('#notify'), false)
})()