Public: anyone can read this; the crew can change it.

Relative times ('3 min ago') carry the exact time as a title and a <time datetime> on every page that prints one #14508

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/14487-relative-times-3-min-ago-carry-the-exact → main 6 commits fork 3 threads · 3 unresolved

  • Merged. scout/14487-relative-times-3-min-ago-carry-the-exact was merged into main as 83faba5.

Review

Sign in to review this change.
13 files changed +82 −45
src/web/pages/claim.ts +2 −1
@@ -68,6 +68,7 @@ import {
6868 import { pageHead, CAME_FROM_ELSEWHERE } from "../chrome.ts";
6969 import { field, readForm } from "../form.ts";
7070 import { html, type Html } from "../html.ts";
71 import { time } from "../time_element.ts";
7172 import { page, redirect } from "../layout.ts";
7273 import { makeOptions, PASSKEY_WORDS, passkeyFields, readPasskey } from "../passkey-ceremony.ts";
7374 import { passkeyJs } from "../passkey-client.ts";
@@ -260,7 +261,7 @@ function claimForm(
260261 ${expiresAt === undefined
261262 ? null
262263 : html`<p class="mb" id="claim-expiry">This link works until
263 <time datetime="${expiresAt}">${whenWords(expiresAt)}</time>
264 ${time(expiresAt, { text: whenWords(expiresAt) })}
264265 (${relativeWords(Date.parse(expiresAt) - Date.now())}). After that, ask
265266 ${spawner?.username ?? "whoever sent it"} to send you a new one.</p>`}
266267 <p class="mb" id="claim-access">${accessSentence(spawned, spawner)}</p>
src/web/pages/home_flow.ts +3 −2
@@ -15,6 +15,7 @@
1515 * version without being drawn. The page is a static picture with scripts off.
1616 */
1717
18 import { time } from "../time_element.ts";
1819 import { requestHolds } from "../../http/conditional.ts";
1920 import { setCookie } from "../../auth/cookies.ts";
2021 import type { App } from "../../app.ts";
@@ -104,7 +105,7 @@ const waitsOf = (url: URL): boolean => url.searchParams.get("waits") === "me";
104105 */
105106 function age(iso: string, now: number): Html {
106107 const at = Date.parse(iso);
107 return html`<time class="hf-age" datetime="${new Date(at).toISOString()}">${span(now - at)}</time>`;
108 return time(new Date(at).toISOString(), { class: "hf-age", text: span(now - at) });
108109 }
109110
110111 const TONE_WORD = {
@@ -319,7 +320,7 @@ export function stripRegion(picture: LanePicture, viewer: StripViewer, dataDir:
319320 ${fig("Median open to landed", lead === null ? "—" : duration(lead * 3_600_000), lead === null ? "nothing landed in 24 hours" : `median of ${count(strip!.lead.landed)} ${strip!.lead.landed === 1 ? "change" : "changes"}, 24 hours`, "/boards")}
320321 ${fig("Crew running", b.slots === 0 ? count(b.running) : `${count(b.running)} of ${count(b.slots)}`, b.slots === 0 ? "no builder slots set" : idle === null ? "builders at work now" : `idle: ${idle.word}`, idle === null ? "/settings/crew" : idle.href)}
321322 ${fig("Week used", week === null ? "—" : week.value, week === null ? "the week is not read yet" : week.note, "/settings/crew", null, week?.attn === true ? "attn" : null)}
322 ${fig("Live version", version === UNSTAMPED ? "—" : version, html`live <time class="hf-age-ago" datetime="${BOOTED}">${span(now - Date.parse(BOOTED))}</time> · ${proof.text}`, "/releases", null, proof.tone)}
323 ${fig("Live version", version === UNSTAMPED ? "—" : version, html`live ${time(BOOTED, { class: "hf-age-ago", text: span(now - Date.parse(BOOTED)) })} · ${proof.text}`, "/releases", null, proof.tone)}
323324 </div>
324325 </section>`;
325326 }
src/web/pages/home_table.ts +2 −3
@@ -14,6 +14,7 @@
1414 * and exist for the kind of row are offered.
1515 */
1616
17 import { time } from "../time_element.ts";
1718 import { applyFleetIds, previewFleetIds } from "../../actions/fleet.ts";
1819 import {
1920 LANES,
@@ -85,9 +86,7 @@ const TONE_DOT = {
8586 function age(iso: string | null, now: number): Html {
8687 if (iso === null) return html`<span class="muted">—</span>`;
8788 const at = Date.parse(iso);
88 return html`<time class="hf-age" datetime="${new Date(at).toISOString()}"
89 >${span(now - at)}</time
90 >`;
89 return time(new Date(at).toISOString(), { class: "hf-age", text: span(now - at) });
9190 }
9291
9392 const HEAD: Record<Column, string> = {
src/web/pages/pull.ts +1 −1
@@ -399,7 +399,7 @@ export function redAloneLine(mark: RedMark | undefined): Html {
399399 if (exact === "") return html``;
400400 return html`<p class="muted small">
401401 ${icon("clock")}red alone at
402 <time datetime="${new Date(mark.at).toISOString()}">${exact}</time>, ${RED_ALONE_WAIT}
402 ${time(new Date(mark.at).toISOString(), { text: exact })}, ${RED_ALONE_WAIT}
403403 </p>`;
404404 }
405405
src/web/setting_line.ts +2 −1
@@ -5,6 +5,7 @@
55 * deeper in a <details>; the mark is drawn as a small bordered button, so it
66 * reads as a control without a word that would cost every row a text block.
77 */
8 import { time } from "./time_element.ts";
89 import { html, raw, type Html } from "./html.ts";
910 import { icon } from "./icons.ts";
1011 import { agoWords } from "../kernel/ago.ts";
@@ -21,7 +22,7 @@ export interface ChangedBy {
2122 */
2223 export function changedNote(last: ChangedBy | undefined, now: number = Date.now()): Html | null {
2324 if (last === undefined) return null;
24 return html`<span class="muted small setting-changed" data-changed>by ${last.by}, <time datetime="${last.at}">${agoWords(last.at, now)}</time></span>`;
25 return html`<span class="muted small setting-changed" data-changed>by ${last.by}, ${time(last.at, { text: agoWords(last.at, now) })}</span>`;
2526 }
2627
2728 /** The reason behind a setting, behind its mark. `id` ties it to the control via aria-describedby. */
src/web/studio/run.ts +2 −2
@@ -8,6 +8,7 @@
88 * at `?all=1`.
99 */
1010
11 import { time } from "../time_element.ts";
1112 import { wayIn } from "../../actions/blocked_words.ts";
1213 import { blockedWay } from "../blocked.ts";
1314 import { checkSteps, stepWord, type LookVitals } from "../../checks/summary.ts";
@@ -91,8 +92,7 @@ function stoppedLine(run: Run): Html | undefined {
9192 const at = run.finishedAt === null ? Number.NaN : Date.parse(run.finishedAt);
9293 if (!Number.isFinite(at)) return html`Stopped by ${name}`;
9394 const iso = new Date(at).toISOString();
94 const exact = `${iso.slice(0, 16).replace("T", " ")} UTC`;
95 return html`Stopped by ${name}, <time datetime="${iso}" title="${exact}">${agoWords(iso)}</time>`;
95 return html`Stopped by ${name}, ${time(iso, { text: agoWords(iso) })}`;
9696 }
9797
9898 /**
src/web/time_element.ts added +35
@@ -0,0 +1,35 @@
1 /** The one place a relative time becomes markup: <time datetime title>, escaped (#14487). */
2 import { html, type Html } from "./html.ts";
3
4 /** A compact relative time: the only clock the UI speaks in. */
5 export function timeAgo(iso: string): string {
6 const seconds = Math.max(0, (Date.now() - Date.parse(iso)) / 1000);
7 if (!Number.isFinite(seconds)) return "";
8 if (seconds < 60) return "just now";
9 const minutes = seconds / 60;
10 if (minutes < 60) return `${Math.floor(minutes)}m ago`;
11 const hours = minutes / 60;
12 if (hours < 24) return `${Math.floor(hours)}h ago`;
13 const days = hours / 24;
14 if (days < 30) return `${Math.floor(days)}d ago`;
15 const months = days / 30;
16 if (months < 12) return `${Math.floor(months)}mo ago`;
17 return `${Math.floor(months / 12)}y ago`;
18 }
19
20 /**
21 * A timestamp a machine and a screen reader can both read: relative text for
22 * the eye, the exact instant in `datetime` and `title` for everyone else.
23 * `date` words it as the calendar day (`2026-12-02`), for an instant ahead
24 * of now, which "ago" cannot name.
25 */
26 export function time(iso: string, opts: { date?: boolean; text?: string; class?: string } = {}): Html {
27 const parsed = Date.parse(iso);

Principle 8/box 1: good single helper. Callers outside the diff (pull.ts:402, claim.ts:263) still hand-build <time>; move them here.

28 if (Number.isNaN(parsed)) return html``;
29 const at = new Date(parsed);
30 const exact = `${at.toISOString().slice(0, 16).replace("T", " ")} UTC`;
31 const cls = opts.class === undefined ? html`` : html` class="${opts.class}"`;
32 return html`<time${cls} datetime="${at.toISOString()}" title="${exact}"
33 >${opts.text ?? (opts.date === true ? at.toISOString().slice(0, 10) : timeAgo(iso))}</time
34 >`;
35 }
src/web/ui.ts +2 −31
@@ -26,6 +26,7 @@ import { icon, type IconName } from "./icons.ts";
2626 import { crewFace, scene, type SceneName } from "./pixel.ts";
2727 import { Html, html, raw, when } from "./html.ts";
2828 import { why } from "./setting_line.ts";
29 import { time, timeAgo } from "./time_element.ts";
2930 import { PREPARED_WORDS } from "../apps/env_phrase.ts";
3031 import { at, countAttr, listAttr, zeroAttr } from "./bind.ts";
3132
@@ -35,37 +36,7 @@ export type Tone = "default" | "success" | "danger" | "merged" | "attn";
3536
3637 // ---- text and time ----
3738
38 /** A compact relative time: the only clock the UI speaks in. */
39 export function timeAgo(iso: string): string {
40 const seconds = Math.max(0, (Date.now() - Date.parse(iso)) / 1000);
41 if (!Number.isFinite(seconds)) return "";
42 if (seconds < 60) return "just now";
43 const minutes = seconds / 60;
44 if (minutes < 60) return `${Math.floor(minutes)}m ago`;
45 const hours = minutes / 60;
46 if (hours < 24) return `${Math.floor(hours)}h ago`;
47 const days = hours / 24;
48 if (days < 30) return `${Math.floor(days)}d ago`;
49 const months = days / 30;
50 if (months < 12) return `${Math.floor(months)}mo ago`;
51 return `${Math.floor(months / 12)}y ago`;
52 }
53
54 /**
55 * A timestamp a machine and a screen reader can both read: relative text for
56 * the eye, the exact instant in `datetime` and `title` for everyone else.
57 * `date` words it as the calendar day (`2026-12-02`), for an instant ahead
58 * of now, which "ago" cannot name.
59 */
60 export function time(iso: string, opts: { date?: boolean; text?: string } = {}): Html {
61 const parsed = Date.parse(iso);
62 if (Number.isNaN(parsed)) return html``;
63 const at = new Date(parsed);
64 const exact = `${at.toISOString().slice(0, 16).replace("T", " ")} UTC`;
65 return html`<time datetime="${at.toISOString()}" title="${exact}"
66 >${opts.text ?? (opts.date === true ? at.toISOString().slice(0, 10) : timeAgo(iso))}</time
67 >`;
68 }
39 export { time, timeAgo };
6940
7041 /** Seconds to one decimal: `3.4s`. A clock that ran backwards reads `0.0s`. */
7142 function seconds(ms: number): string {
test/claim-page-words.test.ts +1 −1
@@ -80,7 +80,7 @@ describe("the claim page in plain words", () => {
8080 expect(res.status).toBe(200);
8181 const html = await res.text();
8282 expect(html).toContain('id="claim-expiry"');
83 expect(html).toMatch(/works until\s*<time datetime="[^"]+">[A-Z][a-z]{2} \d{1,2}, \d\d:\d\d UTC<\/time>\s*\(in (23|24) hours\)/);
83 expect(html).toMatch(/works until\s*<time datetime="[^"]+" title="[^"]+"\s*>[A-Z][a-z]{2} \d{1,2}, \d\d:\d\d UTC<\/time\s*>\s*\(in (23|24) hours\)/);
8484 expect(html).toContain("alice");
8585 });
8686
test/pull-red-alone-line.test.ts +1 −1
@@ -6,7 +6,7 @@ const mark = { at: "2026-10-26T20:41:30.000Z", head: "a".repeat(40), base: "b".r
66 test("a pull held as red alone says so, with a <time> element", () => {
77 const line = redAloneLine(mark).text;
88 expect(line).toContain("red alone at");
9 expect(line).toContain('<time datetime="2026-10-26T20:41:30.000Z">2026-10-26 20:41 UTC</time>');
9 expect(line).toMatch(/<time datetime="2026-10-26T20:41:30.000Z" title="2026-10-26 20:41 UTC"\s*>2026-10-26 20:41 UTC<\/time/);
1010 expect(line).toContain("waiting for a new head or a new main");
1111 });
1212
test/run-stopped-words.test.ts +1 −1
@@ -83,7 +83,7 @@ describe("a run stopped from the page", () => {
8383 const summary = text.match(/<p class="mt" id="run-summary">(.*?)<\/p>/s)?.[1] ?? "";
8484 // The words are the sentence the feed and the terminal say; the time holds the exact instant.
8585 expect(summary.replace(/<[^>]*>/g, "")).toBe("Stopped by alice, just now");
86 const time = summary.match(/<time datetime="([^"]+)" title="([^"]+)">just now<\/time>/);
86 const time = summary.match(/<time datetime="([^"]+)" title="([^"]+)"\s*>just now<\/time\s*>/);
8787 expect(time).not.toBeNull();
8888 expect(Number.isFinite(Date.parse(time![1]!))).toBe(true);
8989 expect(time![2]).toBe(`${time![1]!.slice(0, 16).replace("T", " ")} UTC`);
test/settings-last-change.test.ts +1 −1
@@ -57,7 +57,7 @@ test("a changed setting shows who and when; an untouched one shows nothing", asy
5757 });
5858 expect(res.status).toBeLessThan(400);
5959 const after = await get();
60 expect(row(after, "landing")).toMatch(/by olive, <time datetime="[^"]+">just now<\/time>/);
60 expect(row(after, "landing")).toMatch(/by olive, <time datetime="[^"]+" title="[^"]+"\s*>just now<\/time\s*>/);
6161 expect(row(after, "polishShare")).not.toContain("data-changed");
6262 expect(row(after, "requireReview")).not.toContain("data-changed");
6363 });
test/time-element.test.ts +29
@@ -98,3 +98,32 @@ describe("rendered pages", () => {
9898 expect(body).toMatch(/data-following-history[\s\S]*?<time datetime="[^"]+" title="[^"]+"\s*>2h ago<\/time/);
9999 });
100100 });
101
102 describe("no template builds a relative time by hand (#14487)", () => {
103 test("no <time is written by hand in src/web outside the date-only pages", async () => {
104 const { Glob } = await import("bun");
105 // Date-only or script-owned elements: no relative phrase, so no title to carry.
106 const allowed = new Set([
107 "changelog.ts", "payments.ts", "billing.ts", "frozen.ts", "following.ts", "migrate.ts",
108 "upstream-follow.ts", "fleet-graph.ts", "offline.ts",
outdated

This regex only matches single-line <time> with a literal call in the text, so pull.ts:402 and claim.ts:263 slip through. Invert it: fail on any <time in src/web outside an allowlist of date-only files.

109 "board.ts", // the corner clock: empty, the board script fills it
110 "subtitles.ts", // a caption cue's start, not a moment
111 "client.ts", "live.ts", // scripts that match <time> in fetched markup
112 ]);
113 const offenders: string[] = [];
114 for await (const file of new Glob("src/web/**/*.ts").scan(".")) {
115 const name = file.split("/").pop()!;
116 if (name === "time_element.ts" || allowed.has(name)) continue;
117 const lines = (await Bun.file(file).text()).split("\n");
118 lines.forEach((l, i) => {
119 if (/<time\b/.test(l) && !/^\s*(\*|\/\/|\/\*)/.test(l)) offenders.push(`${file}:${i + 1}: ${l.trim().slice(0, 70)}`);
120 });
121 }
122 expect(offenders).toEqual([]);
123 });
124 test("the helper escapes its words and its class", () => {
125 const out = time(at, { text: "<b>x</b>", class: 'a"b' }).text;
126 expect(out).not.toContain("<b>");
127 expect(out).toContain('class="a&quot;b"');
128 });
129 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs