Mixins / foldkit-mixins-ui

Text and number fields

WidgetWhat it doesState
InputSingle-line text input, label, and FieldValidation helperApplication / Adapter
TextareaAuto-sizing multi-line input with character counterApplication / Adapter
PasswordInputPassword field with reveal toggle, meter, and Caps Lock hintSmall Model / Bundle
SearchFieldNative search input with conditional clear buttonApplication
NumberFieldEditable spinbutton with locale formatting and steppersApplication
OtpFieldOne-time code input mirrored across visual digit cellsApplication
TagsInputMulti-tag input with delimiter, max limit, and focus returnSmall Model / Bundle
InputCopyRead-only input with clipboard copy button and statusSmall Model / Bundle
LabelForm <label> with required/optional indicatorStateless
FieldAccessible wrapper (label, description, errors)Stateless
Fieldset<fieldset> with <legend> and descriptionAdapter
FileInputNative file picker with selected-file listApplication
FileUploadFull uploader with drop zone, previews, and progressSmall Model / Bundle
FileDropDrop-zone adapter over @foldkit/ui/fileDropAdapter / Bundle

Input.view and Textarea.view place their own bundles when you pass a draw callback:

ts
import { Input, Recipes } from 'foldkit-mixins-ui'

const FieldStyle = Recipes.Input.style({})

const emailField = (value: string, h: HtmlBuilder<Message>) =>
  Input.view(
    {
      id: 'email',
      value,
      onInput: value => Message.TypedEmail({ value }),
      type: 'email',
      placeholder: 'you@example.com',
      style: FieldStyle,
      draw: ({ input, label }, h) => h.div([], [h.label(label, ['Email']), h.input(input)]),
    },
    h,
  )

Given a label instead of a draw, Input.view draws the field itself: the label, the control, and the description under it, linked to it. start and end are drawn inside the field's box beside the control, and labelAside stands beside the label, not inside it:

ts
import { Input } from 'foldkit-mixins-ui'

const siteField = (value: string, h: HtmlBuilder<Message>) =>
  Input.view(
    {
      id: 'site',
      label: 'Website',
      description: 'Without the scheme.',
      value,
      onInput: value => Message.TypedTitle({ value }),
      start: h.span([], ['https://']),
      end: h.span([], ['.com']),
      style: FieldStyle,
    },
    h,
  )

The box is the group Slot (data-field-group): it carries the border, the focus ring while the control has focus, and the dimming of a disabled field, and the control inside goes borderless. With neither start nor end no group is drawn and the control keeps its own border. SearchField, PasswordInput, InputCopy and NumberField take the same two options. variant is outline, filled, ghost or underline.

Beyond type and placeholder, Input.view takes name, readOnly, required, autocomplete, inputMode and maxLength, so a form that submits natively needs no hand-drawn input, and attributes: { input?, label?, description? } adds what another component hands a slot (a blur handler, aria-busy) before the mixins resolve. Textarea.view takes name, required, autocomplete and attributes the same way. A field's description (Input.field's and Textarea.field's) is an always-drawn role="status" span, even with nothing to say, since a live region announces only what is put into it.

Input.field and Textarea.field draw a whole field from a FieldValidation.Field: the value, its first error or checking mark as the description, and aria-invalid where the field is invalid. changed maps the typed value to a Message; label is the text over the control; and draw places the resolved label, control and description bundles (the default stacks them):

ts
const titleField = (field: FieldValidation.Field<string>, h: HtmlBuilder<Message>) =>
  Input.field(
    { id: 'title', label: 'Title', field, changed: value => Message.TypedTitle({ value }) },
    h,
  )

Textarea

A textarea also takes what more than one line wants. The recipe's resize is how it changes size: auto (the default) grows with its text from rows lines (two unless given) to maxRows, then scrolls; vertical stays rows lines tall and the reader drags it; none holds it. A maxLength caps the text and counts toward it under the field, in the warning's ink from nine tenths and the error's at the limit, and the count describes the textarea. A footer draws the field as one box, a row of controls under the text and the count at its end:

ts
import { Textarea } from 'foldkit-mixins-ui'

const TextareaStyle = Recipes.Textarea.style({})

