UNPKG

company-cafeteria-shared-demo

Version:

Package partagé pour l'écosystème Cafétéria Entreprise

304 lines 9.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatPrice = formatPrice; exports.formatPriceCompact = formatPriceCompact; exports.formatPercentage = formatPercentage; exports.formatDate = formatDate; exports.formatDateTime = formatDateTime; exports.formatRelativeTime = formatRelativeTime; exports.formatRelativeDate = formatRelativeDate; exports.formatDuration = formatDuration; exports.formatProperName = formatProperName; exports.formatEmailMasked = formatEmailMasked; exports.formatPhoneNumber = formatPhoneNumber; exports.formatFileSize = formatFileSize; exports.formatNumber = formatNumber; exports.formatRating = formatRating; exports.formatPreparationTime = formatPreparationTime; exports.formatAddress = formatAddress; exports.formatStatusWithIcon = formatStatusWithIcon; exports.formatList = formatList; exports.formatPhysicalDistance = formatPhysicalDistance; exports.formatConfidence = formatConfidence; exports.formatNutritionalValue = formatNutritionalValue; exports.truncateText = truncateText; exports.formatSlug = formatSlug; const date_fns_1 = require("date-fns"); const locale_1 = require("date-fns/locale"); /** * Formatage de prix en euros */ function formatPrice(price, options) { const { showCurrency = true, decimals = 2 } = options ?? {}; const formatted = price.toFixed(decimals); return showCurrency ? `${formatted} €` : formatted; } /** * Formatage de prix avec symbole approprié selon la valeur */ function formatPriceCompact(price) { if (price === 0) return 'Gratuit'; if (price < 0) return `- ${formatPrice(Math.abs(price))}`; return formatPrice(price); } /** * Formatage de pourcentage */ function formatPercentage(value, decimals = 0) { return `${value.toFixed(decimals)} %`; } /** * Formatage de date en français */ function formatDate(date, pattern = 'dd/MM/yyyy') { try { const dateObj = typeof date === 'string' ? (0, date_fns_1.parseISO)(date) : date; if (!(0, date_fns_1.isValid)(dateObj)) { return 'Date invalide'; } return (0, date_fns_1.format)(dateObj, pattern, { locale: locale_1.fr }); } catch { return 'Date invalide'; } } /** * Formatage de date et heure */ function formatDateTime(date) { return formatDate(date, 'dd/MM/yyyy à HH:mm'); } /** * Formatage de temps relatif (il y a X minutes) */ function formatRelativeTime(date) { try { const dateObj = typeof date === 'string' ? (0, date_fns_1.parseISO)(date) : date; if (!(0, date_fns_1.isValid)(dateObj)) { return 'Date invalide'; } return (0, date_fns_1.formatDistance)(dateObj, new Date(), { addSuffix: true, locale: locale_1.fr }); } catch { return 'Date invalide'; } } /** * Formatage de temps relatif avec contexte (aujourd'hui, hier, etc.) */ function formatRelativeDate(date) { try { const dateObj = typeof date === 'string' ? (0, date_fns_1.parseISO)(date) : date; if (!(0, date_fns_1.isValid)(dateObj)) { return 'Date invalide'; } return (0, date_fns_1.formatRelative)(dateObj, new Date(), { locale: locale_1.fr }); } catch { return 'Date invalide'; } } /** * Formatage de durée en minutes/heures */ function formatDuration(minutes) { if (minutes < 60) { return `${minutes} min`; } const hours = Math.floor(minutes / 60); const remainingMinutes = minutes % 60; if (remainingMinutes === 0) { return `${hours}h`; } return `${hours}h${remainingMinutes.toString().padStart(2, '0')}`; } /** * Formatage de nom propre (première lettre en majuscule) */ function formatProperName(name) { return name .toLowerCase() .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(' '); } /** * Formatage d'email (masquage partiel) */ function formatEmailMasked(email) { const [localPart, domain] = email.split('@'); if (!domain || !localPart) return email; const maskedLocal = localPart.length > 2 ? localPart[0] + '*'.repeat(localPart.length - 2) + localPart[localPart.length - 1] : localPart; return `${maskedLocal}@${domain}`; } /** * Formatage de numéro de téléphone français */ function formatPhoneNumber(phone) { // Supprime tous les caractères non numériques const cleaned = phone.replace(/\D/g, ''); // Format français: +33 X XX XX XX XX ou 0X XX XX XX XX if (cleaned.startsWith('33') && cleaned.length === 11) { return `+33 ${cleaned[2]} ${cleaned.slice(3, 5)} ${cleaned.slice(5, 7)} ${cleaned.slice(7, 9)} ${cleaned.slice(9)}`; } if (cleaned.startsWith('0') && cleaned.length === 10) { return `${cleaned.slice(0, 2)} ${cleaned.slice(2, 4)} ${cleaned.slice(4, 6)} ${cleaned.slice(6, 8)} ${cleaned.slice(8)}`; } return phone; // Retourne original si format non reconnu } /** * Formatage de taille de fichier */ function formatFileSize(bytes) { const sizes = ['octets', 'Ko', 'Mo', 'Go']; if (bytes === 0) return '0 octet'; const i = Math.floor(Math.log(bytes) / Math.log(1024)); const size = bytes / Math.pow(1024, i); return `${size.toFixed(i === 0 ? 0 : 1)} ${sizes[i]}`; } /** * Formatage de nombre avec séparateurs de milliers */ function formatNumber(num, decimals = 0) { return new Intl.NumberFormat('fr-FR', { minimumFractionDigits: decimals, maximumFractionDigits: decimals }).format(num); } /** * Formatage de note (étoiles) */ function formatRating(rating, maxRating = 5) { const fullStars = Math.floor(rating); const hasHalfStar = rating - fullStars >= 0.5; const emptyStars = maxRating - fullStars - (hasHalfStar ? 1 : 0); return '★'.repeat(fullStars) + (hasHalfStar ? '⭐' : '') + '☆'.repeat(emptyStars); } /** * Formatage de temps de préparation */ function formatPreparationTime(minutes) { if (minutes < 1) return 'Instantané'; if (minutes === 1) return '1 minute'; if (minutes < 60) return `${minutes} minutes`; const hours = Math.floor(minutes / 60); const remainingMinutes = minutes % 60; if (remainingMinutes === 0) { return hours === 1 ? '1 heure' : `${hours} heures`; } return `${hours}h${remainingMinutes.toString().padStart(2, '0')}`; } /** * Formatage d'adresse */ function formatAddress(address) { const parts = [ address.street, address.postalCode && address.city ? `${address.postalCode} ${address.city}` : address.city, address.country && address.country !== 'France' ? address.country : undefined ].filter(Boolean); return parts.join(', '); } /** * Formatage de statut avec icône */ function formatStatusWithIcon(status, icons) { const icon = icons[status] || ''; const formattedStatus = status.replace('_', ' ').toLowerCase(); const capitalizedStatus = formattedStatus.charAt(0).toUpperCase() + formattedStatus.slice(1); return icon ? `${icon} ${capitalizedStatus}` : capitalizedStatus; } /** * Formatage de liste (avec virgules et "et") */ function formatList(items, conjunction = 'et') { if (items.length === 0) return ''; if (items.length === 1) return items[0] || ''; if (items.length === 2) return `${items[0] || ''} ${conjunction} ${items[1] || ''}`; const lastItem = items[items.length - 1]; const otherItems = items.slice(0, -1); if (!lastItem) return ''; return `${otherItems.join(', ')} ${conjunction} ${lastItem}`; } /** * Formatage de distance physique */ function formatPhysicalDistance(meters) { if (meters < 1000) { return `${Math.round(meters)} m`; } const kilometers = meters / 1000; if (kilometers < 10) { return `${kilometers.toFixed(1)} km`; } return `${Math.round(kilometers)} km`; } /** * Formatage de score de confiance IA */ function formatConfidence(confidence) { const percentage = Math.round(confidence * 100); if (percentage >= 90) return `${percentage}% (Très fiable)`; if (percentage >= 75) return `${percentage}% (Fiable)`; if (percentage >= 60) return `${percentage}% (Modéré)`; return `${percentage}% (Faible)`; } /** * Formatage de nutritions (calories, protéines, etc.) */ function formatNutritionalValue(value, unit) { if (value === 0) return `0 ${unit}`; if (value < 1) return `${value.toFixed(1)} ${unit}`; return `${Math.round(value)} ${unit}`; } /** * Raccourcit un texte avec des points de suspension */ function truncateText(text, maxLength) { if (text.length <= maxLength) return text; // Coupe au dernier espace avant la limite pour éviter de couper un mot const truncated = text.substring(0, maxLength); const lastSpace = truncated.lastIndexOf(' '); if (lastSpace > maxLength * 0.7) { return truncated.substring(0, lastSpace) + '...'; } return truncated + '...'; } /** * Formate un slug URL */ function formatSlug(text) { return text .toLowerCase() .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') // Supprime les accents .replace(/[^a-z0-9\s-]/g, '') // Garde seulement lettres, chiffres, espaces et tirets .replace(/\s+/g, '-') // Remplace espaces par tirets .replace(/-+/g, '-') // Supprime tirets multiples .replace(/^-|-$/g, ''); // Supprime tirets au début/fin } //# sourceMappingURL=formatting.js.map