FUNSTACK UI

HomeWhyGetting startedConceptsComponentsRoadmap
GitHub

FUNSTACK UI is in beta. Part of the FUNSTACK family with FUNSTACK Router and FUNSTACK Static, which build this site.

Introduction

  • Why FUNSTACK UI
  • Overview
  • Getting started

Concepts

  • Action props
  • Pending & optimistic state
  • Transitions & ViewTransition
  • Suspense
  • Browser-owned state
  • Server Components

Guides

  • Replacing the element (render)
  • Direction and locales
  • Experimental features
  • Next.js App Router
  • React Router framework mode
  • Content Security Policy
  • Using with AI agents

Components

  • Buttons
    • Button
    • Toggle
    • ToggleGroup
    • Toolbar
  • Disclosure
    • Tabs
    • Accordion
    • Collapsible
    • NavigationMenu
  • Overlays
    • Tooltip
    • HoverCard
    • Popover
    • Dialog
    • AlertDialog
    • Drawer
    • Menu
    • Context menu (Menu)
    • Menubar (Menu)
    • Toast
  • Forms
    • Field and Form
    • Checkbox
    • CheckboxGroup
    • RadioGroup
    • Switch
    • Select
    • Combobox
    • MultiSelect
    • Slider
    • NumberField
    • OTPField
    • TextField
  • Output
    • Progress
    • Meter
    • Avatar
  • Layout
    • Separator
    • Scroll areas (recipe)

Resources

  • Roadmap & changelog
  • GitHub ↗

TextField

A text field that saves itself. The user types freely; when they are done (they leave the field, or press Enter; Ctrl+Enter / Cmd+Enter in a textarea) the field asks for the new text through valueCommitAction, shows data-pending while the save runs, and goes back to the saved text if the save is refused. Escape puts the saved text back. It is one <input>, or a <textarea> through render.

It is not the library's text input: a text control with no save of its own is the native element, or Field.Control inside a Field.

Quarterly report

Show code
TextFieldRename.tsx
"use client";
import { startTransition, useState } from "react";
import { TextField } from "@funstack/ui/text-field";
import { sleep } from "./fake-api.js";

// A pretend rename. The server refuses an empty title and one that ends in "!": it resolves with
// a message (a refusal is not an error).
async function rename(title: string): Promise<{ ok: true } | { ok: false; message: string }> {
  await sleep(800);
  if (title.trim() === "") return { ok: false, message: "A document needs a title." };
  if (title.endsWith("!")) return { ok: false, message: "Titles cannot end with “!”." };
  return { ok: true };
}

// Roll back: edit the title, then Tab away or press Enter. The field pends while the save runs
// (dimmed), and the heading follows when it succeeds. End the title with "!" to see a refusal:
// the saved title comes back and the message says why. Escape while editing puts it back too.
export function TextFieldRename() {
  const [title, setTitle] = useState("Quarterly report");
  const [error, setError] = useState<string | null>(null);
  return (
    <div className="demo-stack">
      <h4 className="demo-text-heading">{title}</h4>
      <TextField
        aria-label="Title"
        aria-describedby="rename-error"
        className="demo-text-title"
        value={title}
        valueCommitAction={async (next) => {
          const result = await rename(next);
          // After an await: re-wrap the update in a transition.
          if (result.ok) startTransition(() => setTitle(next));
          else startTransition(() => setError(result.message));
        }}
        onInput={() => setError(null)}
      />
      <p id="rename-error" role="alert" className="demo-text-error">
        {error}
      </p>
    </div>
  );
}
text-field.css
/* TextField: the title reads as text until it is used (field-sizing: content, a border that
   appears on hover and focus); the notes are an ordinary textarea. Both dim while a save runs. */
.demo-text-heading {
  margin: 0;
  font-size: 1.1rem;
}

.demo-text-title {
  field-sizing: content;
  min-inline-size: 4ch;
  max-inline-size: 100%;
  border: 1px solid transparent;
  border-radius: 6px;
  padding: 0.25rem 0.4rem;
  background: transparent;
  color: var(--color-text);
  font: inherit;
  font-size: 1.25rem;
  font-weight: 600;
}

.demo-text-title:hover,
.demo-text-title:focus-visible {
  border-color: var(--color-border);
}

.demo-text-title:focus-visible {
  outline: 2px solid var(--color-primary);
  outline-offset: 1px;
}

.demo-text-title:not(:focus) {
  text-overflow: ellipsis;
}

.demo-text-label {
  font-weight: 600;
  color: var(--color-text);
}