const replyField = (field: FieldValidation.Field<string>, h: HtmlBuilder<Message>) =>
  Textarea.field(
    {
      id: 'reply',
      label: 'Reply',
      field,
      changed: value => Message.TypedReply({ value }),
      rows: 2,
      maxRows: 8,
      maxLength: 500,
      footer: [Button.view({ label: 'Send', type: 'submit' }, h)],
      style: TextareaStyle,
    },
    h,
  )

Textarea.view takes the same rows, maxRows, maxLength and count, and hands draw the count, frame, footer and meta bundles to place; Textarea.countOf(value, maxLength) is the count's text. resize: 'auto' rests on CSS field-sizing, which sizes the width by the text too where nothing else gives one (it keeps at least 20 columns); a browser without it keeps the textarea at its fewest lines, scrolling.

SearchField

A native type="search" input (role searchbox) named by label, since a search field wears no visible label, and a clear button drawn only while there is text. The view keeps nothing: the application owns the text, onInput reports typing, and clear: { onClear, content? } is what the button and Escape send; a field given no clear has neither. content is drawn in the button in place of the cross. Escape acts only on a field with text, so on an empty one it still reaches an enclosing dialog. start and end are drawn inside the field's box beside the input (a field with no start draws a magnifier there), and busy sets aria-busy and data-busy while a search runs: compose a spinner into end. Pressing the button removes it and the focus it held, so answer onClear with the SearchField.Focus({ id }) Command, which puts focus back on the input and answers SearchField.Message.CompletedFocus (SearchField.inputId(id) is the input's id). words: { clear? } renames the button (default Clear search). A disabled field takes no text or keys and draws no button. routes are application key routes whose input is the field's text.

ts
import { Option } from 'effect'
import { Behaviors } from 'foldkit-mixins'
import { SearchField, SearchFieldSlots } from 'foldkit-mixins-ui'

const Search = defineMessageUnion({
  Typed: { text: Schema.String },
  Cleared: {},
  OpenedResults: {},
})
type Search = typeof Search.Type

const { Keys } = Behaviors

// ArrowDown opens the results, but only once there is text to search for.
const openResults: SearchField.Route<Search> = Keys.route('Open results', {
  on: [Keys.chord('ArrowDown')],
  handle: ({ input }) => (input === '' ? Option.none() : Option.some(Search.OpenedResults())),
})

const searchView = (text: string, h: HtmlBuilder<Search>) =>
  SearchField.view(
    {
      id: 'find',
      label: 'Search products',
      value: text,
      onInput: text => Search.Typed({ text }),
      clear: { onClear: Search.Cleared() },
      routes: [openResults],
      style: Recipes.SearchField.style(),
    },
    h,
  )

The search update answers Cleared with SearchField.Focus({ id: 'find' }).

TagsInput

The tags are a list of chips named by the label, each with a Remove <tag> button (words.remove names it, words.mark is its ×), then a text input. Enter or the delimiter (default ,) adds the draft split at the delimiter and trimmed, refusing empty and repeated parts and parts past max: a refusal (TagsInput.Refusal: Repeat, Empty, Full) is said in a polite message (worded by words.repeat, words.empty and words.full) and shakes the field once, the shake travel-aware. Words are text with blanks, {tag} and {max}; TagsInput.words holds the English defaults and words takes any of them. addOnBlur adds the draft when the input loses focus (off by default).

Backspace in an empty input removes the last tag (Message.BackspacedEmpty, sent only when the input itself holds no text, so text typed since the last frame is edited, not skipped). The chips are one roving tab stop (Model.chip, set by Message.FocusMoved): ArrowLeft and ArrowRight, swapped by direction: 'rtl', move among them, Home and End go to the ends, Backspace and Delete remove the focused one, ArrowRight past the last returns to the input, and ArrowLeft from the start of the input's text, with nothing selected, enters the last chip. A removal, by button or key, focuses the chip that takes its place, else the one before it, else the input, through the Command update returns. The input's keys are Behaviors.Keys routes; routes adds the application's, and one on Enter, the delimiter or Backspace is a mixins:key-conflict. With name, one hidden input per tag, so a form submits the tags and not the draft.

FileInput

