Drag a file here, or

One file, any type

Nothing chosen yet

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/file-drop.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { FileDrop } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    import { type ButtonSize, type ButtonVariant, buttonVariants } from "#ui/button"
    
    /** What the kit's `FileDrop` passes to its `view` closure. */
    export type FileDropParts = Component.Headless.Parts<typeof FileDrop>
    
    /** The drop zone: a dashed box that fills with the brand wash while files are dragged over it. */
    export const FileDropZone = <Msg>(
      h: Html.H<Msg>,
      fileDrop: FileDropParts,
      options: { readonly class?: string | undefined } = {}
    ) =>
      fileDrop.root(
        h.div.class(
          cn(
            "group flex w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-dashed border-input " +
              "bg-background px-6 py-8 text-center transition-colors duration-150 " +
              "data-[drag-over]:border-brand data-[drag-over]:bg-brand-wash " +
              "data-[disabled]:cursor-not-allowed data-[disabled]:bg-muted data-[disabled]:opacity-60",
            options.class
          )
        )
      )
    
    /** A round badge for an icon at the top of the zone. */
    export const FileDropIcon = <Msg>(h: Html.H<Msg>, options: { readonly class?: string | undefined } = {}) =>
      h.span.class(
        cn(
          "mb-1 inline-grid size-9 place-items-center rounded-full bg-muted text-muted-foreground " +
            "group-data-[drag-over]:text-brand [&_svg]:size-4.5",
          options.class
        )
      )
    
    export const FileDropTitle = <Msg>(h: Html.H<Msg>, options: { readonly class?: string | undefined } = {}) =>
      h.p.class(cn("m-0 text-[13px] font-medium text-foreground", options.class))
    
    export const FileDropHint = <Msg>(h: Html.H<Msg>, options: { readonly class?: string | undefined } = {}) =>
      h.p.class(cn("m-0 text-xs text-muted-foreground", options.class))
    
    /** The button that opens the browser's file picker, as a link inside the zone's text. */
    export const FileDropTrigger = <Msg>(
      h: Html.H<Msg>,
      fileDrop: FileDropParts,
      options: { readonly class?: string | undefined } = {}
    ) =>
      fileDrop.trigger(
        h.button.class(
          cn(
            "rounded-xs p-0 font-medium text-foreground underline decoration-muted-foreground/50 underline-offset-4 " +
              "transition-colors duration-150 hover:decoration-current " +
              "data-[disabled]:cursor-not-allowed data-[disabled]:hover:decoration-muted-foreground/50",
            options.class
          )
        )
      )
    
    /** Zone and trigger on one button: press it to browse, or drop files on it. */
    export const FileDropButton = <Msg>(
      h: Html.H<Msg>,
      fileDrop: FileDropParts,
      options: {
        readonly variant?: ButtonVariant | undefined
        readonly size?: ButtonSize | undefined
        readonly class?: string | undefined
      } = {}
    ) =>
      fileDrop.root(
        fileDrop.trigger(
          h.button.class(
            buttonVariants({
              variant: options.variant ?? "outline",
              size: options.size,
              class: cn("data-[drag-over]:border-brand data-[drag-over]:bg-brand-wash", options.class)
            })
          )
        )
      )
    
  3. Import it

    import { FileDropZone, FileDropIcon, FileDropTitle, FileDropHint, FileDropTrigger, FileDropButton } from "#ui/file-drop"
    

Usage

Basic.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { FileDrop } from "@effect/ui-kit"
import { Schema } from "effect"
import { FileDropHint, FileDropIcon, FileDropTitle, FileDropTrigger, FileDropZone } from "#ui/file-drop"

const FileDropBasicMessage = UiSchema.TaggedEnum({
  PickedFile: { name: Schema.String, size: Schema.Number },
  RejectedFiles: { count: Schema.Number }
})

const UploadIcon = <M>(h: Html.H<M>) =>
  h.el("svg")
    .attrs({ viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "aria-hidden": "true" })
    .children(h.el("path").attr("d", "M12 16V4M7 9l5-5 5 5M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"))

const formatSize = (bytes: number) =>
  bytes < 1024
    ? `${bytes} B`
    : bytes < 1024 * 1024
    ? `${(bytes / 1024).toFixed(1)} KB`
    : `${(bytes / 1024 / 1024).toFixed(1)} MB`

export const FileDropBasic = Html.component({
  name: "FileDropBasic",
  model: Schema.Struct({
    file: Schema.NullOr(Schema.Struct({ name: Schema.String, size: Schema.Number })),
    error: Schema.NullOr(Schema.String)
  }),
  message: FileDropBasicMessage
}).make({
  init: () => ({ file: null, error: null }),
  update: {
    // A `File` isn't plain data: the Model keeps its name and size.
    PickedFile: (_, { name, size }) => ({ file: { name, size }, error: null }),
    RejectedFiles: ($, { count }) => $.evolve({ error: `Drop one file, not ${count}.` })
  },
  view: (h, model) =>
    FileDrop(h, {
      onEmit: {
        Picked: ({ files: [file] }) =>
          file === undefined ? undefined : FileDropBasicMessage.PickedFile({ name: file.name, size: file.size }),
        Rejected: ({ files }) => FileDropBasicMessage.RejectedFiles({ count: files.length })
      },
      view: (fileDrop) =>
        h.div.class("mx-auto flex w-full max-w-sm flex-col gap-3").children(
          FileDropZone(h, fileDrop).children(
            FileDropIcon(h).children(UploadIcon(h)),
            FileDropTitle(h).children("Drag a file here, or ", FileDropTrigger(h, fileDrop).children("browse")),
            FileDropHint(h).children("One file, any type")
          ),
          model.error !== null
            ? h.p.class("m-0 text-xs text-destructive").attr("role", "alert").children(model.error)
            : h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(
              model.file === null ? "Nothing chosen yet" : `${model.file.name} (${formatSize(model.file.size)})`
            )
        )
    })
})

Examples

Accepted types

accept splits a batch: matching files are picked, the rest come back as rejected.

Drop images or PDFs, or

PNG, JPG, GIF, WebP or PDF

Multiple files

A list of what was added, each with a remove button.

Drag files here, or

Add as many as you need

  • brief.pdf242.3 KB
  • wireframes.fig3.2 MB
2 files

Button only

root and trigger on one button: press it to browse, or drop a file on it.

No file attached

Image previews

A Command reads each picked image as a data URL for a thumbnail.

Drop photos here, or

Images only

Disabled

Ignores drags, drops and picks, and disables the trigger.

Uploads are closed.

The storage quota is used up

Anatomy

The parts the view closure receives. Apply each one to an element of your own.

PartDescription
rootAny element: the drop target. It can wrap trigger or share one <button> with it.
triggerThe <button> that opens the browser's file picker. Always draw it.
dragOver, disabledValues: whether files are being dragged over root, and the prop.

API reference

Props

PropTypeDescription
acceptstring[]Allowed types: .ext, type/* or type/subtype. Left out, every file is allowed.
multiplebooleanAllows more than one file per drop or pick.
disabledbooleanDisables trigger and ignores drags, drops and picks.

Events

EventDescription
Picked{ files }: the Files that passed accept.
Rejected{ files, reason }: "too-many-files" for a whole batch, or "invalid-type" for the rest.

Data attributes

AttributeDescription
data-drag-overOn root: files are being dragged over it.
data-disabledOn root and trigger.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.