.demo-text-notes {
  inline-size: min(100%, 28rem);
  border: 1px solid var(--color-border);
  border-radius: 8px;
  padding: 0.5rem 0.6rem;
  background: var(--color-bg);
  color: var(--color-text);
  font: inherit;
}

.demo-text-title[data-pending],
.demo-text-notes[data-pending] {
  color: var(--color-text-secondary);
}

.demo-text-error {
  margin: 0;
  min-block-size: 1.25em;
  color: #dc2626;
}

.demo-text-status {
  margin: 0;
  min-block-size: 1.25em;
  color: var(--color-text-secondary);
}

A refused save rolls the text back

When valueCommitAction rejects, or a controlled parent does not adopt the text, the field shows the saved text again. For a title that costs a few characters; for a paragraph it costs the paragraph. Choose in the action: do not adopt and say why (roll back, above), or adopt and say it is not saved (keep the text, below).

Async and platform behaviour: Transition types · Optimistic and pending · Suspense · Browser-owned state · Before hydration

Anatomy

import { TextField } from "@funstack/ui/text-field";

// A document title: saved on blur or Enter, back to the saved title if the save throws.
<TextField aria-label="Title" defaultValue={doc.title} valueCommitAction={renameDocument} />

// Notes, several lines: saved when the user leaves the field, or presses Ctrl+Enter / Cmd+Enter.
<TextField render={<textarea rows={4} />} aria-label="Notes" defaultValue={notes} valueCommitAction={saveNotes} />

// In a Field: the label, the description and validation are the Field's.
<Field.Root name="displayName" required>
  <Field.Label>Display name</Field.Label>
  <TextField defaultValue={user.displayName} valueCommitAction={saveDisplayName} maxLength={40} />
  <Field.Error />
</Field.Root>
  • One element. No Root, no Label, no read view: the input is always there, styled to read as text until it is used (Styling). Name it with a <label for>, Field.Label or aria-label.
  • Supported elements: an <input> of type text (the default), tel, url, email or password, or a <textarea>. Any other type, as a prop or on the render element, logs a development warning and is rendered as given.

type="search" is not supported

In a search field Escape is the browser's own key: it empties the field, and that clear already keeps an enclosing dialog or popover open. It cannot be turned off while leaving Escape to the dialog, so a search field would give Escape two meanings ("empty the field" and "back to the saved text"). TextField keeps one Escape rule instead. For a search box that saves itself, use type="text" with role="searchbox" (the role type="search" gives) and enterKeyHint="search" for the on-screen keyboard:

<TextField type="text" role="searchbox" enterKeyHint="search" aria-label="Saved search" … />

The browser's clear button is not carried over: render a button next to the field if you want one. A search box with no save of its own that wants the browser's Escape is a native <input type="search"> or Field.Control.

How it works

Draft and commit

What happens
TypingEach input event (typing, paste, autofill, an IME) writes the draft. Shown at once; nothing is dispatched. The caret, selection and undo are the browser's.
Blur, the commit keyThe commit: the draft is cleared and valueCommitAction(next, { reason: "activate" }) runs in the field's transition, with data-pending. The commit key is Enter in an <input>: not prevented, so a form's implicit submission follows with the same text. In a <textarea> it is Ctrl+Enter / Cmd+Enter (either, on every platform): always prevented, so no line is added, and it submits no form. Enter alone or with Shift is a new line there; Alt+Enter is not the field's key (the browser decides). An Enter that confirms an IME composition commits nothing.
No changeA draft equal to the shown value (typed and deleted again) commits nothing. disabled and readOnly clear the draft and commit nothing.
EscapeWith an edited draft: the saved (or pending) text shows again, nothing is dispatched, and the key is consumed, so an enclosing Dialog or Popover stays open. The next Escape is not the field's.
  • The action is always called, also for text that fails required, pattern, minLength or a Field's validate, and it is told: details.valid is false. An action that must not save it returns early: if (!details.valid) return;. See details.valid.
  • Invalid text stays a draft (uncontrolled). The commit runs the action (with data-pending) but writes nothing: the text stays in the field as typed, also after the blur, with the Field's error; state.text is that text and state.value is still the saved one. A second blur or Enter on the unchanged text calls nothing. Escape shows the saved text again; fixing the text and committing is a normal save; a form reset, or disabled / readOnly turning on, drops it. A later save that fails rolls back to the saved text, never to the invalid one. If the action rejects the invalid commit itself (a throw, or return details.reject()), the draft is dropped and the saved text shows. Because the library never rewrites the draft, the browser keeps flagging minLength / maxLength, which it checks only for text the user edited. Controlled, nothing of this applies: the draft is cleared at the commit and a parent that does not adopt the text shows the saved one. A form reset is written whatever its validity.
  • A controlled value that changes from outside shows at once when no draft is open; while one is open the draft wins, and Escape then shows the new value.
  • Nothing commits at unmount: an open draft is dropped.
  • The text is committed as typed: no trimming. A parent that normalises adopts the normalised text.

