File upload
패키지 네임스페이스가 아니라 레시피입니다. 컨트롤은 네이티브 <input type="file">이고, useDropzone이 드래그 앤 드롭과 파일 확인을 더하며, 업로드는 직접 작성하는 코드가 맡습니다. FileUpload.* export는 없습니다.
이 페이지의 내용
이미지
라벨이 드롭 대상입니다. 그래서 라벨 어디를 클릭해도 선택기가 열리고, 라벨의 텍스트가 입력의 이름이 됩니다. 거부된 파일은 입력의 aria-describedby가 가리키는 ErrorMessage.Root에 나열하고, 입력에는 aria-invalid를 줍니다. 받은 파일은 그 아래에 나열합니다.
import {
Description,
ErrorMessage,
Stack,
Text,
useDropzone,
type FileRejection,
type FileRejectionReason,
} from '@tounsoo/todae';
import { useId, useState } from 'react';
const MAX_SIZE = 2_000_000;
const REASONS: Record<FileRejectionReason, string> = {
type: 'is not an image',
'too-large': 'is over 2 MB',
'too-small': 'is empty',
'too-many': 'is past the 3 file limit',
};
export default function FileUploadImages() {
const hintId = useId();
const errorId = useId();
const [files, setFiles] = useState<File[]>([]);
const [rejected, setRejected] = useState<FileRejection[]>([]);
const zone = useDropzone({
accept: 'image/*',
multiple: true,
maxFiles: 3,
maxSize: MAX_SIZE,
minSize: 1,
onFiles: (accepted, failed) => {
setFiles(accepted);
setRejected(failed);
},
});
return (
<Stack.Root>
<label
{...zone.getRootProps()}
style={{
display: 'grid',
justifyItems: 'center',
gap: 'var(--todae-space-3)',
padding: 'var(--todae-space-6)',
// A solid border while dragging, so the state shows by more than color.
border: `2px ${zone.dragging ? 'solid' : 'dashed'} var(--todae-color-border-default)`,
borderRadius: 'var(--todae-radius-md)',
background: zone.dragging ? 'var(--todae-color-bg-subtle)' : undefined,
}}
>
<Text.Root as="span">Drop images here, or choose them</Text.Root>
<input
{...zone.getInputProps()}
name="images"
aria-invalid={rejected.length > 0 || undefined}
aria-describedby={rejected.length > 0 ? `${hintId} ${errorId}` : hintId}
/>
</label>
<Description.Root id={hintId}>Up to 3 images, 2 MB each.</Description.Root>
{rejected.length > 0 ? (
<ErrorMessage.Root id={errorId}>
{rejected.map(({ file, reasons }) => `${file.name} ${reasons.map((reason) => REASONS[reason]).join(' and ')}.`).join(' ')}
</ErrorMessage.Root>
) : null}
{files.length > 0 ? (
<ul aria-label="Chosen images">
{files.map((file, index) => (
<li key={`${index}:${file.name}`}>{file.name}</li>
))}
</ul>
) : null}
</Stack.Root>
);
}
드롭 상태는 [data-dragging]이나 dragging 값으로 스타일을 주세요. 오류는 나타날 때 읽어 주지 않습니다. 읽어 주어야 한다면 useAnnouncer를 쓰세요.
업로드
onFiles에서 파일을 보내거나, 입력에 남겨 두고 폼이 제출하게 하세요. 입력에는 받은 파일만 남아 있습니다. 진행률은 Progress 페이지처럼 Progress.Root로 보여 주세요.
접근성을 지키는 조합
Todae가 맡는 것: useDropzone은 네이티브 <input type="file">을 계속 컨트롤로 두므로 role, 키보드, 선택기는 브라우저가 제공합니다. getInputProps()는 type, accept, multiple, disabled를 설정하고, getRootProps()는 드래그 핸들러, paste가 있을 때의 붙여넣기 핸들러, data-dragging만 추가합니다. 검사가 끝나면 입력에는 받은 파일만 남습니다. 훅은 ARIA를 설정하지 않고 아무것도 읽어 주지 않습니다.
직접 제공할 것: 레시피의 마크업이 하는 일을 직접 하세요. 입력의 이름이 되는 <label> 텍스트, aria-describedby로 연결한 힌트, 말로 풀어 쓴 거부 이유, 파일이 거부되었을 때의 aria-invalid와 aria-describedby에 더한 ErrorMessage.Root id, 이름이 있는 받은 파일 목록이 필요합니다. 거부를 들려주어야 한다면 알리세요. 업로드 진행률과 결과는 레이블이 있는 <progress>처럼 텍스트로도 보여 주세요.
주의할 점: 드롭 대상을 꾸미려고 display: none이나 hidden으로 입력을 숨기지 마세요. 드래그는 포인터로만 할 수 있으므로 키보드와 스크린 리더 사용자는 유일한 방법을 잃습니다. 포커스를 받을 수 있게 두고 포커스를 보여 주세요. 더는 렌더링하지 않는 ErrorMessage.Root를 aria-describedby가 계속 가리키게 두지 마세요. 오류를 빨간 테두리만으로 보여 주지 마세요.
언제 쓰나요
언제: 파일을 고르거나 끌어다 놓아 받고, 형식, 크기, 개수를 검사하는 폼.
쓰지 않을 때: 채팅 메시지에 붙이는 파일 → Composer와 Attachment. 드롭 대상도 검사도 없는 선택기 → <input type="file">만.