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.
"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>
);
}/* 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);
}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><label for>, Field.Label or aria-label.<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.| What happens | |
|---|---|
| Typing | Each 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 key | The 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 change | A draft equal to the shown value (typed and deleted again) commits nothing. disabled and readOnly clear the draft and commit nothing. |
| Escape | With 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. |
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.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.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.await, wrap the update in startTransition.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.| Prop | Type | Default | Description |
|---|---|---|---|
value | string | – | The saved text, controlled. undefined is uncontrolled. |
defaultValue | string | "" | Initial saved text in uncontrolled mode; also the form-reset target. |
valueCommitAction | ChangeAction<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. |
name | string | – | Native name: the form posts the text shown. Or the Field's. |
disabled | boolean | false | Native disabled, or the enclosing Field.Root's; never dispatches. A disabled field is not submitted. |
readOnly | boolean | false | Native 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. |
required | boolean | false | Native required; also when the enclosing Field is required. |
type | string | "text" on the default element | text, 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. |
className | string | ((state: TextFieldState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: TextFieldState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
render | ReactElement | ((props, state: TextFieldState) => ReactNode) | – | Replace the default <input> (element form) or take over rendering (function form). |
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).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.
| Attribute | On | Meaning |
|---|---|---|
data-pending | TextField | A commit is in flight (including the Suspense wait of its render). |
data-disabled | TextField | The disabled prop, or the Field's. |
data-readonly | TextField | The readOnly prop, or the Field's. |
data-invalid | TextField | Inside a Field that shows an error; never outside one. |
:focus, :read-only, :placeholder-shown, :user-invalid | TextField | The platform's own states: being edited, read-only, empty, invalid after an edit. |
| Key | Where | Behaviour |
|---|---|---|
| Tab | an <input> or a <textarea> | Reaches the field; leaving it commits. |
| Enter | an <input> | Commits. Not prevented: inside a form the implicit submission follows. |
| Ctrl+Enter / Cmd+Enter | a <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+Enter | a <textarea> | A new line. Nothing is committed. |
| Alt+Enter | a <textarea> | Not the field's key: the browser decides (it inserts nothing in current engines). Nothing is committed. |
| Escape | an <input> or a <textarea> | With an edited draft: reverts it and is consumed. Otherwise not handled (an enclosing dialog closes). |
| Any other key | an <input> or a <textarea> | Native text editing. |
aria-describedby names.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.data-pending): no aria-busy, no native disabled, no announcement. The field stays editable while a save runs.The library says nothing by itself; what the user is told is your element.
role="status") or a toast. If nothing is shown, nothing is announced.aria-describedby names, with role="alert" (the first example).role="status", named by the field's aria-describedby so it is read again when the user returns (the example below).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; }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.
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.
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.
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>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.data-pending on the field for its save, on Form.Submit and the Field parts for the submission.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.valueCommitAction={() => formRef.current?.requestSubmit()}.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();
}}
>/* 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.
<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>"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>
);
}/* 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>}