A save that fails

  • Uncontrolled, the value is written when the action resolves. A rejection reaches the Error Boundary above the field, and the text goes back. An action that catches its own failure resolves, so the new text stays: that is how to keep it without a parent.
  • Controlled, a parent that does not adopt gets the saved text back once the action has settled. After an await, wrap the update in startTransition.
  • A draft the user opened while the save ran stays on screen; it commits at their next blur or commit key.
  • A second commit while the first runs replaces it (latest wins); data-pending stays until both settled. An action that must not be overtaken on the wire aborts or sequences itself. Return without awaiting ((next) => { void save(next); }) for a save nothing should wait for.

Props

PropTypeDefaultDescription
valuestring–The saved text, controlled. undefined is uncontrolled.
defaultValuestring""Initial saved text in uncontrolled mode; also the form-reset target.
valueCommitActionChangeAction<string, TextFieldValueCommitDetails>–Once per edit (blur, Enter in an input, Ctrl+Enter / Cmd+Enter in a textarea), and for a form reset or text adopted at mount. Runs in the field's transition and is awaited, with data-pending. Uncontrolled state is committed when it resolves. May be a Server Function.
namestring–Native name: the form posts the text shown. Or the Field's.
disabledbooleanfalseNative disabled, or the enclosing Field.Root's; never dispatches. A disabled field is not submitted.
readOnlybooleanfalseNative readonly, or the enclosing Field.Root's: no editing, nothing commits, data-readonly. The text is focusable, selectable and submitted, and the platform bars it from validation. Text the browser restored at hydration is put back, not committed.
requiredbooleanfalseNative required; also when the enclosing Field is required.
typestring"text" on the default elementtext, tel, url, email or password. Others warn in development (search is not supported: use type="text" with role="searchbox" and enterKeyHint="search"). The library sets type="text" only on its default <input>: a render element keeps its own type (a <textarea> gets none, an <input> without one is a text input).
placeholder, maxLength, minLength, pattern, autoComplete, inputMode, enterKeyHint, spellCheck, form, id, aria-*native attributes–Passed through, with no library default (no autocomplete="off": a name or an address may be offered by autofill). Inside a Field the id is the Field's.
classNamestring | ((state: TextFieldState) => string | undefined)–A class name, or a function of the part's state.
styleCSSProperties | ((state: TextFieldState) => CSSProperties | undefined)–Inline style, or a function of the part's state.
renderReactElement | ((props, state: TextFieldState) => ReactNode)–Replace the default <input> (element form) or take over rendering (function form).
State
TextFieldState is { value, text, pending, disabled, readOnly, required, invalid }: value is the shown value (optimistic), text the shown text (the draft while the user is editing, else value), pending a valueCommitAction in flight, invalid an error shown by an enclosing Field.Root (data-invalid; false outside one).
Owned
value (the shown text), onChange, onKeyDown, onBlur (onInput, onFocus, onKeyUp and the rest pass through), data-pending, data-disabled, data-readonly; inside a Field also id, name, disabled, required, readOnly, aria-invalid, aria-describedby (token-merged) and data-invalid.

