forked from CredenceOrg/Credence-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.ts
More file actions
374 lines (343 loc) · 10.9 KB
/
Copy pathformat.ts
File metadata and controls
374 lines (343 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* @file format.ts
* @description Shared formatting utilities for the Credence UI.
*
* All monetary display helpers live here so that Bond.tsx,
* CreateBondFlow.tsx, and any future components share a single
* implementation instead of forking ad-hoc copies.
*
* This is the single source of truth for USDC formatting.
*/
/**
* Number formatter for consistent locale-independent formatting.
*/
const numberFormatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
/**
* Formats a numeric USDC amount for display with "USDC" suffix.
*
* Uses the `en-US` locale to ensure locale-independent thousands
* separators and decimal notation across all user environments.
*
* @example
* formatUsdc(1234.5) // → "1,234.5 USDC"
* formatUsdc(0) // → "0 USDC"
* formatUsdc(1e7) // → "10,000,000 USDC"
*/
export function formatUsdc(amount: number): string {
return `${amount.toLocaleString('en-US', { maximumFractionDigits: 2 })} USDC`
}
/**
* Formats a numeric USDC amount for display in activity timelines and transaction surfaces.
*
* Rejects NaN, Infinity, negative values, and undefined/null before formatting, returning '—'.
* Clamps values exceeding MAX_SAFE_INTEGER to prevent floating-point precision loss.
*
* @example
* formatAmount(1500) // → "1,500 USDC"
* formatAmount(0) // → "0 USDC"
* formatAmount(1234.567) // → "1,234.57 USDC"
* formatAmount(-5) // → "—"
* formatAmount(NaN) // → "—"
*/
export function formatAmount(amount?: number | null): string {
if (amount == null || !Number.isFinite(amount) || amount < 0) {
return '—'
}
const safeAmount = Math.min(amount, Number.MAX_SAFE_INTEGER)
const formatted = safeAmount.toLocaleString('en-US', {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
})
return `${formatted} USDC`
}
/**
* Normalizes user-entered USDC string into a consistent representation.
*
* Converts user input (with or without commas) to a fixed 2-decimal string.
* Returns empty string for invalid input. Clamps negative values to 0.
*
* @example
* normalizeUSDC('1,234.5') // → "1234.50"
* normalizeUSDC('100') // → "100.00"
* normalizeUSDC('not a number') // → ""
* normalizeUSDC('-100') // → "0.00"
*/
export function normalizeUSDC(rawValue: string): string {
const trimmed = rawValue.trim()
if (!trimmed) return ''
const normalized = trimmed.replace(/,/g, '')
const numericValue = Number(normalized)
if (!Number.isFinite(numericValue)) return ''
const clamped = Math.max(0, numericValue)
return clamped.toFixed(2)
}
/**
* Formats a USDC string for display with thousand separators.
*
* Returns invalid text unchanged for manual correction by user.
*
* @example
* formatUSDC('1234.5') // → "1,234.50"
* formatUSDC('abc') // → "abc" (unchanged)
* formatUSDC('') // → ""
*/
export function formatUSDC(rawValue: string): string {
const trimmed = rawValue.trim()
if (!trimmed) return ''
const normalized = trimmed.replace(/,/g, '')
const numericValue = Number(normalized)
if (!Number.isFinite(numericValue)) return rawValue
return numberFormatter.format(numericValue)
}
/**
* UI display formatter for USDC amounts.
* Similar to formatUSDC but optimized for UI display contexts.
*
* @example
* formatUSDCDisplay('1234.5') // → "1,234.50"
* formatUSDCDisplay('1000') // → "1,000.00"
*/
export function formatUSDCDisplay(rawValue: string): string {
const trimmed = rawValue.trim()
if (!trimmed) return ''
const normalized = trimmed.replace(/,/g, '')
const numericValue = Number(normalized)
if (!Number.isFinite(numericValue)) return rawValue
return numberFormatter.format(numericValue)
}
/**
* Sanitizes USDC input by removing invalid characters while preserving valid decimal input.
*
* Removes all non-digit and non-dot characters, trims fractions to 2 decimal places,
* and normalizes leading zeros. Handles multiple dots by using only the first one.
*
* @example
* sanitizeUSDCInput('$1,000.50') // → "1000.50"
* sanitizeUSDCInput('12.345') // → "12.34"
* sanitizeUSDCInput('00123') // → "123"
* sanitizeUSDCInput('0.5') // → "0.5"
* sanitizeUSDCInput('100..00') // → "100.00"
*/
export function sanitizeUSDCInput(nextValue: string): string {
const cleaned = nextValue.replace(/[^\d.]/g, '')
// Return empty string if nothing left after cleaning
if (!cleaned) return ''
// Handle multiple dots by splitting on first dot only
const dotIndex = cleaned.indexOf('.')
if (dotIndex === -1) {
// No dot, just remove leading zeros
const trimmed = cleaned.replace(/^0+(?=\d)/, '')
return trimmed || '0'
}
const whole = cleaned.substring(0, dotIndex)
const fraction = cleaned.substring(dotIndex + 1).replace(/\./g, '') // Remove any additional dots
const trimmedWhole = whole.replace(/^0+(?=\d)/, '') || '0'
const trimmedFraction = fraction.slice(0, 2)
return `${trimmedWhole}.${trimmedFraction}`
}
/**
* Formats a numeric amount with locale-aware separators.
*
* Uses `formatNumber` so thousands and decimal separators match
* the conventions of the target locale, with safe fallback to en-US.
*
* @example
* formatMoney(1234.5, 'en-US') // → "1,234.5"
* formatMoney(1234.5, 'es-ES') // → "1,234.5" or "1234,5"
*/
export function formatMoney(amount: number, locale: string = 'en-US'): string {
return formatNumber(amount, locale, { maximumFractionDigits: 2 })
}
/**
* Default fallback locale used when an invalid or unsupported locale is requested.
*/
export const DEFAULT_LOCALE = 'en-US'
/**
* Validates whether a locale string is supported by the Intl runtime.
*
* @example
* isValidLocale('en-US') // → true
* isValidLocale('invalid-locale') // → false
*/
export function isValidLocale(locale: string): boolean {
if (!locale || typeof locale !== 'string') return false
try {
return Intl.NumberFormat.supportedLocalesOf(locale).length > 0
} catch {
return false
}
}
/**
* Returns the provided locale if valid, or DEFAULT_LOCALE as a fallback.
*/
export function getValidLocale(locale?: string): string {
if (locale && isValidLocale(locale)) {
return locale
}
return DEFAULT_LOCALE
}
/**
* Formats a number according to CLDR rules for the given locale.
*
* Supports negative values, zero, large numbers, and custom options.
* Falls back safely to en-US if the locale is unknown or invalid.
*/
export function formatNumber(
value: number,
locale?: string,
options?: Intl.NumberFormatOptions
): string {
if (!Number.isFinite(value)) {
if (Number.isNaN(value)) return 'NaN'
if (value === Infinity) return '∞'
if (value === -Infinity) return '-∞'
}
const safeLocale = getValidLocale(locale)
try {
return new Intl.NumberFormat(safeLocale, options).format(value)
} catch {
return new Intl.NumberFormat(DEFAULT_LOCALE, options).format(value)
}
}
/**
* Formats a monetary amount with currency code and symbol placement per CLDR rules.
*
* Handles negative currency values, custom precision, and invalid currency codes gracefully.
*/
export function formatCurrency(
value: number,
currency: string = 'USD',
locale?: string,
options?: Intl.NumberFormatOptions
): string {
if (!Number.isFinite(value)) {
if (Number.isNaN(value)) return 'NaN'
if (value === Infinity) return '∞'
if (value === -Infinity) return '-∞'
}
const safeLocale = getValidLocale(locale)
try {
return new Intl.NumberFormat(safeLocale, {
style: 'currency',
currency,
...options,
}).format(value)
} catch {
const fallbackOpts: Intl.NumberFormatOptions = {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
...options,
}
const formattedNum = formatNumber(value, safeLocale, fallbackOpts)
return `${formattedNum} ${currency}`
}
}
/**
* Formats a Date object or timestamp into a locale-aware date string.
*
* Supports 'short', 'medium', and 'long' date styles.
* Uses a default UTC timezone for deterministic test output across environments.
*/
export function formatDate(
dateInput: Date | string | number,
formatStyle: 'short' | 'medium' | 'long' = 'medium',
locale?: string,
timeZone: string = 'UTC'
): string {
const d = dateInput instanceof Date ? dateInput : new Date(dateInput)
if (isNaN(d.getTime())) return 'Invalid Date'
const safeLocale = getValidLocale(locale)
const optionsMap: Record<'short' | 'medium' | 'long', Intl.DateTimeFormatOptions> = {
short: { year: 'numeric', month: 'numeric', day: 'numeric', timeZone },
medium: { year: 'numeric', month: 'short', day: 'numeric', timeZone },
long: { year: 'numeric', month: 'long', day: 'numeric', timeZone },
}
try {
return new Intl.DateTimeFormat(safeLocale, optionsMap[formatStyle] || optionsMap.medium).format(
d
)
} catch {
return new Intl.DateTimeFormat(
DEFAULT_LOCALE,
optionsMap[formatStyle] || optionsMap.medium
).format(d)
}
}
/**
* Formats a Date object or timestamp into a 12-hour or 24-hour time string.
*
* Uses a default UTC timezone for deterministic output.
*/
export function formatTime(
dateInput: Date | string | number,
style: '12h' | '24h' = '12h',
locale?: string,
timeZone: string = 'UTC'
): string {
const d = dateInput instanceof Date ? dateInput : new Date(dateInput)
if (isNaN(d.getTime())) return 'Invalid Time'
const safeLocale = getValidLocale(locale)
const hour12 = style === '12h'
const options: Intl.DateTimeFormatOptions = {
hour: 'numeric',
minute: '2-digit',
second: '2-digit',
hour12,
timeZone,
}
try {
return new Intl.DateTimeFormat(safeLocale, options).format(d)
} catch {
return new Intl.DateTimeFormat(DEFAULT_LOCALE, options).format(d)
}
}
/**
* Formats a fractional or whole number as a percentage matching CLDR rules.
*/
export function formatPercent(
value: number,
locale?: string,
options?: Intl.NumberFormatOptions
): string {
if (!Number.isFinite(value)) {
if (Number.isNaN(value)) return 'NaN'
if (value === Infinity) return '∞'
if (value === -Infinity) return '-∞'
}
const safeLocale = getValidLocale(locale)
try {
return new Intl.NumberFormat(safeLocale, {
style: 'percent',
...options,
}).format(value)
} catch {
return new Intl.NumberFormat(DEFAULT_LOCALE, {
style: 'percent',
...options,
}).format(value)
}
}
/**
* Formats a relative time offset matching CLDR relative time conventions.
*/
export function formatRelativeTime(
value: number,
unit: Intl.RelativeTimeFormatUnit,
locale?: string,
options?: Intl.RelativeTimeFormatOptions
): string {
if (!Number.isFinite(value)) return ''
const safeLocale = getValidLocale(locale)
try {
return new Intl.RelativeTimeFormat(safeLocale, options).format(value, unit)
} catch {
try {
return new Intl.RelativeTimeFormat(DEFAULT_LOCALE, options).format(value, unit)
} catch {
return `${value} ${unit}`
}
}
}