# FileDrop

A drop zone and a file-picker button that share one accept and multiple filter.

- Page: https://www.effectcn.com/components/file-drop
- Kind: Headless component with parts
- File: `src/ui/file-drop.ts`
- Built on: `FileDrop` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/file-drop.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/file-drop.ts`

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

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

## Usage

Drop one file on the zone, or press browse. The Model keeps the file's name and size.

```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.

```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 FileDropAcceptMessage = UiSchema.TaggedEnum({
  PickedFiles: { names: Schema.Array(Schema.String) },
  RejectedFiles: { names: Schema.Array(Schema.String) }
})

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"))

export const FileDropAccept = Html.component({
  name: "FileDropAccept",
  model: Schema.Struct({
    accepted: Schema.Array(Schema.String),
    rejected: Schema.Array(Schema.String)
  }),
  message: FileDropAcceptMessage
}).make({
  init: () => ({ accepted: [], rejected: [] }),
  update: {
    // On a mixed batch `Picked` comes first, so clearing here keeps that batch's rejections.
    PickedFiles: ($, { names }) => ({ accepted: [...$.model.accepted, ...names], rejected: [] }),
    RejectedFiles: ($, { names }) => $.evolve({ rejected: names })
  },
  view: (h, model) =>
    FileDrop(h, {
      // The same list filters drops and the browser's picker.
      props: { accept: ["image/*", ".pdf"], multiple: true },
      onEmit: {
        Picked: ({ files }) => FileDropAcceptMessage.PickedFiles({ names: files.map((file) => file.name) }),
        Rejected: ({ files }) => FileDropAcceptMessage.RejectedFiles({ names: files.map((file) => file.name) })
      },
      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("Drop images or PDFs, or ", FileDropTrigger(h, fileDrop).children("browse")),
            FileDropHint(h).children("PNG, JPG, GIF, WebP or PDF")
          ),
          model.rejected.length > 0 &&
            h.p.class("m-0 text-xs text-destructive").attr("role", "alert").children(
              `Not an image or a PDF: ${model.rejected.join(", ")}`
            ),
          model.accepted.length > 0 &&
            h.ul.class("m-0 flex list-none flex-col gap-1 p-0").children(
              ...model.accepted.map((name, index) =>
                h.li.key(`${index}:${name}`).class("truncate rounded-md border px-3 py-2 text-[13px]").children(name)
              )
            )
        )
    })
})
```

### Multiple files

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

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { FileDrop } from "@effect/ui-kit"
import { Array as Arr, Schema } from "effect"
import { Button } from "#ui/button"
import { FileDropHint, FileDropIcon, FileDropTitle, FileDropTrigger, FileDropZone } from "#ui/file-drop"

const PickedFile = Schema.Struct({ name: Schema.String, size: Schema.Number })

const FileDropMultipleMessage = UiSchema.TaggedEnum({
  PickedFiles: { files: Schema.Array(PickedFile) },
  ClickedRemove: { index: Schema.Number },
  ClickedClear: {}
})

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 CloseIcon = <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", "M6 6l12 12M18 6L6 18"))

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