TextFieldValueCommitDetails is { reason, valid, event }: "activate" for a commit (event is the focusout or the keydown of the commit key), "platform" for a form reset (the reset event) and text adopted at mount (undefined); valid: the field would be valid holding the committed text (native constraints, the Field's validate; tooShort / tooLong only as the platform flags them, for edited text). Serialisable: a Server Function receives { reason, valid }. In development a field with no accessible name (no <label>, Field.Label, aria-label or aria-labelledby) logs a warning.

Data attributes

AttributeOnMeaning
data-pendingTextFieldA commit is in flight (including the Suspense wait of its render).
data-disabledTextFieldThe disabled prop, or the Field's.
data-readonlyTextFieldThe readOnly prop, or the Field's.
data-invalidTextFieldInside a Field that shows an error; never outside one.
:focus, :read-only, :placeholder-shown, :user-invalidTextFieldThe platform's own states: being edited, read-only, empty, invalid after an edit.

Keyboard and ARIA

KeyWhereBehaviour
Taban <input> or a <textarea>Reaches the field; leaving it commits.
Enteran <input>Commits. Not prevented: inside a form the implicit submission follows.
Ctrl+Enter / Cmd+Entera <textarea>Commits, as a blur does. Always prevented, even when there is nothing to commit, so no line is added; focus and the caret stay. Submits no form.
Enter / Shift+Entera <textarea>A new line. Nothing is committed.
Alt+Entera <textarea>Not the field's key: the browser decides (it inserts nothing in current engines). Nothing is committed.
Escapean <input> or a <textarea>With an edited draft: reverts it and is consumed. Otherwise not handled (an enclosing dialog closes).
Any other keyan <input> or a <textarea>Native text editing.
  • Nothing on a textarea says that Ctrl+Enter saves, and the library adds no text. Blur saves as well, so the key is a shortcut; a page that relies on it says so in visible text the field's aria-describedby names.
  • A native textbox with its label and value, always present and always in the Tab order. There is no read view that turns into an input, so focus never moves and there is no built-in string.
  • Pending is visual only (data-pending): no aria-busy, no native disabled, no announcement. The field stays editable while a save runs.
  • A revert or a rollback writes the input, so the browser's undo history for the field is gone after it (all three engines).

Telling the user about a save

The library says nothing by itself; what the user is told is your element.

  • Saved. If the page shows a "Saved" mark, make it a status message (role="status") or a toast. If nothing is shown, nothing is announced.
  • Failed, rolled back. The text changes while the user is somewhere else, so a message is required: a toast, or text in an element the field's aria-describedby names, with role="alert" (the first example).
  • Failed, text kept. A "Not saved" text with role="status", named by the field's aria-describedby so it is read again when the user returns (the example below).

Transition types

Concept: Transitions & ViewTransition

Each commit adds fsui-text-field and fsui-text-field-commit; a rollback carries none. No transition prop and no built-in <ViewTransition>: key your own boundary around content the saved text drives (a heading).

::view-transition-old(.doc-title):active-view-transition-type(fsui-text-field-commit) { animation: fade-out .15s; }

Optimistic and pending

Concept: Pending & optimistic state

The draft is urgent library state written from the input event. At the commit the shown value becomes the new text optimistically, so the characters on screen do not change and the caret stays. data-pending until the save (and the render it caused) settles; the field is never disabled meanwhile.

Suspense

Concept: Suspense

Content the saved value drives re-renders in the commit's transition; if it suspends, what is shown stays and the field keeps data-pending until it is ready. The field's own function props must not suspend.

Browser-owned state

Concept: Browser-owned state

Focus, selection, composition and validity are the browser's. A form reset (a reset button, form.reset(), React's reset after a form action, Form.Root's autoReset) clears an open draft and offers the reset target through valueCommitAction with reason: "platform" and the reset event, unless it is what the field already shows. An action that saves checks details.reason if a reset must not be saved.

Before hydration

Concept: Server Components

The server HTML is the input with its value. Text typed before hydration is adopted at mount: still focused, it becomes the draft and the user's blur or commit key commits it; otherwise it is one "platform" commit with no event (a browser's form-state restoration after a reload takes the same path). Nothing is saved without JavaScript. The JS-free way to save one text is a form, which Enter submits natively.

<form action={rename}><input name="title" defaultValue={title} /></form>

Forms

  • One element: it carries name, the constraints and the text the form posts, which is the draft while one is open. A form submitted by a button while the field is focused posts what the user sees.
  • Enter inside a form dispatches the commit first, then the implicit submission runs the form's action with the same text. The two are independent channels: data-pending on the field for its save, on Form.Submit and the Field parts for the submission.
  • Inside a Field.Root the field is the Field's control, as Field.Control is: Field.Label's for names it, the description and error describe it, validate sees the text per keystroke, and a server error is dismissed by the first keystroke. An Escape revert and a rollback re-run validate.
  • A textarea submits nothing, with any key: its Ctrl+Enter / Cmd+Enter only commits (below).
  • "Submit when the user is done with this field" is valueCommitAction={() => formRef.current?.requestSubmit()}.

Submit a form from a textarea

A form that wants Ctrl+Enter / Cmd+Enter to submit says so once, on the form, for every textarea in it (a TextField or not). The handler runs after the field's, as the event bubbles, so a TextField has dispatched its commit first, the order an input's Enter has. Do not skip a prevented event: the field prevents its key. An <input> needs nothing, it has the native submission.

<Form.Root
  action={post}
  onKeyDown={(event) => {
    const { isComposing, keyCode } = event.nativeEvent;
    if (!(event.target instanceof HTMLTextAreaElement) || isComposing || keyCode === 229) return;
    if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) event.currentTarget.requestSubmit();
  }}
>

Styling

