;(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 { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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 ''
}
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 '
' +
'' + pieSvg(p.look.filling) + '' + esc(p.look.emoji) + '
' +
'' + esc(p.pie) + '
' +
(p.note ? '
' + esc(p.note) + '
' : '') + '
' +
'' +
'
' +
''
}
function render() {
renderCount()
if (!pies.length) {
list.innerHTML = '๐ฅงNo pies yet. Be the first to add one!'
return
}
list.innerHTML = groups().map(function (g) {
var names = g.pies.map(function (p) { return p.pie }).join(', ')
return '' +
'' + esc(g.who) + '' +
'' + (g.pies.length === 1 ? '1 pie' : g.pies.length + ' pies') + '
' +
'' + esc(names) + '
' +
'' + g.pies.map(pieRowHtml).join('') + '
'
}).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 =
'What pie?' +
'
' +
'' +
'' +
CHIPS.map(function (c) { return '' }).join('') + '
' +
''
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 '' +
'' + (p.name ? esc(initials(p.name)) : AVATARS[n]) + '' +
'' + esc(p.name || 'Hungry guest') + (p.me ? ' (you)' : '') + ''
}).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 = 'Hosts only ๐
Sign in with Kody to change the date, bring back removed pies, or start a new pie night.
' +
'Sign in'
} else if (boot.mode === 'not-admin') {
admin.hidden = false
admin.innerHTML = 'Hosts only ๐
You are signed in as ' + esc(boot.visitor && boot.visitor.username) + ', but you are not a host for this pie night. Ask a host to add you.
'
} else if (boot.mode === 'admin') {
admin.hidden = false
loadAdmin()
}
function loadAdmin() {
api('GET', '/admin/state').then(renderAdmin).catch(function (err) {
admin.innerHTML = '' + esc(err.message) + '
'
})
}
function renderAdmin(data) {
var ev = data.event
admin.innerHTML =
'Host mode' + (data.visitor ? ': ' + esc(data.visitor.username) : '') + '' +
'Pie night details
' +
'' +
'
Recently removed
' +
(data.removed.length ? '' + data.removed.map(function (p) {
return '- ' + esc(p.look.emoji + ' ' + p.pie) + ' from ' + esc(p.who) + '
'
}).join('') + '
' : 'Nothing removed yet.
') +
'
Co-hosts
' +
'' + esc(ev.creator) + ' started this pie night. Co-hosts can change everything here too. Add Kody usernames, separated by commas.
' +
'' +
'
Notifications
' +
'' +
'
Share
' +
'Send your guests this link. Codes are forgiving about capitals and spaces.
' +
'' + esc(location.origin + boot.eventPath) + '
' +
' + ')
'
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 = 'Notifications are not set up for this app yet.
'
}
if (window.PieNight) PieNight.notifyCard($('#notify'), false)
})()