/** * Human-readable durations and sizes, shared by tool output and (later) the * panel, so both say the same thing about the same task. * * @author mystery4f <40482524+mystery4f@users.noreply.github.com> */ /** * How long a record has been alive: to its end when it has one, to now while it * runs. One formula, because a row, a tool line and a notification all quote the * same task and must not disagree about it. */ export function elapsedOf(task: { createdAt: number; endedAt?: number }, now: number): number { return Math.max(0, (task.endedAt ?? now) - task.createdAt); } /** `0.4s`, `12.3s`, `2m 05s`, `1h 03m`. */ export function formatDuration(milliseconds: number): string { const total = Math.max(0, Math.round(milliseconds)); if (total < 60_000) return `${(total / 1000).toFixed(1)}s`; const totalSeconds = Math.round(total / 1000); const minutes = Math.floor(totalSeconds / 60); const seconds = totalSeconds % 60; if (minutes < 60) return `${String(minutes)}m ${String(seconds).padStart(2, "0")}s`; const hours = Math.floor(minutes / 60); return `${String(hours)}h ${String(minutes % 60).padStart(2, "0")}m`; } /** `512 B`, `1.5 KiB`, `20.0 MiB`. */ export function formatBytes(bytes: number): string { const total = Math.max(0, Math.round(bytes)); if (total < 1024) return `${String(total)} B`; let value = total / 1024; let unit = "KiB"; if (value >= 1024) { value /= 1024; unit = "MiB"; } if (value >= 1024) { value /= 1024; unit = "GiB"; } return `${value.toFixed(1)} ${unit}`; } /** * The first line of a command, cut to a preview length. A record read without * `full` shows this; reading with `full` shows the command as it was given. */ export function commandPreview(command: string, maxLength = 80): string { const firstLine = command.split("\n", 1)[0] ?? ""; const suffix = command.includes("\n") ? " …" : ""; if (firstLine.length + suffix.length <= maxLength) return `${firstLine}${suffix}`; return `${firstLine.slice(0, Math.max(1, maxLength - 1))}…`; } /** A wall-clock time as the panel shows it: `09:30:05`, local time. */ export function formatClockTime(at: number): string { const when = new Date(at); const hours = String(when.getHours()).padStart(2, "0"); const minutes = String(when.getMinutes()).padStart(2, "0"); const seconds = String(when.getSeconds()).padStart(2, "0"); return `${hours}:${minutes}:${seconds}`; } /** * How a fire's number is written: `#3` for a scheduled fire, `m1` for the first * fire started by hand. The negative numbers the store keeps are an encoding, not * something a reader should have to decode (ADR-0018). */ export function fireLabel(fire: number): string { return fire < 0 ? `m${String(-fire)}` : `#${String(fire)}`; }