Inline edit
Switch a label or description into an editable field in place, with explicit save, cancel and retry states.
pnpm dlx shadcn@latest add @haze/inline-edit---
import { Check, CircleAlert, LoaderCircle, Pencil, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
interface Props {
id: string;
name?: string;
label?: string;
value?: string;
placeholder?: string;
multiline?: boolean;
variant?: "title" | "body";
required?: boolean;
disabled?: boolean;
readonly?: boolean;
class?: string;
"aria-describedby"?: string;
[key: string]: unknown;
}
const { id, name = id, label = "Name", value = "", placeholder = "Add a value", multiline = false, variant = "body",
required, disabled, readonly, class: className, "aria-describedby": describedBy, ...rest } = Astro.props;
const type = variant === "title" ? "text-[1.0625rem]/6 font-medium tracking-[-0.01em]" : "text-sm/6 tracking-[-0.01em]";
const field = cn("block min-h-10 w-full min-w-0 rounded-lg bg-field px-2.5 py-1.5 text-foreground placeholder:text-muted-foreground",
"group-data-enhanced/inline:pe-17 focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-ring disabled:opacity-50 aria-invalid:bg-destructive/10 aria-invalid:focus-visible:outline-destructive",
type);
const control = { ...rest, id, name, required, disabled, readonly, placeholder,
"aria-describedby": [describedBy, `${id}-status`].filter(Boolean).join(" ") };
---
<div data-haze-inline-edit data-placeholder={placeholder} class={cn("group/inline grid w-full min-w-0 gap-1.5", className)}>
<label id={`${id}-label`} for={id} class="text-[0.8125rem]/5 font-medium">{label}{required && <span aria-hidden="true" class="ms-0.5 text-destructive">*</span>}</label>
<button type="button" id={`${id}-edit`} data-edit-trigger hidden aria-labelledby={`${id}-action ${id}-label ${id}-value`}
class={cn("relative min-h-10 w-full min-w-0 cursor-pointer rounded-lg px-2.5 py-1.5 pe-17 text-start transition-[color,background-color,scale] duration-150 ease-snappy active:scale-[0.99] active:duration-100 hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-default disabled:opacity-60 aria-disabled:cursor-wait [&[hidden]]:hidden", type)}>
<span id={`${id}-action`} class="sr-only">Edit</span>
<span id={`${id}-value`} data-edit-text class="block whitespace-pre-wrap wrap-anywhere group-data-[state=saved]/inline:motion-safe:animate-rise">{value || placeholder}</span>
<span aria-hidden="true" class="absolute end-2.5 top-2.5 grid size-5 place-items-center text-muted-foreground">
<Pencil class="size-3.5 group-data-[state=pending]/inline:hidden group-data-[state=saved]/inline:hidden group-data-[state=error]/inline:hidden" />
<LoaderCircle class="hidden size-4 group-data-[state=pending]/inline:block motion-safe:animate-spin" />
<Check class="hidden size-4 text-success group-data-[state=saved]/inline:block motion-safe:animate-pop" />
<CircleAlert class="hidden size-4 text-destructive group-data-[state=error]/inline:block" />
</span>
</button>
<div data-edit-panel class="relative min-w-0 [&[hidden]]:hidden">
{multiline
? <textarea {...control} data-edit-input rows="1" class={cn(field, "max-h-60 resize-y field-sizing-content")}>{value}</textarea>
: <input {...control} type="text" data-edit-input value={value} class={cn(field, "h-10")} />}
<div data-edit-actions hidden class="absolute end-1.5 top-1.5 flex gap-0.5 [&[hidden]]:hidden">
<Button size="icon" variant="ghost" data-edit-save aria-label={`Save ${label}`} class="size-7"><Check aria-hidden="true" /></Button>
<Button size="icon" variant="ghost" data-edit-cancel aria-label={`Cancel editing ${label}`} class="size-7"><X aria-hidden="true" /></Button>
</div>
</div>
<p id={`${id}-status`} data-edit-status role="status" aria-atomic="true"
class="sr-only text-[0.8125rem]/5 wrap-anywhere text-destructive group-data-[state=error]/inline:not-sr-only group-data-invalid/inline:not-sr-only"></p>
</div>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const field = root.querySelector<HTMLInputElement | HTMLTextAreaElement>("[data-edit-input]");
const label = root.querySelector("label");
const trigger = root.querySelector<HTMLButtonElement>("[data-edit-trigger]");
const text = root.querySelector<HTMLElement>("[data-edit-text]");
const panel = root.querySelector<HTMLElement>("[data-edit-panel]");
const actions = root.querySelector<HTMLElement>("[data-edit-actions]");
const status = root.querySelector<HTMLElement>("[data-edit-status]");
if (!field || !label || !trigger || !text || !panel || !actions || !status) return;
let saved = field.value;
let retry: string | undefined;
let revision = 0;
const originalInvalid = field.getAttribute("aria-invalid");
const locked = () => field.matches(":disabled, [readonly]");
const present = (state: "read" | "edit" | "pending" | "saved" | "error", message = "") => {
const editing = state === "edit";
root.dataset.state = state;
panel.hidden = !editing;
trigger.hidden = editing;
trigger.disabled = locked();
trigger.setAttribute("aria-disabled", String(locked() || state === "pending"));
trigger.setAttribute("aria-busy", String(state === "pending"));
label.htmlFor = editing ? field.id : trigger.id;
text.textContent = field.value || root.dataset.placeholder || "";
status.textContent = message;
};
const clearError = () => {
root.removeAttribute("data-invalid");
if (originalInvalid === null) field.removeAttribute("aria-invalid");
else field.setAttribute("aria-invalid", originalInvalid);
};
const edit = () => {
if (locked() || root.dataset.state === "pending") return;
if (root.dataset.state !== "edit") {
field.value = retry ?? saved;
retry = undefined;
clearError();
present("edit");
}
field.focus();
field.select();
};
const invalid = () => {
root.setAttribute("data-invalid", "");
field.setAttribute("aria-invalid", "true");
status.textContent = field.validationMessage;
};
const save = async (returnFocus: boolean) => {
if (root.dataset.state !== "edit" || locked()) return;
if (!field.validity.valid) {
invalid();
if (returnFocus) field.focus();
return;
}
const next = field.value;
clearError();
if (next === saved) {
present("read");
if (returnFocus) trigger.focus();
return;
}
const request = ++revision;
const work: Promise<unknown>[] = [];
root.dispatchEvent(new CustomEvent("haze:inline-edit-save", {
bubbles: true,
detail: { value: next, previousValue: saved, waitUntil: (task: Promise<unknown>) => work.push(Promise.resolve(task)) },
}));
present(work.length ? "pending" : "saved", work.length ? "Saving…" : "Changes applied.");
if (returnFocus) trigger.focus();
try {
if (work.length) await Promise.all(work);
if (revision !== request) return;
saved = next;
present("saved", work.length ? "Changes saved." : "Changes applied.");
} catch {
if (revision !== request) return;
retry = next;
field.value = saved;
present("error", "Could not save. Edit again to retry.");
}
};
const cancel = () => {
if (root.dataset.state !== "edit") return;
field.value = saved;
clearError();
present("read", "Edit cancelled.");
trigger.focus();
};
field.addEventListener("keydown", (event: Event) => {
const key = event as KeyboardEvent;
if (key.isComposing) return;
if (key.key === "Escape") {
key.preventDefault();
cancel();
} else if (key.key === "Enter" && !(field instanceof HTMLTextAreaElement && key.shiftKey)) {
key.preventDefault();
void save(true);
}
});
field.addEventListener("invalid", () => {
if (root.dataset.state !== "edit") edit();
invalid();
});
field.addEventListener("input", () => {
if (root.hasAttribute("data-invalid")) {
clearError();
status.textContent = "";
}
if (root.dataset.state !== "edit" && root.dataset.state !== "pending") {
saved = field.value;
retry = undefined;
present("read");
}
});
// Moving focus to Save/Cancel must not blur-save. Keep focus in the field on press
// (preventDefault on mousedown) and ignore focusout whose target is inside the root.
let pressing = false;
actions.addEventListener("pointerdown", () => {
pressing = true;
document.addEventListener("pointerup", () => setTimeout(() => { pressing = false; }, 0), { once: true });
document.addEventListener("pointercancel", () => { pressing = false; }, { once: true });
});
actions.addEventListener("mousedown", (event) => event.preventDefault());
root.addEventListener("focusout", (event) => {
const next = (event as FocusEvent).relatedTarget as Node | null;
if (next && root.contains(next)) return;
queueMicrotask(() => {
if (pressing || root.contains(document.activeElement)) return;
void save(false);
});
});
trigger.addEventListener("click", edit);
actions.querySelector("[data-edit-save]")?.addEventListener("click", () => { void save(true); });
actions.querySelector("[data-edit-cancel]")?.addEventListener("click", cancel);
field.form?.addEventListener("reset", (event) => queueMicrotask(() => {
if (event.defaultPrevented) return;
revision++;
saved = field.value;
retry = undefined;
clearError();
present("read");
}));
new MutationObserver(() => {
trigger.disabled = locked();
trigger.setAttribute("aria-disabled", String(locked() || root.dataset.state === "pending"));
if (locked() && root.dataset.state === "edit") {
field.value = saved;
clearError();
present("read");
}
}).observe(field, { attributeFilter: ["disabled", "readonly"] });
actions.hidden = false;
present("read");
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-inline-edit]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-inline-edit-listener")) {
document.documentElement.setAttribute("data-haze-inline-edit-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- A project title or short description is read often and edited occasionally.
- A settings row needs its own save action and feedback.
When not to use
- Several fields in the same form are reviewed and saved together. Use input or textarea.
Installation
Add the Haze registry to components.json once, then install Inline edit with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/inline-editnpx shadcn@latest add @haze/inline-edityarn dlx shadcn@latest add @haze/inline-editbunx --bun shadcn@latest add @haze/inline-editFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique control ID and prefix for the read button, label and feedback. |
| name | string | id | Name submitted to a native form. |
| label | string | Name | Visible label used when editing and in action names. |
| value | string | "" | Initially committed text. |
| placeholder | string | Add a value | Visible hint when the value is empty. |
| multiline | boolean | false | Use a growing native textarea. Shift+Enter inserts a line break. |
| variant | "title" | "body" | body | Typography shared by the resting text and the field. |
| required / disabled / readonly | boolean | – | Native validation and editing states. |
| class | string | – | Extra classes on the root. |
| ...attributes | HTML form control attributes | – | Forwarded to the input or textarea, including form, maxlength and aria-describedby. |
Keyboard interactions
- EnterSpace
- Open the editor from the value button.
- EnterEscape
- Apply the draft or cancel it and restore the saved value.
- ShiftEnter
- Insert a line break in a multiline value.
- Tab
- Move through save and cancel. Leaving the whole editor commits a valid draft.
Accessibility
- A native button names the field and its value. Save and cancel return keyboard focus to that button.
- Errors and save results use a live region. Without JavaScript the editor is an ordinary labelled form control.
- Changes apply locally. A bubbling haze:inline-edit-save event provides detail.value and detail.previousValue. Call detail.waitUntil(promise) during dispatch to show pending progress and restore the previous value on rejection. Reopening offers the failed draft for retry.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Inline edit" with `npx shadcn@latest add @haze/inline-edit`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import InlineEdit from "@/components/haze/ui/inline-edit.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/inline-edit.md
Customize with real content
Adapt the Haze inline-edit ui for our product. Replace the demo values of these props with our real content: id, name, label, value, placeholder, multiline, variant, required / disabled / readonly, class, ...attributes. Keep the layout, the heading level rules and these accessibility details: A native button names the field and its value. Save and cancel return keyboard focus to that button. Errors and save results use a live region. Without JavaScript the editor is an ordinary labelled form control. Changes apply locally. A bubbling haze:inline-edit-save event provides detail.value and detail.previousValue. Call detail.waitUntil(promise) during dispatch to show pending progress and restore the previous value on rejection. Reopening offers the failed draft for retry. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using inline-edit, check it fits: use it when a project title or short description is read often and edited occasionally.; a settings row needs its own save action and feedback.. Avoid it when several fields in the same form are reviewed and saved together. use input or textarea.. Alternatives: @haze/input, @haze/textarea, @haze/field.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.