Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(frontend): pair every time-varying reading with its own boundary

zchpeter6df76de858f7
diff --git a/docs/design/timestamp-display.md b/docs/design/timestamp-display.md
index 3d41216df0..ca04433bd0 100644
--- a/docs/design/timestamp-display.md
+++ b/docs/design/timestamp-display.md
@@ -113,9 +113,10 @@ deferred.
**D6 — Full date-time tooltip on every reduced display.**
Any timestamp that does not show the full form — relative, date-only after the switch, or the
compact history tier — carries the full absolute date-time with seconds and timezone in its
-tooltip. This is the universal escape hatch that keeps every reduced cell recoverable. Corollary:
-a context that cannot host a tooltip — i18n-interpolated strings, exports, titles — carries the
-full-precision string itself.
+tooltip. This is the universal escape hatch that keeps every reduced cell recoverable. The rule
+cuts both ways: a tooltip carries only what its label hides, so a label already showing the full
+instant gets none of it repeated. Corollary: a context that cannot host a tooltip —
+i18n-interpolated strings, exports, titles — carries the full-precision string itself.
**D7 — History views carry two precision tiers.**
*A history row orients; a history record testifies.* Full precision (seconds + timezone,
@@ -265,11 +266,21 @@ no seconds per D5. Relative age may accompany it in the tooltip.
both JSX and string contexts stays a full-precision string builder — its JSX consumers render
the component instead.
- Staleness: no time-varying display (relative buckets, countdowns, `isExpired` derivations) may
- go stale while mounted; displays that never change with time pay nothing. The mechanism —
- shared clock, cadence, subscribers, consolidating today's ad-hoc per-component timers — is the
- implementation PR's design space, guarded by a render-time `Date.now()` sweep and fake-timer
- tests. GitHub's `relative-time` element, which schedules updates at the next boundary, is the
- reference behavior.
+ go stale while mounted; displays that never change with time pay nothing. GitHub's
+ `relative-time` element, which schedules updates at the next boundary, is the reference
+ behavior. The contract that makes this hold:
+ - **Every time-varying reading comes as a pair** — the function that renders it and the
+ function returning the first instant its output will differ (`Infinity` if never). The pair
+ lives together and is tested together: sampled across ages, the reading is constant up to
+ that instant and differs at it. A boundary borrowed from a different reading, or re-derived by
+ hand beside one, is the defect this rules out — the two drift silently, and a test of the
+ boundary alone cannot see it.
+ - **The shared clock accepts any instant.** It clamps to the platform timer ceiling and re-arms,
+ wakes only the subscribers that are due, and relies on each woken subscriber declaring a
+ strictly later instant.
+ - Guarded by fake-timer tests and a sweep of render-time `Date.now()` over the touched surfaces
+ at implementation time — a review pass, not a lint: telling render scope from handlers and
+ effects statically would flag most legitimate uses.
- Tests: threshold boundary (29d/31d), year handling, zh locale, the three modes, the operational
label/tooltip contract on a sub-minute-tail expiration, the <24h countdown carve-out, and
fake-timer staleness; update the existing `*.test.tsx` files that assert relative strings.
@@ -299,7 +310,7 @@ no seconds per D5. Relative age may accompany it in the tooltip.
evidence surfaces — the audit log and the changelog/revision detail views — so the
year-month-day-hour-minute-second ask is met to the minute on record lists and fully on record
details. If the customer pushes back specifically on visible seconds, the escalation is flipping
- those lists to the full tier — a one-line D7 assignment change, no model change.
+ those lists to the full tier — a mode change at each embedded list, no model change.
- Queue rows 1–29 days old: still "x days ago" (D1/D3 trade-off, accepted because these are queue
readings). **Risk**: if the reported "ticket history" reading includes *recent* issue-list rows,
part of the complaint survives. Mitigation: tooltip; escalation path if it recurs is lowering the
@@ -316,14 +327,20 @@ points where the implementation had to choose:
1. **The relative age on a full cell** (previously open item 5) is rendered as a component the
tooltip mounts only when it opens, not as a string computed with the row. A string would freeze
at whatever the row last rendered, which the staleness rule forbids; this way a closed tooltip
- holds no place on the shared clock and an open one keeps counting.
+ holds no place on the shared clock and an open one keeps counting. The full-tier surfaces — the
+ audit log and the changelog and revision detail views — render through the component to get it.
2. **The operational tooltip carries the full date-time, not the relative age.** D6 owns that slot,
and the pill's reduced minute precision is what needs recovering.
3. **The zh renderings put the timezone before the time** — "2026年9月15日 GMT+8 09:00", where the
examples above show it trailing. That is ICU's pattern for the locale; the strings come from
`Intl` rather than being assembled, so the locale's own order wins.
-The staleness rule is enforced by `useNow`, a single shared clock: subscribers declare the instant
-their rendering next changes rather than a cadence, since the relative buckets turn over relative
-to the timestamp, not the wall clock. It replaced the ad-hoc interval behind the plan-detail
-created time and covers the SQL-editor grant countdown, which had none.
+The staleness rule holds through `useNow` and the reading pairs described under Implementation
+shape. The clock replaced the ad-hoc interval behind the plan-detail created time, and the pairs
+cover the displays that had no clock at all: the SQL-editor grant countdown, the masking-exemption
+expiry label, and the access-grant roster's expired badge.
+
+The rule governs displays of time. Two kinds of clock read stay outside it: **query membership** —
+the masking-exemption status filter, the role-expiry reminder's "within two days" list — which,
+like the fetched data itself, reflects when the query ran; and the **input side**, the validation
+of an expiration being entered, deferred with the pickers.
diff --git a/frontend/src/components/AuditLogTable.test.tsx b/frontend/src/components/AuditLogTable.test.tsx
index becce3a113..bcf595957e 100644
--- a/frontend/src/components/AuditLogTable.test.tsx
+++ b/frontend/src/components/AuditLogTable.test.tsx
@@ -41,6 +41,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
diff --git a/frontend/src/components/AuditLogTable.tsx b/frontend/src/components/AuditLogTable.tsx
index 3f32318020..aa92f6a499 100644
--- a/frontend/src/components/AuditLogTable.tsx
+++ b/frontend/src/components/AuditLogTable.tsx
@@ -13,6 +13,7 @@ import {
type SearchParams,
type ValueOption,
} from "@/components/AdvancedSearch";
+import { HumanizeTs } from "@/components/HumanizeTs";
import { RouterLink } from "@/components/RouterLink";
import { TimeRangePicker } from "@/components/TimeRangePicker";
import { Badge } from "@/components/ui/badge";
@@ -50,7 +51,7 @@ import {
userNamePrefix,
workloadIdentityNamePrefix,
} from "@/stores/modules/v1/common";
-import { getDateForPbTimestampProtoEs } from "@/types";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import { StatusSchema } from "@/types/proto-es/google/rpc/status_pb";
import type {
AuditLog,
@@ -68,11 +69,7 @@ import { RolloutService } from "@/types/proto-es/v1/rollout_service_pb";
import { SQLService } from "@/types/proto-es/v1/sql_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { protobufJsonRegistry } from "@/types/protobufJsonRegistry";
-import {
- formatAbsoluteDateTime,
- getDefaultPagination,
- humanizeDurationV1,
-} from "@/utils";
+import { getDefaultPagination, humanizeDurationV1 } from "@/utils";
import { celString } from "@/utils/v1/celLiteral";
dayjs.extend(utc);
@@ -445,8 +442,13 @@ function useColumnDefs(): ColumnDef[] {
resizable: true,
sortable: true,
render: (log: AuditLog) =>
- formatAbsoluteDateTime(
- getDateForPbTimestampProtoEs(log.createTime)?.getTime() ?? 0
+ log.createTime ? (
+ <HumanizeTs
+ mode="datetime"
+ ts={getTimeForPbTimestampProtoEs(log.createTime) / 1000}
+ />
+ ) : (
+ "-"
),
},
{
diff --git a/frontend/src/components/HumanizeTs.test.tsx b/frontend/src/components/HumanizeTs.test.tsx
index fa273e6d6a..947c66adf5 100644
--- a/frontend/src/components/HumanizeTs.test.tsx
+++ b/frontend/src/components/HumanizeTs.test.tsx
@@ -1,182 +1,151 @@
import { act } from "react";
import { createRoot } from "react-dom/client";
-import { afterEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
}));
-vi.mock("@/utils/datetime", () => ({
+const formatters = vi.hoisted(() => ({
// Age-based so a label that never re-renders is visibly distinguishable from
// one that keeps up with the clock.
formatQueueTime: (ms: number) => `queue:${Date.now() - ms}`,
- nextRelativeChangeAt: (ms: number) => ms + 60_000,
+ formatRelativeTime: (ms: number) => `relative:${Date.now() - ms}`,
formatCompactDateTime: (ms: number) => `compact:${ms}`,
formatOperationalDateTime: (ms: number) => `operational:${ms}`,
- formatAbsoluteDateTime: (ms: number) => `absolute:${ms}`,
- formatRelativeTime: (ms: number) => `relative:${Date.now() - ms}`,
+ formatAbsoluteDateTime: vi.fn((ms: number) => `absolute:${ms}`),
+ // Distinct offsets, so a reading scheduled on the other reading's boundary
+ // wakes at the wrong time and shows it.
+ nextQueueTimeChangeAt: (ms: number) => ms + 60_000,
+ nextRelativeTimeChangeAt: (ms: number) => ms + 45_000,
}));
+vi.mock("@/utils/datetime", () => formatters);
+
import { HumanizeTs } from "./HumanizeTs";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
+const roots: ReturnType<typeof createRoot>[] = [];
+
const mount = () => {
const container = document.createElement("div");
document.body.appendChild(container);
- return { container, root: createRoot(container) };
+ const root = createRoot(container);
+ roots.push(root);
+ return { container, root };
};
-const focus = async (el: Element | null) => {
+const openTooltip = async (el: Element | null) => {
await act(async () => {
el?.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
vi.advanceTimersByTime(100);
});
};
+const overlayText = () =>
+ document.getElementById("bb-react-layer-overlay")?.textContent ?? "";
+
+const secondsAgo = (seconds: number) =>
+ Math.floor(Date.now() / 1000) - seconds;
+
describe("HumanizeTs", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
+ formatters.formatAbsoluteDateTime.mockClear();
+ });
+
afterEach(() => {
+ for (const root of roots.splice(0)) {
+ act(() => root.unmount());
+ }
vi.useRealTimers();
document.body.innerHTML = "";
});
- test("renders the work-queue form by default and the full time on hover", async () => {
- vi.useFakeTimers();
- const { container, root } = mount();
+ test.each([
+ [undefined, "queue:"],
+ ["compact", "compact:"],
+ ["operational", "operational:"],
+ ] as const)(
+ "renders the %s reading and restores the full time on hover",
+ async (mode, prefix) => {
+ const { container, root } = mount();
+ act(() => root.render(<HumanizeTs mode={mode} ts={1000} />));
+ expect(container.textContent).toContain(prefix);
+
+ await openTooltip(container.firstElementChild);
+ expect(overlayText()).toContain("absolute:1000000");
+ }
+ );
- // `ts` is in seconds; both labels are computed from milliseconds.
+ test("builds the full time only once the tooltip opens", async () => {
+ const { container, root } = mount();
act(() => root.render(<HumanizeTs ts={1000} />));
- expect(container.textContent).toContain("queue:");
-
- await focus(container.querySelector("span"));
-
- const overlay = document.getElementById("bb-react-layer-overlay");
- expect(overlay?.textContent).toContain("absolute:1000000");
+ expect(formatters.formatAbsoluteDateTime).not.toHaveBeenCalled();
- act(() => root.unmount());
+ await openTooltip(container.firstElementChild);
+ expect(formatters.formatAbsoluteDateTime).toHaveBeenCalledWith(1000000);
});
- test("renders the compact history tier and keeps full precision on hover", async () => {
- vi.useFakeTimers();
+ test("renders one element, so layout classes reach the box that lays out", () => {
const { container, root } = mount();
-
- act(() => root.render(<HumanizeTs mode="compact" ts={1000} />));
- expect(container.textContent).toContain("compact:1000000");
-
- await focus(container.querySelector("span"));
-
- const overlay = document.getElementById("bb-react-layer-overlay");
- expect(overlay?.textContent).toContain("absolute:1000000");
-
- act(() => root.unmount());
+ act(() =>
+ root.render(<HumanizeTs className="block truncate" ts={1000} />)
+ );
+ expect(container.childElementCount).toBe(1);
+ expect(container.firstElementChild?.className).toContain("block truncate");
+ expect(container.firstElementChild?.childElementCount).toBe(0);
});
- test("names the timezone inline for a time the reader will act on", async () => {
- vi.useFakeTimers();
+ test("offers the age on a full cell, and keeps it counting while open", async () => {
const { container, root } = mount();
-
- act(() => root.render(<HumanizeTs mode="operational" ts={1000} />));
- expect(container.textContent).toContain("operational:1000000");
-
- await focus(container.querySelector("span"));
-
- const overlay = document.getElementById("bb-react-layer-overlay");
- expect(overlay?.textContent).toContain("absolute:1000000");
-
- act(() => root.unmount());
- });
-
- test("offers the age on a full cell, which is the reading its label lacks", async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
- const { container, root } = mount();
- const ts = Math.floor(Date.now() / 1000) - 30;
-
- act(() => root.render(<HumanizeTs mode="datetime" ts={ts} />));
+ act(() => root.render(<HumanizeTs mode="datetime" ts={secondsAgo(30)} />));
expect(container.textContent).toContain("absolute:");
- await focus(container.querySelector("span"));
-
- const overlay = document.getElementById("bb-react-layer-overlay");
+ await openTooltip(container.firstElementChild);
// The tooltip opens 100ms after focus, which the age already reflects.
- expect(overlay?.textContent).toContain("relative:30100");
+ expect(overlayText()).toContain("relative:30100");
- // An age that froze at whatever the row last rendered would be worse than
- // no age at all, so the open tooltip holds its own place on the clock.
+ // The relative reading's own boundary is 45s after the timestamp.
act(() => {
- vi.advanceTimersByTime(60_000);
+ vi.advanceTimersByTime(15_000);
});
- expect(overlay?.textContent).toContain("relative:90100");
-
- act(() => root.unmount());
+ expect(overlayText()).toContain("relative:45100");
});
test("omits the tooltip when tooltip is false", async () => {
- vi.useFakeTimers();
const { container, root } = mount();
-
act(() => root.render(<HumanizeTs ts={1000} tooltip={false} />));
expect(container.textContent).toContain("queue:");
- await focus(container.querySelector("span"));
-
- const overlay = document.getElementById("bb-react-layer-overlay");
- expect(overlay?.textContent ?? "").not.toContain("absolute:");
-
- act(() => root.unmount());
- });
-});
-
-describe("HumanizeTs freshness", () => {
- afterEach(() => {
- vi.useRealTimers();
- document.body.innerHTML = "";
+ await openTooltip(container.firstElementChild);
+ expect(overlayText()).not.toContain("absolute:");
});
test("keeps a mounted work-queue label up with the clock", () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
const { container, root } = mount();
- const ts = Math.floor(Date.now() / 1000) - 30;
-
- act(() => root.render(<HumanizeTs ts={ts} tooltip={false} />));
+ act(() => root.render(<HumanizeTs ts={secondsAgo(30)} tooltip={false} />));
expect(container.textContent).toBe("queue:30000");
+ // The work-queue reading's own boundary is 60s after the timestamp.
act(() => {
- vi.advanceTimersByTime(60_000);
+ vi.advanceTimersByTime(30_000);
});
- expect(container.textContent).toBe("queue:90000");
-
- act(() => root.unmount());
+ expect(container.textContent).toBe("queue:60000");
});
test.each(["compact", "datetime", "operational"] as const)(
"puts no %s display on the shared clock",
(mode) => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
const { root } = mount();
- const ts = Math.floor(Date.now() / 1000) - 30;
-
- act(() => root.render(<HumanizeTs mode={mode} ts={ts} tooltip={false} />));
+ act(() =>
+ root.render(<HumanizeTs mode={mode} ts={secondsAgo(30)} tooltip={false} />)
+ );
expect(vi.getTimerCount()).toBe(0);
-
- act(() => root.unmount());
}
);
-
- test("releases the clock when the last subscriber unmounts", () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
- const { root } = mount();
- const ts = Math.floor(Date.now() / 1000) - 30;
-
- act(() => root.render(<HumanizeTs ts={ts} tooltip={false} />));
- expect(vi.getTimerCount()).toBe(1);
-
- act(() => root.unmount());
- expect(vi.getTimerCount()).toBe(0);
- });
});
diff --git a/frontend/src/components/HumanizeTs.tsx b/frontend/src/components/HumanizeTs.tsx
index fdea0c2672..e555f1f5f5 100644
--- a/frontend/src/components/HumanizeTs.tsx
+++ b/frontend/src/components/HumanizeTs.tsx
@@ -7,7 +7,8 @@ import {
formatOperationalDateTime,
formatQueueTime,
formatRelativeTime,
- nextRelativeChangeAt,
+ nextQueueTimeChangeAt,
+ nextRelativeTimeChangeAt,
} from "@/utils/datetime";
/**
@@ -27,9 +28,10 @@ interface HumanizeTsProps {
/** Unix timestamp in seconds. */
ts: number;
mode?: TimeDisplayMode;
+ /** Applied to the element that renders the time, which is the only one. */
className?: string;
/**
- * Whether to reveal the absolute timestamp on hover. Defaults to true.
+ * Whether to reveal the hidden reading on hover. Defaults to true.
* Disable only inside agent-layer overlays, where the shared Tooltip mounts
* into the lower overlay layer (behind the agent window); supply an
* AgentTooltip at the call site instead.
@@ -44,21 +46,21 @@ const FORMATTERS: Record<TimeDisplayMode, (tsMs: number) => string> = {
datetime: formatAbsoluteDateTime,
};
-/**
- * The age of a full-precision cell, which is the one reading its label lacks.
- *
- * A component rather than a string because the tooltip mounts it only while
- * open: closed, it costs nothing and holds no place on the shared clock; open,
- * it keeps counting rather than freezing at whatever the row last rendered.
- */
+// Tooltip bodies mount only while open, so as components they cost nothing
+// for the rows nobody hovers, and a time-varying one can keep counting.
+function FullDateTime({ tsMs }: { tsMs: number }) {
+ return <>{formatAbsoluteDateTime(tsMs)}</>;
+}
+
function RelativeAge({ tsMs }: { tsMs: number }) {
- useNow(nextRelativeChangeAt(tsMs));
+ useNow(nextRelativeTimeChangeAt(tsMs));
return <>{formatRelativeTime(tsMs)}</>;
}
/**
* Renders a timestamp in the form its surface calls for, and by default
- * reveals the full date-time on hover. This is the single canonical way to
+ * reveals on hover the reading its label hides: the full date-time for every
+ * reduced form, the age for the full one. This is the single canonical way to
* display a record timestamp across the app.
*/
export function HumanizeTs({
@@ -70,22 +72,25 @@ export function HumanizeTs({
// Subscribe to locale changes so the rendered strings update on a language switch.
useTranslation();
const tsMs = ts * 1000;
- // Only the work-queue form ages. The absolute modes render the same string
- // forever, so they take no place on the shared clock -- which matters on the
- // audit log, where thousands of full cells would otherwise subscribe for a
- // label that never moves. The formatters read the clock themselves; this
- // call is what brings the render back around.
- useNow(mode === "queue" ? nextRelativeChangeAt(tsMs) : undefined);
- const label = <span className={className}>{FORMATTERS[mode](tsMs)}</span>;
+ // Only the work-queue label ages; the absolute labels never change, so they
+ // take no place on the shared clock.
+ useNow(mode === "queue" ? nextQueueTimeChangeAt(tsMs) : undefined);
+ const label = FORMATTERS[mode](tsMs);
if (!tooltip) {
- return label;
+ return <span className={className}>{label}</span>;
}
- // Every reduced form hides the exact instant, so its tooltip restores it.
- const content =
- mode === "datetime" ? (
- <RelativeAge tsMs={tsMs} />
- ) : (
- formatAbsoluteDateTime(tsMs)
- );
- return <Tooltip content={content}>{label}</Tooltip>;
+ return (
+ <Tooltip
+ content={
+ mode === "datetime" ? (
+ <RelativeAge tsMs={tsMs} />
+ ) : (
+ <FullDateTime tsMs={tsMs} />
+ )
+ }
+ render={<span className={className} />}
+ >
+ {label}
+ </Tooltip>
+ );
}
diff --git a/frontend/src/components/plan-check/PlanCheckSection.tsx b/frontend/src/components/plan-check/PlanCheckSection.tsx
index 43dfb82332..56eb13477f 100644
--- a/frontend/src/components/plan-check/PlanCheckSection.tsx
+++ b/frontend/src/components/plan-check/PlanCheckSection.tsx
@@ -28,8 +28,8 @@ import {
} from "@/lib/plan/check";
import { cn } from "@/lib/utils";
import {
- getDateForPbTimestampProtoEs,
getRuleLocalization,
+ getTimeForPbTimestampProtoEs,
ruleTemplateMapV2,
ruleTypeToString,
} from "@/types";
@@ -363,9 +363,9 @@ export function PlanCheckResultsDrawer({
<HumanizeTs
className="text-xs text-control-light"
ts={
- (getDateForPbTimestampProtoEs(
+ getTimeForPbTimestampProtoEs(
group.createTime
- )?.getTime() ?? 0) / 1000
+ ) / 1000
}
/>
)}
diff --git a/frontend/src/components/release/ReleaseInfoCard.tsx b/frontend/src/components/release/ReleaseInfoCard.tsx
index bc023cc2e3..5fe4455ba3 100644
--- a/frontend/src/components/release/ReleaseInfoCard.tsx
+++ b/frontend/src/components/release/ReleaseInfoCard.tsx
@@ -6,11 +6,11 @@ import { useTranslation } from "react-i18next";
import { HumanizeTs } from "@/components/HumanizeTs";
import { RouterLink } from "@/components/RouterLink";
import { cn } from "@/lib/utils";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import { State, VCSType } from "@/types/proto-es/v1/common_pb";
import type { Release } from "@/types/proto-es/v1/release_service_pb";
import { Release_Type } from "@/types/proto-es/v1/release_service_pb";
import { isValidReleaseName } from "@/types/release";
-import { getDateForPbTimestampProtoEs } from "@/types/timestamp";
const MAX_DISPLAYED_RELEASE_FILES = 4;
@@ -97,7 +97,7 @@ function ReleaseBlock({ release }: Readonly<{ release: Release }>) {
const { t } = useTranslation();
const displayedFiles = release.files.slice(0, MAX_DISPLAYED_RELEASE_FILES);
const createdTimeMs = release.createTime
- ? getDateForPbTimestampProtoEs(release.createTime)?.getTime()
+ ? getTimeForPbTimestampProtoEs(release.createTime)
: undefined;
return (
diff --git a/frontend/src/components/revision/RevisionDetailPanel.tsx b/frontend/src/components/revision/RevisionDetailPanel.tsx
index 44d093967d..75f1de19d6 100644
--- a/frontend/src/components/revision/RevisionDetailPanel.tsx
+++ b/frontend/src/components/revision/RevisionDetailPanel.tsx
@@ -2,6 +2,7 @@ import { ArrowUpRight, LoaderCircle } from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { sheetServiceClientConnect } from "@/api";
+import { HumanizeTs } from "@/components/HumanizeTs";
import { ReadonlyMonaco } from "@/components/monaco";
import { RouterLink } from "@/components/RouterLink";
import { TaskRunLogViewer } from "@/components/task-run-log";
@@ -10,7 +11,7 @@ import { CopyButton } from "@/components/ui/copy-button";
import { useRevisionByName } from "@/hooks/useAppState";
import { useAppStore } from "@/stores/app";
import { getTimeForPbTimestampProtoEs } from "@/types";
-import { bytesToString, formatAbsoluteDateTime } from "@/utils";
+import { bytesToString } from "@/utils";
import { extractProjectResourceName } from "@/utils/v1/project";
import { extractTaskLink, getRevisionType } from "@/utils/v1/revision";
@@ -112,9 +113,10 @@ export function RevisionDetailPanel({
const taskFullLink = revision?.taskRun
? extractTaskLink(revision.taskRun)
: "";
- const formattedCreateTime = revision
- ? formatAbsoluteDateTime(getTimeForPbTimestampProtoEs(revision.createTime))
- : "";
+ // A revision without a create time shows none, rather than the time now.
+ const createTimeMs = revision?.createTime
+ ? getTimeForPbTimestampProtoEs(revision.createTime)
+ : undefined;
const formattedStatementSize = statement
? bytesToString(new TextEncoder().encode(statement).length)
: "";
@@ -140,8 +142,12 @@ export function RevisionDetailPanel({
</h2>
<div className="flex items-center gap-x-3 text-sm text-control-light">
<span>{getRevisionType(revision.type)}</span>
- {formattedCreateTime ? <span aria-hidden="true">•</span> : null}
- {formattedCreateTime ? <span>{formattedCreateTime}</span> : null}
+ {createTimeMs !== undefined ? (
+ <>
+ <span aria-hidden="true">•</span>
+ <HumanizeTs mode="datetime" ts={createTimeMs / 1000} />
+ </>
+ ) : null}
</div>
</div>
diff --git a/frontend/src/components/ui/tooltip.tsx b/frontend/src/components/ui/tooltip.tsx
index 3d8879ec6e..696da0a5df 100644
--- a/frontend/src/components/ui/tooltip.tsx
+++ b/frontend/src/components/ui/tooltip.tsx
@@ -23,7 +23,11 @@ export function Tooltip({
popupClassName,
open,
onOpenChange,
-}: TooltipProps) {
+ render,
+}: TooltipProps & {
+ /** The trigger element; defaults to an inline-flex wrapper around `children`. */
+ readonly render?: ComponentProps<typeof BaseTooltip.Trigger>["render"];
+}) {
if (!content) {
return <>{children}</>;
}
@@ -32,7 +36,7 @@ export function Tooltip({
<BaseTooltip.Root open={open} onOpenChange={onOpenChange}>
<BaseTooltip.Trigger
delay={delayDuration}
- render={<span className="inline-flex" />}
+ render={render ?? <span className="inline-flex" />}
>
{children}
</BaseTooltip.Trigger>
diff --git a/frontend/src/hooks/useNow.test.tsx b/frontend/src/hooks/useNow.test.tsx
new file mode 100644
index 0000000000..39bcc650ef
--- /dev/null
+++ b/frontend/src/hooks/useNow.test.tsx
@@ -0,0 +1,138 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { useNow } from "./useNow";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const DAY_MS = 86_400_000;
+
+function Probe({
+ changesAtMs,
+ onRender,
+}: {
+ changesAtMs: () => number | undefined;
+ onRender: () => void;
+}) {
+ useNow(changesAtMs());
+ onRender();
+ return null;
+}
+
+// Unmounted in afterEach so a failed assertion cannot leave a subscriber on
+// the module-level clock for the next test.
+const roots: ReturnType<typeof createRoot>[] = [];
+
+const mount = (probes: { changesAtMs: () => number | undefined }[]) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ roots.push(root);
+ const renders = probes.map(() => 0);
+ act(() =>
+ root.render(
+ <>
+ {probes.map((probe, index) => (
+ <Probe
+ changesAtMs={probe.changesAtMs}
+ // biome-ignore lint/suspicious/noArrayIndexKey: fixed probe list
+ key={index}
+ onRender={() => {
+ renders[index] += 1;
+ }}
+ />
+ ))}
+ </>
+ )
+ );
+ return { root, renders };
+};
+
+describe("useNow", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
+ });
+
+ afterEach(() => {
+ for (const root of roots.splice(0)) {
+ act(() => root.unmount());
+ }
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ test("wakes a subscriber at its deadline and not before", () => {
+ const deadlineMs = Date.now() + 1_000;
+ const { root, renders } = mount([{ changesAtMs: () => deadlineMs }]);
+
+ act(() => {
+ vi.advanceTimersByTime(999);
+ });
+ expect(renders).toEqual([1]);
+
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(renders).toEqual([2]);
+
+ act(() => root.unmount());
+ });
+
+ test("waits quietly for a deadline beyond the platform timer ceiling", () => {
+ // setTimeout holds its delay in 32 bits; anything past ~24.8 days fires at
+ // once. A date waiting for the year to turn is ordinary input.
+ const deadlineMs = Date.now() + 90 * DAY_MS;
+ const { root, renders } = mount([{ changesAtMs: () => deadlineMs }]);
+ const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
+
+ act(() => {
+ vi.advanceTimersByTime(1_000);
+ });
+ expect(setTimeoutSpy).not.toHaveBeenCalled();
+ expect(renders).toEqual([1]);
+
+ act(() => {
+ vi.advanceTimersByTime(90 * DAY_MS);
+ });
+ expect(renders).toEqual([2]);
+
+ act(() => root.unmount());
+ });
+
+ test("wakes each due subscriber once and re-arms once for the lot", () => {
+ const firstMs = Date.now() + 1_000;
+ const secondMs = firstMs + 60_000;
+ // Each subscriber, once woken, declares the next deadline — as a relative
+ // label does when its bucket turns over.
+ const probes = Array.from({ length: 50 }, () => ({
+ changesAtMs: () => (Date.now() < firstMs ? firstMs : secondMs),
+ }));
+ const { root, renders } = mount(probes);
+ const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
+
+ act(() => {
+ vi.advanceTimersByTime(5_000);
+ });
+ expect(renders.every((count) => count === 2)).toBe(true);
+ expect(setTimeoutSpy.mock.calls.length).toBeLessThanOrEqual(2);
+
+ act(() => root.unmount());
+ });
+
+ test("releases the timer when the last subscriber leaves", () => {
+ const { root } = mount([{ changesAtMs: () => Date.now() + 1_000 }]);
+ expect(vi.getTimerCount()).toBe(1);
+
+ act(() => root.unmount());
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ test("holds nothing for a display that does not vary with time", () => {
+ const { root } = mount([{ changesAtMs: () => undefined }]);
+ expect(vi.getTimerCount()).toBe(0);
+
+ act(() => root.unmount());
+ });
+});
diff --git a/frontend/src/hooks/useNow.ts b/frontend/src/hooks/useNow.ts
index 125fcbd0ed..766ad86832 100644
--- a/frontend/src/hooks/useNow.ts
+++ b/frontend/src/hooks/useNow.ts
@@ -1,76 +1,93 @@
-import { useEffect, useState } from "react";
+import { useEffect, useReducer } from "react";
/**
- * A single clock shared by every time-varying display, replacing the
- * per-component intervals that used to tick independently.
+ * A single clock shared by every time-varying display.
*
- * Each subscriber declares the instant at which its own rendering could next
- * differ, so the clock holds one timeout — set to the earliest of those — and
- * wakes only the subscribers whose instant has arrived. A display that never
- * changes with time subscribes to nothing and costs nothing. This is the
- * scheduling behavior of GitHub's `relative-time` element.
+ * Each subscriber declares the instant its rendering next changes, so the clock
+ * holds one timeout, set for the earliest of those, and wakes only the
+ * subscribers that are due. A woken subscriber re-renders and must declare a
+ * strictly later instant; one that does not is left out of the next deadline,
+ * so a boundary that fails to advance freezes its label rather than spinning
+ * the clock. A display that never changes with time subscribes to nothing.
*/
type Subscriber = {
changesAtMs: number;
- notify: () => void;
+ wake: () => void;
};
const subscribers = new Set<Subscriber>();
let timer: ReturnType<typeof setTimeout> | undefined;
+let armedForMs = Number.POSITIVE_INFINITY;
-// A boundary computed as already past would otherwise spin the event loop.
-const MIN_DELAY_MS = 16;
+// setTimeout keeps its delay in a signed 32-bit integer and fires at once when
+// asked for more, so a far deadline is reached in steps of at most this.
+const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
-function reschedule(): void {
+function disarm(): void {
if (timer !== undefined) {
clearTimeout(timer);
timer = undefined;
}
- let earliest = Number.POSITIVE_INFINITY;
- for (const subscriber of subscribers) {
- earliest = Math.min(earliest, subscriber.changesAtMs);
- }
- if (!Number.isFinite(earliest)) {
+ armedForMs = Number.POSITIVE_INFINITY;
+}
+
+function arm(changesAtMs: number): void {
+ disarm();
+ if (!Number.isFinite(changesAtMs)) {
return;
}
- timer = setTimeout(
- () => {
- timer = undefined;
- const nowMs = Date.now();
- for (const subscriber of [...subscribers]) {
- if (subscriber.changesAtMs <= nowMs) {
- subscriber.notify();
- }
- }
- reschedule();
- },
- Math.max(earliest - Date.now(), MIN_DELAY_MS)
+ armedForMs = changesAtMs;
+ const delayMs = Math.min(
+ Math.max(changesAtMs - Date.now(), 0),
+ MAX_TIMER_DELAY_MS
);
+ timer = setTimeout(tick, delayMs);
+}
+
+function tick(): void {
+ timer = undefined;
+ armedForMs = Number.POSITIVE_INFINITY;
+ const nowMs = Date.now();
+ // Woken subscribers still hold the instant that just passed until they
+ // re-render, so the next deadline comes only from those still waiting; each
+ // woken one re-arms the clock as it declares its next instant.
+ let nextMs = Number.POSITIVE_INFINITY;
+ for (const subscriber of subscribers) {
+ if (subscriber.changesAtMs <= nowMs) {
+ subscriber.wake();
+ } else {
+ nextMs = Math.min(nextMs, subscriber.changesAtMs);
+ }
+ }
+ arm(nextMs);
}
/**
- * Re-renders the caller once `changesAtMs` arrives, and returns the current
- * time. Pass `undefined` for a display that does not vary with time — it then
- * holds no subscription.
+ * Re-renders the caller once `changesAtMs` arrives. Pass `undefined` for a
+ * display that does not vary with time; it then holds no subscription.
*/
-export function useNow(changesAtMs: number | undefined): number {
- const [nowMs, setNowMs] = useState(() => Date.now());
+export function useNow(changesAtMs: number | undefined): void {
+ // A counter rather than the time: setting a timestamp can bail out when two
+ // wakes land in the same millisecond, and a missed render is a frozen label.
+ const [, wake] = useReducer((count: number) => count + 1, 0);
useEffect(() => {
if (changesAtMs === undefined || !Number.isFinite(changesAtMs)) {
return;
}
- const subscriber: Subscriber = {
- changesAtMs,
- notify: () => setNowMs(Date.now()),
- };
+ const subscriber: Subscriber = { changesAtMs, wake };
subscribers.add(subscriber);
- reschedule();
+ if (changesAtMs < armedForMs) {
+ arm(changesAtMs);
+ }
return () => {
subscribers.delete(subscriber);
- reschedule();
+ // Leaving the timer armed for a departed subscriber costs at most one
+ // early wake, which re-arms from those remaining; only an empty clock
+ // needs no timer at all.
+ if (subscribers.size === 0) {
+ disarm();
+ }
};
}, [changesAtMs]);
-
- return nowMs;
}
diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
index d6780bcad4..261ecb52fa 100644
--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
@@ -6,19 +6,19 @@ import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { useNow } from "@/hooks/useNow";
import { cn } from "@/lib/utils";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
-import { formatAbsoluteDateTime } from "@/utils";
import {
getAccessGrantDisplayStatus,
getAccessGrantDisplayStatusText,
- getAccessGrantExpirationText,
- getAccessGrantExpireTimeMs,
getAccessGrantStatusTagType,
} from "@/utils/accessGrant";
-
-const MINUTE_MS = 60_000;
-const DAY_MS = 24 * 60 * MINUTE_MS;
+import {
+ formatAbsoluteDateTime,
+ nextCountdownChangeAt,
+ readCountdown,
+} from "@/utils/datetime";
function mapTagTypeToBadgeVariant(
tagType: "success" | "warning" | "error" | "default"
@@ -52,41 +52,41 @@ export function AccessGrantItem({
const isRejectedOrCanceled =
displayStatus !== "ACTIVE" && displayStatus !== "PENDING";
const statusLabel = getAccessGrantDisplayStatusText(grant, issue);
- const expireTimeMs = getAccessGrantExpireTimeMs(grant);
+ // Only an activated grant carries a fixed deadline; a pending one holds a
+ // duration that starts counting at approval, so it has nothing to count down.
+ const deadlineMs =
+ (isActive || isExpired) && grant.expiration.case === "expireTime"
+ ? getTimeForPbTimestampProtoEs(grant.expiration.value)
+ : undefined;
const statusTagType = getAccessGrantStatusTagType(displayStatus);
const badgeVariant = mapTagTypeToBadgeVariant(statusTagType);
- // A countdown that stops counting is worse than no countdown, so hold a place
- // on the shared clock until the grant has lapsed: at the minute while the
- // remaining time is shown as one, and otherwise at the moment the display
- // turns from an absolute time into a countdown.
useNow(
- (() => {
- if (expireTimeMs === undefined || isExpired) return undefined;
- const remainingMs = expireTimeMs - Date.now();
- if (remainingMs <= 0) return undefined;
- if (remainingMs > DAY_MS) return expireTimeMs - DAY_MS;
- return Date.now() + (remainingMs % MINUTE_MS || MINUTE_MS);
- })()
+ deadlineMs === undefined ? undefined : nextCountdownChangeAt(deadlineMs)
);
- const expirationText = (() => {
- if (displayStatus !== "ACTIVE" && displayStatus !== "EXPIRED") return;
- const info = getAccessGrantExpirationText(grant);
- if (info.type === "never" || info.type === "duration") return;
-
- if (!isExpired && expireTimeMs !== undefined) {
- const diff = expireTimeMs - Date.now();
- const hours = Math.floor(diff / (1000 * 60 * 60));
- if (hours >= 24) {
- return t("sql-editor.expire-at", { time: info.value });
+ // The countdown is the one form that hides the deadline, so it alone carries
+ // it in a tooltip; the other two are interpolated sentences and state the
+ // deadline in full themselves.
+ const expiration = (() => {
+ if (deadlineMs === undefined) return undefined;
+ const countdown = readCountdown(deadlineMs);
+ const deadline = formatAbsoluteDateTime(deadlineMs);
+ switch (countdown.kind) {
+ case "passed":
+ return { text: `${t("issue.access-grant.expired-at")} ${deadline}` };
+ case "beyondDay":
+ return { text: t("sql-editor.expire-at", { time: deadline }) };
+ case "within": {
+ const { hours, minutes } = countdown;
+ const left = hours > 0 ? `${hours}h${minutes}m` : `${minutes}m`;
+ return {
+ text: t("sql-editor.expire-in", { time: left }),
+ hiddenDeadline: deadline,
+ };
}
- const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
- const dur = hours > 0 ? `${hours}h${minutes}m` : `${minutes}m`;
- return t("sql-editor.expire-in", { time: dur });
}
- return `${t("issue.access-grant.expired-at")} ${info.value}`;
})();
const visibleTargets = grant.targets.slice(0, 2);
@@ -161,18 +161,13 @@ export function AccessGrantItem({
</Badge>
)}
</div>
- {expirationText &&
- (expireTimeMs !== undefined ? (
- <Tooltip content={formatAbsoluteDateTime(expireTimeMs)}>
- <span className="text-xs text-control-placeholder shrink-0">
- {expirationText}
- </span>
- </Tooltip>
- ) : (
+ {expiration && (
+ <Tooltip content={expiration.hiddenDeadline}>
<span className="text-xs text-control-placeholder shrink-0">
- {expirationText}
+ {expiration.text}
</span>
- ))}
+ </Tooltip>
+ )}
</div>
<Tooltip
diff --git a/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx b/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx
index 62a2d975ca..6195c89888 100644
--- a/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx
+++ b/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx
@@ -151,6 +151,9 @@ vi.mock("@/types", () => ({
getDateForPbTimestampProtoEs: vi.fn((ts: unknown) =>
ts ? new Date("2024-01-15T10:30:00Z") : new Date(0)
),
+ getTimeForPbTimestampProtoEs: vi.fn((ts: unknown, defaultValue = 0) =>
+ ts ? new Date("2024-01-15T10:30:00Z").getTime() : defaultValue
+ ),
}));
vi.mock("@/utils", () => ({
diff --git a/frontend/src/modules/sql-editor/components/HistoryPane.tsx b/frontend/src/modules/sql-editor/components/HistoryPane.tsx
index b1029ed7cd..f48c181a19 100644
--- a/frontend/src/modules/sql-editor/components/HistoryPane.tsx
+++ b/frontend/src/modules/sql-editor/components/HistoryPane.tsx
@@ -27,7 +27,7 @@ import {
useSQLEditorTabState,
} from "@/modules/sql-editor/store/tab";
import { useAppStore } from "@/stores/app";
-import { DEBOUNCE_SEARCH_DELAY, getDateForPbTimestampProtoEs } from "@/types";
+import { DEBOUNCE_SEARCH_DELAY, getTimeForPbTimestampProtoEs } from "@/types";
import type { QueryHistory } from "@/types/proto-es/v1/query_history_service_pb";
import {
extractProjectResourceName,
@@ -121,11 +121,11 @@ export function HistoryPane() {
[resetPageToken, historyQuery]
);
- // Feeds a tab title, which cannot host a tooltip, so it stays full precision.
+ // A tab title cannot host a tooltip, so it names the time in full.
const titleOfQueryHistory = (h: QueryHistory) =>
- formatAbsoluteDateTime(
- (getDateForPbTimestampProtoEs(h.createTime) as Date).getTime()
- );
+ h.createTime
+ ? `Query history at ${formatAbsoluteDateTime(getTimeForPbTimestampProtoEs(h.createTime))}`
+ : "Query history";
const handleHistoryClick = async (history: QueryHistory) => {
const { statement } = history;
@@ -138,7 +138,7 @@ export function HistoryPane() {
} else {
tabsState.addTab(
{
- title: `Query history at ${titleOfQueryHistory(history)}`,
+ title: titleOfQueryHistory(history),
statement,
},
/* beside */ true
@@ -206,15 +206,13 @@ export function HistoryPane() {
>
<div className="w-full flex flex-row justify-between items-center">
<div className="flex items-start gap-x-1">
- <HumanizeTs
- className="text-xs text-control-placeholder"
- mode="compact"
- ts={
- (
- getDateForPbTimestampProtoEs(history.createTime) as Date
- ).getTime() / 1000
- }
- />
+ {history.createTime && (
+ <HumanizeTs
+ className="text-xs text-control-placeholder"
+ mode="compact"
+ ts={getTimeForPbTimestampProtoEs(history.createTime) / 1000}
+ />
+ )}
</div>
<div className="flex items-center gap-x-1">
<Button
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx
index 7111b38e33..e07e5cedca 100644
--- a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx
+++ b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx
@@ -37,7 +37,7 @@ import {
import { useAppStore } from "@/stores/app";
import {
DEFAULT_SQL_EDITOR_TAB_MODE,
- getDateForPbTimestampProtoEs,
+ getTimeForPbTimestampProtoEs,
isValidDatabaseName,
isValidInstanceName,
isValidProjectName,
@@ -411,9 +411,9 @@ export function SQLEditorRouteShell() {
}
}
- const title = `Query history at ${formatAbsoluteDateTime(
- (getDateForPbTimestampProtoEs(history.createTime) as Date).getTime()
- )}`;
+ const title = history.createTime
+ ? `Query history at ${formatAbsoluteDateTime(getTimeForPbTimestampProtoEs(history.createTime))}`
+ : "Query history";
const tab = getSQLEditorTabsState().addTab(
{
title,
diff --git a/frontend/src/routes/project/DatabaseChangelogDetailPage.test.tsx b/frontend/src/routes/project/DatabaseChangelogDetailPage.test.tsx
index d60641ec58..c6e8cb0396 100644
--- a/frontend/src/routes/project/DatabaseChangelogDetailPage.test.tsx
+++ b/frontend/src/routes/project/DatabaseChangelogDetailPage.test.tsx
@@ -211,6 +211,11 @@ vi.mock("@/utils/v1/project", () => ({
extractProjectResourceName: (name: string) => name.split("/").at(-1) ?? "",
}));
+vi.mock("@/utils/datetime", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/utils/datetime")>()),
+ formatAbsoluteDateTime: () => "formatted time",
+}));
+
vi.mock("@/utils", () => ({
autoDatabaseRoute: (database: { name: string; project: string }) => {
const parent = database.name.split("/databases/")[0];
diff --git a/frontend/src/routes/project/DatabaseChangelogDetailPage.tsx b/frontend/src/routes/project/DatabaseChangelogDetailPage.tsx
index 955a3b4fad..6795550517 100644
--- a/frontend/src/routes/project/DatabaseChangelogDetailPage.tsx
+++ b/frontend/src/routes/project/DatabaseChangelogDetailPage.tsx
@@ -8,6 +8,7 @@ import {
PROJECT_V1_ROUTE_DATABASES,
PROJECT_V1_ROUTE_SYNC_SCHEMA,
} from "@/app/router/handles";
+import { HumanizeTs } from "@/components/HumanizeTs";
import { ReadonlyDiffMonaco, ReadonlyMonaco } from "@/components/monaco";
import { RouterLink } from "@/components/RouterLink";
import { TaskRunLogViewer } from "@/components/task-run-log";
@@ -30,7 +31,6 @@ import {
autoDatabaseRoute,
bytesToString,
extractDatabaseResourceName,
- formatAbsoluteDateTime,
getInstanceResource,
} from "@/utils";
import { instanceV1SupportsSchemaRollback } from "@/utils/v1/instance";
@@ -303,14 +303,9 @@ export function DatabaseChangelogDetailPage({
const databaseDisplayName =
extractDatabaseResourceName(detail.database?.name ?? "").databaseName ||
databaseName;
- const formattedCreateTime = useMemo(() => {
- if (!resolvedChangelog?.createTime) {
- return "";
- }
- return formatAbsoluteDateTime(
- getTimeForPbTimestampProtoEs(resolvedChangelog.createTime)
- );
- }, [resolvedChangelog?.createTime]);
+ const createTimeMs = resolvedChangelog?.createTime
+ ? getTimeForPbTimestampProtoEs(resolvedChangelog.createTime)
+ : undefined;
const formattedSchemaSize = useMemo(() => {
if (!resolvedChangelog?.schemaSize) {
return "";
@@ -407,10 +402,10 @@ export function DatabaseChangelogDetailPage({
) : null}
<div className="flex items-center gap-x-3 text-sm text-control-light">
<ChangelogStatusIndicator status={resolvedChangelog.status} />
- {formattedCreateTime ? (
+ {createTimeMs !== undefined ? (
<>
<span aria-hidden="true">•</span>
- <span>{formattedCreateTime}</span>
+ <HumanizeTs mode="datetime" ts={createTimeMs / 1000} />
</>
) : null}
</div>
diff --git a/frontend/src/routes/project/ProjectAccessGrantsPage.tsx b/frontend/src/routes/project/ProjectAccessGrantsPage.tsx
index 6e7b0a543b..0c59e16297 100644
--- a/frontend/src/routes/project/ProjectAccessGrantsPage.tsx
+++ b/frontend/src/routes/project/ProjectAccessGrantsPage.tsx
@@ -37,6 +37,7 @@ import {
distributeColumnWidths,
useColumnWidths,
} from "@/hooks/useColumnWidths";
+import { useNow } from "@/hooks/useNow";
import { PagedTableFooter, usePagedData } from "@/hooks/usePagedData";
import { useProjectByName } from "@/hooks/useProjectByName";
import { pushNotification } from "@/stores";
@@ -56,12 +57,11 @@ import {
type AccessGrantDisplayStatus,
getAccessGrantDisplayStatus,
getAccessGrantDisplayStatusText,
- getAccessGrantExpirationText,
- getAccessGrantExpireTimeMs,
getAccessGrantStatusTagType,
getDefaultPagination,
hasProjectPermissionV2,
} from "@/utils";
+import { nextPassedAt } from "@/utils/datetime";
import { extractDatabaseResourceName } from "@/utils/v1/database";
type SortKey = "creator" | "create_time" | "expire_time";
@@ -752,13 +752,18 @@ function AccessGrantRow({
? getTimeForPbTimestampProtoEs(grant.createTime)
: undefined;
- const expirationInfo = getAccessGrantExpirationText(grant);
// The roster's creation column is meta on a management list, read for
// freshness; the grant's operational fact is when it lapses.
const expireTimeMs =
- expirationInfo.type === "datetime"
- ? getAccessGrantExpireTimeMs(grant)
+ grant.expiration.case === "expireTime"
+ ? getTimeForPbTimestampProtoEs(grant.expiration.value)
: undefined;
+ // An active grant's badge turns to expired when its deadline passes.
+ useNow(
+ status === "ACTIVE" && expireTimeMs !== undefined
+ ? nextPassedAt(expireTimeMs)
+ : undefined
+ );
return (
<TableRow>
diff --git a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx
index 02557b4b58..d4dbdd673a 100644
--- a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx
+++ b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx
@@ -30,6 +30,7 @@ import {
} from "@/components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useCurrentUser } from "@/hooks/useAppState";
+import { useNow } from "@/hooks/useNow";
import { useProjectByName } from "@/hooks/useProjectByName";
import {
buildMemberSummary,
@@ -64,6 +65,7 @@ import {
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { getDefaultPagination, hasProjectPermissionV2 } from "@/utils";
+import { nextDaysLeftChangeAt, readDaysLeft } from "@/utils/datetime";
import {
batchConvertFromCELString,
type ConditionExpression,
@@ -1085,20 +1087,28 @@ function ExemptionGrantSection({
const title = useMemo(() => generateGrantTitle(grant), [grant]);
- const isExpired =
- !!grant.expirationTimestamp && grant.expirationTimestamp <= Date.now();
+ const daysLeft = grant.expirationTimestamp
+ ? readDaysLeft(grant.expirationTimestamp)
+ : undefined;
+ useNow(
+ grant.expirationTimestamp
+ ? nextDaysLeftChangeAt(grant.expirationTimestamp)
+ : undefined
+ );
+ const isExpired = daysLeft?.kind === "passed";
const expiryLabel = (() => {
- if (!grant.expirationTimestamp) return "";
- const msRemaining = grant.expirationTimestamp - Date.now();
- const hoursRemaining = msRemaining / (1000 * 60 * 60);
- if (hoursRemaining < 24)
- return t("project.masking-exemption.expires-today");
- const days = Math.ceil(hoursRemaining / 24);
- return t("project.masking-exemption.expires-in-days", {
- days,
- count: days,
- });
+ switch (daysLeft?.kind) {
+ case "today":
+ return t("project.masking-exemption.expires-today");
+ case "days":
+ return t("project.masking-exemption.expires-in-days", {
+ days: daysLeft.days,
+ count: daysLeft.days,
+ });
+ default:
+ return "";
+ }
})();
return (
diff --git a/frontend/src/routes/project/database-detail/changelog/DatabaseChangelogTable.tsx b/frontend/src/routes/project/database-detail/changelog/DatabaseChangelogTable.tsx
index 899ec0f7ef..906373c9f1 100644
--- a/frontend/src/routes/project/database-detail/changelog/DatabaseChangelogTable.tsx
+++ b/frontend/src/routes/project/database-detail/changelog/DatabaseChangelogTable.tsx
@@ -11,7 +11,7 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
-import { getDateForPbTimestampProtoEs } from "@/types";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import {
type Changelog,
Changelog_Status,
@@ -104,11 +104,7 @@ export function DatabaseChangelogTable({
<HumanizeTs
mode="compact"
ts={
- (
- getDateForPbTimestampProtoEs(
- changelog.createTime
- ) as Date
- ).getTime() / 1000
+ getTimeForPbTimestampProtoEs(changelog.createTime) / 1000
}
/>
) : (
diff --git a/frontend/src/routes/project/database-detail/panels/DatabaseOverviewPanel.test.tsx b/frontend/src/routes/project/database-detail/panels/DatabaseOverviewPanel.test.tsx
index 61bf89b33c..2e0c13d0e7 100644
--- a/frontend/src/routes/project/database-detail/panels/DatabaseOverviewPanel.test.tsx
+++ b/frontend/src/routes/project/database-detail/panels/DatabaseOverviewPanel.test.tsx
@@ -149,7 +149,8 @@ vi.mock("@/utils/datetime", () => ({
formatOperationalDateTime: mocks.formatAbsoluteDateTime,
formatAbsoluteDateTime: mocks.formatAbsoluteDateTime,
formatRelativeTime: mocks.formatRelativeTime,
- nextRelativeChangeAt: () => Number.POSITIVE_INFINITY,
+ nextQueueTimeChangeAt: () => Number.POSITIVE_INFINITY,
+ nextRelativeTimeChangeAt: () => Number.POSITIVE_INFINITY,
}));
vi.mock("@/utils", () => ({
diff --git a/frontend/src/routes/project/database-detail/revision/DatabaseRevisionTable.tsx b/frontend/src/routes/project/database-detail/revision/DatabaseRevisionTable.tsx
index 4b2317cdbc..4023323796 100644
--- a/frontend/src/routes/project/database-detail/revision/DatabaseRevisionTable.tsx
+++ b/frontend/src/routes/project/database-detail/revision/DatabaseRevisionTable.tsx
@@ -10,7 +10,7 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
-import { getDateForPbTimestampProtoEs } from "@/types";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
import { getRevisionType, revisionLink } from "@/utils/v1/revision";
@@ -108,11 +108,7 @@ export function DatabaseRevisionTable({
{revision.createTime ? (
<HumanizeTs
mode="compact"
- ts={
- (
- getDateForPbTimestampProtoEs(revision.createTime) as Date
- ).getTime() / 1000
- }
+ ts={getTimeForPbTimestampProtoEs(revision.createTime) / 1000}
/>
) : (
"-"
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
index 1c1197a69b..59ff609fc9 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
@@ -6,13 +6,10 @@ import { HumanizeTs } from "@/components/HumanizeTs";
import { useProjectByName } from "@/hooks/useProjectByName";
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
-import { isValidDatabaseName } from "@/types";
+import { getTimeForPbTimestampProtoEs, isValidDatabaseName } from "@/types";
import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
import { extractProjectResourceName, hasProjectPermissionV2 } from "@/utils";
-import {
- getAccessGrantExpirationText,
- getAccessGrantExpireTimeMs,
-} from "@/utils/accessGrant";
+import { getAccessGrantExpirationText } from "@/utils/accessGrant";
import { useIssueDetailContext } from "../context/IssueDetailContext";
export function IssueDetailAccessGrantDetails() {
@@ -178,11 +175,13 @@ export function IssueDetailAccessGrantDetails() {
// post-activation (input-only proto field); we
// can't recover it without double-counting the
// approval wait. Bot review #3370767734.
- accessGrant && (
+ accessGrant.expiration.case === "expireTime" && (
<HumanizeTs
mode="operational"
ts={
- (getAccessGrantExpireTimeMs(accessGrant) ?? 0) / 1000
+ getTimeForPbTimestampProtoEs(
+ accessGrant.expiration.value
+ ) / 1000
}
/>
)}
diff --git a/frontend/src/routes/workspace/MembersPage.tsx b/frontend/src/routes/workspace/MembersPage.tsx
index caecfc703f..b8b31eb96f 100644
--- a/frontend/src/routes/workspace/MembersPage.tsx
+++ b/frontend/src/routes/workspace/MembersPage.tsx
@@ -865,13 +865,6 @@ function computeExpirationTimestamp(days?: number): number | undefined {
return Date.now() + days * 86400000;
}
-// Interpolated into an i18n sentence, which cannot host a tooltip, so this
-// carries the full precision itself rather than a reduced form.
-function formatExpirationDate(timestampMs?: number): string {
- if (!timestampMs) return "";
- return formatAbsoluteDateTime(timestampMs);
-}
-
// Validates the form's expiration against the workspace cap. "Never" (no
// timestamp) is only allowed when no cap is configured; a chosen timestamp
// must be in the future and within the cap.
@@ -1326,7 +1319,9 @@ function ProjectRoleBindingForm({
{!form.expirationCustom && form.expirationTimestampInMS && (
<p className="text-xs leading-4 text-control-light">
{t("project.members.expires-at", {
- date: formatExpirationDate(form.expirationTimestampInMS),
+ // An interpolated sentence cannot host a tooltip, so it carries
+ // the full precision itself.
+ date: formatAbsoluteDateTime(form.expirationTimestampInMS),
})}
</p>
)}
diff --git a/frontend/src/utils/accessGrant.ts b/frontend/src/utils/accessGrant.ts
index f81e2f1ce1..315e8cea64 100644
--- a/frontend/src/utils/accessGrant.ts
+++ b/frontend/src/utils/accessGrant.ts
@@ -7,7 +7,7 @@ import {
} from "@/types/proto-es/v1/access_grant_service_pb";
import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
-import { formatAbsoluteDateTime } from "@/utils/datetime";
+import { formatAbsoluteDateTime, hasPassed } from "@/utils/datetime";
export type AccessGrantFilterStatus =
| "ACTIVE"
@@ -76,7 +76,7 @@ export const getAccessGrantDisplayStatus = (
if (
grant.status === AccessGrant_Status.ACTIVE &&
expireMs !== undefined &&
- expireMs < Date.now()
+ hasPassed(expireMs)
) {
return "EXPIRED";
}
diff --git a/frontend/src/utils/datetime.test.ts b/frontend/src/utils/datetime.test.ts
index 8994075bab..8b7cd23ebc 100644
--- a/frontend/src/utils/datetime.test.ts
+++ b/frontend/src/utils/datetime.test.ts
@@ -26,8 +26,15 @@ import {
formatOperationalDateTime,
formatQueueTime,
formatRelativeTime,
- nextRelativeChangeAt,
+ hasPassed,
+ nextCountdownChangeAt,
+ nextDaysLeftChangeAt,
+ nextPassedAt,
+ nextQueueTimeChangeAt,
+ nextRelativeTimeChangeAt,
RELATIVE_THRESHOLD_MS,
+ readCountdown,
+ readDaysLeft,
} from "./datetime";
describe("formatRelativeTime", () => {
@@ -190,48 +197,215 @@ describe("formatOperationalDateTime", () => {
});
});
-describe("nextRelativeChangeAt", () => {
+const SECOND_MS = 1_000;
+const MINUTE_MS = 60_000;
+const HOUR_MS = 3_600_000;
+const DAY_MS = 86_400_000;
+
+// Ages around every edge the relative reading has: the "now" threshold, each
+// unit switch, the half-unit points where a rounded count turns over, and the
+// 30-day switch. Negative ages are future timestamps.
+const SAMPLED_AGES_MS = [
+ 0,
+ 5 * SECOND_MS,
+ 9_999,
+ 10 * SECOND_MS,
+ 10_400,
+ 10_500,
+ 30 * SECOND_MS,
+ 59_400,
+ 59_500,
+ MINUTE_MS,
+ 89 * SECOND_MS,
+ 90 * SECOND_MS,
+ 119 * SECOND_MS,
+ 30 * MINUTE_MS,
+ 59.5 * MINUTE_MS,
+ HOUR_MS,
+ 1.5 * HOUR_MS,
+ 23.4 * HOUR_MS,
+ DAY_MS,
+ 1.2 * DAY_MS,
+ 1.5 * DAY_MS,
+ 29 * DAY_MS,
+ 29.5 * DAY_MS,
+ 30 * DAY_MS - 1,
+ 30 * DAY_MS,
+ 45 * DAY_MS,
+ 400 * DAY_MS,
+].flatMap((ageMs) => (ageMs === 0 ? [0] : [ageMs, -ageMs]));
+
+// The contract a boundary keeps with the reading it schedules: the reading
+// holds right up to the named instant and changes at it. A boundary checked
+// on its own cannot see that it was derived from the wrong reading.
+const expectBoundaryMatchesReading = (
+ read: (tsMs: number) => string,
+ nextChangeAt: (tsMs: number) => number,
+ tsMs: number
+) => {
+ const startMs = Date.now();
+ const reading = read(tsMs);
+ const changesAtMs = nextChangeAt(tsMs);
+ if (changesAtMs === Number.POSITIVE_INFINITY) {
+ for (const laterMs of [
+ MINUTE_MS,
+ HOUR_MS,
+ DAY_MS,
+ 20 * DAY_MS,
+ 100 * DAY_MS,
+ ]) {
+ vi.setSystemTime(startMs + laterMs);
+ expect(read(tsMs)).toBe(reading);
+ }
+ return;
+ }
+ expect(changesAtMs).toBeGreaterThan(startMs);
+ vi.setSystemTime(startMs + Math.floor((changesAtMs - startMs) / 2));
+ expect(read(tsMs)).toBe(reading);
+ vi.setSystemTime(changesAtMs - 1);
+ expect(read(tsMs)).toBe(reading);
+ vi.setSystemTime(changesAtMs);
+ expect(read(tsMs)).not.toBe(reading);
+};
+
+describe("reading boundaries", () => {
+ const baseMs = new Date("2026-03-02T12:00:00Z").getTime();
+
beforeEach(() => {
vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
+ vi.setSystemTime(baseMs);
});
afterEach(() => {
vi.useRealTimers();
});
- test("tracks the second while the label still counts seconds", () => {
- expect(nextRelativeChangeAt(Date.now() - 30_000)).toBe(Date.now() + 1_000);
- });
-
- test("waits for the turn of the minute, not a fixed minute from now", () => {
- expect(nextRelativeChangeAt(Date.now() - 90_000)).toBe(Date.now() + 30_000);
- });
-
- test("counts a future timestamp down to the same boundary", () => {
- expect(nextRelativeChangeAt(Date.now() + 90_000)).toBe(Date.now() + 30_000);
- });
+ test.each(SAMPLED_AGES_MS)(
+ "names the instant the work-queue reading changes (age %i ms)",
+ (ageMs) => {
+ expectBoundaryMatchesReading(
+ formatQueueTime,
+ nextQueueTimeChangeAt,
+ baseMs - ageMs
+ );
+ }
+ );
- test("wakes at the 30-day switch rather than at the next day", () => {
- const ts = Date.now() - (RELATIVE_THRESHOLD_MS - 3_600_000);
- expect(nextRelativeChangeAt(ts)).toBe(Date.now() + 3_600_000);
- });
+ test.each(SAMPLED_AGES_MS)(
+ "names the instant the relative reading changes (age %i ms)",
+ (ageMs) => {
+ expectBoundaryMatchesReading(
+ formatRelativeTime,
+ nextRelativeTimeChangeAt,
+ baseMs - ageMs
+ );
+ }
+ );
- test.each([-90_000, 90_000])(
+ test.each([-100_000, 100_000])(
"names the same instant on every render inside a bucket (offset %i)",
(offsetMs) => {
const ts = Date.now() + offsetMs;
- const first = nextRelativeChangeAt(ts);
+ const first = nextQueueTimeChangeAt(ts);
// A value that drifted with the clock would re-key the subscription on
// every render, so the shared clock would thrash through a list.
vi.advanceTimersByTime(100);
- expect(nextRelativeChangeAt(ts)).toBe(first);
+ expect(nextQueueTimeChangeAt(ts)).toBe(first);
+ }
+ );
+});
+
+describe("deadline readings", () => {
+ const baseMs = new Date("2026-03-02T12:00:00Z").getTime();
+
+ // Time left before a deadline, around each edge the readings have: passing,
+ // every minute and the one-day line, and whole days beyond it.
+ const SAMPLED_REMAINING_MS = [
+ -DAY_MS,
+ -1,
+ 0,
+ 1,
+ 30 * SECOND_MS,
+ MINUTE_MS - 1,
+ MINUTE_MS,
+ MINUTE_MS + 1,
+ 90 * SECOND_MS,
+ HOUR_MS - 1,
+ HOUR_MS,
+ 3 * HOUR_MS + 20 * MINUTE_MS,
+ DAY_MS - 1,
+ DAY_MS,
+ DAY_MS + 1,
+ 1.5 * DAY_MS,
+ 2 * DAY_MS,
+ 2 * DAY_MS + 1,
+ 45 * DAY_MS,
+ 400 * DAY_MS,
+ ];
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(baseMs);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test.each(SAMPLED_REMAINING_MS)(
+ "names the instant the countdown changes (%i ms left)",
+ (remainingMs) => {
+ expectBoundaryMatchesReading(
+ (targetMs) => JSON.stringify(readCountdown(targetMs)),
+ nextCountdownChangeAt,
+ baseMs + remainingMs
+ );
+ }
+ );
+
+ test.each(SAMPLED_REMAINING_MS)(
+ "names the instant the days-left reading changes (%i ms left)",
+ (remainingMs) => {
+ expectBoundaryMatchesReading(
+ (targetMs) => JSON.stringify(readDaysLeft(targetMs)),
+ nextDaysLeftChangeAt,
+ baseMs + remainingMs
+ );
}
);
- test("never wakes for a label already showing an absolute date", () => {
- const ts = Date.now() - RELATIVE_THRESHOLD_MS - 86_400_000;
- expect(nextRelativeChangeAt(ts)).toBe(Number.POSITIVE_INFINITY);
+ test.each(SAMPLED_REMAINING_MS)(
+ "names the instant a deadline passes (%i ms left)",
+ (remainingMs) => {
+ expectBoundaryMatchesReading(
+ (targetMs) => String(hasPassed(targetMs)),
+ nextPassedAt,
+ baseMs + remainingMs
+ );
+ }
+ );
+
+ test("counts down in hours and minutes within the last day", () => {
+ expect(
+ readCountdown(baseMs + 3 * HOUR_MS + 20 * MINUTE_MS + 59_999)
+ ).toEqual({ kind: "within", hours: 3, minutes: 20 });
+ expect(readCountdown(baseMs + DAY_MS)).toEqual({ kind: "beyondDay" });
+ expect(readCountdown(baseMs)).toEqual({
+ kind: "within",
+ hours: 0,
+ minutes: 0,
+ });
+ expect(readCountdown(baseMs - 1)).toEqual({ kind: "passed" });
+ });
+
+ test("rounds whole days up, and treats the deadline itself as passed", () => {
+ expect(readDaysLeft(baseMs + DAY_MS + 1)).toEqual({
+ kind: "days",
+ days: 2,
+ });
+ expect(readDaysLeft(baseMs + DAY_MS)).toEqual({ kind: "days", days: 1 });
+ expect(readDaysLeft(baseMs + DAY_MS - 1)).toEqual({ kind: "today" });
+ expect(readDaysLeft(baseMs)).toEqual({ kind: "passed" });
});
});
diff --git a/frontend/src/utils/datetime.ts b/frontend/src/utils/datetime.ts
index ef772fb697..a2e8087c29 100644
--- a/frontend/src/utils/datetime.ts
+++ b/frontend/src/utils/datetime.ts
@@ -1,6 +1,11 @@
import i18n from "@/lib/i18n";
-export const RELATIVE_THRESHOLD_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
+const SECOND_MS = 1_000;
+const MINUTE_MS = 60 * SECOND_MS;
+const HOUR_MS = 60 * MINUTE_MS;
+const DAY_MS = 24 * HOUR_MS;
+
+export const RELATIVE_THRESHOLD_MS = 30 * DAY_MS;
export const DEFAULT_NOW_THRESHOLD_MS = 10_000;
type RelativeTimeFormatOptions = {
@@ -11,36 +16,72 @@ export function getActiveLocale(): string {
return i18n.language;
}
+type RelativeUnit = {
+ fromMs: number;
+ unitMs: number;
+ unit: Intl.RelativeTimeFormatUnit;
+};
+
+// The units a relative reading counts in, each from the age it takes over at.
+// Below the first, the reading is "now". Both `formatRelativeTime` and the
+// boundaries that schedule it read this table, so the two cannot drift apart.
+const relativeUnits = (nowThresholdMs: number): RelativeUnit[] => [
+ { fromMs: nowThresholdMs, unitMs: SECOND_MS, unit: "second" },
+ { fromMs: MINUTE_MS, unitMs: MINUTE_MS, unit: "minute" },
+ { fromMs: HOUR_MS, unitMs: HOUR_MS, unit: "hour" },
+ { fromMs: DAY_MS, unitMs: DAY_MS, unit: "day" },
+];
+
+const unitIndexForAge = (units: RelativeUnit[], ageMs: number): number =>
+ units.findLastIndex((unit) => ageMs >= unit.fromMs);
+
+// Building an Intl formatter costs tens of times more than formatting with one,
+// and these run in every table cell, so each is built once per locale. The time
+// zone is fixed when a formatter is built: a zone change mid-session shows on
+// reload, and every string that names its zone names the one it was built in.
+const formatterCache = new Map<string, unknown>();
+
+function cachedFormatter<T>(name: string, build: (locale: string) => T): T {
+ const locale = getActiveLocale();
+ const key = `${name}|${locale}`;
+ let formatter = formatterCache.get(key) as T | undefined;
+ if (formatter === undefined) {
+ formatter = build(locale);
+ formatterCache.set(key, formatter);
+ }
+ return formatter;
+}
+
+const dateTimeFormatter = (
+ name: string,
+ options: Intl.DateTimeFormatOptions
+): Intl.DateTimeFormat =>
+ cachedFormatter(name, (locale) => new Intl.DateTimeFormat(locale, options));
+
export function formatRelativeTime(
timestampMs: number,
options: RelativeTimeFormatOptions = {}
): string {
const { nowThresholdMs = DEFAULT_NOW_THRESHOLD_MS } = options;
const diffMs = Date.now() - timestampMs;
- const absDiff = Math.abs(diffMs);
- const sign = diffMs >= 0 ? -1 : 1;
-
- const rtf = new Intl.RelativeTimeFormat(getActiveLocale(), {
- numeric: "auto",
- });
+ const ageMs = Math.abs(diffMs);
+ const rtf = cachedFormatter(
+ "relative",
+ (locale) => new Intl.RelativeTimeFormat(locale, { numeric: "auto" })
+ );
- if (absDiff < nowThresholdMs) {
+ const units = relativeUnits(nowThresholdMs);
+ const index = unitIndexForAge(units, ageMs);
+ if (index < 0) {
return rtf.format(0, "second");
}
- if (absDiff < 60_000) {
- return rtf.format(sign * Math.round(absDiff / 1000), "second");
- }
- if (absDiff < 3_600_000) {
- return rtf.format(sign * Math.round(absDiff / 60_000), "minute");
- }
- if (absDiff < 86_400_000) {
- return rtf.format(sign * Math.round(absDiff / 3_600_000), "hour");
- }
- return rtf.format(sign * Math.round(absDiff / 86_400_000), "day");
+ const { unitMs, unit } = units[index];
+ const sign = diffMs >= 0 ? -1 : 1;
+ return rtf.format(sign * Math.round(ageMs / unitMs), unit);
}
export function formatAbsoluteDateTime(timestampMs: number): string {
- return new Intl.DateTimeFormat(getActiveLocale(), {
+ return dateTimeFormatter("datetime", {
month: "short",
day: "numeric",
year: "numeric",
@@ -48,25 +89,21 @@ export function formatAbsoluteDateTime(timestampMs: number): string {
minute: "2-digit",
second: "2-digit",
timeZoneName: "short",
- }).format(new Date(timestampMs));
+ }).format(timestampMs);
}
export function formatAbsoluteDate(timestampMs: number): string {
- const date = new Date(timestampMs);
- const now = new Date();
-
- if (date.getFullYear() === now.getFullYear()) {
- return new Intl.DateTimeFormat(getActiveLocale(), {
+ if (new Date(timestampMs).getFullYear() === new Date().getFullYear()) {
+ return dateTimeFormatter("date", {
month: "short",
day: "numeric",
- }).format(date);
+ }).format(timestampMs);
}
-
- return new Intl.DateTimeFormat(getActiveLocale(), {
+ return dateTimeFormatter("dateWithYear", {
month: "short",
day: "numeric",
year: "numeric",
- }).format(date);
+ }).format(timestampMs);
}
export function formatQueueTime(timestampMs: number): string {
@@ -77,52 +114,201 @@ export function formatQueueTime(timestampMs: number): string {
}
export function formatCompactDateTime(timestampMs: number): string {
- return new Intl.DateTimeFormat(getActiveLocale(), {
+ return dateTimeFormatter("compact", {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
- }).format(new Date(timestampMs));
+ }).format(timestampMs);
}
export function formatOperationalDateTime(timestampMs: number): string {
- return new Intl.DateTimeFormat(getActiveLocale(), {
+ return dateTimeFormatter("operational", {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
timeZoneName: "short",
- }).format(new Date(timestampMs));
+ }).format(timestampMs);
}
/**
- * The instant at which `formatQueueTime` would next render this timestamp
- * differently, or `Infinity` once it has settled on an absolute date.
- *
- * Buckets are measured from the timestamp, not from the wall clock: a row
- * created at 10:00:30 turns over to "1 minute ago" at 10:01:30. A display that
- * woke on a fixed cadence instead would lag by up to a whole bucket.
+ * The ages bracketing `ageMs` at which a relative reading changes: the latest
+ * at or below it and the earliest above it. A reading changes where its unit
+ * switches and, because the count is rounded, at every half unit in between.
+ * At `capMs` it stops counting altogether.
*/
-export function nextRelativeChangeAt(timestampMs: number): number {
- const nowMs = Date.now();
- const ageMs = Math.abs(nowMs - timestampMs);
- if (ageMs >= RELATIVE_THRESHOLD_MS) {
+function relativeChangePoints(
+ ageMs: number,
+ nowThresholdMs: number,
+ capMs: number
+): { atOrBelowMs?: number; aboveMs: number } {
+ if (ageMs >= capMs) {
+ return { atOrBelowMs: capMs, aboveMs: Number.POSITIVE_INFINITY };
+ }
+ const units = relativeUnits(nowThresholdMs);
+ const index = unitIndexForAge(units, ageMs);
+ if (index < 0) {
+ return { aboveMs: Math.min(units[0].fromMs, capMs) };
+ }
+ const { fromMs, unitMs } = units[index];
+ const toMs = Math.min(
+ units[index + 1]?.fromMs ?? Number.POSITIVE_INFINITY,
+ capMs
+ );
+ return {
+ atOrBelowMs: Math.max(
+ (Math.floor(ageMs / unitMs - 0.5) + 0.5) * unitMs,
+ fromMs
+ ),
+ aboveMs: Math.min((Math.floor(ageMs / unitMs + 0.5) + 0.5) * unitMs, toMs),
+ };
+}
+
+function nextRelativeReadingChangeAt(
+ timestampMs: number,
+ nowThresholdMs: number,
+ capMs: number
+): number {
+ const diffMs = Date.now() - timestampMs;
+ const { atOrBelowMs, aboveMs } = relativeChangePoints(
+ Math.abs(diffMs),
+ nowThresholdMs,
+ capMs
+ );
+ if (diffMs >= 0) {
+ return Math.ceil(timestampMs + aboveMs);
+ }
+ // A future timestamp counts down, so its reading changes the moment its age
+ // drops below the change point at or under it. Inside the "now" window there
+ // is none: "now" holds across the timestamp until the past side leaves it.
+ if (atOrBelowMs === undefined) {
+ return Math.ceil(timestampMs + nowThresholdMs);
+ }
+ return Math.floor(timestampMs - atOrBelowMs) + 1;
+}
+
+/**
+ * The first instant `formatQueueTime` renders this timestamp differently, or
+ * `Infinity` once it has settled on a date for good.
+ */
+export function nextQueueTimeChangeAt(timestampMs: number): number {
+ const changesAtMs = nextRelativeReadingChangeAt(
+ timestampMs,
+ DEFAULT_NOW_THRESHOLD_MS,
+ RELATIVE_THRESHOLD_MS
+ );
+ if (Math.abs(Date.now() - timestampMs) < RELATIVE_THRESHOLD_MS) {
+ return changesAtMs;
+ }
+ // A date shows its year unless it falls in the current one, so the reading
+ // also changes when the current year turns into or out of the timestamp's.
+ const timestampYear = new Date(timestampMs).getFullYear();
+ const yearTurnsMs = [timestampYear, timestampYear + 1]
+ .map((year) => new Date(year, 0, 1).getTime())
+ .find((yearStartMs) => yearStartMs > Date.now());
+ return Math.min(changesAtMs, yearTurnsMs ?? Number.POSITIVE_INFINITY);
+}
+
+/** The first instant `formatRelativeTime` renders this timestamp differently. */
+export function nextRelativeTimeChangeAt(
+ timestampMs: number,
+ options: RelativeTimeFormatOptions = {}
+): number {
+ return nextRelativeReadingChangeAt(
+ timestampMs,
+ options.nowThresholdMs ?? DEFAULT_NOW_THRESHOLD_MS,
+ Number.POSITIVE_INFINITY
+ );
+}
+
+// Readings of a deadline. Each is paired with the first instant it changes, so
+// a display showing one stays current on the shared clock.
+
+/** Whether a deadline is behind us; the deadline instant itself is not. */
+export function hasPassed(targetMs: number): boolean {
+ return targetMs < Date.now();
+}
+
+export function nextPassedAt(targetMs: number): number {
+ return hasPassed(targetMs)
+ ? Number.POSITIVE_INFINITY
+ : Math.floor(targetMs) + 1;
+}
+
+/**
+ * Time left before a deadline as a countdown: hours and whole minutes within
+ * the last day, and no count beyond it.
+ */
+export type Countdown =
+ | { kind: "passed" }
+ | { kind: "beyondDay" }
+ | { kind: "within"; hours: number; minutes: number };
+
+export function readCountdown(targetMs: number): Countdown {
+ const remainingMs = targetMs - Date.now();
+ if (remainingMs < 0) {
+ return { kind: "passed" };
+ }
+ if (remainingMs >= DAY_MS) {
+ return { kind: "beyondDay" };
+ }
+ return {
+ kind: "within",
+ hours: Math.floor(remainingMs / HOUR_MS),
+ minutes: Math.floor((remainingMs % HOUR_MS) / MINUTE_MS),
+ };
+}
+
+export function nextCountdownChangeAt(targetMs: number): number {
+ const remainingMs = targetMs - Date.now();
+ if (remainingMs < 0) {
return Number.POSITIVE_INFINITY;
}
- const bucketMs =
- ageMs < 60_000
- ? 1_000
- : ageMs < 3_600_000
- ? 60_000
- : ageMs < 86_400_000
- ? 3_600_000
- : 86_400_000;
- // A past timestamp grows into the next bucket; a future one shrinks back
- // into the previous one.
- const intoBucketMs = ageMs % bucketMs;
- const untilBucketEdgeMs =
- nowMs >= timestampMs ? bucketMs - intoBucketMs : intoBucketMs || bucketMs;
- return nowMs + Math.min(untilBucketEdgeMs, RELATIVE_THRESHOLD_MS - ageMs);
+ // The count is whole minutes left, so it drops the moment the time left
+ // falls below the current count. With no minute left, that is the deadline.
+ const thresholdMs =
+ remainingMs >= DAY_MS
+ ? DAY_MS
+ : Math.floor(remainingMs / MINUTE_MS) * MINUTE_MS;
+ return Math.floor(targetMs - thresholdMs) + 1;
+}
+
+/**
+ * Time left before a deadline in whole days, rounded up; "today" within the
+ * last day. Unlike `hasPassed`, the deadline instant itself counts as passed.
+ */
+export type DaysLeft =
+ | { kind: "passed" }
+ | { kind: "today" }
+ | { kind: "days"; days: number };
+
+export function readDaysLeft(targetMs: number): DaysLeft {
+ const remainingMs = targetMs - Date.now();
+ if (remainingMs <= 0) {
+ return { kind: "passed" };
+ }
+ if (remainingMs < DAY_MS) {
+ return { kind: "today" };
+ }
+ return { kind: "days", days: Math.ceil(remainingMs / DAY_MS) };
+}
+
+export function nextDaysLeftChangeAt(targetMs: number): number {
+ const remainingMs = targetMs - Date.now();
+ if (remainingMs <= 0) {
+ return Number.POSITIVE_INFINITY;
+ }
+ if (remainingMs < DAY_MS) {
+ return Math.ceil(targetMs);
+ }
+ // Rounded up, the count drops once the time left reaches the count below
+ // it — except the last whole day, which turns into "today" only once less
+ // than a day remains.
+ const days = Math.ceil(remainingMs / DAY_MS);
+ return days === 1
+ ? Math.floor(targetMs - DAY_MS) + 1
+ : Math.ceil(targetMs - (days - 1) * DAY_MS);
}