diff --git a/packages/tools/src/format/constants.ts b/packages/tools/src/format/constants.ts index 11fb892..0ce4b37 100644 --- a/packages/tools/src/format/constants.ts +++ b/packages/tools/src/format/constants.ts @@ -16,6 +16,21 @@ export const LTR_ISOLATE_END = '⁩'; export const PERSIAN_DIGITS = '۰۱۲۳۴۵۶۷۸۹'; export const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩'; +/** Between the date and the time: `15 خرداد 1404، ساعت 14:30`. */ +export const DATE_TIME_JOINER = '، ساعت '; +/** The product's fixed wording, which CLDR words differently («اکنون»). */ +export const JUST_NOW = 'همین الان'; +export const LESS_THAN = 'کمتر از'; + +/** A prediction horizon's unit letter → its Intl unit. */ +export const HORIZON_UNITS = { + h: 'hour', + d: 'day', + w: 'week', + m: 'month', + y: 'year', +} as const; + export const MINUTE_MS = 60_000; export const HOUR_MS = 60 * MINUTE_MS; export const DAY_MS = 24 * HOUR_MS; diff --git a/packages/tools/src/format/format.ts b/packages/tools/src/format/format.ts index 058250c..47ed751 100644 --- a/packages/tools/src/format/format.ts +++ b/packages/tools/src/format/format.ts @@ -1,8 +1,12 @@ import { ARABIC_DIGITS, + DATE_TIME_JOINER, DAY_MS, DECIMAL_SEPARATOR, + HORIZON_UNITS, HOUR_MS, + JUST_NOW, + LESS_THAN, LOCALE, LTR_ISOLATE_END, LTR_ISOLATE_START, @@ -13,7 +17,12 @@ import { THOUSANDS_SEPARATOR, TIME_ZONE, } from './constants'; -import type { DateFormatOptions, DateInput, ShebaFormatOptions } from './types'; +import type { + DateFormatOptions, + DateInput, + DurationUnit, + ShebaFormatOptions, +} from './types'; // Formatters are built once per fixed locale and time zone (flyweight); they never hold per-request data. const dateFormatter = new Intl.DateTimeFormat(LOCALE, { @@ -22,11 +31,8 @@ const dateFormatter = new Intl.DateTimeFormat(LOCALE, { month: 'long', year: 'numeric', }); -const dateTimeFormatter = new Intl.DateTimeFormat(LOCALE, { +const timeFormatter = new Intl.DateTimeFormat(LOCALE, { timeZone: TIME_ZONE, - day: 'numeric', - month: 'long', - year: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23', @@ -35,6 +41,21 @@ const relativeFormatter = new Intl.RelativeTimeFormat(LOCALE, { numeric: 'auto', }); const numberFormatters = new Map(); +const unitFormatters = new Map(); + +/** `13 روز`: the unit word comes from CLDR, so it stays in step with the locale. */ +function unitAmount(value: number, unit: DurationUnit): string { + let formatter = unitFormatters.get(unit); + if (!formatter) { + formatter = new Intl.NumberFormat(LOCALE, { + style: 'unit', + unit, + unitDisplay: 'long', + }); + unitFormatters.set(unit, formatter); + } + return formatter.format(value); +} function numberFormatter(decimals: number): Intl.NumberFormat { let formatter = numberFormatters.get(decimals); @@ -71,23 +92,42 @@ export function latinDigits(value: string): string { }); } -/** `1234567.8` → `1٬234٬567٫8`. The font draws the digits in Persian. */ -export function number(value: number, decimals = 0): string { - return persianSeparators( - numberFormatter(decimals).format(Math.abs(value)), - ).replace(/^/, value < 0 ? MINUS_SIGN : ''); +/** True when `value` shows as zero at `decimals`, so `-0.4` never prints as `−0`. */ +function roundsToZero(value: number, decimals: number): boolean { + return Number(Math.abs(value).toFixed(decimals)) === 0; } -/** A price keeps the decimals it has: `1.092` → `1٫092`. */ -export function price(value: number): string { - const decimals = Math.min(value.toString().split('.')[1]?.length ?? 0, 8); +/** `+`, `−`, or nothing for a value that rounds to zero. */ +function sign(value: number, decimals: number): string { + if (roundsToZero(value, decimals)) return ''; + return value > 0 ? '+' : MINUS_SIGN; +} + +/** `1234567.8` → `1٬234٬567٫8`. The font draws the digits in Persian. */ +export function number(value: number, decimals = 0): string { + const digits = persianSeparators( + numberFormatter(decimals).format(Math.abs(value)), + ); + return value < 0 && !roundsToZero(value, decimals) + ? `${MINUS_SIGN}${digits}` + : digits; +} + +/** A price keeps the decimals it has, up to 6: `1.092` → `1٫092`. A missing price shows `—`. */ +export function price(value: number | null | undefined): string { + if (value == null || Number.isNaN(value)) return '—'; + // Not toString(): it writes 1.2e-7 in exponent notation. + const plain = value.toLocaleString('en-US', { + useGrouping: false, + maximumFractionDigits: 20, + }); + const decimals = Math.min(plain.split('.')[1]?.length ?? 0, 6); return number(value, decimals); } -/** Always shows `+` or `−`, inside an LTR isolate: `−120٬000`. */ +/** Shows `+` or `−` (none for zero), inside an LTR isolate: `−120٬000`. */ export function signed(value: number, decimals = 0): string { - const sign = value > 0 ? '+' : value < 0 ? MINUS_SIGN : ''; - return iso(`${sign}${number(Math.abs(value), decimals)}`); + return iso(`${sign(value, decimals)}${number(Math.abs(value), decimals)}`); } /** `62.86` → `62٫9٪`. The value is already a percentage, not a fraction. */ @@ -95,10 +135,11 @@ export function percent(value: number, decimals = 1): string { return `${number(value, decimals)}${PERCENT_SIGN}`; } -/** `4` → `+4٫0٪` inside an LTR isolate. */ +/** `4` → `+4٫0٪` inside an LTR isolate (no sign for zero). */ export function signedPercent(value: number, decimals = 1): string { - const sign = value > 0 ? '+' : value < 0 ? MINUS_SIGN : ''; - return iso(`${sign}${number(Math.abs(value), decimals)}${PERCENT_SIGN}`); + return iso( + `${sign(value, decimals)}${number(Math.abs(value), decimals)}${PERCENT_SIGN}`, + ); } /** `1 : 2٫8` inside an LTR isolate. */ @@ -112,31 +153,18 @@ export function date( { time = true }: DateFormatOptions = {}, ): string { const at = toDate(value); - if (!time) return dateFormatter.format(at); - - // CLDR joins date and time with « ساعت »; the product style adds the Persian comma before it. - const parts = dateTimeFormatter.formatToParts(at); - const hourIndex = parts.findIndex((part) => part.type === 'hour'); - const datePart = parts - .slice(0, hourIndex - 1) - .map((part) => part.value) - .join(''); - const joiner = parts[hourIndex - 1]?.value.trim() ?? ''; - const timePart = parts - .slice(hourIndex) - .map((part) => part.value) - .join(''); - return `${datePart}، ${joiner} ${timePart}`; + const day = dateFormatter.format(at); + return time ? `${day}${DATE_TIME_JOINER}${timeFormatter.format(at)}` : day; } -/** `5 دقیقه پیش`, `2 ساعت پیش`, `دیروز`; older than a day → `date()`. */ +/** `همین الان`, `5 دقیقه پیش`, `2 ساعت پیش`, `دیروز`; older than that → `date()`. */ export function relative( value: DateInput, now: DateInput = Date.now(), ): string { const at = toDate(value); const diff = toDate(now).getTime() - at.getTime(); - if (diff < MINUTE_MS) return relativeFormatter.format(0, 'second'); + if (diff < MINUTE_MS) return JUST_NOW; if (diff < HOUR_MS) return relativeFormatter.format(-Math.floor(diff / MINUTE_MS), 'minute'); if (diff < DAY_MS) @@ -145,13 +173,42 @@ export function relative( return date(at); } -/** `IR620120000000101234567890` → `IR62 0120 0000 0010 1234 5678 90`. */ +/** + * `IR620120000000101234567890` → `IR62 0120 0000 0010 1234 5678 90`, grouped as banks print it. + * `{ prefix: false }` drops `IR` and keeps the same groups: `62 0120 0000 …`. + */ export function sheba( value: string, { prefix = true }: ShebaFormatOptions = {}, ): string { const digits = latinDigits(value).replace(/^IR/i, '').replace(/\D/g, ''); - const grouped = - (prefix ? `IR${digits}` : digits).match(/.{1,4}/g)?.join(' ') ?? ''; - return grouped; + const grouped = `IR${digits}`.match(/.{1,4}/g)?.join(' ') ?? ''; + return prefix ? grouped : grouped.slice(2); +} + +/** + * A span of time, for a prediction's holding time or time past its horizon: under an hour + * `کمتر از 1 ساعت`, under 48 hours rounded hours (`5 ساعت`), then rounded days (`13 روز`). + */ +export function duration(ms: number): string { + const hours = Math.max(0, ms) / HOUR_MS; + if (hours < 1) return `${LESS_THAN} ${unitAmount(1, 'hour')}`; + if (hours < 48) return unitAmount(Math.round(hours), 'hour'); + return unitAmount(Math.round(hours / 24), 'day'); +} + +/** A prediction's horizon as the API sends it: `3d` → `3 روز`, `2w` → `2 هفته`. Unknown input passes through. */ +export function horizon(value: string): string { + const match = /^(\d+)\s*([hdwmy])$/i.exec(value.trim()); + if (!match) return value; + const unit = + HORIZON_UNITS[match[2].toLowerCase() as keyof typeof HORIZON_UNITS]; + return unitAmount(Number(match[1]), unit); +} + +/** Seconds as a countdown clock: `102` → `01:42`. Negative values show `00:00`. */ +export function clock(totalSeconds: number): string { + const seconds = Math.max(0, Math.ceil(totalSeconds)); + const pad = (part: number) => String(part).padStart(2, '0'); + return `${pad(Math.floor(seconds / 60))}:${pad(seconds % 60)}`; } diff --git a/packages/tools/src/format/index.ts b/packages/tools/src/format/index.ts index e4916bd..e6214f2 100644 --- a/packages/tools/src/format/index.ts +++ b/packages/tools/src/format/index.ts @@ -1,5 +1,8 @@ export { + clock, date, + duration, + horizon, iso, latinDigits, number, diff --git a/packages/tools/src/format/types.ts b/packages/tools/src/format/types.ts index 4271649..1cdb22c 100644 --- a/packages/tools/src/format/types.ts +++ b/packages/tools/src/format/types.ts @@ -9,3 +9,6 @@ export type ShebaFormatOptions = { /** Include the leading `IR`. Default `true`; pass `false` for the field after its fixed prefix. */ prefix?: boolean; }; + +/** The Intl units that durations and horizons are written in. */ +export type DurationUnit = 'hour' | 'day' | 'week' | 'month' | 'year'; diff --git a/packages/tools/src/index.ts b/packages/tools/src/index.ts index 0ac5df2..717145e 100644 --- a/packages/tools/src/index.ts +++ b/packages/tools/src/index.ts @@ -1,5 +1,8 @@ export { + clock, date, + duration, + horizon, iso, latinDigits, LOCALE,