import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" import {VIEW_DECIMAL_POINT} from "@/const/common.const"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } export const formatKoreanBaseDate = (date = new Date()) => { const year = String(date.getFullYear()).slice(-2); return `${year}년 ${date.getMonth() + 1}월 ${date.getDate()}일 기준`; }; /** * 다양한 형식의 값을 숫자로 파싱합니다. * - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리 * - null/undefined/빈문자열/"−" 등은 null 반환 * - 유한하지 않은 숫자는 null 반환 */ export function parseNumber( value: unknown, options?: { allowComma?: boolean; // 기본값: true allowPercent?: boolean; // 기본값: true allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함) } ): number | null { const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {}; if (value === null || value === undefined) return null; if (typeof value === "number") { return Number.isFinite(value) ? value : null; } if (typeof value === "string") { let s = value.trim(); if (s === "" || s === "-" || s === "−") return null; s = s.replaceAll("(", ""); s = s.replaceAll(")", ""); if (allowComma) s = s.replaceAll(",", ""); if (allowPercent) s = s.replaceAll("%", ""); if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스 const n = Number(s); return Number.isFinite(n) ? n : null; } return null; } export const roundNumber = (num: number|null, decimalPoint?: number) => { if(num == null) return null; decimalPoint ??= VIEW_DECIMAL_POINT; const factor = 10 ** decimalPoint; return Math.round(num * factor) / factor; }; export const downloadFile = (blob: Blob, filename: string) => { const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }; export const downloadBase64File = (base64: string, filename: string) => { const byteString = atob(base64); const arrayBuffer = new ArrayBuffer(byteString.length); const uint8Array = new Uint8Array(arrayBuffer); for (let i = 0; i < byteString.length; i++) { uint8Array[i] = byteString.charCodeAt(i); } const blob = new Blob([arrayBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }); downloadFile(blob, filename); }; export type CompressImageFileOptions = { maxWidth?: number; maxHeight?: number; quality?: number; mimeType?: "image/jpeg" | "image/webp" | "image/png"; skipBelowBytes?: number; }; const getCompressedImageName = (fileName: string, mimeType: string) => { const extension = mimeType === "image/png" ? "png" : mimeType === "image/webp" ? "webp" : "jpg"; const baseName = fileName.replace(/\.[^.]+$/, ""); return `${baseName || "image"}.${extension}`; }; const loadImageElement = (file: File) => { return new Promise((resolve, reject) => { const url = URL.createObjectURL(file); const image = new Image(); image.onload = () => { URL.revokeObjectURL(url); resolve(image); }; image.onerror = () => { URL.revokeObjectURL(url); reject(new Error("Failed to load image.")); }; image.src = url; }); }; const canvasToBlob = (canvas: HTMLCanvasElement, mimeType: string, quality: number) => { return new Promise((resolve, reject) => { canvas.toBlob( (blob) => { if (blob) resolve(blob); else reject(new Error("Failed to compress image.")); }, mimeType, quality ); }); }; export const compressImageFile = async ( file: File, options: CompressImageFileOptions = {} ) => { if (!file.type.startsWith("image/") || file.type === "image/svg+xml" || file.type === "image/gif") { return file; } const { maxWidth = 1600, maxHeight = 1600, quality = 0.75, mimeType = "image/jpeg", skipBelowBytes = 500 * 1024, } = options; if (file.size <= skipBelowBytes) return file; try { const image = await loadImageElement(file); const ratio = Math.min(maxWidth / image.naturalWidth, maxHeight / image.naturalHeight, 1); const width = Math.max(1, Math.round(image.naturalWidth * ratio)); const height = Math.max(1, Math.round(image.naturalHeight * ratio)); const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); if (!ctx) return file; canvas.width = width; canvas.height = height; if (mimeType === "image/jpeg") { ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, width, height); } ctx.drawImage(image, 0, 0, width, height); const blob = await canvasToBlob(canvas, mimeType, quality); if (blob.size >= file.size) return file; return new File([blob], getCompressedImageName(file.name, mimeType), { type: blob.type || mimeType, lastModified: Date.now(), }); } catch { return file; } }; export const compressImageFiles = ( files: File[], options?: CompressImageFileOptions ) => Promise.all(files.map((file) => compressImageFile(file, options)));