Skip to main content

TypeScript Guide

Dropup is written in TypeScript and provides comprehensive type definitions.

Basic Usage

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 is DropupFile[]
// actions is DropupActions
// state is DropupState

return (
// ...
);
}

Importing Types

import type {
// Core types
DropupFile,
DropupState,
DropupActions,
DropupError,

// Options & Config
UseDropupOptions,
UploadConfig,
CustomUploader,
ValidationRule,

// Status types
FileStatus,
DropupStatus,

// Return type
UseDropupReturn,

// Validation
ValidationError,
} from '@samithahansaka/dropup';

Typed Options

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('Added:', files);
},

onUploadComplete: (file: DropupFile, response: unknown) => {
console.log('Complete:', file.uploadedUrl);
},

customRules: [
(file: File): boolean | string => {
if (file.name.length > 100) {
return 'Filename too long';
}
return true;
},
],
};

const { files, actions, state } = useDropup(options);

Type-Safe Callbacks

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
},
};

Custom Uploader Type

import type { CustomUploader, UploadOptions, UploadResult } from '@samithahansaka/dropup';

const myUploader: CustomUploader = async (
file, // DropupFile
options // UploadOptions
): Promise<UploadResult> => {
const { signal, onProgress } = options;

// Upload logic here...
onProgress(50);

return {
url: 'https://example.com/uploaded-file',
response: { id: '123' },
};
};

useDropup({
upload: myUploader,
});

Validation Rules Type

import type { ValidationRule } from '@samithahansaka/dropup';

// Sync rule
const checkFilename: ValidationRule = (file: File) => {
if (file.name.includes('draft')) {
return 'Draft files not allowed';
}
return true;
};

// Async rule
const checkServer: ValidationRule = async (file: File) => {
const exists = await fetch(`/api/check?name=${file.name}`);
if (await exists.json()) {
return 'File already exists';
}
return true;
};

useDropup({
customRules: [checkFilename, checkServer],
});

Generic Drop Zone Props

import { useDropup } from '@samithahansaka/dropup';

function TypedDropZone() {
const { getDropProps, getInputProps } = useDropup();

// Specify the element type for getDropProps
const dropProps = getDropProps<HTMLDivElement>({
className: 'dropzone',
'data-testid': 'upload-zone',
});

return (
<div {...dropProps}>
<input {...getInputProps()} />
</div>
);
}

File Status Type Guards

import type { DropupFile, FileStatus } from '@samithahansaka/dropup';

// Type guard functions
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';
}

// Usage
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>
))}
</>
);
}

Extending DropupFile Metadata

import type { DropupFile } from '@samithahansaka/dropup';

// Define your metadata type
interface CustomMeta {
category: string;
tags: string[];
description?: string;
}

// Use with type assertion
const { files, actions } = useDropup();

// Update with typed metadata
actions.updateFileMeta(files[0].id, {
category: 'documents',
tags: ['important', 'work'],
} as CustomMeta);

// Access with type assertion
const meta = files[0].meta as CustomMeta | undefined;
console.log(meta?.category);

Component Props with 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 (
// ...
);
}

// File preview component
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)}>Remove</button>
</div>
);
}

Cloud Uploader Types

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();
},
});

Strict Mode Configuration

For maximum type safety:

// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUncheckedIndexedAccess": true
}
}

Declaration Files

If you need to extend Dropup types:

// types/dropup.d.ts
import '@samithahansaka/dropup';

declare module '@samithahansaka/dropup' {
interface DropupFile {
// Add custom properties
customField?: string;
}
}

React Component Types

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>
);
}