A FileInput is a native file input and the button that labels it, so a press on the button and Enter or Space on the focused input open the browser's dialog with no script. The application owns the chosen files, Files compared by identity: fold a pick in with FileInput.added(files, picked, { multiple }) (a single field takes the newest pick, multiple appends and skips a file already held by name, size, type and modification time), and answer onChange and onRemove with the FileInput.Sync({ id, files }) Command, which writes the list back into the input so a surrounding form submits exactly the list shown (Foldkit empties the input after each pick; an empty list resets its value, so a removed file can be chosen again). Answer onRemove with FileInput.Focus({ id }) as well, which puts focus on the input, since the button that held it left with its row, as SearchField.Focus does; both answer CompletedSync and CompletedFocus, which ...FileInput.cases adds to your Message union (a missing one is a type error where you return the Command). Each row has a remove button named Remove {name} (words: { remove? }). name, accept, multiple and required are the native attributes; invalid is aria-invalid, and description is read after the name. A disabled field takes no pick and its rows no remove.

Keeping the Files in the Model or a Message (Schema.instanceOf(File)) has a cost under vite dev: a File is not JSON, and Foldkit's dev-tools relay, which exists only where import.meta.hot does, has been seen to reject with SchemaError: Expected JSON value as an unhandled rejection. A production build has no relay; a test that fails on page errors (an end-to-end run against vite dev) should expect it.

ts
import { modifyFields } from 'foldkit/struct'
import type { Return } from 'foldkit/update'
import { FileInput, FileInputSlots } from 'foldkit-mixins-ui'

const FilesModel = Schema.Struct({ files: Schema.Array(Schema.instanceOf(File)) })
const FilesMessage = defineMessageUnion({
  Picked: { files: Schema.Array(Schema.instanceOf(File)) },
  Removed: { file: Schema.instanceOf(File) },
  ...FileInput.cases,
})
type FilesMessage = typeof FilesMessage.Type

const FileFieldStyle = Recipes.FileInput.style()

const filesUpdate = (
  model: typeof FilesModel.Type,
  message: FilesMessage,
): Return<typeof FilesModel.Type, FilesMessage> =>
  FilesMessage.match(message, {
    Picked: ({ files }) => {
      const next = FileInput.added(model.files, files, { multiple: true })
      return {
        model: modifyFields(model, { files: () => next }),
        commands: [FileInput.Sync({ id: 'cv', files: next })],
      }
    },
    Removed: ({ file }) => {
      const next = model.files.filter(each => each !== file)
      return {
        model: modifyFields(model, { files: () => next }),
        commands: [FileInput.Sync({ id: 'cv', files: next }), FileInput.Focus({ id: 'cv' })],
      }
    },
    CompletedSync: () => ({ model }),
    CompletedFocus: () => ({ model }),
  })

const filesView = (model: typeof FilesModel.Type, h: HtmlBuilder<FilesMessage>) =>
  FileInput.view(
    {
      id: 'cv',
      label: 'Attach files',
      name: 'attachments',
      multiple: true,
      files: model.files,
      onChange: files => FilesMessage.Picked({ files }),
      onRemove: file => FilesMessage.Removed({ file }),
      style: FileFieldStyle,
    },
    h,
  )

Nothing here reads the input: the browser's dialog, the native input and the form are the platform's, and the view declares them. Sync and Focus are the only calls that touch the page.

FileUpload

A FileUpload is a field that holds files and says what became of each: chosen by the dialog, dropped or pasted, judged against limits (kind, size, count, duplicates), listed with a thumbnail, and, when the application asks, sent. Its Model and update are the whole machine, which the application places and folds as it places TagsInput; the view draws them.

Choose by what you need to own:

You needUse
a native picker whose File[] you keep, with no checks, drop, previews or statusFileInput
a drop zone over @foldkit/ui's SubmodelFileDrop
files judged, listed, previewed, dropped, removed, retried, optionally sent and sortedFileUpload

It owns the list and each entry's status. It does not own the transport (the application's Subscription sends a file and answers in its own Messages), the order (the application places Reorder), or the bytes of an uploaded file (a Stored entry holds an address).

Offered -> validate -> Held | Queued -> Uploading(lane) -> Done | Failed -> Retried

