Lewati ke konten utama

Panduan TypeScript

Dropup ditulis dalam TypeScript dan menyediakan definisi tipe yang komprehensif.

Penggunaan Dasar

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

return (
// ...
);
}

Mengimpor Tipe

import type {
// Tipe inti
DropupFile,
DropupState,
DropupActions,
DropupError,

// Opsi & Konfigurasi
UseDropupOptions,
UploadConfig,
CustomUploader,
ValidationRule,

// Tipe status
FileStatus,
DropupStatus,

// Tipe return
UseDropupReturn,

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

Opsi Bertipe

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

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

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

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

Callback dengan Type-Safe

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

Tipe Custom Uploader

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

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

// Logika upload di sini...
onProgress(50);

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

useDropup({
upload: myUploader,
});

Tipe Aturan Validasi

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

// Aturan sync
const checkFilename: ValidationRule = (file: File) => {
if (file.name.includes('draft')) {
return 'File draft tidak diperbolehkan';
}
return true;
};

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

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

Props Drop Zone Generik

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

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

// Tentukan tipe elemen untuk getDropProps
const dropProps = getDropProps<HTMLDivElement>({
className: 'dropzone',
'data-testid': 'upload-zone',
});

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

Type Guards Status File

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

// Fungsi 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';
}

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

Memperluas Metadata DropupFile

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

// Definisikan tipe metadata Anda
interface CustomMeta {
category: string;
tags: string[];
description?: string;
}

// Gunakan dengan type assertion
const { files, actions } = useDropup();

// Update dengan metadata bertipe
actions.updateFileMeta(files[0].id, {
category: 'documents',
tags: ['penting', 'kerja'],
} as CustomMeta);

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

Props Komponen dengan 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 (
// ...
);
}

// Komponen preview file
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)}>Hapus</button>
</div>
);
}

Tipe Cloud Uploader

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

Konfigurasi Mode Strict

Untuk keamanan tipe maksimum:

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

File Deklarasi

Jika Anda perlu memperluas tipe Dropup:

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

declare module '@samithahansaka/dropup' {
interface DropupFile {
// Tambahkan properti kustom
customField?: string;
}
}

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