Skip to content
Plinth

Forms

Editable Field

Inline editing that actually handles persistence: trim and validate, await saves, retain failed drafts, retry or cancel, and restore keyboard focus.

#inline-edit#forms#validation#async#accessible

Install

npx shadcn@latest add https://plinthui.com/r/editable-field.json
Open in v0
'use client';

import { useEffect, useId, useRef, useState } from 'react';

const css = `.ef-root {
  --ef-ink: #28372e; --ef-muted: #687463; --ef-paper: #f8f9f3; --ef-soft: #edf2e4; --ef-line: #d8e1d0; --ef-accent: #486a32; --ef-error: #a43825;
  width: min(100%, 380px); color: var(--ef-ink); font: 13px/1.5 system-ui, sans-serif;
}
.ef-root * { box-sizing: border-box; }
.ef-panel { padding: 19px; border: 1px solid var(--ef-line); border-radius: 18px; background: var(--ef-paper); box-shadow: 0 10px 28px #2130200c; }
.ef-top { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 11px; }
.ef-label { margin: 0; color: var(--ef-muted); font-size: 10px; line-height: 1.5; letter-spacing: .06em; text-transform: uppercase; }
.ef-badge { color: var(--ef-accent); font: 10px/1.5 ui-monospace, monospace; }
.ef-badge:empty { display: none; }
.ef-view { display: flex; align-items: center; justify-content: space-between; gap: 14px; }
.ef-value { margin: 0; min-width: 0; color: var(--ef-ink); font-size: 18px; line-height: 1.4; font-weight: 550; letter-spacing: -.035em; overflow-wrap: anywhere; }
.ef-value[data-empty="true"] { color: var(--ef-muted); font-size: 14px; font-weight: 400; }
.ef-root button { font: inherit; cursor: pointer; }
.ef-edit { flex: none; display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 7px 9px; border: 1px solid var(--ef-line); border-radius: 8px; color: var(--ef-accent); background: transparent; font-size: 11px !important; }
.ef-edit svg { width: 12px; height: 12px; }
.ef-edit:hover, .ef-cancel:hover { background: var(--ef-soft); }
.ef-root button:focus-visible, .ef-input:focus-visible { outline: 2px solid var(--ef-accent); outline-offset: 3px; }
.ef-editor { animation: ef-enter 160ms ease-out; }
.ef-editor[hidden], .ef-view[hidden] { display: none; }
.ef-input { display: block; width: 100%; min-width: 0; padding: 10px 11px; border: 1px solid var(--ef-line); border-radius: 9px; background: var(--ef-paper); color: var(--ef-ink); font: 14px/1.4 system-ui, sans-serif; }
.ef-input[aria-invalid="true"] { border-color: var(--ef-error); }
.ef-input:read-only { opacity: .7; }
.ef-meta { display: flex; justify-content: space-between; gap: 10px; margin-top: 8px; color: var(--ef-muted); font-size: 10px; }
.ef-help, .ef-count { margin: 0; }
.ef-count { flex: none; font-variant-numeric: tabular-nums; }
.ef-error { margin: 9px 0 0; color: var(--ef-error); font-size: 11px; }
.ef-error:empty { display: none; }
.ef-actions { display: flex; justify-content: flex-end; gap: 7px; margin-top: 13px; }
.ef-actions button { padding: 7px 12px; border: 1px solid var(--ef-line); border-radius: 8px; font-size: 11px; }
.ef-cancel { background: transparent; color: var(--ef-muted); }
.ef-actions .ef-save { color: #f9fff1; background: #486a32; border-color: #486a32; }
.ef-actions .ef-save:hover { background: #395628; }
.ef-root button[aria-disabled="true"] { opacity: .6; cursor: wait; }
.ef-note { margin: 13px 0 0; padding-top: 11px; border-top: 1px solid var(--ef-line); color: var(--ef-muted); font-size: 10px; }
.ef-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
:root[data-theme="dark"] .ef-root { --ef-ink: #e6ecdf; --ef-muted: #a2af9c; --ef-paper: #232c23; --ef-soft: #2c372a; --ef-line: #3e4b37; --ef-accent: #bedc96; --ef-error: #ffad99; }
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .ef-root { --ef-ink: #e6ecdf; --ef-muted: #a2af9c; --ef-paper: #232c23; --ef-soft: #2c372a; --ef-line: #3e4b37; --ef-accent: #bedc96; --ef-error: #ffad99; } }
@keyframes ef-enter { from { opacity: .6; transform: translateY(3px); } to { opacity: 1; transform: translateY(0); } }
@media (prefers-reduced-motion: reduce) { .ef-editor { animation: none; } }
`;

