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

Relative times render as <time> with the exact time in the title, with no layout shift #13986

Merged opened this

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

Merged

scout/forge:scout/13974-relative-times-render-as-time-with-the-e → main 7 commits fork 5 threads · 5 unresolved

  • Merged. scout/13974-relative-times-render-as-time-with-the-e was merged into main as 7a10319.

Review

Sign in to review this change.
18 files changed +132 −31
src/web/chrome.ts +1 −1
@@ -59,7 +59,7 @@ export function loadRepo(ctx: Ctx): Repo | undefined {
5959 return repo;
6060 }
6161
62 export const repoBase = (repo: Repo): string =>
62 export const repoBase = (repo: Pick<Repo, "ownerName" | "name">): string =>
6363 `/${repo.ownerName}/${repo.name}`;
6464
6565 export function crumbsFor(repo: Repo): { label: string; href: string }[] {
src/web/pages/detach.ts +2 −2
@@ -16,7 +16,7 @@ import { repoBase } from "../chrome.ts";
1616 import { html, type Html } from "../html.ts";
1717 import { icon } from "../icons.ts";
1818 import { flashTo } from "../layout.ts";
19 import { confirmAction, timeAgo } from "../ui.ts";
19 import { confirmAction, time } from "../ui.ts";
2020 import type { Database } from "bun:sqlite";
2121 import { adminForm } from "../admin_form.ts";
2222
@@ -52,7 +52,7 @@ export function detachBlock({ name, action, job }: DetachView): Html {
5252 job?.phase === "repacking"
5353 ? html`<p data-detach-progress>
5454 ${icon("sync")} Detaching from ${name}: copying the objects it lends
55 into this repository, started ${timeAgo(job.startedAt)}. Reload to
55 into this repository, started ${time(job.startedAt)}. Reload to
5656 see it finish; pushes and clones keep working meanwhile.
5757 </p>`
5858 : html`${job?.phase === "failed"
src/web/pages/following.ts +2 −2
@@ -49,7 +49,7 @@ import { proposesViaFork } from "../../origins/fork-route.ts";
4949 import { field, readForm } from "../form.ts";
5050 import { html, when, type Html } from "../html.ts";
5151 import { flashOrJson } from "../layout.ts";
52 import { badge, btn, icon, row, timeAgo, type Tone } from "../ui.ts";
52 import { badge, btn, icon, row, time, type Tone } from "../ui.ts";
5353 import { disconnectedOn } from "./frozen.ts";
5454
5555 /** The first node (parents before children) the viewer owns and is not looking at. */
@@ -257,7 +257,7 @@ function incomingList(incoming: Incoming): Html {
257257 ${incoming.commits.map((c) =>
258258 row({
259259 title: c.subject === "" ? c.oid.slice(0, 7) : c.subject,
260 meta: html`<span class="mono">${c.oid.slice(0, 7)}</span> · ${c.author} · ${timeAgo(c.date)}`,
260 meta: html`<span class="mono">${c.oid.slice(0, 7)}</span> · ${c.author} · ${time(c.date)}`,
261261 }),
262262 )}
263263 ${incoming.more > 0
src/web/pages/fork-offers.ts +3 −2
@@ -5,8 +5,9 @@ import type { ForkOffer } from "../../core/fork_offers.ts";
55 import type { Repo } from "../../core/repos.ts";
66 import { repoBase } from "../chrome.ts";
77 import { html, type Html } from "../html.ts";
8 import { time } from "../ui.ts";
89
9 export function forkOffersCard(repo: Repo, offers: readonly ForkOffer[]): Html | null {
10 export function forkOffersCard(repo: Pick<Repo, "ownerName" | "name">, offers: readonly ForkOffer[]): Html | null {
1011 if (offers.length === 0) return null;
1112 return html`<section aria-labelledby="fork-offers-h">
1213 <h2 id="fork-offers-h">Offered by forks</h2>
@@ -14,7 +15,7 @@ export function forkOffersCard(repo: Repo, offers: readonly ForkOffer[]): Html |
1415 (o) => html`<li>
1516 <a class="row" href="${repoBase(repo)}/pulls/${o.number}"
1617 ><span class="row-main"><span class="row-title">${o.title}</span>
17 <span class="row-meta"><span>${o.fork}</span> <span>${agoWords(o.createdAt)}</span></span></span></a>
18 <span class="row-meta"><span>${o.fork}</span> <span>${time(o.createdAt, { text: agoWords(o.createdAt) })}</span></span></span></a>
1819 </li>`,
1920 )}</ul>
2021 </section>`;
src/web/pages/now.ts +2 −2
@@ -11,7 +11,7 @@ import type { Ctx } from "../../http/context.ts";
1111 import { notFoundPage, signInFirst } from "../chrome.ts";
1212 import { html } from "../html.ts";
1313 import { page } from "../layout.ts";
14 import { row, timeAgo } from "../ui.ts";
14 import { row, time } from "../ui.ts";
1515
1616 // GET /now/:stage
1717 export function nowPage(ctx: Ctx): Response {
@@ -32,7 +32,7 @@ export function nowPage(ctx: Ctx): Response {
3232 nav: true,
3333 title: html`${r.title}`,
3434 meta: html`${r.repo} · ${r.note}`,
35 trail: html`<span class="muted small">${timeAgo(r.at)}</span>`,
35 trail: html`<span class="muted small">${time(r.at)}</span>`,
3636 }),
3737 )}
3838 </ul>`;
src/web/pages/prompts.ts +1 −2
@@ -27,7 +27,6 @@ import {
2727 field as formField,
2828 row,
2929 time,
30 timeAgo,
3130 } from "../ui.ts";
3231 import { adminForm } from "../admin_form.ts";
3332 import { settingsPageResponse, timedAdminRepo } from "./settings.ts";
@@ -77,7 +76,7 @@ function promptsView(base: string, sources: PromptSourceView[]): Html {
7776 meta: html`${source.lastRanAt === null
7877 ? "Has not run yet."
7978 : html`Last ran ${time(source.lastRanAt)}. ${source.lastSaid}`}
80 Token refreshed ${timeAgo(source.tokenRefreshedAt)}; the forge
79 Token refreshed ${time(source.tokenRefreshedAt)}; the forge
8180 refreshes it again around ${refreshDay(source.tokenRefreshedAt)}.`,
8281 trail: html`<form method="post" action="${at(source.id)}/run">
8382 ${btn("Fetch now", { size: "sm", icon: "sync" })}
src/web/pages/subscriptions.ts +1 −2
@@ -52,7 +52,6 @@ import {
5252 listCard,
5353 row,
5454 time,
55 timeAgo,
5655 tokenCount,
5756 userLink,
5857 } from "../ui.ts";
@@ -183,7 +182,7 @@ export function subscriptionsPage(ctx: Ctx): Response {
183182 ·
184183 ${s.lastUsedAt === null
185184 ? "never used"
186 : html`last used ${timeAgo(s.lastUsedAt)}`}${when(
185 : html`last used ${time(s.lastUsedAt)}`}${when(
187186 rests && s.restingSaid !== "",
188187 () => html` · ${s.restingSaid}`,
189188 )}${when(
src/web/pages/teams.ts +2 −3
@@ -10,7 +10,6 @@ import { changeTeam, readTeamQueue, readTeams, teamChanges, TEAM_SAYS } from "..
1010 import type { Agent } from "../../core/agents.ts";
1111 import { CHARTER_MAX, DIAL_MAX, shareSays, type Team } from "../../core/teams.ts";
1212 import type { QueuedPull } from "../../core/team_queue.ts";
13 import { timeAgo } from "../ui.ts";
1413 import type { Ctx } from "../../http/context.ts";
1514 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1615 import { notFoundPage, settingsLayout } from "../chrome.ts";
@@ -18,7 +17,7 @@ import { field, readForm } from "../form.ts";
1817 import { eventStream } from "../../http/sse.ts";
1918 import { html, raw, type Html } from "../html.ts";
2019 import { flashTo, page } from "../layout.ts";
21 import { btn, icon, row } from "../ui.ts";
20 import { btn, icon, row, time } from "../ui.ts";
2221 import { accountSections } from "./origins.ts";
2322
2423 const isAdminPerson = (ctx: Ctx): boolean =>
@@ -73,7 +72,7 @@ function teamBody(t: Team, agents: readonly Agent[], waiting: readonly QueuedPul
7372 <dl class="status-rows">${waiting.map(
7473 (w) => html`<div class="status-row">
7574 <dt><a href="/${w.owner}/${w.repo}/pulls/${String(w.number)}">${w.owner}/${w.repo} #${String(w.number)}</a></dt>
76 <dd>${w.title} <span class="muted">${timeAgo(w.createdAt)}</span></dd>
75 <dd>${w.title} <span class="muted">${time(w.createdAt)}</span></dd>
7776 </div>`,
7877 )}</dl>`}
7978 <form method="post" action="/settings/teams/${t.slug}">
src/web/pages/upstream-follow.ts +4 −4
@@ -45,7 +45,7 @@ import { html, when, type Html } from "../html.ts";
4545 import { icon } from "../icons.ts";
4646 import { isLocalPath } from "../flash.ts";
4747 import { flashTo } from "../layout.ts";
48 import { btn, field as formField, row, timeAgo } from "../ui.ts";
48 import { btn, field as formField, row, time } from "../ui.ts";
4949
5050 /** Where to land: a validated same-origin path the form names as `back`, else the settings card. */
5151 function backTo(form: Awaited<ReturnType<typeof readForm>> & object, fallback: string): string {
@@ -118,7 +118,7 @@ export function behindLine(ctx: Ctx, repo: Repo): Html | null {
118118 ? html`<a href="${base}/settings#upstream">${text}</a>`
119119 : html`<a href="${base}/issues/${waiting.number}">${conflictWaitingWords(waiting)}</a>`
120120 : html`${text} ·`}
121 checked ${timeAgo(checkedAt)}
121 checked ${time(checkedAt)}
122122 ${when(admin, () => updateAction(base))}
123123 </div>`;
124124 }
@@ -137,7 +137,7 @@ export function originAheadLine(ctx: Ctx, repo: Repo): Html | null {
137137 const base = repoBase(repo);
138138 return html`<div class="small muted" data-origin-ahead>
139139 ${icon("sync")}
140 ${aheadWords(ahead)} · read ${timeAgo(ahead.at)}
140 ${aheadWords(ahead)} · read ${time(ahead.at)}
141141 ${when(
142142 requireWriter(ctx.app, ctx.auth.user, repo).ok,
143143 () => html`<form method="post" action="${base}/sync/take" class="inline">
@@ -152,7 +152,7 @@ function historyList(ctx: Ctx, repo: Repo): Html | null {
152152 const checks = listChecks(ctx.app.db, repo.id, 5);
153153 if (checks.length === 0) return null;
154154 return html`<ul class="list" data-following-history>
155 ${checks.map((c) => row({ title: checkLine(c, timeAgo(c.at)) }))}
155 ${checks.map((c) => row({ title: html`${time(c.at)}${checkLine(c, "")}` }))}
156156 </ul>`;
157157 }
158158
src/web/scope.ts +2 −2
@@ -44,7 +44,7 @@ import { html, when, type Html } from "./html.ts";
4444 import { repoSteps } from "./repo_steps.ts";
4545 import { icon, type IconName } from "./icons.ts";
4646 import type { PaletteItem } from "./layout.ts";
47 import { timeAgo } from "./ui.ts";
47 import { time, timeAgo } from "./ui.ts";
4848
4949 /** Which side of the world a page is reading. */
5050 export type ScopeKind = "local" | "origin";
@@ -534,7 +534,7 @@ export function studioOriginNote(repo: Repo | undefined): Html | null {
534534 >${host}</a
535535 >`}${at.lastFetchAt === null
536536 ? ""
537 : html`, synced ${timeAgo(at.lastFetchAt)}`}
537 : html`, synced ${time(at.lastFetchAt)}`}
538538 </p>`;
539539 }
540540
src/web/studio/flow_card.ts +2 −2
@@ -12,14 +12,14 @@ import { readStalled, type StalledStep } from "../../flow/stalled.ts";
1212 import type { User } from "../../core/users.ts";
1313 import type { Ctx } from "../../http/context.ts";
1414 import { html, type Html } from "../html.ts";
15 import { badge, btn, card, timeAgo } from "../ui.ts";
15 import { badge, btn, card, time } from "../ui.ts";
1616
1717 const BUTTON: Record<StalledStep["action"], string> = { run: "Run check", rerun: "Re-run" };
1818
1919 function stalledCard(s: StalledStep): Html {
2020 const base = `/${s.ownerName}/${s.repoName}/pulls/${s.pull}`;
2121 const head = html`${badge(s.stage, { variant: "secondary" })}
22 <span class="muted small">${s.ownerName}/${s.repoName} · stuck since ${timeAgo(s.since)}</span>`;
22 <span class="muted small">${s.ownerName}/${s.repoName} · stuck since ${time(s.since)}</span>`;
2323 const body = html`<p class="break"><a href="${base}">${s.title}</a>${s.issue === null ? null : html` <span class="muted small">for #${String(s.issue)}</span>`}</p>
2424 <form method="post" action="${base}/checks" class="bar">
2525 <input type="hidden" name="next" value="/">
src/web/studio/forks_card.ts +2 −2
@@ -11,7 +11,7 @@ import type { User } from "../../core/users.ts";
1111 import type { Database } from "bun:sqlite";
1212 import type { Ctx } from "../../http/context.ts";
1313 import { html, type Html } from "../html.ts";
14 import { icon, listCard, row, timeAgo } from "../ui.ts";
14 import { icon, listCard, row, time } from "../ui.ts";
1515 import { repoBase } from "../chrome.ts";
1616
1717 /** How many forks the app page lists. */
@@ -62,7 +62,7 @@ export function forksCard(ctx: Ctx, repo: Repo): Html | null {
6262 row({
6363 href: `/${encodeURIComponent(f.owner)}/${encodeURIComponent(f.name)}`,
6464 title: html`${f.owner} / ${f.name}`,
65 meta: f.changedAt === "" ? html`` : html`changed ${timeAgo(f.changedAt)}`,
65 meta: f.changedAt === "" ? html`` : html`changed ${time(f.changedAt)}`,
6666 data: { fork: `${f.owner}/${f.name}` },
6767 }),
6868 ),
src/web/studio/home.ts +2 −2
@@ -53,7 +53,7 @@ import {
5353 envStateBadge,
5454 icon,
5555 row,
56 timeAgo,
56 time,
5757 copyField,
5858 } from "../ui.ts";
5959 import {
@@ -590,7 +590,7 @@ function doorLive(front: FrontPage): Html | null {
590590 ${pulse.changes.map(
591591 (c) => html`<li>
592592 <a class="truncate" href="${c.href}" title="${c.title}">${c.title}</a>
593 <span class="muted small door-when">${c.repo} · ${timeAgo(c.mergedAt)}</span>
593 <span class="muted small door-when">${c.repo} · ${time(c.mergedAt)}</span>
594594 </li>`,
595595 )}
596596 </ul>`,
src/web/style/base.ts +3
@@ -187,6 +187,9 @@ export const utilities = /* css */ `
187187 .muted { color: var(--muted-fg); }
188188 .small { font-size: 13px; }
189189 .num { font-variant-numeric: tabular-nums; }
190 /* A relative time is a <time datetime title>. It reserves 7ch, so "9m ago" turning
191 into "10m ago" or "just now" into "1m ago" does not move the line. */
outdated

Tabular digits and nowrap do not reserve width: the text still changes length ('9m ago' to '10m ago', 'just now' to '1m ago'). Box 2 of #13974 asks that nothing shifts; add a min-width in ch (inline-block) and wrap the comment under 100 columns.

192 time[datetime] { display: inline-block; min-width: 7ch; text-align: start; font-variant-numeric: tabular-nums; white-space: nowrap; }

Non-blocking: 7ch is narrower than "just now" (8 chars), so the comment's claim is not true for that case. Use 8ch. Also the global min-width adds a gap before punctuation in running sentences.

190193 .grow { flex: 1; min-width: 0; }
191194 .spacer { flex: 1; }
192195 .truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
test/danger-language.test.ts +1 −1
@@ -97,7 +97,7 @@ test("the detach shows its running state since when, and its failure over the pl
9797 const running = String(detachBlock({ name: "upstreamer/up", action, job: { phase: "repacking", startedAt, message: "", done } }));
9898 expect(running).toContain('<section class="settings-block" id="detach">');
9999 expect(running).toContain("data-detach-progress");
100 expect(running).toContain("started 5m ago");
100 expect(running).toMatch(/started <time [^>]*>5m ago<\/time\s*>/);
101101 expect(running).not.toContain("/-/confirm");
102102
103103 const failed = String(
test/repo-behind-line.test.ts +1 −1
@@ -90,7 +90,7 @@ test("behind: the count, the upstream, the age, linking to the settings", async
9090 const line = html.match(/<div[^>]*data-behind-upstream[\s\S]*?<\/div>/)?.[0] ?? "";
9191 expect(line.replace(/\s+/g, " ")).toContain("12 commits behind trevato/forge");
9292 expect(line).toContain('href="/amy/behind/settings#upstream"');
93 expect(line).toContain("checked 2h ago");
93 expect(line).toMatch(/checked <time [^>]*>2h ago<\/time\s*>/);
9494 expect(timing).toContain("behind;");
9595 expect(line).toContain('<form method="post" action="/amy/behind/settings/upstream/check"');
9696 expect(line).toContain('name="back" value="/amy/behind"');
test/time-element.test.ts added +100
@@ -0,0 +1,100 @@
1 /** A relative time on a rendered page is a <time datetime title>, never bare text (#13974). */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { openIssue } from "../src/actions/issues.ts";
7 import { openPull } from "../src/actions/pulls.ts";
8 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
9 import { createApp, type App } from "../src/app.ts";
10 import { noteCheck, putFollow } from "../src/core/upstream_follow.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { forkOffersCard } from "../src/web/pages/fork-offers.ts";
14 import { time } from "../src/web/ui.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 const at = new Date(Date.now() - 3 * 60_000).toISOString();
20
21 /** A relative-time phrase as the UI speaks it. */
22 const RELATIVE = /\b(\d+(s|m|h|d|mo|y) ago|just now)\b/;
23 const TIME_ELEMENT = /<time\b[^>]*\bdatetime="[^"]+"[^>]*\btitle="[^"]+"[^>]*>[\s\S]*?<\/time\s*>/g;
24
25 describe("the time helper", () => {
26 test("emits datetime and the exact UTC title around the relative words", () => {
27 const out = time(at).text;
28 expect(out).toMatch(/<time datetime="[^"]+"\s+title="\d{4}-\d\d-\d\d \d\d:\d\d UTC"\s*>3m ago<\/time\s*>/);
29 });
30 test("a bad instant emits nothing rather than a bare string", () => {
31 expect(time("nope").text).toBe("");
32 });
33 test("a fork offer's age is a <time>", () => {
34 const out = forkOffersCard({ ownerName: "a", name: "b" }, [{ fork: "x/y", createdAt: at, number: 1, title: "t" }])?.text ?? "";
35 expect(out).toMatch(/<time datetime="[^"]+"/);
36 });
37 });
38
39 describe("rendered pages", () => {
40 let dataDir: string;
41 let app: App;
42 let servers: Servers;
43 let cookie: string;
44
45 beforeAll(async () => {
46 dataDir = await mkdtemp(join(tmpdir(), "forge-time-element-"));
47 app = createApp({ dataDir, port: 0, host: "forge.test" });
outdated

This regex only matches a template that opens and closes on one line, so any multi-line html`` with timeAgo( passes unseen (upstream-follow.ts:155 is one). Render pages and assert instead.

48 servers = await serve(app);
49 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "amy", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
50 if (!made.ok) throw new Error(made.error);
51 const user = made.value;
52 const signin = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "amy", password: "a-good-passphrase" }), redirect: "manual" });
53 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
outdated

Asserting the CSS string exists proves nothing about layout; it would pass with the rule present but ineffective. Replace with a render check.

54 const repo = await createRepo(app, user, { name: "r", visibility: "public" });
55 if (!repo.ok) throw new Error(String(repo.error));
56 await commitToBranch(app, user, repo.value, { message: "first", files: [{ path: "a.txt", content: "a\n" }] });
57 await commitToBranch(app, user, repo.value, { branch: "feature", message: "feature", files: [{ path: "b.txt", content: "b\n" }] });
58 const issue = openIssue(app, user, repo.value, { title: "An issue" });
59 if (!issue.ok) throw new Error(String(issue.error));
60 const pull = await openPull(app, user, repo.value, { title: "A pull", baseBranch: "main", headBranch: "feature" });
61 if (!pull.ok) throw new Error(String(pull.error));
62 putFollow(app.db, { repoId: repo.value.id, url: "https://github.com/trevato/forge.git", branch: "main", enabled: true, byId: user.id, originId: "" });
63 noteCheck(app.db, repo.value.id, { at: new Date(Date.now() - 2 * 3600_000).toISOString(), behind: 4, error: "" });
64 });
65
66 afterAll(async () => {
67 await servers.stop();
68 await rm(dataDir, { recursive: true, force: true });
69 });
70
71 const pages: readonly string[] = [
72 "/",
73 "/now/check",
74 "/amy/r/following",
75 "/amy/r",
76 "/amy/r/issues",
77 "/amy/r/issues/1",
78 "/amy/r/pulls",
79 "/amy/r/pulls/2",
80 "/amy/r/settings",
81 ];
82
83 for (const path of pages) {
84 test(`${path}: every relative time sits inside <time datetime title>`, async () => {
85 const res = await fetch(`${servers.url}${path}`, { headers: { cookie } });
86 expect(res.status).toBe(200);
87 const body = await res.text();
88 const bare = body
89 .replace(/<(script|style)\b[\s\S]*?<\/\1>/g, "")
90 .replace(TIME_ELEMENT, "")
91 .replace(/<[^>]*>/g, " ");
92 expect(bare.match(RELATIVE)?.[0]).toBeUndefined();
93 });
94 }
95
96 test("the upstream history's age is a <time>", async () => {
97 const body = await (await fetch(`${servers.url}/amy/r/settings`, { headers: { cookie } })).text();
98 expect(body).toMatch(/data-following-history[\s\S]*?<time datetime="[^"]+" title="[^"]+"\s*>2h ago<\/time/);
99 });
100 });
test/upstream-follow-history.test.ts +1 −1
@@ -83,7 +83,7 @@ test("25 checks keep 20 and show 5, newest first, each outcome worded", async ()
8383 expect(checkLine(conflict!, "2h ago")).toBe("2h ago · 3 behind · conflict in 2 files");
8484
8585 const page = await card();
86 expect(page.match(/row-title"[^>]*>[^<]*· \d+ behind ·/g)).toHaveLength(5);
86 expect(page.match(/row-title"[^>]*><time[\s\S]*?<\/time\s*>[^<]*· \d+ behind ·/g)).toHaveLength(5);
8787 expect(page).toContain("data-following-history");
8888 expect(page).toContain("· conflict in 2 files");
8989 expect(page.indexOf("4 behind · merged")).toBeLessThan(page.indexOf("conflict in 2 files"));

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs