| 1 | // presenter-clock.mjs — the presenter window's timer and clock (spec |
| 2 | // §5, §5.5): the timer in numbers only, from the talk's first press, |
| 3 | // and the clock in the room's own time. No words. |
| 4 | // |
| 5 | // The timer's start is its element's data-timer-since (Unix seconds), |
| 6 | // which the server draws, a press in this window sets at once (press), |
| 7 | // and the server's word sets from then on, whichever window pressed |
| 8 | // (heard: the talk's timerAt in ms, or null after a reset). |
| 9 | |
| 10 | const MOVING = new Set(['next', 'back', 'first', 'last', 'goto']) |
| 11 | |
| 12 | /** The timer and the clock, ticking. timer and clock may be absent. */ |
| 13 | export function mountClock (timer, clock) { |
| 14 | const since = () => timer && timer.getAttribute('data-timer-since') |
| 15 | const two = n => (n < 10 ? '0' : '') + n |
| 16 | function timerNow () { |
| 17 | const at = since() |
| 18 | if (!at) return |
| 19 | const s = Math.max(0, Math.floor(Date.now() / 1000 - Number(at))) |
| 20 | const h = Math.floor(s / 3600) |
| 21 | const m = Math.floor(s / 60) % 60 |
| 22 | timer.textContent = h ? h + ':' + two(m) + ':' + two(s % 60) : m + ':' + two(s % 60) |
| 23 | } |
| 24 | function clockNow () { |
| 25 | if (clock) clock.textContent = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) |
| 26 | } |
| 27 | function reset () { |
| 28 | if (!since()) return |
| 29 | timer.removeAttribute('data-timer-since') |
| 30 | timer.textContent = '0:00' |
| 31 | } |
| 32 | timerNow() |
| 33 | clockNow() |
| 34 | setInterval(timerNow, 1000) |
| 35 | setInterval(clockNow, 15000) |
| 36 | return { |
| 37 | /** A press made here: a move starts a timer that is not running. */ |
| 38 | press (move) { |
| 39 | if (timer && MOVING.has(move.op) && !since()) timer.setAttribute('data-timer-since', String(Math.floor(Date.now() / 1000))) |
| 40 | }, |
| 41 | /** The server's timerAt: Unix ms, or null for a timer reset. */ |
| 42 | heard (ms) { |
| 43 | if (!timer) return |
| 44 | if (ms === null) { reset(); return } |
| 45 | const at = String(Math.floor(ms / 1000)) |
| 46 | if (since() !== at) timer.setAttribute('data-timer-since', at) |
| 47 | }, |
| 48 | /** Back to 0:00, waiting for the next press. */ |
| 49 | reset |
| 50 | } |
| 51 | } |
| 52 | |