import { Component, input, output, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; /** * Drag-and-drop and file-picker area that validates files by extension and size. * With `keepSelection` it keeps and emits the whole selected list; without it, * it emits only each batch of newly accepted files and keeps nothing. */ @Component({ imports: [MatButtonModule, MatIconModule], selector: 'app-file-dropzone', styleUrl: './file-dropzone.scss', templateUrl: './file-dropzone.html', }) export class FileDropzone { readonly accept = input.required(); readonly multiple = input(true); readonly keepSelection = input(true); readonly filesChange = output(); readonly files = signal([]); readonly fileMessages = signal([]); readonly isDragOver = signal(false); private dragDepth = 0; get allowedExtensions(): Set { return new Set(this.accept().map((extension) => extension.toLowerCase())); } get acceptAttribute(): string { return this.accept().map((extension) => `.${extension}`).join(','); } get formatsLabel(): string { return this.accept().map((extension) => extension.toUpperCase()).join(' · '); } onFileSelection(event: Event): void { const input = event.target as HTMLInputElement; this.addFiles(input.files ? Array.from(input.files) : []); input.value = ''; } onDragEnter(event: DragEvent): void { event.preventDefault(); this.dragDepth++; this.isDragOver.set(true); } onDragOver(event: DragEvent): void { event.preventDefault(); if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy'; } onDragLeave(event: DragEvent): void { event.preventDefault(); this.dragDepth = Math.max(0, this.dragDepth - 1); if (this.dragDepth === 0) this.isDragOver.set(false); } onDrop(event: DragEvent): void { event.preventDefault(); this.dragDepth = 0; this.isDragOver.set(false); this.addFiles(event.dataTransfer?.files ? Array.from(event.dataTransfer.files) : []); } removeFile(fileToRemove: File): void { this.files.update((files) => files.filter((file) => file !== fileToRemove)); this.filesChange.emit(this.files()); } formatFileSize(size: number): string { if (size < 1024) return `${size} bytes`; const units = ['KB', 'MB', 'GB']; let value = size / 1024; let unit = 0; while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; } return `${new Intl.NumberFormat('es-MX', { maximumFractionDigits: 1 }).format(value)} ${units[unit]}`; } fileIcon(file: File): string { const extension = this.extensionOf(file.name); if (extension === 'pdf') return 'picture_as_pdf'; if (extension === 'csv' || extension === 'xlsx') return 'table_chart'; return 'data_object'; } private addFiles(incomingFiles: File[]): void { const messages: string[] = []; const kept = this.keepSelection() && this.multiple() ? [...this.files()] : []; const accepted = [...kept]; for (const file of incomingFiles) { const extension = this.extensionOf(file.name); if (!this.allowedExtensions.has(extension)) { messages.push(`${file.name} no fue agregado. Formato no compatible.`); continue; } if (file.size === 0) { messages.push(`${file.name} no fue agregado. El archivo está vacío.`); continue; } if (accepted.some((existing) => existing.name === file.name && existing.size === file.size)) { messages.push(`${file.name} ya se encuentra seleccionado.`); continue; } if (!this.multiple()) { accepted.length = 0; } accepted.push(file); if (!this.multiple()) break; } this.fileMessages.set(messages); if (this.keepSelection()) { this.files.set(accepted); this.filesChange.emit(accepted); } else if (accepted.length > kept.length) { this.filesChange.emit(accepted.slice(kept.length)); } } private extensionOf(fileName: string): string { const finalDot = fileName.lastIndexOf('.'); return finalDot >= 0 ? fileName.slice(finalDot + 1).toLowerCase() : ''; } }