A picked, dropped or pasted batch is one Offered Message. update checks each file (kind, then size, then duplicate), refuses a whole batch that would pass maxFiles, and lists the rest Held, or Queued when the field has lanes. A queued file starts as a lane frees. The Model keeps each File and writes the list back into the native input after every change (FileInput.Sync), so a plain form post carries exactly the local files, dropped ones included.

Place it in the application's Model and wrap its Messages:

ts
import * as Command from 'foldkit/command'
import { FileUpload, FileUploadSlots } from 'foldkit-mixins-ui'

const UpModel = Schema.Struct({ upload: FileUpload.Model })
type UpModel = typeof UpModel.Type
const UpMessage = defineMessageUnion({ GotUpload: { message: FileUpload.Message } })
type UpMessage = typeof UpMessage.Type

const upInit = (): UpModel => ({
  upload: FileUpload.init({
    id: 'documents',
    multiple: true,
    accept: ['.pdf', 'image/*'],
    maxFiles: 5,
    maxSize: 5_000_000,
  }),
})

const upUpdate = (model: UpModel, message: UpMessage): Return<UpModel, UpMessage> =>
  UpMessage.match(message, {
    GotUpload: ({ message: inner }) => {
      const { model: upload, commands } = FileUpload.update(model.upload, inner)
      return {
        model: upload === model.upload ? model : modifyFields(model, { upload: () => upload }),
        commands: Command.mapMessages(commands ?? [], next => UpMessage.GotUpload({ message: next })),
      }
    },
  })

const UpStyle = Recipes.FileUpload.style({ layout: 'zone' })

const upView = (model: UpModel, h: HtmlBuilder<UpMessage>) =>
  FileUpload.view(
    {
      model: model.upload,
      onMessage: message => UpMessage.GotUpload({ message }),
      label: 'browse',
      name: 'documents',
      words: { prompt: 'Drop files here or' },
      style: UpStyle,
    },
    h,
  )

