File dropzone
Form and input
A transparent field with a neutral border and a focus ring, label above, hint and inline error text below, in the body typeface. File drop targets follow the same field style. Settings pages use a label column and a value column with a save bar that appears only after a change.
실제로 돌아가는 부품입니다. 눌러 보고 입력해 보세요.
내 앱에 넣기
아직 npm 패키지가 없어서 Taster 리포를 받아 그 안의 명령을 씁니다. 내 앱 폴더가 들어 있는 폴더에서 한 번만 받습니다.
git clone https://github.com/makim-414/taster.git && npm ci --prefix taster/packages/engine내 앱 폴더에서 이 부품을 넣습니다. 부품 파일과 토큰 파일이
src/components/taster에 들어갑니다.node ../taster/packages/engine/cli.mjs add blocks/file-dropzone --from https://taster-six.vercel.app --dir src/components/taster부품은 Tailwind 클래스로 그리고, Taster 프리셋이 그 클래스를 토큰에 연결합니다. Tailwind CSS 를 설치하고,
tokens.css를 앱 루트에서 한 번 불러온 뒤, 앱 루트에 이 설정을 둡니다. 프리셋이 없으면 빌드는 되어도 부품이 스타일 없이 나옵니다.// tailwind.config.cjs module.exports = { presets: [require('./src/components/taster/tailwind-preset.cjs')], content: ['./index.html', './src/**/*.{ts,tsx}'], };Tailwind v3 는 이 파일을 그대로 읽습니다. v4 는 Tailwind 를 불러오는
src/의 스타일시트 맨 위에 이 두 줄을 넣습니다.@import "tailwindcss"; @config "../tailwind.config.cjs";tokens.css는:root에--bg,--text,--border,--accent를 정의합니다. 내 앱의 스타일시트가 같은 이름을 뒤에서 다시 정의하면 그쪽 색이 이깁니다. 새 Vite 앱의 스타터 CSS 처럼 그런 변수가 있으면 지우거나 이름을 바꾸세요.
언제 쓰나요
- Text input fieldA transparent field with a neutral border and a focus ring, label above, hint and inline error text below, in the body typeface. File drop targets follow the same field style. Settings pages use a label column and a value column with a save bar that appears only after a change.
대신 없애 주는 AI 티
- Tinted notice band (AC-06)
- Monospace font for interface labels (AC-09)
- Flat gray card with a hairline border, everywhere (AC-14)
- Touch target under 44px (RSP-06)
정보
코드 보기
'use client'
import * as React from 'react'
import { cn } from './_cn'
// FileDropzone. A drop target that is also a real file input: drag files in, or tab to it and press Enter or Space
// to open the picker. Accepted files are listed with their size and a remove button; files that break `accept` or
// `maxSize` are listed with the reason in plain words. Only a small mark carries the danger color.
export interface FileDropzoneProps {
label: React.ReactNode
hint?: React.ReactNode
/** Same syntax as the input attribute, for example ".csv,.xlsx" or "image/*". */
accept?: string
multiple?: boolean
/** Largest file in bytes. */
maxSize?: number
defaultFiles?: File[]
onFilesChange?: (files: File[]) => void
disabled?: boolean
className?: string
/** Wording, so the component can be translated. */
dropLabel?: string
browseLabel?: string
removeLabel?: (name: string) => string
}
interface Rejected {
file: File
reason: string
}
export function formatBytes(n: number): string {
if (n < 1024) return `${n} B`
if (n < 1024 * 1024) return `${Math.round(n / 102.4) / 10} KB`
return `${Math.round(n / (1024 * 102.4)) / 10} MB`
}
function matchesAccept(file: File, accept?: string): boolean {
if (!accept) return true
const name = file.name.toLowerCase()
const type = file.type.toLowerCase()
return accept
.split(',')
.map((s) => s.trim().toLowerCase())
.filter(Boolean)
.some((rule) => {
if (rule.startsWith('.')) return name.endsWith(rule)
if (rule.endsWith('/*')) return type.startsWith(rule.slice(0, -1))
return type === rule
})
}
export function FileDropzone({
label,
hint,
accept,
multiple = true,
maxSize,
defaultFiles = [],
onFilesChange,
disabled,
className,
dropLabel = 'Drop files here or',
browseLabel = 'choose files',
removeLabel = (name) => `Remove ${name}`,
}: FileDropzoneProps) {
const reactId = React.useId()
const inputId = `drop-${reactId}`
const hintId = hint ? `${inputId}-hint` : undefined
const [files, setFiles] = React.useState<File[]>(defaultFiles)
const [rejected, setRejected] = React.useState<Rejected[]>([])
const [over, setOver] = React.useState(false)
const update = (next: File[]) => {
setFiles(next)
onFilesChange?.(next)
}
const add = (list: FileList | null) => {
if (!list) return
const ok: File[] = []
const bad: Rejected[] = []
for (const f of Array.from(list)) {
if (!matchesAccept(f, accept)) bad.push({ file: f, reason: `Not an accepted type (${accept})` })
else if (maxSize && f.size > maxSize) bad.push({ file: f, reason: `Larger than ${formatBytes(maxSize)}` })
else ok.push(f)
}
setRejected(bad)
if (ok.length) update(multiple ? [...files, ...ok] : ok.slice(0, 1))
}
return (
<div className={cn('flex w-full min-w-0 flex-col gap-2', className)}>
<div className="text-sm font-medium text-text" id={`${inputId}-label`}>
{label}
</div>
<label
htmlFor={inputId}
onDragOver={(e) => {
if (disabled) return
e.preventDefault()
setOver(true)
}}
onDragLeave={() => setOver(false)}
onDrop={(e) => {
if (disabled) return
e.preventDefault()
setOver(false)
add(e.dataTransfer.files)
}}
className={cn(
'flex min-h-28 flex-col items-center justify-center gap-1 rounded-md border border-dashed px-4 py-6 text-center text-sm',
'transition-colors duration-press has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring',
disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
over ? 'border-text bg-bg-sunken' : 'border-border-input hover:border-text-subtle',
)}
>
<input
id={inputId}
type="file"
accept={accept}
multiple={multiple}
disabled={disabled}
aria-labelledby={`${inputId}-label`}
aria-describedby={hintId}
onChange={(e) => {
add(e.target.files)
e.target.value = ''
}}
className="sr-only"
/>
<span className="text-text-muted">
{dropLabel} <span className="font-medium text-text underline underline-offset-4">{browseLabel}</span>
</span>
{hint && (
<span id={hintId} className="text-label text-text-subtle">
{hint}
</span>
)}
</label>
{(files.length > 0 || rejected.length > 0) && (
<ul className="divide-y divide-border" aria-live="polite">
{files.map((f, i) => (
<li key={`${f.name}-${i}`} className="flex min-h-11 items-center gap-3 py-1">
<span className="min-w-0 flex-1 break-all text-sm text-text">{f.name}</span>
<span className="shrink-0 text-label tabular-nums text-text-subtle">{formatBytes(f.size)}</span>
<button
type="button"
aria-label={removeLabel(f.name)}
onClick={() => update(files.filter((_, j) => j !== i))}
className={cn(
'-mr-2 inline-flex size-11 shrink-0 items-center justify-center rounded-md text-text-subtle outline-none desk:size-8',
'transition-colors duration-press hover:text-text focus-visible:ring-2 focus-visible:ring-ring',
)}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" aria-hidden="true">
<path d="M6 6l12 12M18 6L6 18" />
</svg>
</button>
</li>
))}
{rejected.map((r, i) => (
<li key={`bad-${r.file.name}-${i}`} className="flex min-h-11 items-start gap-2 py-2.5 text-sm">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" aria-hidden="true" className="mt-1 shrink-0 text-danger">
<circle cx="12" cy="12" r="9" />
<path d="M12 7.5v5.5M12 16.5h.01" />
</svg>
<span className="min-w-0 break-all text-text">
{r.file.name}
<span className="text-text-muted">: {r.reason}</span>
</span>
</li>
))}
</ul>
)}
</div>
)
}