Spaces:
Running

AHMDRTAP / src /lib /format.ts
ahmdelbaz28-ux
fix(pwa+numerals): stuck-device SW cure — build-signed SW URL; device-locale-proof digits
c7ed040
Raw History Blame Contribute Delete
2.49 kB
/**
* Site-wide number & date formatting — explicit locales, NEVER device locale.
*
* ROOT-CAUSE FIX (owner report, 2026-12-03): "home page numbers are Arabic
* while the rest of the site is English". Every bare `.toLocaleString()` /
* `.toLocaleDateString()` call follows the BROWSER/OS locale, so a device
* whose regional format is Arabic rendered ٠١٢٣ Arabic-Indic digits inside
* the English UI. The fix is a single rule used everywhere:
*
* • Numbers → ALWAYS Western (0-9) digits via an explicit "en-US" locale.
* This matches the platform's existing digits convention (hero "500+",
* promo countdown, lesson indexes, certificate codes are all raw JS
* numbers = Western), so digits are now uniform in BOTH site languages
* and on EVERY device — no mismatch is possible by construction.
*
* • Dates → follow the SITE language (en → "en-US", ar → "ar-EG"), which
* is the long-standing convention of the Home article teaser
* (AR_DATE_FMT / EN_DATE_FMT). Site language, not device language.
*
* Every exported helper is pure and safe against invalid input.
*/
export type FormatLang = "ar" | "en";
const NUMBER_FMT = new Intl.NumberFormat("en-US");
/**
* Format a number for display: Western digits, en-US grouping, regardless of
* device locale or site language. Non-finite input formats as "0".
*/
export function formatNumber(value: number): string {
if (!Number.isFinite(value)) return NUMBER_FMT.format(0);
return NUMBER_FMT.format(value);
}
function toDate(value: string | number | Date): Date | null {
const d = new Date(value);
return Number.isNaN(d.getTime()) ? null : d;
}
/**
* Short date (e.g. "Dec 3, 2026") in the SITE language. Invalid input → "—".
*/
export function formatDate(value: string | number | Date, lang: FormatLang): string {
const d = toDate(value);
if (!d) return "—";
return new Intl.DateTimeFormat(lang === "ar" ? "ar-EG" : "en-US", {
day: "numeric",
month: "short",
year: "numeric",
}).format(d);
}
/**
* Date + time (e.g. "Dec 3, 2026, 4:25 PM") in the SITE language.
* Invalid input → "—".
*/
export function formatDateTime(value: string | number | Date, lang: FormatLang): string {
const d = toDate(value);
if (!d) return "—";
return new Intl.DateTimeFormat(lang === "ar" ? "ar-EG" : "en-US", {
day: "numeric",
month: "short",
year: "numeric",
hour: "numeric",
minute: "2-digit",
}).format(d);
}