Skip to content
Atoms

Inline edit

Click the text to edit, Enter saves, Esc undoes.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add inline-edit

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/inline-edit.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/inline-edit and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { InlineEdit } from "asta-ui/inline-edit";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface InlineEditProps {
      value?: string;
      defaultValue?: string;
      /** Called with the new text. Return a promise to show a saving state. If it rejects, editing stays open. */
      onSave?: (value: string) => void | Promise<void>;
      /** Called when an edit is dropped with Esc. */
      onCancel?: () => void;
      /** Shown when the value is empty. */
      placeholder?: string;
      /** Accessible name, e.g. "Project name". */
      label: string;
      /** Empty text can't be saved. Esc or blur puts the old text back. */
      required?: boolean;
      maxLength?: number;
      /** Save when focus leaves the field. Off means blur cancels. */
      saveOnBlur?: boolean;
      size?: "sm" | "md" | "lg";
      disabled?: boolean;
      className?: string;
    }
    
    const KEYFRAMES = `@keyframes asta-inline-edit-tick { 0% { opacity: 0; transform: scale(.6) } 18% { opacity: 1; transform: scale(1) } 80% { opacity: 1; transform: scale(1) } 100% { opacity: 0; transform: scale(1) } }`;
    
    const TEXT = { sm: "text-[16px] sm:text-[13px]", md: "text-[16px] sm:text-[14.5px]", lg: "text-[20px] font-medium tracking-[-0.02em]" };
    
    /**
     * Text that turns into a field when you click it or press Enter. Enter saves, Esc puts the old text back,
     * and a small tick fades in beside the text once it's saved. Async saves keep the field open until they land.
     */
    export function InlineEdit({ value, defaultValue = "", onSave, onCancel, placeholder = "Empty", label, required, maxLength, saveOnBlur = true, size = "md", disabled, className }: InlineEditProps) {
      const [inner, setInner] = useState(defaultValue);
      const current = value ?? inner;
      const [editing, setEditing] = useState(false);
      const [draft, setDraft] = useState(current);
      const [saving, setSaving] = useState(false);
      const [failed, setFailed] = useState(false);
      const [saved, setSaved] = useState(0);
      const failId = useId();
    
      const input = useRef<HTMLInputElement>(null);
      const display = useRef<HTMLButtonElement>(null);
      // Enter saves, then the field unmounts and fires blur. This keeps that second close from running.
      const closing = useRef(false);
      const refocus = useRef(false);
      const alive = useRef(true);
      const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
    
      useEffect(() => {
        alive.current = true;
        return () => {
          alive.current = false;
          if (timer.current) clearTimeout(timer.current);
        };
      }, []);
    
      useLayoutEffect(() => {
        if (editing) {
          input.current?.focus();
          input.current?.select();
        } else if (refocus.current) {
          refocus.current = false;
          display.current?.focus();
        }
      }, [editing]);
    
      const open = () => {
        if (disabled || editing) return;
        closing.current = false;
        setDraft(current);
        setFailed(false);
        setEditing(true);
      };
    
      const close = (keepFocus: boolean) => {
        refocus.current = keepFocus;
        setEditing(false);
        setSaving(false);
      };
    
      const cancel = (keepFocus: boolean) => {
        if (closing.current || saving) return;
        closing.current = true;
        close(keepFocus);
        onCancel?.();
      };
    
      const save = async (keepFocus: boolean) => {
        if (closing.current || saving) return;
        const next = draft.trim();
        // Nothing changed: just close. Empty but required: drop the edit and keep the old text.
        if (next === current.trim()) {
          closing.current = true;
          close(keepFocus);
          return;
        }
        if (required && !next) {
          cancel(keepFocus);
          return;
        }
        closing.current = true;
        try {
          const pending = onSave?.(next);
          if (pending) {
            setSaving(true);
            await pending;
          }
        } catch {
          if (!alive.current) return;
          closing.current = false;
          setSaving(false);
          setFailed(true);
          requestAnimationFrame(() => input.current?.focus());
          return;
        }
        if (!alive.current) return;
        if (value === undefined) setInner(next);
        close(keepFocus);
        setSaved((n) => n + 1);
        if (timer.current) clearTimeout(timer.current);
        timer.current = setTimeout(() => alive.current && setSaved(0), 1700);
      };
    
      const box = "-mx-2 rounded-[7px] px-2 py-1";
    
      return (
        <span className={cx("relative inline-flex max-w-full items-center gap-1.5", TEXT[size], className)}>
          <style href="asta-inline-edit" precedence="asta">{KEYFRAMES}</style>
          {editing ? (
            <span className="inline-grid min-w-[6ch] max-w-full">
              {/* An invisible copy sizes the field to its text, so the row doesn't jump between modes. */}
              <span aria-hidden className={cx("invisible col-start-1 row-start-1 whitespace-pre", box)}>
                {(draft || placeholder) + " "}
              </span>
              <input
                ref={input}
                value={draft}
                onChange={(e) => {
                  setDraft(e.target.value);
                  if (failed) setFailed(false);
                }}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    e.preventDefault();
                    void save(true);
                  } else if (e.key === "Escape") {
                    e.preventDefault();
                    e.stopPropagation();
                    cancel(true);
                  }
                }}
                onBlur={() => (saveOnBlur ? void save(false) : cancel(false))}
                aria-label={label}
                aria-invalid={failed || undefined}
                aria-describedby={failed ? failId : undefined}
                autoComplete="off"
                aria-busy={saving || undefined}
                readOnly={saving}
                maxLength={maxLength}
                placeholder={placeholder}
                className={cx(
                  "col-start-1 row-start-1 w-full min-w-0 bg-paper text-ink outline-none transition-[box-shadow,opacity] duration-200 placeholder:text-mute",
                  "shadow-[inset_0_0_0_1.5px_var(--color-brand),0_0_0_4px_color-mix(in_srgb,var(--color-brand)_14%,transparent)]",
                  saving && "opacity-60",
                  box,
                )}
              />
            </span>
          ) : (
            <button
              ref={display}
              type="button"
              onClick={open}
              disabled={disabled}
              aria-label={`${label}: ${current || placeholder}. Edit`}
              className={cx(
                "group/ie inline-flex min-w-0 max-w-full items-center gap-2 text-left outline-none transition-colors duration-200 hover:bg-paper-2 focus-visible:ring-2 focus-visible:ring-brand/50 disabled:pointer-events-none",
                current ? "text-ink" : "text-mute",
                box,
              )}
            >
              <span className="truncate">{current || placeholder}</span>
              <svg
                viewBox="0 0 24 24"
                className="h-[0.85em] w-[0.85em] shrink-0 text-mute opacity-0 transition-[opacity,translate] duration-200 ease-[cubic-bezier(.16,1,.3,1)] -translate-x-0.5 group-hover/ie:translate-x-0 group-hover/ie:opacity-100 group-focus-visible/ie:translate-x-0 group-focus-visible/ie:opacity-100 motion-reduce:transition-none"
                fill="none"
                stroke="currentColor"
                strokeWidth="2.4"
                strokeLinecap="round"
                strokeLinejoin="round"
                aria-hidden
              >
                <path d="M4.5 19.5 5 16 15.5 5.5a2.1 2.1 0 0 1 3 3L8 19Z" />
                <path d="m13.5 7.5 3 3" />
              </svg>
            </button>
          )}
          {saved > 0 && !editing && (
            <svg
              key={saved}
              viewBox="0 0 24 24"
              className="h-[0.9em] w-[0.9em] shrink-0 text-brand animate-[asta-inline-edit-tick_1.7s_cubic-bezier(.16,1,.3,1)_both] motion-reduce:animate-none"
              fill="none"
              stroke="currentColor"
              strokeWidth="3"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden
            >
              <path d="m5 12.5 4.5 4.5L19 7.5" />
            </svg>
          )}
          <span role="status" className="sr-only">
            {saved > 0 ? "Saved" : failed ? "Couldn't save. Try again or press Escape." : ""}
          </span>
          {failed && editing && (
            <span id={failId} className="shrink-0 text-[12px] text-mute">
              Couldn&apos;t save. Press Enter to retry.
            </span>
          )}
        </span>
      );
    }
    
    export default InlineEdit;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Inline edit component to my project.
    
    Click the text to edit, Enter saves, Esc undoes.
    It includes: click to edit, enter, escape, async save, required, sm, md, lg.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add inline-edit --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/inline-edit.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { InlineEdit } from "@/components/astabyte/inline-edit";
    ```
    
    Usage example and props: https://ui.astabyte.com/inline-edit
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Needs asta.js. Save fires asta:save; point hx-post at your endpoint (it answers 2xx or an error). -->
    <div style="display:flex;flex-direction:column;gap:12px;width:100%"><span data-asta-inline data-required class="asta-inline-edit asta-inline-edit-lg"><button type="button" data-asta-inline-view aria-label="Project name: Astabyte site. Edit" class="asta-inline-edit-view"><span class="asta-inline-edit-text" data-asta-inline-text>Astabyte site</span> <svg viewBox="0 0 16 16" class="asta-inline-edit-pencil" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.5 2.5l3 3L6 13H3v-3l7.5-7.5z"></path></svg></button> <span class="asta-inline-edit-editor"><span aria-hidden="true" data-asta-inline-sizer class="asta-inline-edit-sizer">Astabyte site </span> <input name="project" value="Astabyte site" data-asta-inline-input data-saved="Astabyte site" aria-label="Project name" placeholder="Empty" autocomplete="off" class="asta-inline-edit-input" hx-post="/save" hx-swap="none" hx-trigger="asta:save"></span> <svg viewBox="0 0 16 16" data-asta-inline-tick class="asta-inline-edit-tick hidden" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3.5 8.5 3 3 6-7"></path></svg> <span class="asta-inline-edit-failed">Couldn't save. Press Enter to retry.</span> <span role="status" class="asta-sr-only" data-asta-inline-status></span></span><span data-asta-inline data-cancel-on-blur class="asta-inline-edit"><button type="button" data-asta-inline-view aria-label="Note: Add a note. Edit" class="asta-inline-edit-view asta-inline-edit-empty"><span class="asta-inline-edit-text" data-asta-inline-text>Add a note…</span> <svg viewBox="0 0 16 16" class="asta-inline-edit-pencil" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.5 2.5l3 3L6 13H3v-3l7.5-7.5z"></path></svg></button> <span class="asta-inline-edit-editor"><span aria-hidden="true" data-asta-inline-sizer class="asta-inline-edit-sizer">Add a note… </span> <input name="note" value="" data-asta-inline-input data-saved="" aria-label="Note" placeholder="Add a note…" autocomplete="off" class="asta-inline-edit-input"></span> <svg viewBox="0 0 16 16" data-asta-inline-tick class="asta-inline-edit-tick hidden" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3.5 8.5 3 3 6-7"></path></svg> <span class="asta-inline-edit-failed">Couldn't save. Press Enter to retry.</span> <span role="status" class="asta-sr-only" data-asta-inline-status></span></span><p style="margin:0;font-size:13px;opacity:.7">Saving “fail” shows the error state.</p></div>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { InlineEdit } from "@/components/astabyte/inline-edit";

const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));

export default function InlineEditDemo() {
  const [title, setTitle] = useState("Homepage refresh");

  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-sm flex-col gap-8">
        <div className="rounded-xl bg-paper-2 p-5">
          <p className="text-[12px] text-mute">Project</p>
          <div className="mt-1">
            <InlineEdit label="Project name" size="lg" required value={title} onSave={async (v) => { await wait(450); setTitle(v); }} />
          </div>
          <div className="mt-4 flex flex-col gap-2">
            <div className="flex items-center justify-between gap-4">
              <span className="shrink-0 text-[13px] text-mute">Owner</span>
              <InlineEdit label="Owner" size="sm" defaultValue="Maya Rahman" />
            </div>
            <div className="flex items-center justify-between gap-4">
              <span className="shrink-0 text-[13px] text-mute">Due</span>
              <InlineEdit label="Due date" size="sm" defaultValue="Friday, 14 Nov" />
            </div>
            <div className="flex items-center justify-between gap-4">
              <span className="shrink-0 text-[13px] text-mute">Notes</span>
              <InlineEdit label="Notes" size="sm" placeholder="Add a note…" maxLength={60} />
            </div>
          </div>
        </div>

        <p className="text-center text-[12.5px] text-mute">Click or press Enter to edit. Enter saves, Esc puts the old text back.</p>
      </div>
    </div>
  );
}