import { type ClassValue, clsx } from "clsx" import { twMerge } from "tailwind-merge" /** * Combines multiple class names into a single string, handling conditional classes * and merging Tailwind CSS classes properly. * * @param inputs - Class names or conditional class expressions * @returns Merged class string * * @example * // Basic usage * cn("text-red-500", "bg-blue-500") * // => "text-red-500 bg-blue-500" * * @example * // With conditionals * cn("text-white", isActive && "bg-blue-500", !isActive && "bg-gray-500") * // => "text-white bg-blue-500" or "text-white bg-gray-500" */ export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } /** * Formats a date to a localized string * * @param date - Date to format * @param locale - Locale to use for formatting (defaults to 'fr-FR') * @returns Formatted date string */ export function formatDate(date: Date, locale = "fr-FR"): string { return new Intl.DateTimeFormat(locale, { day: "numeric", month: "long", year: "numeric", }).format(date) } /** * Truncates a string to a specified length and adds an ellipsis * * @param text - Text to truncate * @param length - Maximum length before truncation * @returns Truncated text with ellipsis if needed */ export function truncateText(text: string, length: number): string { if (text.length <= length) return text return text.slice(0, length) + "..." } /** * Debounces a function to limit how often it can be called * * @param fn - Function to debounce * @param delay - Delay in milliseconds * @returns Debounced function */ export function debounce any>(fn: T, delay: number): (...args: Parameters) => void { let timeoutId: NodeJS.Timeout return (...args: Parameters) => { clearTimeout(timeoutId) timeoutId = setTimeout(() => fn(...args), delay) } } /** * Generates a random ID string * * @param length - Length of the ID (default: 8) * @returns Random ID string */ export function generateId(length = 8): string { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" let result = "" for (let i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)) } return result } /** * Checks if the current client is on a mobile device * * @returns Boolean indicating if the client is on a mobile device */ export function isMobileDevice(): boolean { if (typeof window === "undefined") return false return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) } /** * Converts a hex color to RGBA * * @param hex - Hex color code * @param alpha - Alpha value (0-1) * @returns RGBA color string */ export function hexToRgba(hex: string, alpha = 1): string { // Remove # if present hex = hex.replace("#", "") // Parse the hex values const r = Number.parseInt(hex.substring(0, 2), 16) const g = Number.parseInt(hex.substring(2, 4), 16) const b = Number.parseInt(hex.substring(4, 6), 16) // Return rgba value return `rgba(${r}, ${g}, ${b}, ${alpha})` } /** * Capitalizes the first letter of each word in a string * * @param str - String to capitalize * @returns Capitalized string */ export function capitalizeWords(str: string): string { return str .split(" ") .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join(" ") } /** * Formats a number as currency * * @param amount - Amount to format * @param currency - Currency code (default: 'EUR') * @param locale - Locale to use for formatting (default: 'fr-FR') * @returns Formatted currency string */ export function formatCurrency(amount: number, currency = "EUR", locale = "fr-FR"): string { return new Intl.NumberFormat(locale, { style: "currency", currency, }).format(amount) } /** * Safely access nested object properties without throwing errors * * @param obj - Object to access * @param path - Path to the property (dot notation) * @param defaultValue - Default value if property doesn't exist * @returns Property value or default value */ export function getNestedValue(obj: Record, path: string, defaultValue: T): T { const keys = path.split(".") let result = obj for (const key of keys) { if (result === undefined || result === null || !result.hasOwnProperty(key)) { return defaultValue } result = result[key] } return result as unknown as T } /** * Removes accents from a string * * @param str - String with accents * @returns String without accents */ export function removeAccents(str: string): string { return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "") } /** * Creates a slug from a string * * @param str - String to convert to slug * @returns Slug string */ export function slugify(str: string): string { return removeAccents(str) .toLowerCase() .replace(/[^\w\s-]/g, "") .replace(/[\s_-]+/g, "-") .replace(/^-+|-+$/g, "") }