A file input that fits a form: one file held in the field, or several listed under it.
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 { Button } from "./ui/uicontext/components/Button.ts"import { uploadStatus } from "./ui/uicontext/components/domain/Upload.ts"import { FormField, Input } from "./ui/uicontext/components/FormControls.ts"import { sx } from "./ui/uicontext/components/Sx.ts"import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"import { FileField } from "./ui/uicontext/components/upload/FileField.ts"import { AddUploads, ChangeUpload, simulatedTransport, uploadsLayer, WatchUploads } from "./ui/uicontext/components/upload/Uploads.ts"const styles = stylex.create({ form: { display: "grid", gap: space.lg, inlineSize: "min(100%, 26rem)" }, foot: { display: "flex", alignItems: "center", gap: space.md, flexWrap: "wrap" }, note: { margin: 0, color: color.muted, fontSize: font.sm },})const Message = UiSchema.TaggedEnum({ ChangedMerchant: { value: Schema.String }, ChangedAmount: { value: Schema.String }, PickedReceipt: { files: Schema.Array(Schema.instanceOf(File)), replacing: Schema.NullOr(Schema.String) }, RequestedRemoveReceipt: { id: Schema.String }, RequestedRetryReceipt: { id: Schema.String }, SubmittedExpense: {},})const ExpenseFormNoDeps = Html.component({ name: "ExpenseForm", model: Schema.Struct({ merchant: Schema.String, amount: Schema.String, submitted: Schema.Boolean }), message: Message, queries: { uploads: { query: WatchUploads, args: () => ({}) } },}).make({ init: () => ({ merchant: "Harbor Café", amount: "412.80", submitted: false }), update: { ChangedMerchant: ($, { value }) => $.evolve({ merchant: value, submitted: false }), ChangedAmount: ($, { value }) => $.evolve({ amount: value, submitted: false }), // one receipt: a new one takes the old one's place PickedReceipt: ($, { files, replacing }) => $.evolve({ submitted: false }).run(AddUploads.make({ files })).run(...(replacing === null ? [] : [ChangeUpload.make({ id: replacing, action: "remove" })])), RequestedRemoveReceipt: ($, { id }) => $.evolve({ submitted: false }).run(ChangeUpload.make({ id, action: "remove" })), RequestedRetryReceipt: ($, { id }) => $.run(ChangeUpload.make({ id, action: "retry" })), SubmittedExpense: ($) => $.evolve({ submitted: true }), }, view: (h, model) => { const receipt = AsyncResult.getOrElse(h.queries.uploads, () => []).slice(-1) const current = receipt[0] const ready = current !== undefined && uploadStatus(current) === "done" && model.merchant.trim() !== "" && Number(model.amount) > 0 return h.form.attrs({ novalidate: "", ...sx(styles.form) }).on("submit", Message.SubmittedExpense()).children( FormField(h, { id: "merchant", label: "Merchant" }, (attrs) => Input(h).attrs(attrs).value(model.merchant).on("input", ({ value }) => Message.ChangedMerchant({ value }))), FormField(h, { id: "amount", label: "Amount (USD)" }, (attrs) => Input(h).attrs({ ...attrs, inputmode: "decimal" }).value(model.amount).on("input", ({ value }) => Message.ChangedAmount({ value }))), FormField(h, { id: "receipt", label: "Receipt", description: "A photo or a PDF, up to 10 MB." }, (field) => FileField(h, { props: { field, value: receipt, accept: { types: ["image/*", ".pdf"], typeLabel: "a photo or a PDF", typeNoun: "a receipt we can read", maxSize: 10 * 1024 * 1024 }, placeholder: "No receipt yet", }, onEmit: { Picked: ({ files }) => Message.PickedReceipt({ files, replacing: current?.id ?? null }), Refused: () => undefined, RequestedRemove: ({ id }) => Message.RequestedRemoveReceipt({ id }), RequestedRetry: ({ id }) => Message.RequestedRetryReceipt({ id }), }, })), h.div.attrs(sx(styles.foot)).children( Button(h, { tone: "primary", type: "submit" }).disabled(!ready).children("Submit expense"), h.p.attrs({ role: "status", ...sx(styles.note) }).children( model.submitted ? "Submitted for approval." : current === undefined ? "Add the receipt to submit." : uploadStatus(current) === "done" ? "" : "Uploading the receipt…", ), ), ) },})export const ExpenseForm = ExpenseFormNoDeps.pipe(Component.provide(uploadsLayer(simulatedTransport({ bytesPerSecond: 900_000 }), { idPrefix: "receipt" })))Installation
pnpm dlx shadcn@latest add checkfu/uicontext/file-fieldUsage
import type { UploadItem } from "./ui/uicontext/components/domain/Upload.ts"import { FormField } from "./ui/uicontext/components/FormControls.ts"import { FileField } from "./ui/uicontext/components/upload/FileField.ts"const Message = UiSchema.TaggedEnum({ PickedResume: { file: Schema.instanceOf(File) }, RequestedRemoveResume: { id: Schema.String },})// One file, in a form: the label opens the picker, and the field shows the file once chosenexport const ResumeField = (h: Html.H<typeof Message.Type>, value: ReadonlyArray<UploadItem>) => FormField(h, { id: "resume", label: "Résumé", description: "PDF, up to 5 MB." }, (field) => FileField(h, { props: { field, value, accept: { types: [".pdf"], typeLabel: "PDF", typeNoun: "a PDF", maxSize: 5 * 1024 * 1024 } }, onEmit: { Picked: ({ files }) => (files[0] === undefined ? undefined : Message.PickedResume({ file: files[0] })), Refused: () => undefined, RequestedRemove: ({ id }) => Message.RequestedRemoveResume({ id }), RequestedRetry: () => undefined, }, }))Examples
Several files, kept for the form
Up to five signed contracts, as PDFs. They're listed under the field and go with the form when it's sent; a sixth file or a Word document is turned away.
Choose filesAdd more
- Northwind — Master services agreement (signed).pdf1.2 MB
PDFs, up to 5 files and 20 MB each.
import { UiSchema } from "@effect/ui"import { Html } from "@effect/ui/html"import * as stylex from "@stylexjs/stylex"import { Schema } from "effect"import { UploadItem } from "./ui/uicontext/components/domain/Upload.ts"import { FormField } from "./ui/uicontext/components/FormControls.ts"import { sx } from "./ui/uicontext/components/Sx.ts"import { FileField } from "./ui/uicontext/components/upload/FileField.ts"const styles = stylex.create({ frame: { inlineSize: "min(100%, 26rem)" } })const Message = UiSchema.TaggedEnum({ PickedContracts: { files: Schema.Array(Schema.Struct({ name: Schema.String, size: Schema.Number, type: Schema.String })) }, RequestedRemoveContract: { id: Schema.String },})// the form keeps the plain facts; the `File`s would go in a FormData when it's sentexport const DealContracts = Html.component({ name: "DealContracts", model: Schema.Struct({ contracts: Schema.Array(UploadItem), added: Schema.Number }), message: Message,}).make({ init: () => ({ contracts: [{ id: "c0", name: "Northwind — Master services agreement (signed).pdf", size: 1_284_000, type: "application/pdf", outcome: { _tag: "Accepted", request: "c0" } }], added: 0, }), update: { PickedContracts: ($, { files }) => $.evolve({ contracts: (all) => [...all, ...files.map((f, i) => ({ id: `c${$.model.added + i + 1}`, ...f, outcome: { _tag: "Accepted" as const, request: `c${$.model.added + i + 1}` } }))], added: (n) => n + files.length, }), RequestedRemoveContract: ($, { id }) => $.evolve({ contracts: (all) => all.filter((c) => c.id !== id) }), }, view: (h, model) => h.div.attrs(sx(styles.frame)).children( FormField(h, { id: "contracts", label: "Signed contracts", description: "PDFs, up to 5 files and 20 MB each." }, (field) => FileField(h, { props: { field, label: "Signed contracts", value: model.contracts, multiple: true, accept: { types: [".pdf"], typeLabel: "PDF", typeNoun: "a PDF", maxSize: 20 * 1024 * 1024, maxFiles: 5 }, }, onEmit: { Picked: ({ files }) => Message.PickedContracts({ files: files.map((f) => ({ name: f.name, size: f.size, type: f.type })) }), Refused: () => undefined, RequestedRemove: ({ id }) => Message.RequestedRemoveContract({ id }), RequestedRetry: () => undefined, }, })), ),})API reference
Props
| Name | Type | Default | Description |
|---|---|---|---|
label | string | — | The control's name, when no Form Field's label names it |
field | { id, aria-describedby, aria-invalid, … } | — | The attributes a Form Field hands its control: id, description and error wiring |
valuerequired | UploadItem[] | — | The chosen files, with their upload's progress and Outcome when they upload at once |
accept | UploadAccept | — | — |
multiple | boolean | one | Take several files; one by default |
placeholder | string | — | The text in the empty field; the accepted types and size by default |
disabled | boolean | — | — |
locale | string | — | — |
Events
| Event | Payload | Description |
|---|---|---|
Picked | { files: instanceOf[] } | Files that passed the rules; with one file, the new one replaces the old |
Refused | { refused: UploadRefusal[] } | Files the rules turned away; the field says why under itself |
RequestedRemove | { id: string } | — |
RequestedRetry | { id: string } | — |