Examples
Save and recover changes
Compare a draft with its saved snapshot, validate fields, and recover from a failed save.
Workspace settings with draft, validation, saving, failure, and discard states
"use client";
import { useEffect, useId, useRef, useState } from "react";
import type { FormEvent } from "react";
import { CheckCircleIcon } from "@phuctech/ui/icons";
import { Button } from "@phuctech/ui/components/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@phuctech/ui/components/card";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@phuctech/ui/components/dialog";
import { Field, FieldDescription, FieldError, FieldLabel } from "@phuctech/ui/components/field";
import { Input } from "@phuctech/ui/components/input";
type SettingsValues = {
workspaceName: string;
replyTo: string;
};
type SettingsField = keyof SettingsValues;
type SettingsErrors = Partial<Record<SettingsField, string>>;
type SaveState = "idle" | "saving" | "saved" | "error";
const initialSettings: SettingsValues = {
workspaceName: "PhucTech",
replyTo: "hello@phuctech.dev",
};
const fields: readonly SettingsField[] = ["workspaceName", "replyTo"];
function validateField(field: SettingsField, value: string) {
if (field === "workspaceName" && value.trim().length < 3) {
return "Use at least three characters for the workspace name.";
}
if (field === "replyTo" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim())) {
return "Enter a valid reply-to email, such as name@example.com.";
}
return undefined;
}
function validate(values: SettingsValues): SettingsErrors {
return Object.fromEntries(
fields.flatMap((field) => {
const error = validateField(field, values[field]);
return error ? [[field, error]] : [];
}),
) as SettingsErrors;
}
function focusElement(target: HTMLElement | null) {
target?.focus({ preventScroll: true });
target?.scrollIntoView?.({ block: "center", inline: "nearest" });
}
export function SettingsPattern() {
const [draft, setDraft] = useState<SettingsValues>(() => ({ ...initialSettings }));
const [saved, setSaved] = useState<SettingsValues>(() => ({ ...initialSettings }));
const [errors, setErrors] = useState<SettingsErrors>({});
const [saveState, setSaveState] = useState<SaveState>("idle");
const [serviceError, setServiceError] = useState("");
const [failNextSave, setFailNextSave] = useState(false);
const [discardOpen, setDiscardOpen] = useState(false);
const [invalidSubmitCount, setInvalidSubmitCount] = useState(0);
const [discardCount, setDiscardCount] = useState(0);
const firstInvalidFieldRef = useRef<SettingsField | null>(null);
const nameInputRef = useRef<HTMLInputElement>(null);
const replyInputRef = useRef<HTMLInputElement>(null);
const statusRef = useRef<HTMLDivElement>(null);
const saveTimerRef = useRef<number | null>(null);
const idPrefix = `workspace-settings-${useId().replace(/:/g, "")}`;
const formTitleId = `${idPrefix}-title`;
const nameId = `${idPrefix}-name`;
const nameHelpId = `${idPrefix}-name-help`;
const nameErrorId = `${idPrefix}-name-error`;
const replyId = `${idPrefix}-reply`;
const replyHelpId = `${idPrefix}-reply-help`;
const replyErrorId = `${idPrefix}-reply-error`;
const identityHeadingId = `${idPrefix}-identity`;
const notificationsHeadingId = `${idPrefix}-notifications`;
const saving = saveState === "saving";
const hasChanges = draft.workspaceName !== saved.workspaceName || draft.replyTo !== saved.replyTo;
useEffect(() => {
if (invalidSubmitCount === 0) return;
const target = firstInvalidFieldRef.current === "workspaceName"
? nameInputRef.current
: replyInputRef.current;
focusElement(target);
}, [invalidSubmitCount]);
useEffect(() => {
if (discardCount > 0) focusElement(nameInputRef.current);
}, [discardCount]);
useEffect(() => {
if (saveState === "saving") focusElement(statusRef.current);
}, [saveState]);
useEffect(() => () => {
if (saveTimerRef.current !== null) window.clearTimeout(saveTimerRef.current);
}, []);
function updateValue(field: SettingsField, value: string) {
if (saving) return;
setDraft((current) => ({ ...current, [field]: value }));
setErrors((current) => {
if (!current[field]) return current;
const next = { ...current };
const error = validateField(field, value);
if (error) next[field] = error;
else delete next[field];
return next;
});
setSaveState("idle");
setServiceError("");
}
function validateOnBlur(field: SettingsField) {
if (saving) return;
const error = validateField(field, draft[field]);
setErrors((current) => {
const next = { ...current };
if (error) next[field] = error;
else delete next[field];
return next;
});
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (saving || !hasChanges) return;
const nextErrors = validate(draft);
setErrors(nextErrors);
setServiceError("");
const firstInvalidField = fields.find((field) => nextErrors[field]);
if (firstInvalidField) {
firstInvalidFieldRef.current = firstInvalidField;
setInvalidSubmitCount((count) => count + 1);
setSaveState("error");
return;
}
const nextValues = {
workspaceName: draft.workspaceName.trim(),
replyTo: draft.replyTo.trim(),
};
const shouldFail = failNextSave;
setFailNextSave(false);
setSaveState("saving");
saveTimerRef.current = window.setTimeout(() => {
saveTimerRef.current = null;
if (shouldFail) {
setServiceError("The simulated save failed. Your changes are still here; try again.");
setSaveState("error");
return;
}
setSaved(nextValues);
setDraft(nextValues);
setSaveState("saved");
}, 450);
}
function handleDiscard() {
if (saving) return;
setDraft({ ...saved });
setErrors({});
setServiceError("");
setFailNextSave(false);
setSaveState("idle");
setDiscardOpen(false);
setDiscardCount((count) => count + 1);
}
return (
<Card className="w-full max-w-2xl min-w-0">
<form onSubmit={handleSubmit} noValidate aria-labelledby={formTitleId}>
<CardHeader>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<CardTitle id={formTitleId}>Workspace settings</CardTitle>
<CardDescription>
Edit this local example. Saving updates its snapshot without making a backend request.
</CardDescription>
</div>
{hasChanges ? (
<span className="rounded-full border border-[color:var(--color-warning-border)] bg-[color:var(--color-warning-bg)] px-2 py-1 text-xs font-medium text-[color:var(--color-warning-text)]">
Unsaved changes
</span>
) : null}
</div>
</CardHeader>
<CardContent className="grid min-w-0 gap-6">
<section className="grid min-w-0 gap-4" aria-labelledby={identityHeadingId}>
<div>
<h4 id={identityHeadingId} className="text-sm font-semibold text-foreground">
Workspace identity
</h4>
<p className="mt-1 text-sm text-muted-foreground">
This name appears in invitations and project headers.
</p>
</div>
<Field invalid={Boolean(errors.workspaceName)}>
<FieldLabel htmlFor={nameId}>Workspace name</FieldLabel>
<Input
ref={nameInputRef}
id={nameId}
name="workspaceName"
value={draft.workspaceName}
onChange={(event) => updateValue("workspaceName", event.target.value)}
onBlur={() => validateOnBlur("workspaceName")}
aria-invalid={Boolean(errors.workspaceName) || undefined}
aria-describedby={errors.workspaceName ? `${nameHelpId} ${nameErrorId}` : nameHelpId}
disabled={saving}
required
/>
<FieldDescription id={nameHelpId}>Use a name your team will recognize.</FieldDescription>
<div className="min-h-10 sm:min-h-5">
<FieldError id={nameErrorId} match={Boolean(errors.workspaceName)}>
{errors.workspaceName}
</FieldError>
</div>
</Field>
</section>
<section
className="grid min-w-0 gap-4 border-t border-border pt-5"
aria-labelledby={notificationsHeadingId}
>
<div>
<h4 id={notificationsHeadingId} className="text-sm font-semibold text-foreground">
Notifications
</h4>
<p className="mt-1 text-sm text-muted-foreground">
Choose where workspace activity replies should go.
</p>
</div>
<Field invalid={Boolean(errors.replyTo)}>
<FieldLabel htmlFor={replyId}>Reply-to email</FieldLabel>
<Input
ref={replyInputRef}
id={replyId}
name="replyTo"
type="email"
value={draft.replyTo}
onChange={(event) => updateValue("replyTo", event.target.value)}
onBlur={() => validateOnBlur("replyTo")}
aria-invalid={Boolean(errors.replyTo) || undefined}
aria-describedby={errors.replyTo ? `${replyHelpId} ${replyErrorId}` : replyHelpId}
disabled={saving}
required
/>
<FieldDescription id={replyHelpId}>
Replies from activity emails use this address.
</FieldDescription>
<div className="min-h-10 sm:min-h-5">
<FieldError id={replyErrorId} match={Boolean(errors.replyTo)}>
{errors.replyTo}
</FieldError>
</div>
</Field>
</section>
<div
ref={statusRef}
role="status"
aria-live="polite"
aria-atomic="true"
tabIndex={-1}
className="min-h-5 min-w-0 break-words text-sm"
>
{saving ? (
<p className="text-muted-foreground">Saving settings in this example.</p>
) : saveState === "saved" ? (
<p className="flex items-center gap-2 text-[color:var(--color-success-text)]">
<CheckCircleIcon aria-hidden="true" className="size-4 shrink-0" />
Saved to this example’s local snapshot. No backend request was made.
</p>
) : serviceError ? (
<p className="text-destructive">{serviceError}</p>
) : failNextSave ? (
<p className="text-muted-foreground">The next save will fail in this example.</p>
) : null}
</div>
</CardContent>
<CardFooter className="flex-wrap">
<Button
type="submit"
loading={saving}
loadingLabel="Saving settings"
disabled={!hasChanges}
>
Save changes
</Button>
<Dialog open={discardOpen} onOpenChange={setDiscardOpen}>
<DialogTrigger
render={
<Button type="button" variant="outline" disabled={!hasChanges || saving}>
Discard changes
</Button>
}
/>
<DialogContent>
<DialogHeader>
<DialogTitle>Discard unsaved changes?</DialogTitle>
<DialogDescription>
Restore the last saved workspace name and reply-to email. Your current draft will be lost.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose render={<Button type="button" variant="outline" autoFocus>Keep editing</Button>} />
<Button type="button" variant="destructive" onClick={handleDiscard}>
Discard changes
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Button
type="button"
variant="ghost"
onClick={() => setFailNextSave(true)}
disabled={!hasChanges || saving || failNextSave}
>
Simulate next save failure
</Button>
</CardFooter>
</form>
</Card>
);
}
When to use
Use Settings when a person edits durable preferences rather than a one-off record. Give each group a short heading and description so a long page remains scannable. Keep a draft separate from the last saved values so Save and Discard have predictable results.
States
Layout
- Keep the section heading, explanation, fields, and actions in one surface when they belong to the same decision.
- Disable Save when there are no changes or a save is already in flight; leave it available for a changed draft so validation can explain an invalid value.
- Reserve room for inline errors so blur validation does not shift Save during a pointer click.
- Confirm Discard before restoring the last saved snapshot. Cancel the confirmation without changing the draft.
- Use a page for settings that need navigation or a multi-step workflow; do not force a large settings area into a Dialog.
The example saves only to a local snapshot and uses a timed, one-use failure fixture; it makes no backend request. The Preview and Code/Copy tabs use the same source file, src/components/design/examples/source/settings-pattern.tsx. This pattern has no property playground because it has no public pattern-level props. The isolated example has no route change; the Workspace Settings example shows a navigation guard for an unsaved draft.
Accessibility
- Use headings for groups and keep their descriptions adjacent to the controls they explain.
- Connect each visible label, description, and inline error to its control with a unique ID. Validate on blur and update an existing error as that field changes.
- After an invalid Save, focus the first invalid field, including on repeated attempts. Do not move focus during typing or blur.
- Move focus to the nearby status when saving disables Save, then update that
aria-live="polite"region with the result without moving focus again. - Do not communicate unsaved, error, or success state by color alone; include text.
- Keep the Discard confirmation keyboard operable, focus its non-destructive action first, and return focus to Workspace name after confirming Discard.
Do and don’t
Show the changed state as soon as a value differs from the saved snapshot, preserve the draft after a failed save, and make recovery obvious.
Auto-save every keystroke for consequential settings, discard edits without confirmation, or silently discard edits on navigation.