utils.ts
1,789 bytes
| 1 | import { clsx, type ClassValue } from 'clsx'; |
|---|---|
| 2 | import { twMerge } from 'tailwind-merge'; |
| 3 | |
| 4 | /** shadcn/ui class combiner: clsx semantics + Tailwind conflict resolution. */ |
| 5 | export function cn(...inputs: ClassValue[]): string { |
| 6 | return twMerge(clsx(inputs)); |
| 7 | } |
| 8 | |
| 9 | /** Format a USD cost with adaptive precision (fractions of a cent stay legible). */ |
| 10 | export function formatUsd(amount: number): string { |
| 11 | if (amount === 0) return '$0.00'; |
| 12 | if (amount < 0.01) return `$${amount.toFixed(4)}`; |
| 13 | if (amount < 1) return `$${amount.toFixed(3)}`; |
| 14 | return `$${amount.toFixed(2)}`; |
| 15 | } |
| 16 | |
| 17 | export function formatTokens(n: number): string { |
| 18 | if (n < 1000) return String(n); |
| 19 | if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`; |
| 20 | return `${(n / 1_000_000).toFixed(1)}M`; |
| 21 | } |
| 22 | |
| 23 | export function formatLatency(ms: number): string { |
| 24 | if (ms < 1000) return `${Math.round(ms)}ms`; |
| 25 | return `${(ms / 1000).toFixed(1)}s`; |
| 26 | } |
| 27 | |
| 28 | export function formatDuration(ms: number): string { |
| 29 | const s = Math.round(ms / 1000); |
| 30 | if (s < 60) return `${s}s`; |
| 31 | const m = Math.floor(s / 60); |
| 32 | return `${m}m ${s % 60}s`; |
| 33 | } |
| 34 | |
| 35 | export function formatRelativeTime(date: Date | string): string { |
| 36 | const d = typeof date === 'string' ? new Date(date) : date; |
| 37 | const diff = Date.now() - d.getTime(); |
| 38 | const mins = Math.floor(diff / 60_000); |
| 39 | if (mins < 1) return 'just now'; |
| 40 | if (mins < 60) return `${mins}m ago`; |
| 41 | const hours = Math.floor(mins / 60); |
| 42 | if (hours < 24) return `${hours}h ago`; |
| 43 | const days = Math.floor(hours / 24); |
| 44 | if (days < 30) return `${days}d ago`; |
| 45 | return d.toLocaleDateString(); |
| 46 | } |
| 47 | |
| 48 | /** Truncate to a max length (including the trailing "..."). */ |
| 49 | export function truncate(s: string, max: number): string { |
| 50 | if (s.length <= max) return s; |
| 51 | return `${s.slice(0, Math.max(0, max - 3))}...`; |
| 52 | } |
| 53 | |