init refuses an accept token that is not .ext, type/* or type/subtype, a negative or fractional maxSize, maxFiles or lanes, a maxFiles without multiple, and several initial files without it. update returns an OutMessage: Picked (the ids added and replaced, and every Refusal) after an offer, Removed after a removal. A no-op returns the Model it was given.

The picker. The input is a native type="file" drawn first, a transparent pixel rather than hidden, and the picker is its label, always its next sibling. A press on the picker, and Enter or Space on the focused input, open the browser's dialog with no script between; the picker rings on keyboard focus. The picker also owns the four drag events and data-dragging. Recipes.FileUpload's layout (button, zone, avatar, cover) only restyles it. What is drawn follows what the view is given, not the recipe: words.prompt draws a drop zone's invitation, picture draws the single-image face, description and the limits draw their paragraphs. The input is named by the picker's words (prompt and label), so give label the words that name the files.

Refusals and the live region. Each refusal names its file and is listed in errors, which is not live; one polite status region, drawn always, says each change once (3 added, Removed a.png, a.png uploaded) and never says a percentage. Two identical notices in a row are not spoken twice. words holds every sentence, with {name}, {count}, {max}, {size} and {reason} standing for what it is about.

Previews. An added image asks for an object URL through a Command and shows it in the row's preview. FileUpload.released(model) revokes every URL: call it from the Message that drops the widget (a route change, a dialog closing). Nothing revokes on unmount, so without it the URLs live until the document unloads.

A single image. Give picture a function from the first entry's address to what the picker holds. The list is not drawn, and the one file's Remove button follows the picker, over its corner in avatar and cover:

ts
const UpAvatarStyle = Recipes.FileUpload.style({ layout: 'avatar' })

const upAvatar = (model: UpModel, h: HtmlBuilder<UpMessage>) =>
  FileUpload.view(
    {
      model: model.upload,
      onMessage: message => UpMessage.GotUpload({ message }),
      label: 'Change photo',
      picture: url =>
        Option.match(url, {
          onNone: () => h.span([], ['No photo']),
          onSome: src => h.img([h.Src(src), h.Alt('')]),
        }),
      style: UpAvatarStyle,
    },
    h,
  )

Uploads. init({ lanes }) sends that many files at once; 0 sends nothing and every file stays Held. A queued file takes the first free lane, and a lane number holds for the whole send, so one Subscription entry per lane never restarts another's upload. The application supplies the send (foldkit-media/browser's uploadFile, a hand-written stream, a simulation) and answers in its own Messages, which fold Progressed, Succeeded or Failed back into the widget. FileUpload.lanes makes every lane's entry for a count, so the entries cannot be fewer than lanes: take the count from the one constant that feeds both.

ts
import { Stream } from 'effect'

const UP_LANES = 2

const upSubscriptions = FileUpload.lanes<UpModel, UpMessage>({
  count: UP_LANES,
  model: parent => parent.upload,
  send: job =>
    Stream.make(
      UpMessage.GotUpload({
        message: FileUpload.Message.Succeeded({
          id: job.id,
          attempt: job.attempt,
          url: Option.none(),
        }),
      }),
    ),
})

(FileUpload.lane({ lane, model, send }) is one lane's entry, for an application that names its Subscription entries itself.) Removing an uploading entry empties its lane, the entry's dependency changes and the request aborts: the same button reads Cancel {name} while a file uploads. A Failed answer says whether it may be retryable; Retried queues it again, as a new attempt. A Message of another attempt, or of an entry that is gone, changes nothing.

Progress is a value the application builds, so a field that sends nothing never loads the Progress widget. Give the view progress and an uploading row draws a bar (or, with Recipes.Progress({ shape: 'ring' }), a ring) named by Uploading {name}; without it the row says the same in its state text:

ts
import { FileUploadProgress } from 'foldkit-mixins-ui'

const UpBar = FileUploadProgress.make({ style: Recipes.Progress.style() })
// FileUpload.view({ ..., progress: UpBar }, h)

Pieces. FileUpload.parts(options, h) returns the drawings view assembles, apart: input, picker, errors, status, summary and an items entry per file with its preview, name, meta, state, progress, actions and grip (an uploading row with progress draws no state text). Lay them into Table.view or Card.view yourself; view is written in terms of parts, so there is one drawing.

Placed and configured. Bundles.FileUpload is the same init and update for foldkit-bundle, with init's options as the args. It reports Picked and Removed, which a placement answers with onOut or Bundle.ignore, and it sends nothing: an application with lanes still adds FileUpload.lanes to its own Subscriptions. FileUpload.configure({ base, presets }) returns { view, parts } bound to what a site gives once: style, words, picture, itemActions, progress and mixins. sort reads the Model at each draw and routes hold Messages, so both stay at the call.

Sorting. Order is the application's: it places Reorder as documented for primitives and hands the Behavior to the view as sort: { input, mixin }, which draws a grip per row, marks the list data-sortable and reads input for the Behavior. The widget imports neither Reorder nor its pointer drag, so a field with no sorting loads neither. The application's onOut applies the Moved fact with FileUpload.ordered and reads every fact out through the one live region with FileUpload.announce. A keyed move drops the browser's focus, so beside the widget's own focus Commands add FileUploadSort.keepFocus to mixins (it keeps a grip's focus and covers without); it is a module of its own because it loads FocusRecovery.

ts
import { Bundle } from 'foldkit-bundle'
import { Reorder } from 'foldkit-primitives/interaction'
import { FileUploadSort } from 'foldkit-mixins-ui'

const SortRows = Bundle.declare(Reorder.bundle, 'rows')
const SortModel = Schema.Struct({ ...SortRows.fields, upload: FileUpload.Model })
type SortModel = typeof SortModel.Type
const SortMessage = defineMessageUnion({
  ...SortRows.cases,
  GotUpload: { message: FileUpload.Message },
})
type SortMessage = typeof SortMessage.Type

const SortAssembly = Bundle.parent({ Model: SortModel, Message: SortMessage }).assemble(
  Bundle.parent({ Model: SortModel, Message: SortMessage }).at(SortRows, {
    onOut: (fact: Reorder.OutMessage) => (model: SortModel) => {
      const label = (id: string) => model.upload.entries.find(entry => entry.id === id)?.name ?? id
      const said = FileUpload.announce(model.upload, Reorder.announcement(fact, { label }))
      return {
        model: Reorder.OutMessage.match(fact, {
          Moved: move =>
            modifyFields(model, {
              upload: () =>
                FileUpload.ordered(said, Reorder.apply(FileUpload.ids(model.upload), move)),
            }),
          PickedUp: () => modifyFields(model, { upload: () => said }),
          PassedOver: () => modifyFields(model, { upload: () => said }),
          PutBack: () => modifyFields(model, { upload: () => said }),
        }),
      }
    },
  }),
)

const Sorting = Reorder.behavior(SortRows)(FileUploadSlots)<SortModel, SortMessage>({
  container: 'list',
  item: 'item',
  handle: 'grip',
  items: model => FileUpload.ids(model.upload),
  orientation: 'both',
})
// FileUpload.view({ ..., sort: { input: model, mixin: Sorting.mixin }, mixins: FileUploadSort.keepFocus }, h)

Keys. Enter and Space belong to the dialog, and Backspace and Delete on the input remove the last file; routes takes the rest. A route on one of those four throws mixins:key-conflict, and FileUpload.conflict(routes) returns that diagnostic without drawing.

Forms. name goes on the real input, and Sync runs after every change. A Stored entry is not in the input: post its address with a hidden input of your own. Give no name when lanes sends the bytes. required is the native attribute, and a field with only stored files fails it, since the input holds none. disabled disables the input and the buttons; readOnly draws no picker, remove or grip and keeps the input out of the tab order, so a form still posts.

Failure and recovery. A Model holding a Local entry is not JSON: settled(model) turns uploaded entries into stored ones, drops every other local file and clears dragging, the refusals, the notice and the previews, and the result encodes and decodes. A removed entry takes its button, so focus moves by Command to the next entry's remove button, else the previous, else the input; FileUpload.without(model, ids) removes for the application and moves no focus. Dropping files, writing input.files and the synthetic drop are proven in Chromium only.

Other fields

  • NumberField. value is an Option<number> (Option.none() clears aria-valuenow and starts steppers from the bounds; clearing text emits Option.none()). locale formats and parses localized numbers (de-DE: 1.234,5), or pass custom format/parse (NumberField.parseNumber and NumberField.settled are pure helpers). Arrows, PageUp/PageDown, Home/End step the value; steppers sit outside tab order and disable at bounds; readOnly leaves text selectable with steppers disabled; name submits the formatted text.
  • OtpField. One native input (autocomplete="one-time-code") mirrored across visual cells, with the next empty cell marked data-next and mask hiding digits as password dots. OtpField.kept(text, length, pattern) filters pasted text; readOnly allows copying and invalid marks the input aria-invalid and cells data-invalid.
  • InputCopy. Stateless view; handle onCopy with InputCopy.Copy({ text }) (ClipboardMessage). InputCopy.init({ resetAfter? }) (default 2000 ms) and InputCopy.update (or Bundles.InputCopy) manage the copied and failed indicators in a polite status region (words: copy, copied, failed).
  • PasswordInput. Keeps spellcheck and autocorrect off, maps autocomplete (current-password default, or new-password), and renders optional strength (Meter.view), requirements (words.met / words.unmet), and polite Caps Lock warning (capsLockOf). Your Model owns the text; PasswordInput.init/update (or Bundles.PasswordInput) owns visibility and Caps Lock state via ...PasswordInput.controls(model, onMessage). Supports resumable OnInput attributes ({ input: [rh.KeepTyped()] }; see Form participation).
  • Label, Field, and Fieldset. Label connects to a control by for (derived via FieldAssociation), marks required visually and optional audibly, and sets data-disabled/data-invalid. Field wraps any custom control with header, label, description, and error alert (Field.describedBy(h, id, { description, errors }) links descriptions before rendering). Fieldset adapts <fieldset> with plain, bordered, and filled variants.
  • FileDrop. Adapter over @foldkit/ui/fileDrop using a File codec without decoding services; Bundles.FileDrop places its Model with { id } and reports ReceivedFiles or RejectedNonFiles in onOut. Render with h.submodel and FileDrop.toView; Recipes.FileDrop rings keyboard focus and dims disabled drop zones.