import m, {MithrilComponent} from '@garage44/mithril' /** A span as a clock reads it: 42 → "0:42", 754 → "12:34", 4000 → "1:06:40". */ export function clockOf(secs: number): string { const s = Math.max(0, Math.floor(secs)) const h = Math.floor(s / 3600) const mm = Math.floor((s % 3600) / 60) const ss = String(s % 60).padStart(2, '0') return h ? `${h}:${String(mm).padStart(2, '0')}:${ss}` : `${mm}:${ss}` } /** "~4 min", for how long a thing usually takes. */ export const usually = (secs: number) => (secs < 90 ? `~${Math.max(5, Math.round(secs / 5) * 5)} s` : `~${Math.round(secs / 60)} min`) /** "in 4:12", counting down each second to a time to come; "any moment now" once it has come. */ export class Until extends MithrilComponent<{at: number}> { at = 0 timer = 0 oncreate(v: m.VnodeDOM<{at: number}>) { this.at = v.attrs.at const tick = () => { const left = this.at - Date.now() / 1000 ;(v.dom as HTMLElement).textContent = left > 0 ? `in ${clockOf(left)}` : 'any moment now' } tick() this.timer = window.setInterval(tick, 1000) } onupdate(v: m.VnodeDOM<{at: number}>) { this.at = v.attrs.at } onremove() { window.clearInterval(this.timer) } view() { return } } interface Attrs { /** When it began, in unix seconds; nothing shows without it. */ since: number | null /** How long it takes as a rule, in seconds, where that is known. */ typical: number | null /** Shown from this many seconds on: a moment says nothing. */ after?: number } /** * How long something has taken so far, and against what it takes as a rule: a * thin bar that fills toward it, which gives way to words once it has run longer. * It sets its own text each second, so a ticking clock redraws nothing else. */ export class Elapsed extends MithrilComponent { attrs: Attrs = {since: null, typical: null} timer = 0 tick = () => {} oncreate(v: m.VnodeDOM) { this.attrs = v.attrs const tick = (this.tick = () => { const el = v.dom as HTMLElement const {since: from, typical, after = 3} = this.attrs const gone = from == null ? null : Date.now() / 1000 - from const shown = gone != null && gone >= after el.hidden = !shown if (!shown) return const over = typical != null && gone > typical ;(el.querySelector('.elapsed__time') as HTMLElement).textContent = clockOf(gone) + (typical == null ? '' : over ? ` · longer than usual (${usually(typical)})` : ` · usually ${usually(typical)}`) const bar = el.querySelector('.elapsed__meter') as HTMLElement bar.hidden = typical == null || over if (typical) bar.style.setProperty('--done', `${Math.min(100, (gone / typical) * 100)}%`) }) tick() this.timer = window.setInterval(tick, 1000) } // The same element for the next thing it does (the line is not keyed, its siblings are not): // the clock starts over from the new `since` at once, and what it is measured against // can arrive later, with the hub's next board. onupdate(v: m.VnodeDOM) { this.attrs = v.attrs this.tick() } onremove() { window.clearInterval(this.timer) } view() { return (