Repository Public
1// Locale-aware formatting through Intl only. Every function takes the active locale so output follows the user2// profile; absent values are never rendered here (callers show an availability state instead of 0 or blank).34export type Locale = "fr" | "en";5// Canadian conventions for dates (ISO-like numeric dates, day before month in text). Units use the tags whose CLDR6// short forms are the tersest ("12 min 5 sec", "2.5 MB/s") — the cockpit is dense.7const dateTag = (l: Locale) => (l === "fr" ? "fr-CA" : "en-CA");8const unitTag = (l: Locale) => (l === "fr" ? "fr-CA" : "en-US");910const nf = new Map<string, Intl.NumberFormat>();11function number(l: Locale, opts: Intl.NumberFormatOptions): Intl.NumberFormat {12 const key = l + JSON.stringify(opts);13 let f = nf.get(key);14 if (!f) nf.set(key, (f = new Intl.NumberFormat(unitTag(l), opts)));15 return f;16}17const df = new Map<string, Intl.DateTimeFormat>();18function date(l: Locale, opts: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {19 const key = l + JSON.stringify(opts);20 let f = df.get(key);21 if (!f) df.set(key, (f = new Intl.DateTimeFormat(dateTag(l), opts)));22 return f;23}2425export function formatNumber(l: Locale, v: number, maxFractionDigits = 1): string {26 return number(l, { maximumFractionDigits: maxFractionDigits }).format(v);27}28export function formatInteger(l: Locale, v: number): string {29 return number(l, { maximumFractionDigits: 0 }).format(v);30}31/** `v` is 0–100. */32export function formatPercent(l: Locale, v: number, digits = 0): string {33 return number(l, { style: "percent", maximumFractionDigits: digits, minimumFractionDigits: digits }).format(v / 100);34}35/** `v` is a 0–1 ratio. */36export function formatRatio(l: Locale, v: number, digits = 0): string {37 return number(l, { style: "percent", maximumFractionDigits: digits }).format(v);38}3940const BYTE_UNITS = ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte"] as const;41/** Binary multiples (1024) labelled with the customary unit of the locale (Go / GB). */42export function formatBytes(l: Locale, bytes: number, digits?: number): string {43 let i = 0;44 let v = Math.abs(bytes);45 while (v >= 1024 && i < BYTE_UNITS.length - 1) {46 v /= 1024;47 i++;48 }49 const d = digits ?? (i === 0 ? 0 : v >= 100 ? 0 : v >= 10 ? 1 : 2);50 return number(l, { style: "unit", unit: BYTE_UNITS[i] ?? "byte", unitDisplay: "short", maximumFractionDigits: d }).format(bytes < 0 ? -v : v);51}52export function formatByteRate(l: Locale, bytesPerSecond: number): string {53 let i = 0;54 let v = Math.abs(bytesPerSecond);55 while (v >= 1024 && i < BYTE_UNITS.length - 1) {56 v /= 1024;57 i++;58 }59 const d = i === 0 ? 0 : v >= 100 ? 0 : 1;60 return number(l, { style: "unit", unit: `${BYTE_UNITS[i] ?? "byte"}-per-second`, unitDisplay: "short", maximumFractionDigits: d }).format(v);61}62export function formatMs(l: Locale, ms: number): string {63 return number(l, { style: "unit", unit: "millisecond", unitDisplay: "short", maximumFractionDigits: ms < 10 ? 1 : 0 }).format(ms);64}6566/** Compact duration from seconds: "3 j 4 h", "12 min 5 s". At most two units. */67export function formatDuration(l: Locale, seconds: number): string {68 const s = Math.max(0, Math.round(seconds));69 const parts: [number, "day" | "hour" | "minute" | "second"][] = [70 [Math.floor(s / 86400), "day"],71 [Math.floor((s % 86400) / 3600), "hour"],72 [Math.floor((s % 3600) / 60), "minute"],73 [s % 60, "second"],74 ];75 const first = parts.findIndex(([n]) => n > 0);76 if (first === -1) return number(l, { style: "unit", unit: "second", unitDisplay: "short" }).format(0);77 return parts78 .slice(first, first + 2)79 .filter(([n], i) => i === 0 || n > 0)80 .map(([n, unit]) => number(l, { style: "unit", unit, unitDisplay: "short" }).format(n))81 .join(" ");82}8384const toDate = (v: string | number | Date) => (v instanceof Date ? v : new Date(v));8586/** Clock time as HH:mm[:ss] (24 h) in both locales: compact and unambiguous in dense tables. */87function clock(v: Date, seconds: boolean, timeZone?: string): string {88 const parts = date("en", { hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", ...(timeZone ? { timeZone } : {}) }).formatToParts(v);89 const get = (t: string) => parts.find((p) => p.type === t)?.value ?? "00";90 return seconds ? `${get("hour")}:${get("minute")}:${get("second")}` : `${get("hour")}:${get("minute")}`;91}92function zoneName(l: Locale, v: Date, timeZone?: string): string {93 return date(l, { hour: "2-digit", timeZoneName: "short", ...(timeZone ? { timeZone } : {}) }).formatToParts(v).find((p) => p.type === "timeZoneName")?.value ?? "";94}9596/** Local date and time with the zone abbreviation made explicit ("18 nov. 2026 16:05 HNE"). */97export function formatDateTime(l: Locale, v: string | number | Date, opts: { seconds?: boolean; zone?: boolean; timeZone?: string } = {}): string {98 const d = toDate(v);99 const day = date(l, { year: "numeric", month: "short", day: "numeric", ...(opts.timeZone ? { timeZone: opts.timeZone } : {}) }).format(d);100 const zone = opts.zone === false ? "" : ` ${zoneName(l, d, opts.timeZone)}`;101 return `${day} ${clock(d, opts.seconds ?? false, opts.timeZone)}${zone}`;102}103/** UTC timestamp for audit views: ISO date, seconds, always suffixed "UTC" — identical in both locales. */104export function formatUtc(_l: Locale, v: string | number | Date): string {105 const iso = toDate(v).toISOString();106 return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;107}108export function formatDate(l: Locale, v: string | number | Date, timeZone?: string): string {109 return date(l, { year: "numeric", month: "short", day: "numeric", ...(timeZone ? { timeZone } : {}) }).format(toDate(v));110}111export function formatTime(_l: Locale, v: string | number | Date, opts: { seconds?: boolean; timeZone?: string } = {}): string {112 return clock(toDate(v), opts.seconds !== false, opts.timeZone);113}114115const rtf = new Map<Locale, Intl.RelativeTimeFormat>();116/** "il y a 3 min" / "3 min. ago" relative to `now`. */117export function formatRelative(l: Locale, v: string | number | Date, now: number = Date.now()): string {118 let f = rtf.get(l);119 if (!f) rtf.set(l, (f = new Intl.RelativeTimeFormat(unitTag(l), { numeric: "auto", style: "short" })));120 const diff = (toDate(v).getTime() - now) / 1000;121 const abs = Math.abs(diff);122 if (abs < 60) return f.format(Math.round(diff), "second");123 if (abs < 3600) return f.format(Math.round(diff / 60), "minute");124 if (abs < 86400) return f.format(Math.round(diff / 3600), "hour");125 return f.format(Math.round(diff / 86400), "day");126}127128/** Formats a metric value from its catalog unit (percent, bytes, bytes_per_s, ms, seconds, count, level, celsius, watts). */129export function formatMetric(l: Locale, value: number, unit: string | undefined): string {130 switch (unit) {131 case "percent": return formatPercent(l, value, value < 10 && value !== 0 ? 1 : 0);132 case "bytes": return formatBytes(l, value);133 case "bytes_per_s": return formatByteRate(l, value);134 case "ms": return formatMs(l, value);135 case "seconds": return formatDuration(l, value);136 case "celsius": return number(l, { style: "unit", unit: "celsius", maximumFractionDigits: 1 }).format(value);137 case "watts": return `${formatNumber(l, value, 1)}\u00a0W`; // "watt" is not a unit Intl.NumberFormat accepts138 case "count":139 case "level":140 case undefined:141 case "": return formatNumber(l, value, 2);142 default: return `${formatNumber(l, value, 2)} ${unit}`;143 }144}145146export function localTimeZone(): string {147 return Intl.DateTimeFormat().resolvedOptions().timeZone;148}149150/** `<input type="datetime-local">` value for an instant, in the browser zone. */151export function toLocalInput(v: string | number | Date): string {152 const d = toDate(v);153 const p = (n: number) => String(n).padStart(2, "0");154 return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;155}156export function fromLocalInput(v: string): string | null {157 if (!v) return null;158 const d = new Date(v);159 return Number.isNaN(d.getTime()) ? null : d.toISOString();160}161