export const FileDropMultiple = Html.component({
  name: "FileDropMultiple",
  model: Schema.Struct({ files: Schema.Array(PickedFile) }),
  message: FileDropMultipleMessage
}).make({
  init: () => ({
    files: [
      { name: "brief.pdf", size: 248_113 },
      { name: "wireframes.fig", size: 3_402_911 }
    ]
  }),
  update: {
    PickedFiles: ($, { files }) => $.evolve({ files: Arr.appendAll(files) }),
    ClickedRemove: ($, { index }) => $.evolve({ files: Arr.remove(index) }),
    ClickedClear: ($) => $.evolve({ files: [] })
  },
  view: (h, model) =>
    FileDrop(h, {
      props: { multiple: true },
      onEmit: {
        Picked: ({ files }) =>
          FileDropMultipleMessage.PickedFiles({ files: files.map(({ name, size }) => ({ name, size })) }),
        Rejected: () => undefined
      },
      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 files here, or ", FileDropTrigger(h, fileDrop).children("browse")),
            FileDropHint(h).children("Add as many as you need")
          ),
          model.files.length > 0 &&
            h.ul.class("m-0 flex list-none flex-col gap-1 p-0").children(
              ...model.files.map(({ name, size }, index) =>
                h.li.key(`${index}:${name}`)
                  .class("flex items-center gap-2 rounded-md border py-1 ps-3 pe-1 text-[13px]")
                  .children(
                    h.span.class("min-w-0 flex-1 truncate").children(name),
                    h.span.class("text-xs text-muted-foreground tabular-nums").children(formatSize(size)),
                    Button(h, {
                      variant: "ghost",
                      size: "icon-sm",
                      onPress: FileDropMultipleMessage.ClickedRemove({ index })
                    }).attr("aria-label", `Remove ${name}`).children(CloseIcon(h))
                  )
              )
            ),
          model.files.length > 0 &&
            h.div.class("flex items-center justify-between").children(
              h.span.class("text-xs text-muted-foreground tabular-nums").children(
                model.files.length === 1 ? "1 file" : `${model.files.length} files`
              ),
              Button(h, { variant: "ghost", size: "sm", onPress: FileDropMultipleMessage.ClickedClear() }).children(
                "Clear all"
              )
            )
        )
    })
})
```

### Button only

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

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { FileDrop } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { FileDropButton } from "#ui/file-drop"

const FileDropCompactMessage = UiSchema.TaggedEnum({
  PickedFile: { name: Schema.String },
  ClickedRemove: {}
})

const PaperclipIcon = <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",
        "M21 11.5l-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6l7.9-7.9"
      )
    )

const CloseIcon = <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", "M6 6l12 12M18 6L6 18"))

export const FileDropCompact = Html.component({
  name: "FileDropCompact",
  model: Schema.Struct({ name: Schema.NullOr(Schema.String) }),
  message: FileDropCompactMessage
}).make({
  init: () => ({ name: null }),
  update: {
    PickedFile: ($, { name }) => $.evolve({ name }),
    ClickedRemove: ($) => $.evolve({ name: null })
  },
  view: (h, model) =>
    FileDrop(h, {
      onEmit: {
        Picked: ({ files: [file] }) => file === undefined ? undefined : FileDropCompactMessage.PickedFile({ name: file.name }),
        Rejected: () => undefined
      },
      view: (fileDrop) =>
        h.div.class("flex flex-wrap items-center gap-2.5").children(
          FileDropButton(h, fileDrop).children(PaperclipIcon(h), "Attach file"),
          model.name === null
            ? h.span.class("text-xs text-muted-foreground").children("No file attached")
            : h.span.class("inline-flex items-center gap-1 rounded-md bg-secondary py-0.5 ps-2.5 pe-0.5 text-[13px]")
              .children(
                h.span.class("max-w-48 truncate").children(model.name),
                Button(h, { variant: "ghost", size: "icon-sm", onPress: FileDropCompactMessage.ClickedRemove() })
                  .attr("aria-label", `Remove ${model.name}`)
                  .children(CloseIcon(h))
              )
        )
    })
})
```

### Image previews

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

