All files / lib/utils utils.ts

100% Statements 16/16
100% Branches 8/8
100% Functions 9/9
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            1421x     22x         22x           22x             22x         22x             278x         186x         59x         5x 2x   2x     5x         7x 7x         40x          
import {clsx, type ClassValue} from "clsx";
import {twMerge} from "tailwind-merge";
import type {Metric, MetricFormat} from "@/types/dashboard";
 
/** Merge Tailwind classes without duplicating conflicting utilities. */
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
 
const compactNumber = new Intl.NumberFormat("en-US", {
  notation: "compact",
  maximumFractionDigits: 1,
});
 
const currency = new Intl.NumberFormat("en-US", {
  currency: "USD",
  maximumFractionDigits: 0,
  style: "currency",
});
 
const compactCurrency = new Intl.NumberFormat("en-US", {
  currency: "USD",
  maximumFractionDigits: 1,
  notation: "compact",
  style: "currency",
});
 
const percent = new Intl.NumberFormat("en-US", {
  maximumFractionDigits: 1,
  style: "percent",
});
 
const wholePercent = new Intl.NumberFormat("en-US", {
  maximumFractionDigits: 0,
  style: "percent",
});
 
/** Format a currency value for dense dashboard surfaces. */
export function formatCurrency(value: number, compact = false) {
  return compact ? compactCurrency.format(value) : currency.format(value);
}
 
/** Format a number using compact dashboard notation. */
export function formatNumber(value: number) {
  return compactNumber.format(value);
}
 
/** Format decimal values as percentages. */
export function formatPercent(value: number, whole = false) {
  return (whole ? wholePercent : percent).format(value);
}
 
/** Format a KPI value using the metric's declared presentation format. */
export function formatMetricValue(metric: Pick<Metric, "format" | "value">) {
  const formatters: Record<MetricFormat, (value: number) => string> = {
    currency: (value) => formatCurrency(value, value >= 100000),
    number: formatNumber,
    percentage: (value) => formatPercent(value / 100),
  };
 
  return formatters[metric.format](metric.value);
}
 
/** Format a signed trend delta for KPI cards. */
export function formatDelta(value: number) {
  const prefix = value > 0 ? "+" : "";
  return `${prefix}${value.toFixed(1)}%`;
}
 
/** Format ISO dates for compact table cells. */
export function formatDate(value: string) {
  return new Intl.DateTimeFormat("en-US", {
    day: "2-digit",
    month: "short",
  }).format(new Date(value));
}