export function EditableField({
  label = 'Project name', defaultValue = '', placeholder = 'Add a value',
  maxLength = 80, allowEmpty = false, validate, onSave, note,
}: {
  label?: string;
  /** Initial value. Remount with a different key when switching records. */
  defaultValue?: string;
  placeholder?: string;
  maxLength?: number;
  allowEmpty?: boolean;
  validate?: (value: string) => string | undefined;
  /** Resolve only after persistence succeeds. Return a canonical string if needed. */
  onSave: (value: string) => void | string | Promise<void | string>;
  note?: string;
}) {
  const id = useId();
  const root = useRef<HTMLElement>(null);
  const field = useRef<HTMLInputElement>(null);
  const trigger = useRef<HTMLButtonElement>(null);
  const busyRef = useRef(false);
  const restoreFocus = useRef(false);
  const [value, setValue] = useState(defaultValue);
  const [draft, setDraft] = useState(defaultValue);
  const [editing, setEditing] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [saved, setSaved] = useState(false);
  const [announcement, setAnnouncement] = useState('');
  const limit = Number.isFinite(maxLength) ? Math.max(1, Math.floor(maxLength)) : 80;

  useEffect(() => {
    if (editing) { field.current?.focus(); field.current?.select(); }
    else if (restoreFocus.current) { trigger.current?.focus(); restoreFocus.current = false; }
  }, [editing]);

  function cancel() {
    if (busyRef.current) return;
    setDraft(value); setError(''); setEditing(false); restoreFocus.current = true;
    setAnnouncement('Editing cancelled. Original value restored.');
  }

  async function save() {
    if (busyRef.current) return;
    const next = draft.trim();
    let invalid = !allowEmpty && !next ? `${label} cannot be empty.` : next.length > limit ? `Use ${limit} characters or fewer.` : '';
    try { if (!invalid) invalid = validate?.(next) || ''; }
    catch { invalid = 'This value could not be validated. Try again.'; }
    if (invalid) { setError(invalid); field.current?.focus(); return; }
    if (next === value) { cancel(); setAnnouncement('No changes to save.'); return; }
    if (typeof onSave !== 'function') { setError('Connect a save handler to apply changes.'); return; }
    busyRef.current = true; setBusy(true); setError(''); setAnnouncement(`Saving ${label}…`);
    try {
      const result = await onSave(next);
      const committed = typeof result === 'string' ? result : next;
      const stillHere = root.current?.contains(document.activeElement) ?? false;
      setValue(committed); setDraft(committed); setEditing(false); setSaved(true);
      restoreFocus.current = stillHere; setAnnouncement(`${label} saved.`);
    } catch {
      setError('Could not save. Your changes are still here. Try again.');
      setAnnouncement('');
      if (root.current?.contains(document.activeElement)) field.current?.focus();
    } finally { busyRef.current = false; setBusy(false); }
  }

  return <>
    <style>{css}</style>
    <section ref={root} className="ef-root" aria-labelledby={`${id}-label`} onKeyDown={event => {
      if (event.key === 'Escape' && !event.nativeEvent.isComposing && editing && !busyRef.current) { event.preventDefault(); event.stopPropagation(); cancel(); }
    }}>
      <div className="ef-panel">
        <div className="ef-top"><p className="ef-label" id={`${id}-label`}>{label}</p><span className="ef-badge" aria-hidden="true">{saved && !editing ? '✓ Saved' : ''}</span></div>
        {!editing ? <div className="ef-view">
          <p className="ef-value" data-empty={!value}>{value || placeholder}</p>
          <button ref={trigger} type="button" className="ef-edit" aria-label={`Edit ${label}`} onClick={() => { setDraft(value); setError(''); setSaved(false); setAnnouncement(''); setEditing(true); }}><svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"><path d="m10 3 3 3M3 13l1-4 7-7 3 3-7 7-4 1Z" /></svg>Edit</button>
        </div> : <div className="ef-editor" aria-busy={busy}>
          <input ref={field} className="ef-input" aria-labelledby={`${id}-label`} aria-describedby={`${id}-help ${id}-error`} aria-invalid={!!error} type="text" value={draft} maxLength={limit} readOnly={busy} onChange={event => { setDraft(event.target.value); setError(''); }} onKeyDown={event => {
            if (event.key === 'Enter' && !event.nativeEvent.isComposing) { event.preventDefault(); void save(); }
          }} />
          <div className="ef-meta"><p className="ef-help" id={`${id}-help`}>Enter to save · Esc to cancel</p><p className="ef-count">{draft.length} / {limit}</p></div>
          <p className="ef-error" role="alert" id={`${id}-error`}>{error}</p>
          <div className="ef-actions"><button type="button" className="ef-cancel" aria-disabled={busy} onClick={cancel}>Cancel</button><button type="button" className="ef-save" aria-disabled={busy} onClick={() => { void save(); }}>{busy ? 'Saving…' : 'Save changes'}</button></div>
        </div>}
        {note && <p className="ef-note">{note}</p>}
      </div>
      <p className="ef-sr" role="status">{announcement}</p>
    </section>
  </>;
}

More in Forms

Similar tags