Skip to content

Utils

@granit/utils provides shared utility functions used across all Granit frontend applications. Class merging with Tailwind conflict resolution, locale-aware number formatting, and date formatting powered by date-fns.

Peer dependencies: clsx, tailwind-merge, date-fns

import { cn, formatDate, formatNumber } from '@granit/utils';

No provider or initialization required — all functions are pure and stateless.

Merges CSS class names with Tailwind conflict resolution. Combines clsx (conditional classes) with tailwind-merge (last-wins for conflicting utilities).

function cn(...inputs: ClassValue[]): string;
cn('px-4 py-2', 'px-6'); // "py-2 px-6"
cn('text-sm', isActive && 'bg-primary'); // "text-sm bg-primary" (when active)
cn('rounded-md', className); // safe to pass undefined className

Formats a number using Intl.NumberFormat with the en-US locale.

function formatNumber(value: number, opts?: Intl.NumberFormatOptions): string;
formatNumber(1234567); // "1,234,567"
formatNumber(0.125, { style: 'percent' }); // "12.5%"
formatNumber(99.956, { maximumFractionDigits: 1 }); // "100.0"

Formats a date to long readable form using date-fns format PPP.

function formatDate(date: string | Date): string;
formatDate('2026-02-27'); // "February 27, 2026"
formatDate(new Date()); // "March 13, 2026"

Formats a date with time using date-fns format PPP HH:mm:ss.

function formatDateTime(date: string | Date): string;
formatDateTime('2026-02-27T14:30:00'); // "February 27, 2026 14:30:00"

Formats a date as relative time using date-fns formatDistanceToNow.

function formatTimeAgo(date: string | Date): string;
formatTimeAgo(twoHoursAgo); // "about 2 hours ago"
formatTimeAgo(yesterday); // "1 day ago"

Calculates a percentage rounded to the nearest integer. Returns 0 when total is 0 (no division by zero).

function calculatePercentage(value: number, total: number): number;
calculatePercentage(25, 100); // 25
calculatePercentage(1, 3); // 33
calculatePercentage(5, 0); // 0
CategoryKey exportsPackage
CSScn()@granit/utils
Number formattingformatNumber(), calculatePercentage()@granit/utils
Date formattingformatDate(), formatDateTime(), formatTimeAgo()@granit/utils