// A POST ITEM's CLOCK (umtool/docs/report-video.md, "The clock"; operator, 4 Nov: // "show a clock advancing as we show the newest posts/replies chronologically // and quickly to convey how much he's posting in bursts" -- "the clock should // probably just be for mr obvious' replies and ignore the messages he's replying // to so it generally always goes forward unless there's a compelling reason to // go back at some point (e.g. 'you want to die' combo)"). // // A small clock-and-date chip on the card: "4:10 AM ET · Wed 4 Nov", in the // operator's zone (America/New_York; render.posts.clock.zone). It shows the // ITEM's own post time (entry.date) -- never a parent's or a quote's, and it // does not move while they are read. Between two consecutive clock items, in // the first CLOCK_TICK seconds of the second it RUNS from the earlier time to // this one: the hands spin, the minutes roll, the date flips, the gap flashes // ("+38 min", "+2 h 14 min", "+3 d 4 h"). When this post is EARLIER than the // one before (a stinger that jumps back), it REWINDS: the hands spin backwards, // a "⟲ rewind" badge with the gap, the date flipping back -- deliberate, never a // glitch. `rewind: "off"` cuts straight to the time; `"on"` rewinds even // forward (or across no gap: a repeated post spins back a full turn to itself). // // render.posts.clock = { on?: true, zone?: "America/New_York" } // the cut's default // entry.fx = [{ kind: "clock", on?: false, rewind?: "auto" | "on" | "off" }] // one item's // // WHERE: the card's bottom-right corner (beside the counts row, never read // text), else its top-right; the first place over no word of the card. Drawn // OVER the card, never in it (no data-w, no data-post-block): readInViewErrors // never counts it, and it covers no read text. // // Pure but for the DOM functions (mountClock, measureClockPlace, setClockState), // SELF-CONTAINED: the build passes them to a page, Play calls them on its frame. import { mixHex, rgbaOf } from "./post-item.mjs"; export const CLOCK_ZONE = "America/New_York"; /** How long the clock runs from the earlier time to this one, seconds. */ export const CLOCK_TICK = 0.8; /** The gap's badge stays this long after the run, then fades over CLOCK_FLASH_OUT. */ export const CLOCK_FLASH_HOLD = 0.9; export const CLOCK_FLASH_OUT = 0.4; export const CLOCK_REWINDS = Object.freeze(["auto", "on", "off"]); const CLOCK_KEYS = new Set(["kind", "on", "rewind"]); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); /** A zone Intl knows. */ export function validZone(zone) { try { new Intl.DateTimeFormat("en-US", { timeZone: String(zone) }); return typeof zone === "string" && zone.length > 0; } catch { return false; } } /** Every reason a clock fx (entry `e`'s fx[i], named `fw`) cannot be built. word-zoom.mjs validatePostFx calls it. */ export function clockErrors(e, fx, fw) { const errors = []; for (const k of Object.keys(fx)) if (!CLOCK_KEYS.has(k)) errors.push(`${fw}.${k} is not a clock key (${[...CLOCK_KEYS].join(", ")})`); if (fx.on !== undefined && typeof fx.on !== "boolean") errors.push(`${fw}.on must be true or false`); if (fx.rewind !== undefined && !CLOCK_REWINDS.includes(fx.rewind)) errors.push(`${fw}.rewind must be one of ${CLOCK_REWINDS.join(", ")}`); if ((Array.isArray(e?.fx) ? e.fx : []).filter((f) => f?.kind === "clock").length > 1) errors.push(`${fw}: one clock per item`); if (fx.on !== false && !Number.isFinite(Date.parse(String(e?.date ?? "")))) errors.push(`${fw}: the post has no date to show (its date)`); return errors; } /** Every reason `render.posts.clock` is refused (post-redact.mjs validatePostsRender calls it). */ export function validateClockRender(c) { if (c === undefined) return []; if (!isObj(c)) return ["render.posts.clock must be { on?, zone? }"]; const errors = []; for (const k of Object.keys(c)) if (!["on", "zone"].includes(k)) errors.push(`render.posts.clock.${k} is not a clock knob (on, zone)`); if (c.on !== undefined && typeof c.on !== "boolean") errors.push("render.posts.clock.on must be true or false"); if (c.zone !== undefined && !validZone(c.zone)) errors.push(`render.posts.clock.zone ${JSON.stringify(c.zone)} is not a time zone (an IANA name: America/New_York)`); return errors; } /** The item's clock fx, or null. */ const clockFxOf = (entry) => (Array.isArray(entry?.fx) ? entry.fx.find((f) => isObj(f) && f.kind === "clock") ?? null : null); /** Whether post item `entry` shows the clock: its own fx (on unless `on: false`), else the cut's `render.posts.clock.on`. */ export function clockOn(entry, render) { if (entry?.type !== undefined && entry.type !== "post") return false; if (!Number.isFinite(Date.parse(String(entry?.date ?? "")))) return false; const fx = clockFxOf(entry); if (fx) return fx.on !== false; return render?.posts?.clock?.on === true; } /** The cut's zone. */ export const clockZoneOf = (render) => (validZone(render?.posts?.clock?.zone) ? render.posts.clock.zone : CLOCK_ZONE); /** * THE CLOCK's PLAN for post item `entry`: `{ to, from, mode, zone, gap }` -- * `to` its post's time (ms), `from` the time the clock showed on the item * before it when that one is a clock item too (else null: no run), `mode` * "forward" | "rewind" | "none", `gap` to - from (ms). Null when it shows no clock. * @param {Record} entry * @param {Record} [render] * @param {Record | null} [prev] * @returns {{ to: number, from: number | null, mode: "forward" | "rewind" | "none", zone: string, gap: number, forced: boolean } | null} */ export function clockPlan(entry, render = undefined, prev = null) { if (!clockOn(entry, render)) return null; const to = Date.parse(entry.date); const zone = clockZoneOf(render); const rewind = clockFxOf(entry)?.rewind ?? "auto"; const from = prev && clockOn(prev, render) ? Date.parse(prev.date) : null; if (from === null || rewind === "off") return { to, from: null, mode: "none", zone, gap: 0, forced: false }; if (rewind === "on") return { to, from: from > to ? from : to + 12 * 3600e3, mode: "rewind", zone, gap: to - from, forced: from <= to }; if (from === to) return { to, from: null, mode: "none", zone, gap: 0, forced: false }; return { to, from, mode: from > to ? "rewind" : "forward", zone, gap: to - from, forced: false }; } /** A gap as the badge says it: "+38 min", "+2 h 14 min", "+3 d 4 h", "+45 s" (its sign kept). */ export function gapLabel(ms) { const sign = ms < 0 ? "−" : "+"; let s = Math.round(Math.abs(ms) / 1000); if (s < 60) return `${sign}${s} s`; const d = Math.floor(s / 86400); s -= d * 86400; const h = Math.floor(s / 3600); s -= h * 3600; const m = Math.floor(s / 60); if (d) return `${sign}${d} d${h ? ` ${h} h` : ""}`; if (h) return `${sign}${h} h${m ? ` ${m} min` : ""}`; return `${sign}${m} min`; } const fmtCache = new Map(); const fmt = (zone, o) => { const k = `${zone}|${JSON.stringify(o)}`; if (!fmtCache.has(k)) fmtCache.set(k, new Intl.DateTimeFormat(o.locale ?? "en-US", { timeZone: zone, ...o, locale: undefined })); return fmtCache.get(k); }; /** A moment's face in a zone: `{ time: "4:10 AM", zone: "ET", date: "Wed 4 Nov", h, m }` (h 0–23, m 0–59.99 its local clock). */ export function clockFace(ms, zone = CLOCK_ZONE) { const d = new Date(ms); const time = fmt(zone, { hour: "numeric", minute: "2-digit" }).format(d); const zn = (fmt(zone, { timeZoneName: "shortGeneric", hour: "numeric" }).formatToParts(d).find((p) => p.type === "timeZoneName")?.value ?? "").replace(/^GMT$/, "UTC"); const date = fmt(zone, { locale: "en-GB", weekday: "short", day: "numeric", month: "short" }).format(d).replace(",", ""); const parts = Object.fromEntries(fmt(zone, { hourCycle: "h23", hour: "2-digit", minute: "2-digit", second: "2-digit" }).formatToParts(d).map((p) => [p.type, p.value])); return { time, zone: zn, date, h: Number(parts.hour) % 24, m: Number(parts.minute) + Number(parts.second) / 60 }; } const easeInOut = (x) => { const v = Math.min(1, Math.max(0, x)); return v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2; }; /** * THE CLOCK AT item second `s`: what the chip shows -- `{ time, zone, date, * hour, minute (hand angles, degrees), gap, gapOpacity, mode, running }`. The * hands' angles run continuously from the earlier time (a rewind: backwards). * @param {ReturnType} plan * @param {number} s */ export function clockStateAt(plan, s) { if (!plan) return null; const run = plan.from === null || plan.mode === "none" ? 1 : easeInOut(s / CLOCK_TICK); const shown = plan.from === null ? plan.to : plan.from + (plan.to - plan.from) * run; const face = clockFace(shown, plan.zone); // The hands from the minutes elapsed (continuous across days: the hour hand turns once per 12 h, the minute hand per hour). const end = clockFace(plan.to, plan.zone); const endMin = end.h * 60 + end.m; const minutes = endMin + (shown - plan.to) / 60000; const ga = plan.mode === "none" ? 0 : s < CLOCK_TICK + CLOCK_FLASH_HOLD ? Math.min(1, s / 0.15) : Math.max(0, 1 - (s - CLOCK_TICK - CLOCK_FLASH_HOLD) / CLOCK_FLASH_OUT); return { time: face.time, zone: face.zone, date: face.date, hour: ((minutes / 2) % 360 + 360) % 360, minute: ((minutes * 6) % 360 + 360) % 360, // Unwrapped (the DOM rotates by these, so a run spins rather than snapping back across 0). hourTurn: minutes / 2, minuteTurn: minutes * 6, gap: plan.mode === "rewind" ? `⟲ rewind${plan.forced ? "" : ` ${gapLabel(plan.gap)}`}` : plan.mode === "forward" ? gapLabel(plan.gap) : "", gapOpacity: Math.round(ga * 1000) / 1000, mode: plan.mode, running: plan.mode !== "none" && s < CLOCK_TICK, }; } /** The item seconds whose frames differ (the run and the badge's fade), at `fps`: `[0, 1/fps, …]` up to the last change. */ export function clockFrameTimes(plan, fps = 30) { if (!plan || plan.mode === "none") return [0]; const end = CLOCK_TICK + CLOCK_FLASH_HOLD + CLOCK_FLASH_OUT; const out = []; for (let f = 0; f / fps <= end + 1e-9; f += 1) out.push(f / fps); return out; } // --------------------------------------------------------------------------- // THE LOOK, and the DOM (self-contained). // --------------------------------------------------------------------------- /** The chip's CSS for a page `height` px tall, in the card's palette. */ export function clockCss({ height = 1080, palette = {} } = {}) { const k = height / 1080; const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; const panel = mixHex(pal.bg, pal.fg, 0.08); const px = (v) => `${Math.round(v * k)}px`; return ` [data-post-clock-layer] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 61; } .pclock { position: absolute; left: 0; top: 0; display: flex; align-items: center; gap: ${px(12)}; padding: ${px(7)} ${px(16)} ${px(7)} ${px(9)}; background: ${panel}; color: ${pal.fg}; border: ${Math.max(1, Math.round(1.5 * k))}px solid ${rgbaOf(pal.fg, 0.18)}; border-radius: ${px(999)}; box-shadow: 0 ${px(4)} ${px(16)} ${rgbaOf("#000000", 0.4)}; font-family: 'PostSans', 'Noto Sans CJK JP', sans-serif; white-space: nowrap; font-synthesis: none; } .pclock-face { width: ${px(44)}; height: ${px(44)}; flex: none; } .pclock-face circle { fill: ${rgbaOf(pal.bg, 0.6)}; stroke: ${pal.accent}; stroke-width: 2.4; } .pclock-face .tk { stroke: ${rgbaOf(pal.fg, 0.45)}; stroke-width: 1.6; } .pclock-face .hh { stroke: ${pal.fg}; stroke-width: 3.2; stroke-linecap: round; } .pclock-face .mh { stroke: ${pal.accent}; stroke-width: 2.2; stroke-linecap: round; } .pclock-txt { display: flex; flex-direction: column; line-height: 1.12; } .pclock-time { font-family: 'PostSansBold', 'Noto Sans CJK JP', sans-serif; font-size: ${px(26)}; font-variant-numeric: tabular-nums; } .pclock-zone { font-family: 'PostSans', sans-serif; color: ${pal.muted}; font-size: ${px(18)}; margin-left: ${px(5)}; } .pclock-date { color: ${mixHex(pal.fg, pal.muted, 0.4)}; font-size: ${px(18)}; letter-spacing: 0.02em; } .pclock-gap { position: absolute; right: calc(100% + ${px(10)}); top: 50%; transform: translateY(-50%); padding: ${px(4)} ${px(12)}; border-radius: ${px(999)}; font-family: 'PostSansBold', sans-serif; font-size: ${px(22)}; background: ${pal.accent}; color: ${pal.bg}; opacity: 0; font-variant-numeric: tabular-nums; } .pclock[data-mode="rewind"] .pclock-gap { background: ${pal.fg}; color: ${pal.bg}; } .pclock[data-mode="rewind"][data-running="1"] .pclock-face circle { stroke: ${pal.fg}; stroke-dasharray: 4 3; } .pclock[data-running="1"] .pclock-date { color: ${pal.accent}; } `; } /** The chip's HTML (its face with 12 ticks; the text filled by setClockState). */ export function clockHtml() { const ticks = Array.from({ length: 12 }, (_, i) => { const a = (i * Math.PI) / 6; const r0 = i % 3 ? 15 : 13; return ``; }).join(""); return `${ticks}0:00 AMETMon 1 Jan`; } /** * Mount the clock over the card page (`{ css, html, widest }`: `widest` a state * to lay it out at its widest), hidden. Returns its size `{ width, height }`. * @param {{ css: string, html: string, widest?: Record | null } | null} arg * @param {Document} [doc] */ export function mountClock(arg, doc = document) { doc.querySelectorAll("[data-post-clock-layer], style[data-post-clock-css]").forEach((el) => el.remove()); if (!arg || !arg.html) return null; const style = doc.createElement("style"); style.setAttribute("data-post-clock-css", ""); style.textContent = arg.css || ""; doc.head.appendChild(style); const layer = doc.createElement("div"); layer.setAttribute("data-post-clock-layer", ""); const el = doc.createElement("div"); el.className = "pclock"; el.setAttribute("data-post-clock", ""); el.style.opacity = "0"; el.innerHTML = arg.html; layer.appendChild(el); doc.body.appendChild(layer); const w = arg.widest || {}; const set = (sel, v) => { const n = el.querySelector(sel); if (n && v !== undefined) n.textContent = v; }; set("[data-clock-time]", w.time); set("[data-clock-zone]", w.zone); set("[data-clock-date]", w.date); const b = el.getBoundingClientRect(); // Its width held at the widest (a running time never resizes it). el.style.minWidth = `${Math.ceil(b.width)}px`; return { width: Math.ceil(b.width), height: Math.ceil(b.height) }; } /** * Where the clock goes on the card as drawn: the bottom-right corner (beside * the counts row), else the top-right, the first over no word of the card * (`[data-w]`); `{ x, y, place, covers, tries }`. `size` its box, `inset` from * the card's edge; `fixed`: the places to judge (an earlier call's `tries`), * only counted here -- the build places it once and judges it over the read. * @param {{ size: { width: number, height: number }, inset: number, fixed?: Array<{ x: number, y: number, place: string }> | null }} arg * @param {Document} [doc] */ export function measureClockPlace(arg, doc = document) { const card = doc.querySelector("[data-post-card]"); if (!card || !arg || !arg.size) return null; const c = card.getBoundingClientRect(); const words = Array.from(doc.querySelectorAll("[data-w]")).flatMap((el) => Array.from(el.getClientRects())).filter((r) => r.width > 0); const hit = (r) => words.filter((w) => Math.min(r.x + r.width, w.right) - Math.max(r.x, w.left) > 1 && Math.min(r.y + r.height, w.bottom) - Math.max(r.y, w.top) > 1).length; // Its own post's counts row (a threaded card draws one per tile: the post's tile, else the last). const all = Array.from(card.querySelectorAll(".counts")); const counts = card.querySelector('[data-thread-tile="post"] .counts') || all[all.length - 1] || null; const cb = counts ? counts.getBoundingClientRect() : null; const x = Math.round(c.right - arg.inset - arg.size.width); // Bottom: centred on the counts row when there is one, else in the card's foot. const yb = cb && cb.height > 0 ? Math.round(cb.top + (cb.height - arg.size.height) / 2 + 4) : Math.round(c.bottom - arg.inset - arg.size.height); const tries = (arg.fixed || [ { x, y: Math.min(yb, Math.round(c.bottom - arg.size.height - 4)), place: "bottom-right" }, { x, y: Math.round(c.top + arg.inset), place: "top-right" }, ]).map((t) => ({ ...t, covers: hit({ x: t.x - arg.size.width * 0.6, y: t.y, width: arg.size.width * 1.6, height: arg.size.height }) })); const best = tries.find((t) => !t.covers) || tries.slice().sort((a, b) => a.covers - b.covers)[0]; return { ...best, tries }; } /** * Set the clock: `{ x, y, opacity, st }` (`st` clockStateAt's), or null to hide. * @param {{ x: number, y: number, opacity?: number, st: Record } | null} arg * @param {Document} [doc] */ export function setClockState(arg, doc = document) { const el = doc.querySelector("[data-post-clock]"); if (!el) return; if (!arg || !arg.st) { el.style.opacity = "0"; return; } const st = arg.st; el.style.transform = `translate(${Math.round(arg.x)}px, ${Math.round(arg.y)}px)`; el.style.opacity = String(arg.opacity === undefined ? 1 : arg.opacity); el.setAttribute("data-mode", st.mode); el.setAttribute("data-running", st.running ? "1" : "0"); const set = (sel, v) => { const n = el.querySelector(sel); if (n && n.textContent !== v) n.textContent = v; }; set("[data-clock-time]", st.time); set("[data-clock-zone]", st.zone); set("[data-clock-date]", st.date); set("[data-clock-gap]", st.gap); const gap = el.querySelector("[data-clock-gap]"); if (gap) gap.style.opacity = st.gap ? String(st.gapOpacity) : "0"; const hh = el.querySelector("[data-clock-hh]"); const mh = el.querySelector("[data-clock-mh]"); if (hh) hh.setAttribute("transform", `rotate(${st.hourTurn.toFixed(2)} 22 22)`); if (mh) mh.setAttribute("transform", `rotate(${st.minuteTurn.toFixed(2)} 22 22)`); }