utils.ts
Overview
The utils.ts file provides a set of utility functions designed to simplify common tasks related to CSS class name management and data size formatting. This file primarily offers:
cn: A function to merge and conditionally concatenate CSS class names using the popularclsxandtailwind-mergelibraries, facilitating seamless integration with Tailwind CSS.formatBytes: A function to convert raw byte values into human-readable strings, supporting both standard and binary size units and customizable decimal precision.
These utilities are generally used throughout the application to maintain consistency in styling and data representation.
Functions
cn(...inputs: ClassValue[]): string
Description
Combines multiple CSS class values into a single string with proper merging and conflict resolution tailored for Tailwind CSS classes.
Parameters
...inputs: ClassValue[]
A variadic list of class values. EachClassValuecan be a string, object, or array accepted by theclsxlibrary, allowing conditional and complex class name constructions.
Returns
string
A merged and optimized string of class names suitable for use in JSX or HTML elements.
Usage Example
import { cn } from './utils';
const buttonClass = cn(
'btn',
isPrimary && 'btn-primary',
isDisabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-blue-500'
);
// buttonClass might output: "btn btn-primary hover:bg-blue-500"
Implementation Details
Uses
clsxto normalize and conditionally build a class name string.Passes the result to
twMergeto intelligently merge Tailwind CSS classes, avoiding conflicts like multiple background colors or paddings.This function abstracts away the complexity of managing dynamic class names in Tailwind environments.
formatBytes(bytes: number, opts?: { decimals?: number; sizeType?: 'accurate' | 'normal' }): string
Description
Converts a byte count into a human-readable string with appropriate size units, supporting both standard decimal units (KB, MB) and binary IEC units (KiB, MiB).
Parameters
bytes: number
The size in bytes to format.opts?: { decimals?: number; sizeType?: 'accurate' | 'normal' }(optional)
An options object with the following properties:decimals?: number
Number of decimal places to display. Defaults to0.sizeType?: 'accurate' | 'normal'
Determines whether to use binary IEC units (e.g., KiB, MiB) when'accurate'or decimal units (KB, MB) when'normal'. Defaults to'normal'.
Returns
string
A formatted string representing the size with the chosen units.
Usage Example
import { formatBytes } from './utils';
console.log(formatBytes(1024));
// Output: "1 KB"
console.log(formatBytes(1024, { decimals: 2, sizeType: 'accurate' }));
// Output: "1.00 KiB"
console.log(formatBytes(123456789, { decimals: 1 }));
// Output: "117.7 MB"
Implementation Details
Defines two arrays for size labels: one for normal SI units (
Bytes,KB,MB, etc.) and one for accurate binary units (Bytes,KiB,MiB, etc.).Uses logarithms to calculate the appropriate size index based on powers of 1024.
Defaults to returning
'0 Byte'for zero input.Uses
toFixed(decimals)to format the number with the specified decimal precision.Falls back to
'Bytes'if the index exceeds the defined arrays, ensuring no runtime errors.
Interaction with Other Parts of the System
cnFunction
This function integrates with the UI layer, helping components handle dynamic styling efficiently. It relies on external dependencies:clsxfor conditional class name concatenation.tailwind-mergefor resolving Tailwind CSS class conflicts.
It is typically imported and used wherever class names are dynamically constructed for React components or other frontend elements.
formatBytesFunction
Used in places where file sizes or data amounts need to be displayed to users in a readable format, such as file upload dialogs, storage usage indicators, or download progress displays.
Mermaid Diagram
flowchart TD
A[cn(...inputs: ClassValue[])] --> B[clsx(inputs)]
B --> C[twMerge(classString)]
C --> D[Returns merged class string]
E[formatBytes(bytes, opts?)] --> F{bytes === 0?}
F -- Yes --> G["Returns '0 Byte'"]
F -- No --> H[Calculate index i = floor(log(bytes)/log(1024))]
H --> I[Divide bytes by 1024^i and format with decimals]
I --> J{opts.sizeType === 'accurate'?}
J -- Yes --> K[Use accurateSizes[i]]
J -- No --> L[Use sizes[i]]
K & L --> M[Return formatted string]
Summary
The utils.ts file provides essential helper functions that enhance styling management and data size formatting within the application. By abstracting common patterns into reusable utilities, it promotes cleaner code and consistent behavior across UI components and data presentation layers. The use of well-maintained external libraries (clsx and tailwind-merge) combined with straightforward algorithms (logarithmic scaling for byte formatting) makes these utilities reliable and performant.