Guía de TypeScript
Dropup está escrito en TypeScript y proporciona definiciones de tipos comprehensivas.
Uso básico
import { useDropup } from '@samithahansaka/dropup';
import type { DropupFile, UseDropupOptions } from '@samithahansaka/dropup';
function Uploader() {
const { files, actions, state } = useDropup({
accept: 'image/*',
maxSize: 10 * 1024 * 1024,
});
// files es DropupFile[]
// actions es DropupActions
// state es DropupState
return (
// ...
);
}
Importando tipos
import type {
// Tipos principales
DropupFile,
DropupState,
DropupActions,
DropupError,
// Opciones y configuración
UseDropupOptions,
UploadConfig,
CustomUploader,
ValidationRule,
// Tipos de estado
FileStatus,
DropupStatus,
// Tipo de retorno
UseDropupReturn,
// Validación
ValidationError,
} from '@samithahansaka/dropup';
Opciones con tipos
const options: UseDropupOptions = {
accept: ['image/*', 'application/pdf'],
maxSize: 10 * 1024 * 1024,
maxFiles: 5,
upload: {
url: '/api/upload',
method: 'POST',
headers: {
'Authorization': 'Bearer token',
},
},
onFilesAdded: (files: DropupFile[]) => {
console.log('Agregados:', files);
},
onUploadComplete: (file: DropupFile, response: unknown) => {
console.log('Completado:', file.uploadedUrl);
},
customRules: [
(file: File): boolean | string => {
if (file.name.length > 100) {
return 'Nombre de archivo muy largo';
}
return true;
},
],
};
const { files, actions, state } = useDropup(options);
Callbacks con tipos seguros
import type { DropupFile, DropupError, ValidationError } from '@samithahansaka/dropup';
const options: UseDropupOptions = {
onFilesAdded: (files: DropupFile[]) => {
files.forEach(file => {
console.log(file.id); // string
console.log(file.name); // string
console.log(file.size); // number
console.log(file.status); // FileStatus
});
},
onValidationError: (errors: ValidationError[]) => {
errors.forEach(({ file, errors }) => {
console.log(file.name); // File.name
console.log(errors); // string[]
});
},
onUploadError: (file: DropupFile, error: DropupError) => {
console.log(error.code); // string
console.log(error.message); // string
console.log(error.cause); // Error | undefined
},
};
Tipo de cargador personalizado
import type { CustomUploader, UploadOptions, UploadResult } from '@samithahansaka/dropup';
const myUploader: CustomUploader = async (
file, // DropupFile
options // UploadOptions
): Promise<UploadResult> => {
const { signal, onProgress } = options;
// Lógica de carga aquí...
onProgress(50);
return {
url: 'https://example.com/uploaded-file',
response: { id: '123' },
};
};
useDropup({
upload: myUploader,
});
Tipo de reglas de validación
import type { ValidationRule } from '@samithahansaka/dropup';
// Regla síncrona
const checkFilename: ValidationRule = (file: File) => {
if (file.name.includes('draft')) {
return 'No se permiten archivos de borrador';
}
return true;
};
// Regla asíncrona
const checkServer: ValidationRule = async (file: File) => {
const exists = await fetch(`/api/check?name=${file.name}`);
if (await exists.json()) {
return 'El archivo ya existe';
}
return true;
};
useDropup({
customRules: [checkFilename, checkServer],
});
Props genéricos de zona de soltar
import { useDropup } from '@samithahansaka/dropup';
function TypedDropZone() {
const { getDropProps, getInputProps } = useDropup();
// Especificar el tipo de elemento para getDropProps
const dropProps = getDropProps<HTMLDivElement>({
className: 'dropzone',
'data-testid': 'upload-zone',
});
return (
<div {...dropProps}>
<input {...getInputProps()} />
</div>
);
}
Type guards para estado de archivo
import type { DropupFile, FileStatus } from '@samithahansaka/dropup';
// Funciones type guard
function isUploading(file: DropupFile): file is DropupFile & { status: 'uploading' } {
return file.status === 'uploading';
}
function isComplete(file: DropupFile): file is DropupFile & { status: 'complete' } {
return file.status === 'complete';
}
function hasError(file: DropupFile): file is DropupFile & { status: 'error' } {
return file.status === 'error';
}
// Uso
function FileList({ files }: { files: DropupFile[] }) {
const uploading = files.filter(isUploading);
const completed = files.filter(isComplete);
const failed = files.filter(hasError);
return (
<>
{uploading.map(file => (
<div key={file.id}>
{file.name} - {file.progress}%
</div>
))}
</>
);
}
Extendiendo metadatos de DropupFile
import type { DropupFile } from '@samithahansaka/dropup';
// Define tu tipo de metadatos
interface CustomMeta {
category: string;
tags: string[];
description?: string;
}
// Usar con aserción de tipo
const { files, actions } = useDropup();
// Actualizar con metadatos tipados
actions.updateFileMeta(files[0].id, {
category: 'documentos',
tags: ['importante', 'trabajo'],
} as CustomMeta);
// Acceder con aserción de tipo
const meta = files[0].meta as CustomMeta | undefined;
console.log(meta?.category);
Props de componente con Dropup
import type { DropupFile, DropupState, DropupActions } from '@samithahansaka/dropup';
interface UploaderProps {
onUploadComplete?: (files: DropupFile[]) => void;
maxFiles?: number;
accept?: string | string[];
}
function Uploader({ onUploadComplete, maxFiles, accept }: UploaderProps) {
const { files, state, actions, getDropProps, getInputProps } = useDropup({
maxFiles,
accept,
onAllComplete: onUploadComplete,
});
return (
// ...
);
}
// Componente de vista previa de archivo
interface FilePreviewProps {
file: DropupFile;
onRemove: (id: string) => void;
}
function FilePreview({ file, onRemove }: FilePreviewProps) {
return (
<div>
<span>{file.name}</span>
<span>{file.status}</span>
<button onClick={() => onRemove(file.id)}>Eliminar</button>
</div>
);
}
Tipos de cargador en la nube
import { createS3Uploader } from '@samithahansaka/dropup/cloud/s3';
import type { DropupFile } from '@samithahansaka/dropup';
interface PresignedUrlResponse {
url: string;
fields?: Record<string, string>;
}
const s3Uploader = createS3Uploader({
getPresignedUrl: async (file: DropupFile): Promise<PresignedUrlResponse> => {
const response = await fetch('/api/presign', {
method: 'POST',
body: JSON.stringify({
filename: file.name,
contentType: file.type,
}),
});
return response.json();
},
});
Configuración de modo estricto
Para máxima seguridad de tipos:
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUncheckedIndexedAccess": true
}
}
Archivos de declaración
Si necesitas extender los tipos de Dropup:
// types/dropup.d.ts
import '@samithahansaka/dropup';
declare module '@samithahansaka/dropup' {
interface DropupFile {
// Agregar propiedades personalizadas
customField?: string;
}
}
Tipos de componentes React
import type { ReactNode, CSSProperties } from 'react';
import type { UseDropupReturn } from '@samithahansaka/dropup';
interface DropZoneProps {
children?: ReactNode;
style?: CSSProperties;
className?: string;
dropup: UseDropupReturn;
}
function DropZone({ children, style, className, dropup }: DropZoneProps) {
const { getDropProps, getInputProps, state } = dropup;
return (
<div
{...getDropProps({ style, className })}
data-dragging={state.isDragging}
>
<input {...getInputProps()} />
{children}
</div>
);
}