{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "inline-edit",
  "title": "Inline edit",
  "description": "A value that edits in place as text, textarea or select, with save feedback and errors.",
  "dependencies": [
    "@keyline-icons/react@^2.2.0"
  ],
  "registryDependencies": [
    "@khaeli/icon-swap",
    "@khaeli/input",
    "@khaeli/loader",
    "@khaeli/native-select",
    "@khaeli/textarea",
    "@khaeli/utils"
  ],
  "files": [
    {
      "path": "registry/khaeli/ui/inline-edit.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { CheckIcon } from \"@keyline-icons/react\"\nimport { cn } from \"@/lib/utils\"\n\nimport { IconSwap } from \"@/components/ui/icon-swap\"\nimport { Input } from \"@/components/ui/input\"\nimport { Loader } from \"@/components/ui/loader\"\nimport { NativeSelect, NativeSelectOption } from \"@/components/ui/native-select\"\nimport { Textarea } from \"@/components/ui/textarea\"\n\n// --- InlineEdit ---\n// Display state = the 30px control\n// at the control radius, px-2, hover bg-accent, 14/500\n// truncate; editing state = the same box with a 1px primary inset ring and a\n// borderless registry Input/NativeSelect/Textarea inside (autofocus +\n// select-all). Enter saves (Shift+Enter newline in textarea), Escape cancels,\n// blur saves when changed; selects save immediately on change. onSave\n// rejection keeps the editor open, marks the control aria-invalid and shows\n// the message at 12px destructive as an alert linked by aria-describedby. A\n// save that lands draws a check beside the value for a moment and says\n// \"Saved\" politely. The root carries data-editing=\"true|false\"; clicks never\n// bubble to DataGrid rows while the editor is live. The inner controls drop\n// their registry data-slots so the global control chrome (shadow-control,\n// focus ring pair) stays off — the box itself is the field.\n\nconst SAVED_MS = 1500\n\nconst displayClasses =\n  \"flex h-7.5 w-full min-w-0 items-center gap-1 rounded-control px-2 text-left text-base font-medium\"\n\n// An invalid control turns the box's ring destructive; the control's own registry invalid ring stays off.\nconst editBoxClasses =\n  \"flex w-full min-w-0 gap-1 rounded-control bg-background px-2 shadow-[inset_0_0_0_1px_var(--primary)] has-aria-invalid:shadow-[inset_0_0_0_1px_var(--destructive)] [&_[aria-invalid=true]]:ring-0\"\n\nconst controlResetClasses =\n  \"flex-1 rounded-none border-none bg-transparent px-0 py-0 text-base font-medium shadow-none focus-visible:border-none focus-visible:ring-0 dark:bg-transparent\"\n\nfunction InlineEdit({\n  value,\n  placeholder,\n  onSave,\n  kind = \"text\",\n  options,\n  renderValue,\n  disabled = false,\n  ariaLabel,\n  className,\n}: {\n  value: string | null\n  placeholder?: string\n  onSave: (next: string) => Promise<void> | void\n  kind?: \"text\" | \"email\" | \"url\" | \"number\" | \"textarea\"\n  options?: { value: string; label: string }[]\n  renderValue?: (value: string) => React.ReactNode\n  disabled?: boolean\n  ariaLabel: string\n  className?: string\n}) {\n  const [editing, setEditing] = React.useState(false)\n  const [draft, setDraft] = React.useState(\"\")\n  const [pending, setPending] = React.useState(false)\n  const [error, setError] = React.useState<string | null>(null)\n  const [saved, setSaved] = React.useState(false)\n  const savedTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n  const controlRef = React.useRef<HTMLElement | null>(null)\n  const displayRef = React.useRef<HTMLButtonElement | null>(null)\n  const pendingRef = React.useRef(false)\n  const skipBlurRef = React.useRef(false)\n  // Set when the editor closes from a key (Enter, Escape) or a select change:\n  // the control unmounts, so focus returns to the field instead of the page.\n  // Only when focus was actually lost: a save can resolve after the person\n  // has tabbed or clicked elsewhere, and their new focus must stay.\n  const restoreFocusRef = React.useRef(false)\n  const describedById = React.useId()\n  const errorId = React.useId()\n\n  React.useEffect(() => () => clearTimeout(savedTimer.current), [])\n\n  const current = value ?? \"\"\n  const hasValue = current !== \"\"\n\n  React.useEffect(() => {\n    if (!editing) {\n      const active = document.activeElement\n      const lost = active === null || active === document.body\n      if (restoreFocusRef.current && lost) displayRef.current?.focus()\n      restoreFocusRef.current = false\n      return\n    }\n    const el = controlRef.current\n    if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n      el.focus()\n      el.select()\n    } else if (el instanceof HTMLSelectElement) {\n      el.focus()\n      try {\n        ;(el as { showPicker?: () => void }).showPicker?.()\n      } catch {\n        // showPicker needs transient user activation; the select still opens on click\n      }\n    }\n  }, [editing])\n\n  const setControl = (node: HTMLElement | null) => {\n    controlRef.current = node\n  }\n\n  const beginEdit = () => {\n    if (disabled || pending) return\n    skipBlurRef.current = false\n    setDraft(current)\n    setError(null)\n    setEditing(true)\n  }\n\n  const commit = async (next: string) => {\n    if (pendingRef.current) return\n    if (next === current) {\n      setEditing(false)\n      setError(null)\n      return\n    }\n    pendingRef.current = true\n    setPending(true)\n    try {\n      await onSave(next)\n      setEditing(false)\n      setError(null)\n      clearTimeout(savedTimer.current)\n      setSaved(true)\n      savedTimer.current = setTimeout(() => setSaved(false), SAVED_MS)\n    } catch (err) {\n      restoreFocusRef.current = false\n      setError(\n        err instanceof Error && err.message\n          ? err.message\n          : \"Couldn't save changes\"\n      )\n    } finally {\n      pendingRef.current = false\n      setPending(false)\n    }\n  }\n\n  const cancel = () => {\n    skipBlurRef.current = true\n    setEditing(false)\n    setError(null)\n  }\n\n  const handleBlur = () => {\n    if (skipBlurRef.current) {\n      skipBlurRef.current = false\n      return\n    }\n    if (pendingRef.current) return\n    void commit(draft)\n  }\n\n  const handleKeyDown = (event: React.KeyboardEvent) => {\n    if (event.key === \"Escape\") {\n      event.preventDefault()\n      event.stopPropagation()\n      restoreFocusRef.current = true\n      cancel()\n      return\n    }\n    if (event.key === \"Enter\") {\n      if (kind === \"textarea\" && event.shiftKey) return\n      event.preventDefault()\n      event.stopPropagation()\n      restoreFocusRef.current = true\n      void commit(draft)\n    }\n  }\n\n  const handleSelectKeyDown = (event: React.KeyboardEvent) => {\n    if (event.key === \"Escape\") {\n      event.preventDefault()\n      event.stopPropagation()\n      restoreFocusRef.current = true\n      cancel()\n    }\n  }\n\n  const shown = hasValue ? (\n    renderValue\n      ? renderValue(current)\n      : options\n        ? (options.find((option) => option.value === current)?.label ?? current)\n        : current\n  ) : (\n    placeholder\n  )\n\n  let body: React.ReactNode\n  if (!editing) {\n    // The visible text names the field (an aria-label would replace it, so a\n    // title would be announced as \"Task title\"); the field's name and the\n    // action are its description. That holds for an empty field's placeholder\n    // too; only a field that shows nothing falls back to the field name.\n    body = disabled ? (\n      <div className={displayClasses}>\n        <span\n          className={cn(\"truncate\", !hasValue && \"text-subtle-foreground\")}\n          title={typeof shown === \"string\" ? shown : undefined}\n        >\n          {shown}\n        </span>\n      </div>\n    ) : (\n      <button\n        ref={displayRef}\n        type=\"button\"\n        aria-label={hasValue || placeholder ? undefined : ariaLabel}\n        aria-describedby={describedById}\n        onClick={(event) => {\n          event.stopPropagation()\n          beginEdit()\n        }}\n        className={cn(displayClasses, \"focus-ring hover:bg-accent focus-visible:bg-accent\")}\n      >\n        <span\n          className={cn(\"truncate\", !hasValue && \"text-subtle-foreground\")}\n          title={typeof shown === \"string\" ? shown : undefined}\n        >\n          {shown}\n        </span>\n        <span aria-hidden=\"true\" className=\"ml-auto flex shrink-0 text-positive\">\n          <IconSwap state={saved ? \"saved\" : \"idle\"}>\n            {saved ? <CheckIcon className=\"size-3.5\" /> : null}\n          </IconSwap>\n        </span>\n        <span id={describedById} aria-hidden=\"true\" className=\"sr-only\">\n          Edit {ariaLabel}\n        </span>\n      </button>\n    )\n  } else if (options) {\n    body = (\n      <div\n        className={cn(\n          editBoxClasses,\n          \"h-7.5 items-center\",\n          \"[&_select]:h-full [&_select]:w-full [&_select]:rounded-none [&_select]:border-none [&_select]:bg-transparent [&_select]:pl-0 [&_select]:text-base [&_select]:font-medium [&_select]:shadow-none [&_select:focus-visible]:ring-0\"\n        )}\n      >\n        <NativeSelect\n          data-slot=\"inline-edit-control\"\n          ref={setControl}\n          autoFocus\n          aria-label={ariaLabel}\n          aria-invalid={error ? true : undefined}\n          aria-describedby={error ? errorId : undefined}\n          defaultValue={current}\n          disabled={pending}\n          onChange={(event) => {\n            restoreFocusRef.current = true\n            void commit(event.target.value)\n          }}\n          onKeyDown={handleSelectKeyDown}\n          onBlur={handleBlur}\n          className=\"h-full min-w-0 flex-1\"\n        >\n          {!hasValue ? (\n            <NativeSelectOption value=\"\" disabled hidden>\n              {placeholder ?? \"Select…\"}\n            </NativeSelectOption>\n          ) : null}\n          {options.map((option) => (\n            <NativeSelectOption key={option.value} value={option.value}>\n              {option.label}\n            </NativeSelectOption>\n          ))}\n        </NativeSelect>\n        {pending ? (\n          <Loader size={14} className=\"shrink-0 text-muted-foreground\" />\n        ) : null}\n      </div>\n    )\n  } else if (kind === \"textarea\") {\n    body = (\n      <div className={cn(editBoxClasses, \"items-start py-1.5\")}>\n        <Textarea\n          data-slot=\"inline-edit-control\"\n          ref={setControl}\n          autoFocus\n          aria-label={ariaLabel}\n          aria-invalid={error ? true : undefined}\n          aria-describedby={error ? errorId : undefined}\n          placeholder={placeholder}\n          value={draft}\n          readOnly={pending}\n          onChange={(event) => setDraft(event.target.value)}\n          onKeyDown={handleKeyDown}\n          onBlur={handleBlur}\n          className={cn(controlResetClasses, \"min-h-16\")}\n        />\n        {pending ? (\n          <Loader size={14} className=\"mt-1 shrink-0 text-muted-foreground\" />\n        ) : null}\n      </div>\n    )\n  } else {\n    body = (\n      <div className={cn(editBoxClasses, \"h-7.5 items-center\")}>\n        <Input\n          data-slot=\"inline-edit-control\"\n          ref={setControl}\n          type={kind}\n          autoFocus\n          enterKeyHint=\"done\"\n          autoCapitalize={kind === \"email\" || kind === \"url\" ? \"none\" : undefined}\n          autoCorrect={kind === \"email\" || kind === \"url\" ? \"off\" : undefined}\n          spellCheck={kind === \"email\" || kind === \"url\" ? false : undefined}\n          aria-label={ariaLabel}\n          aria-invalid={error ? true : undefined}\n          aria-describedby={error ? errorId : undefined}\n          placeholder={placeholder}\n          value={draft}\n          readOnly={pending}\n          onChange={(event) => setDraft(event.target.value)}\n          onKeyDown={handleKeyDown}\n          onBlur={handleBlur}\n          className={cn(controlResetClasses, \"h-full\")}\n        />\n        {pending ? (\n          <Loader size={14} className=\"shrink-0 text-muted-foreground\" />\n        ) : null}\n      </div>\n    )\n  }\n\n  return (\n    <div\n      data-slot=\"inline-edit\"\n      data-editing={editing ? \"true\" : \"false\"}\n      onClick={editing ? (event) => event.stopPropagation() : undefined}\n      onMouseDown={editing ? (event) => event.stopPropagation() : undefined}\n      className={cn(\"flex w-full min-w-0 flex-col gap-1\", className)}\n    >\n      {body}\n      {error ? (\n        <p id={errorId} role=\"alert\" className=\"px-2 text-xs text-destructive\">\n          {error}\n        </p>\n      ) : null}\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {saved ? `${ariaLabel} saved` : null}\n      </span>\n    </div>\n  )\n}\n\nexport { InlineEdit }\n",
      "type": "registry:ui"
    }
  ],
  "docs": "Install @khaeli/foundation first: this item's styling lives in its tokens and [data-slot] rules.",
  "type": "registry:ui"
}