Drop, paste or choose files, checked against types, size and count, with the reason for each file turned away.
Team offsite dinner
Harbor Café · November 21
Drop files here or chooseChoose files
JPG, PNG, HEIC or PDF, up to 10 MB, 10 files at most
1 of 1 uploaded
1 uploaded · 1.8 MB
- Harbor Café receipt.jpgUploaded
1.8 MB
import { Component, UiSchema } from "@effect/ui"import { Html } from "@effect/ui/html"import * as stylex from "@stylexjs/stylex"import { Schema } from "effect"import { AsyncResult } from "effect/reactivity"import { sx } from "./ui/uicontext/components/Sx.ts"import { color, font, radius, space } from "./ui/uicontext/components/tokens.stylex.ts"import { Dropzone } from "./ui/uicontext/components/upload/Dropzone.ts"import { UploadQueue } from "./ui/uicontext/components/upload/UploadQueue.ts"import { AddUploads, ChangeUpload, ClearDoneUploads, simulatedTransport, uploadsLayer, WatchUploads } from "./ui/uicontext/components/upload/Uploads.ts"import { fileFromDataUrl, receiptImage } from "./uploads.ts"const styles = stylex.create({ card: { display: "grid", gap: space.xl, inlineSize: "min(100%, 34rem)", padding: space.xl, borderWidth: 1, borderStyle: "solid", borderColor: color.line, borderRadius: radius.xl, backgroundColor: color.panel, }, head: { display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: space.lg, flexWrap: "wrap" }, title: { margin: 0, fontSize: font.lg, fontWeight: 600, letterSpacing: "-0.01em" }, meta: { margin: 0, color: color.muted, fontSize: font.sm }, amount: { fontSize: font.lg, fontWeight: 600, fontVariantNumeric: "tabular-nums" },})const Message = UiSchema.TaggedEnum({ PickedReceipts: { files: Schema.Array(Schema.instanceOf(File)) }, RequestedReceiptChange: { id: Schema.String, action: Schema.Literals(["pause", "resume", "cancel", "retry", "remove"]) }, RequestedClearReceipts: {},})const ExpenseReceiptsNoDeps = Html.component({ name: "ExpenseReceipts", model: Schema.Struct({}), message: Message, queries: { receipts: { query: WatchUploads, args: () => ({}) } },}).make({ init: () => ({}), update: { PickedReceipts: ($, { files }) => $.run(AddUploads.make({ files })), RequestedReceiptChange: ($, { id, action }) => $.run(ChangeUpload.make({ id, action })), RequestedClearReceipts: ($) => $.run(ClearDoneUploads.make()), }, view: (h) => { const receipts = AsyncResult.getOrElse(h.queries.receipts, () => []) return h.div.attrs(sx(styles.card)).children( h.div.attrs(sx(styles.head)).children( h.div.children( h.h3.attrs(sx(styles.title)).children("Team offsite dinner"), h.p.attrs(sx(styles.meta)).children("Harbor Café · November 21"), ), h.span.attrs(sx(styles.amount)).children("$412.80"), ), Dropzone(h, { props: { label: "Upload receipts", accept: { types: ["image/png", "image/jpeg", "image/heic", ".pdf"], typeLabel: "JPG, PNG, HEIC or PDF", typeNoun: "a receipt we can read", maxSize: 10 * 1024 * 1024, maxFiles: 10 }, count: receipts.length, page: true, }, onEmit: { Picked: ({ files }) => Message.PickedReceipts({ files }), Refused: () => undefined, }, }), receipts.length > 0 && UploadQueue(h, { props: { label: "Receipts", files: receipts, pausable: true }, onEmit: { RequestedPause: ({ id }) => Message.RequestedReceiptChange({ id, action: "pause" }), RequestedResume: ({ id }) => Message.RequestedReceiptChange({ id, action: "resume" }), RequestedCancel: ({ id }) => Message.RequestedReceiptChange({ id, action: "cancel" }), RequestedRetry: ({ id }) => Message.RequestedReceiptChange({ id, action: "retry" }), RequestedRemove: ({ id }) => Message.RequestedReceiptChange({ id, action: "remove" }), RequestedClearDone: () => Message.RequestedClearReceipts(), }, }), ) },})// stands in for your file storage: about 1.5 MB a secondconst receipt = fileFromDataUrl(receiptImage, "harbor-cafe-receipt.svg")export const ExpenseReceipts = ExpenseReceiptsNoDeps.pipe(Component.provide(uploadsLayer(simulatedTransport({ bytesPerSecond: 1_500_000 }), { idPrefix: "receipt", initial: [{ id: "receipt-0", name: "Harbor Café receipt.jpg", size: 1_840_000, type: "image/svg+xml", loaded: 1_840_000, outcome: { _tag: "Accepted", request: "receipt-0" }, file: receipt }],})))Installation
pnpm dlx shadcn@latest add checkfu/uicontext/dropzoneUsage
import { Dropzone } from "./ui/uicontext/components/upload/Dropzone.ts"const Message = UiSchema.TaggedEnum({ PickedReceipts: { files: Schema.Array(Schema.instanceOf(File)) } })// The zone checks the rules and hands over the files that pass; your app uploads themexport const ReceiptDrop = (h: Html.H<typeof Message.Type>) => Dropzone(h, { props: { label: "Upload receipts", accept: { types: ["image/*", ".pdf"], typeLabel: "photos or PDFs", typeNoun: "a receipt we can read", maxSize: 10 * 1024 * 1024 }, }, onEmit: { Picked: ({ files }) => Message.PickedReceipts({ files }), Refused: () => undefined, }, })Examples
Import a CSV with a size limit
One CSV up to 5 MB. The file is read in the browser and previewed before anything is imported; a bigger file or a spreadsheet is turned away with the reason.
Drop a CSV here or choose one
CSV, up to 5 MB
import { Command, UiSchema } from "@effect/ui"import { Html, HtmlFiles } from "@effect/ui/html"import * as stylex from "@stylexjs/stylex"import { Effect, Schema } from "effect"import { Button } from "./ui/uicontext/components/Button.ts"import { formatCount } from "./ui/uicontext/components/domain/Format.ts"import { formatBytes } from "./ui/uicontext/components/domain/Upload.ts"import { sx } from "./ui/uicontext/components/Sx.ts"import { color, font, radius, space } from "./ui/uicontext/components/tokens.stylex.ts"import { Dropzone } from "./ui/uicontext/components/upload/Dropzone.ts"const Preview = Schema.Struct({ name: Schema.String, size: Schema.Number, headers: Schema.Array(Schema.String), rows: Schema.Array(Schema.Array(Schema.String)), count: Schema.Number })const Model = UiSchema.TaggedEnum({ Choosing: {}, Reading: { name: Schema.String }, Previewing: { preview: Preview }, Imported: { name: Schema.String, count: Schema.Number }, Failed: { name: Schema.String },})type Model = typeof Model.Typeconst Message = UiSchema.TaggedEnum({ PickedCsv: { file: Schema.instanceOf(File) }, CompletedReadCsv: { preview: Preview }, FailedReadCsv: { name: Schema.String }, ClickedImport: {}, ClickedStartOver: {},})/** The first lines of a CSV, split on commas outside quotes. */const parse = (text: string) => { const lines = text.split(/\r?\n/u).filter((line) => line.trim() !== "") const cells = (line: string) => [...line.matchAll(/("([^"]|"")*"|[^,]*)(,|$)/gu)].map((m) => (m[1] ?? "").replace(/^"|"$/gu, "").replaceAll('""', '"')).slice(0, -1) return { headers: cells(lines[0] ?? ""), rows: lines.slice(1, 4).map(cells), count: Math.max(0, lines.length - 1) }}// reading a big file is cancelled if another is chosen firstconst ReadCsv = Command.make("csv/ReadCsv", { args: { file: Schema.instanceOf(File) }, mode: "switch" }, ({ file }) => HtmlFiles.readAsText(file).pipe( Effect.match({ onSuccess: (text) => Message.CompletedReadCsv({ preview: { name: file.name, size: file.size, ...parse(text) } }), onFailure: () => Message.FailedReadCsv({ name: file.name }), }), ))const styles = stylex.create({ panel: { display: "grid", gap: space.lg, inlineSize: "min(100%, 34rem)" }, note: { margin: 0, color: color.muted, fontSize: font.sm }, table: { inlineSize: "100%", borderCollapse: "collapse", fontSize: font.sm, tableLayout: "fixed" }, scroll: { overflowX: "auto", borderWidth: 1, borderStyle: "solid", borderColor: color.line, borderRadius: radius.md }, th: { paddingBlock: space.sm, paddingInline: space.md, textAlign: "start", fontWeight: 500, color: color.muted, backgroundColor: color.raised, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }, td: { paddingBlock: space.sm, paddingInline: space.md, borderBlockStartWidth: 1, borderBlockStartStyle: "solid", borderBlockStartColor: color.line, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }, row: { display: "flex", alignItems: "center", gap: space.sm, flexWrap: "wrap" }, strong: { color: color.fg, fontWeight: 500 },})export const ContactImport = Html.component({ name: "ContactImport", model: Model, message: Message }).make({ init: () => Model.Choosing(), update: { PickedCsv: ($, { file }) => $.set(Model.Reading({ name: file.name })).run(ReadCsv.make({ file })), CompletedReadCsv: (_, { preview }) => Model.Previewing({ preview }), FailedReadCsv: (_, { name }) => Model.Failed({ name }), ClickedImport: ($) => ($.model._tag === "Previewing" ? Model.Imported({ name: $.model.preview.name, count: $.model.preview.count }) : $.model), ClickedStartOver: () => Model.Choosing(), }, view: (h, model) => h.div.attrs(sx(styles.panel)).children( (model._tag === "Choosing" || model._tag === "Failed") && Dropzone(h, { props: { label: "Import contacts from a CSV", size: "sm", prompt: "Drop a CSV here or choose one", accept: { types: [".csv", "text/csv"], typeLabel: "CSV", typeNoun: "a CSV file", maxSize: 5 * 1024 * 1024, maxFiles: 1 }, }, onEmit: { Picked: ({ files }) => (files[0] === undefined ? undefined : Message.PickedCsv({ file: files[0] })), Refused: () => undefined, }, }), model._tag === "Failed" && h.p.attrs({ role: "alert", ...sx(styles.note) }).children(`${model.name} couldn't be read. Try saving it again as CSV.`), model._tag === "Reading" && h.p.attrs({ role: "status", ...sx(styles.note) }).children(`Reading ${model.name}…`), model._tag === "Previewing" && [ h.p.key("summary").attrs(sx(styles.note)).children( h.span.attrs(sx(styles.strong)).children(model.preview.name), ` · ${formatBytes(model.preview.size)} · ${formatCount(model.preview.count, "contact")}`, ), model.preview.headers.length > 0 && h.div.key("table").attrs(sx(styles.scroll)).children( h.table.attrs(sx(styles.table)).children( h.thead.children(h.tr.children(model.preview.headers.map((cell, i) => h.th.key(String(i)).attrs({ scope: "col", ...sx(styles.th) }).children(cell)))), h.tbody.children(model.preview.rows.map((row, r) => h.tr.key(String(r)).children(model.preview.headers.map((_, i) => h.td.key(String(i)).attrs(sx(styles.td)).children(row[i] ?? ""))))), ), ), h.div.key("actions").attrs(sx(styles.row)).children( Button(h, { tone: "primary" }).disabled(model.preview.count === 0).on("click", Message.ClickedImport()) .children(model.preview.count === 0 ? "Nothing to import" : `Import ${formatCount(model.preview.count, "contact")}`), Button(h, { emphasis: "ghost" }).on("click", Message.ClickedStartOver()).children("Choose another file"), ), ], model._tag === "Imported" && [ h.p.key("done").attrs({ role: "status", ...sx(styles.note) }).children(`Imported ${formatCount(model.count, "contact")} from ${model.name}.`), Button(h, { emphasis: "ghost" }).key("again").on("click", Message.ClickedStartOver()).children("Import another file"), ], ),})API reference
Props
| Name | Type | Description |
|---|---|---|
labelrequired | string | What the files are for, as a name for the zone: "Upload receipts" |
prompt | string | The line in the zone; "Drop files here or choose them" by default |
accept | UploadAccept | The rules files must pass |
multiple | boolean | Take several files at once; true unless accept.maxFiles is 1 |
count | number | How many files are already added, for accept.maxFiles |
page | boolean | Take drops and pastes anywhere on the page, and cover it while files are dragged over |
disabledReason | string | null | Why files can't be added now ("Uploads are off for guests"); takes nothing while set |
size | "md" | "sm" | sm is a one-line strip for tight spaces: a ticket's reply box, a table's empty state |
locale | string | — |
Events
| Event | Payload | Description |
|---|---|---|
Picked | { files: instanceOf[] } | Files that passed the rules, in the order given: upload them, or keep them for a form |
Refused | { refused: UploadRefusal[] } | Files the rules turned away; the zone shows these itself |