```ts
import { Command, UiSchema } from "@effect/ui"
import { Html, HtmlFiles } from "@effect/ui/html"
import { FileDrop } from "@effect/ui-kit"
import { Array as Arr, Effect, Schema } from "effect"
import { FileDropHint, FileDropIcon, FileDropTitle, FileDropTrigger, FileDropZone } from "#ui/file-drop"

const FileDropPreviewsMessage = UiSchema.TaggedEnum({
  PickedImages: { files: Schema.Array(Schema.instanceOf(File)) },
  RejectedFiles: { count: Schema.Number },
  SucceededReadImage: { name: Schema.String, url: Schema.String },
  FailedReadImage: { name: Schema.String },
  ClickedRemove: { index: Schema.Number }
})

// The `File` travels in the message and the Command's args; the Model keeps the data URL.
const ReadImage = Command.make(
  "FileDropPreviews/ReadImage",
  { args: { file: Schema.instanceOf(File) } },
  ({ file }) =>
    HtmlFiles.readAsDataUrl(file).pipe(
      Effect.match({
        onSuccess: (url) => FileDropPreviewsMessage.SucceededReadImage({ name: file.name, url }),
        onFailure: () => FileDropPreviewsMessage.FailedReadImage({ name: file.name })
      })
    )
)

const ImageIcon = <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",
        "M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1zM3 16l5-5 4 4 3-3 6 6M15.5 9.5h.01"
      )
    )

const CloseIcon = <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", "M6 6l12 12M18 6L6 18"))

export const FileDropPreviews = Html.component({
  name: "FileDropPreviews",
  model: Schema.Struct({
    images: Schema.Array(Schema.Struct({ name: Schema.String, url: Schema.String })),
    error: Schema.NullOr(Schema.String)
  }),
  message: FileDropPreviewsMessage
}).make({
  init: () => ({ images: [], error: null }),
  update: {
    PickedImages: ($, { files }) => $.evolve({ error: null }).run(...files.map((file) => ReadImage.make({ file }))),
    RejectedFiles: ($, { count }) =>
      $.evolve({ error: count === 1 ? "1 file isn't an image." : `${count} files aren't images.` }),
    SucceededReadImage: ($, { name, url }) => $.evolve({ images: Arr.append({ name, url }) }),
    FailedReadImage: ($, { name }) => $.evolve({ error: `Couldn't read ${name}.` }),
    ClickedRemove: ($, { index }) => $.evolve({ images: Arr.remove(index) })
  },
  view: (h, model) =>
    FileDrop(h, {
      props: { accept: ["image/*"], multiple: true },
      onEmit: {
        Picked: ({ files }) => FileDropPreviewsMessage.PickedImages({ files }),
        Rejected: ({ files }) => FileDropPreviewsMessage.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(ImageIcon(h)),
            FileDropTitle(h).children("Drop photos here, or ", FileDropTrigger(h, fileDrop).children("browse")),
            FileDropHint(h).children("Images only")
          ),
          model.error !== null && h.p.class("m-0 text-xs text-destructive").attr("role", "alert").children(model.error),
          model.images.length > 0 &&
            h.ul.class("m-0 grid list-none grid-cols-4 gap-2 p-0").children(
              ...model.images.map(({ name, url }, index) =>
                h.li.key(`${index}:${name}`)
                  .class("group relative aspect-square overflow-hidden rounded-md border bg-muted")
                  .children(
                    h.img.class("size-full object-cover").attrs({ src: url, alt: name }),
                    h.button
                      .class(
                        "absolute end-1 top-1 inline-grid size-5 place-items-center rounded-full bg-background/90 " +
                          "text-foreground opacity-0 shadow-sm transition-opacity duration-150 " +
                          "group-hover:opacity-100 focus-visible:opacity-100 [&_svg]:size-3"
                      )
                      .attrs({ type: "button", "aria-label": `Remove ${name}` })
                      .on("click", FileDropPreviewsMessage.ClickedRemove({ index }))
                      .children(CloseIcon(h))
                  )
              )
            )
        )
    })
})
```

### Disabled

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

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

export const FileDropDisabled = Html.component({
  name: "FileDropDisabled",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    FileDrop(h, {
      // Disabled still takes the drop, so the browser doesn't open the file in the tab.
      props: { disabled: true },
      view: (fileDrop) =>
        FileDropZone(h, fileDrop, { class: "mx-auto max-w-sm" }).children(
          FileDropTitle(h).children("Uploads are closed. ", FileDropTrigger(h, fileDrop).children("Browse")),
          FileDropHint(h).children("The storage quota is used up")
        )
    })
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `root` | Any element: the drop target. It can wrap trigger or share one <button> with it. |
| `trigger` | The <button> that opens the browser's file picker. Always draw it. |
| `dragOver, disabled` | Values: whether files are being dragged over root, and the prop. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `accept` | `string[]` | Allowed types: .ext, type/* or type/subtype. Left out, every file is allowed. |
| `multiple` | `boolean` | Allows more than one file per drop or pick. |
| `disabled` | `boolean` | Disables trigger and ignores drags, drops and picks. |

### Events

| Event | Description |
| --- | --- |
| `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

| Attribute | Description |
| --- | --- |
| `data-drag-over` | On root: files are being dragged over it. |
| `data-disabled` | On root and trigger. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