/* Reads as text until it is used; as wide as its content. */
.title { field-sizing: content; min-inline-size: 4ch; border: 1px solid transparent; font: inherit; }
.title:hover, .title:focus-visible { border-color: var(--border); }
.title:not(:focus) { text-overflow: ellipsis; }
.title[data-pending] { color: var(--muted); }
/* A spinner next to it: an input has no pseudo-elements, so the wrapper draws it. */
.cell:has(.title[data-pending])::after { content: ""; /* spinner */ }

Keep a visible affordance when you remove the border: a hover and focus style at least. A field that looks exactly like text is not discoverable.

Recipes

Roll back and say why

<TextField
  value={title}
  aria-describedby="title-error"
  valueCommitAction={async (next) => {
    const result = await rename(id, next);
    if (result.ok) startTransition(() => setTitle(next));   // after an await: re-wrap
    else startTransition(() => setError(result.message));   // not adopted: the old title returns
  }}
/>
<p id="title-error" role="alert">{error}</p>

Keep the text and say it is not saved

Show code
TextFieldNotes.tsx
"use client";
import { startTransition, useState } from "react";
import { Button } from "@funstack/ui/button";
import { TextField } from "@funstack/ui/text-field";
import { sleep } from "./fake-api.js";

// Keep the text: write some notes and leave the field or press Ctrl+Enter / Cmd+Enter (Enter is a
// new line). With "Make the save fail" on, the notes stay as typed, marked "Not saved", with a retry.
export function TextFieldNotes() {
  const [fail, setFail] = useState(false);
  const [notes, setNotes] = useState("Call the printer about the cover.");
  const [unsaved, setUnsaved] = useState(false);

  async function save(_next: string): Promise<boolean> {
    await sleep(800);
    return !fail;
  }

  return (
    <div className="demo-stack">
      <label className="demo-field">
        <input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} />
        Make the save fail
      </label>
      <label htmlFor="notes" className="demo-text-label">
        Notes
      </label>
      <TextField
        id="notes"
        aria-describedby="notes-status"
        className="demo-text-notes"
        render={<textarea rows={4} />}
        value={notes}
        valueCommitAction={async (next) => {
          const ok = await save(next);
          // Adopt the text either way: nothing the user typed is lost.
          startTransition(() => {
            setNotes(next);
            setUnsaved(!ok);
          });
        }}
      />
      <p id="notes-status" role="status" className="demo-text-status">
        {unsaved ? "Not saved." : ""}
      </p>
      {unsaved && (
        <Button
          className="demo-button"
          action={async () => {
            const ok = await save(notes);
            startTransition(() => setUnsaved(!ok));
          }}
        >
          Try again
        </Button>
      )}
    </div>
  );
}
text-field.css
/* TextField: the title reads as text until it is used (field-sizing: content, a border that
   appears on hover and focus); the notes are an ordinary textarea. Both dim while a save runs. */
.demo-text-heading {
  margin: 0;
  font-size: 1.1rem;
}

.demo-text-title {
  field-sizing: content;
  min-inline-size: 4ch;
  max-inline-size: 100%;
  border: 1px solid transparent;
  border-radius: 6px;
  padding: 0.25rem 0.4rem;
  background: transparent;
  color: var(--color-text);
  font: inherit;
  font-size: 1.25rem;
  font-weight: 600;
}

.demo-text-title:hover,
.demo-text-title:focus-visible {
  border-color: var(--color-border);
}

.demo-text-title:focus-visible {
  outline: 2px solid var(--color-primary);
  outline-offset: 1px;
}

.demo-text-title:not(:focus) {
  text-overflow: ellipsis;
}

.demo-text-label {
  font-weight: 600;
  color: var(--color-text);
}

.demo-text-notes {
  inline-size: min(100%, 28rem);
  border: 1px solid var(--color-border);
  border-radius: 8px;
  padding: 0.5rem 0.6rem;
  background: var(--color-bg);
  color: var(--color-text);
  font: inherit;
}

.demo-text-title[data-pending],
.demo-text-notes[data-pending] {
  color: var(--color-text-secondary);
}

.demo-text-error {
  margin: 0;
  min-block-size: 1.25em;
  color: #dc2626;
}

.demo-text-status {
  margin: 0;
  min-block-size: 1.25em;
  color: var(--color-text-secondary);
}
<TextField
  value={notes}
  render={<textarea rows={4} />}
  aria-describedby="notes-status"
  valueCommitAction={async (next) => {
    const result = await saveNotes(id, next);
    startTransition(() => { setNotes(next); setUnsaved(!result.ok); });
  }}
/>
<p id="notes-status" role="status">{unsaved ? "Not saved." : ""}</p>
{unsaved && <Button action={() => retry(notes)}>Try again</Button>}